You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1201 lines
29KB

  1. #include <algorithm>
  2. #include <set>
  3. #include <thread>
  4. #include <condition_variable>
  5. #include <mutex>
  6. #include <atomic>
  7. #include <tuple>
  8. #include <pmmintrin.h>
  9. #include <pthread.h>
  10. #include <engine/Engine.hpp>
  11. #include <settings.hpp>
  12. #include <system.hpp>
  13. #include <random.hpp>
  14. #include <context.hpp>
  15. #include <patch.hpp>
  16. #include <plugin.hpp>
  17. namespace rack {
  18. namespace engine {
  19. static void initMXCSR() {
  20. // Set CPU to flush-to-zero (FTZ) and denormals-are-zero (DAZ) mode
  21. // https://software.intel.com/en-us/node/682949
  22. _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
  23. _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
  24. // Reset other flags
  25. _MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST);
  26. }
  27. /** Allows multiple "reader" threads to obtain a lock simultaneously, but only one "writer" thread.
  28. This implementation is currently just a wrapper for pthreads, which works on Linux/Mac/.
  29. This is available in C++17 as std::shared_mutex, but unfortunately we're using C++11.
  30. */
  31. struct ReadWriteMutex {
  32. pthread_rwlock_t rwlock;
  33. ReadWriteMutex() {
  34. if (pthread_rwlock_init(&rwlock, NULL))
  35. throw Exception("pthread_rwlock_init failed");
  36. }
  37. ~ReadWriteMutex() {
  38. pthread_rwlock_destroy(&rwlock);
  39. }
  40. void lockReader() {
  41. if (pthread_rwlock_rdlock(&rwlock))
  42. throw Exception("pthread_rwlock_rdlock failed");
  43. }
  44. void unlockReader() {
  45. if (pthread_rwlock_unlock(&rwlock))
  46. throw Exception("pthread_rwlock_unlock failed");
  47. }
  48. void lockWriter() {
  49. if (pthread_rwlock_wrlock(&rwlock))
  50. throw Exception("pthread_rwlock_wrlock failed");
  51. }
  52. void unlockWriter() {
  53. if (pthread_rwlock_unlock(&rwlock))
  54. throw Exception("pthread_rwlock_unlock failed");
  55. }
  56. };
  57. struct ReadLock {
  58. ReadWriteMutex& m;
  59. ReadLock(ReadWriteMutex& m) : m(m) {
  60. m.lockReader();
  61. }
  62. ~ReadLock() {
  63. m.unlockReader();
  64. }
  65. };
  66. struct WriteLock {
  67. ReadWriteMutex& m;
  68. WriteLock(ReadWriteMutex& m) : m(m) {
  69. m.lockWriter();
  70. }
  71. ~WriteLock() {
  72. m.unlockWriter();
  73. }
  74. };
  75. struct Barrier {
  76. std::mutex mutex;
  77. std::condition_variable cv;
  78. int count = 0;
  79. int total = 0;
  80. void wait() {
  81. // Waiting on one thread is trivial.
  82. if (total <= 1)
  83. return;
  84. std::unique_lock<std::mutex> lock(mutex);
  85. int id = ++count;
  86. if (id == total) {
  87. count = 0;
  88. cv.notify_all();
  89. }
  90. else {
  91. cv.wait(lock);
  92. }
  93. }
  94. };
  95. struct SpinBarrier {
  96. std::atomic<int> count{0};
  97. int total = 0;
  98. void wait() {
  99. int id = ++count;
  100. if (id == total) {
  101. count = 0;
  102. }
  103. else {
  104. while (count != 0) {
  105. _mm_pause();
  106. }
  107. }
  108. }
  109. };
  110. /** Spinlocks until all `total` threads are waiting.
  111. If `yield` is set to true at any time, all threads will switch to waiting on a mutex instead.
  112. All threads must return before beginning a new phase. Alternating between two barriers solves this problem.
  113. */
  114. struct HybridBarrier {
  115. std::atomic<int> count {0};
  116. int total = 0;
  117. std::mutex mutex;
  118. std::condition_variable cv;
  119. std::atomic<bool> yield {false};
  120. void wait() {
  121. int id = ++count;
  122. // End and reset phase if this is the last thread
  123. if (id == total) {
  124. count = 0;
  125. if (yield) {
  126. std::unique_lock<std::mutex> lock(mutex);
  127. cv.notify_all();
  128. yield = false;
  129. }
  130. return;
  131. }
  132. // Spinlock
  133. while (!yield) {
  134. if (count == 0)
  135. return;
  136. _mm_pause();
  137. }
  138. // Wait on mutex
  139. {
  140. std::unique_lock<std::mutex> lock(mutex);
  141. cv.wait(lock, [&] {
  142. return count == 0;
  143. });
  144. }
  145. }
  146. };
  147. struct EngineWorker {
  148. Engine* engine;
  149. int id;
  150. std::thread thread;
  151. bool running = false;
  152. void start() {
  153. assert(!running);
  154. running = true;
  155. thread = std::thread([&] {
  156. run();
  157. });
  158. }
  159. void requestStop() {
  160. running = false;
  161. }
  162. void join() {
  163. assert(thread.joinable());
  164. thread.join();
  165. }
  166. void run();
  167. };
  168. struct Engine::Internal {
  169. std::vector<Module*> modules;
  170. std::vector<Cable*> cables;
  171. std::set<ParamHandle*> paramHandles;
  172. // moduleId
  173. std::map<int64_t, Module*> modulesCache;
  174. // cableId
  175. std::map<int64_t, Cable*> cablesCache;
  176. // (moduleId, paramId)
  177. std::map<std::tuple<int64_t, int>, ParamHandle*> paramHandlesCache;
  178. float sampleRate = 0.f;
  179. float sampleTime = 0.f;
  180. int64_t block = 0;
  181. int64_t frame = 0;
  182. int64_t blockFrame = 0;
  183. double blockTime = 0.0;
  184. int blockFrames = 0;
  185. Module* primaryModule = NULL;
  186. // Parameter smoothing
  187. Module* smoothModule = NULL;
  188. int smoothParamId = 0;
  189. float smoothValue = 0.f;
  190. /** Mutex that guards the Engine state, such as settings, Modules, and Cables.
  191. Writers lock when mutating the engine's state or stepping the block.
  192. Readers lock when using the engine's state.
  193. */
  194. ReadWriteMutex mutex;
  195. /** Mutex that guards stepBlock() so it's not called simultaneously.
  196. */
  197. std::mutex blockMutex;
  198. int threadCount = 0;
  199. std::vector<EngineWorker> workers;
  200. HybridBarrier engineBarrier;
  201. HybridBarrier workerBarrier;
  202. std::atomic<int> workerModuleIndex;
  203. Context* context;
  204. };
  205. static void Engine_updateExpander(Engine* that, Module* module, bool side) {
  206. Module::Expander& expander = side ? module->rightExpander : module->leftExpander;
  207. Module* oldExpanderModule = expander.module;
  208. if (expander.moduleId >= 0) {
  209. if (!expander.module || expander.module->id != expander.moduleId) {
  210. expander.module = that->getModule(expander.moduleId);
  211. }
  212. }
  213. else {
  214. if (expander.module) {
  215. expander.module = NULL;
  216. }
  217. }
  218. if (expander.module != oldExpanderModule) {
  219. // Trigger ExpanderChangeEvent event
  220. Module::ExpanderChangeEvent e;
  221. e.side = side;
  222. module->onExpanderChange(e);
  223. }
  224. }
  225. static void Engine_relaunchWorkers(Engine* that, int threadCount) {
  226. Engine::Internal* internal = that->internal;
  227. if (threadCount == internal->threadCount)
  228. return;
  229. if (internal->threadCount > 0) {
  230. // Stop engine workers
  231. for (EngineWorker& worker : internal->workers) {
  232. worker.requestStop();
  233. }
  234. internal->engineBarrier.wait();
  235. // Join and destroy engine workers
  236. for (EngineWorker& worker : internal->workers) {
  237. worker.join();
  238. }
  239. internal->workers.resize(0);
  240. }
  241. // Configure engine
  242. internal->threadCount = threadCount;
  243. // Set barrier counts
  244. internal->engineBarrier.total = threadCount;
  245. internal->workerBarrier.total = threadCount;
  246. if (threadCount > 0) {
  247. // Create and start engine workers
  248. internal->workers.resize(threadCount - 1);
  249. for (int id = 1; id < threadCount; id++) {
  250. EngineWorker& worker = internal->workers[id - 1];
  251. worker.id = id;
  252. worker.engine = that;
  253. worker.start();
  254. }
  255. }
  256. }
  257. static void Engine_stepWorker(Engine* that, int threadId) {
  258. Engine::Internal* internal = that->internal;
  259. // int threadCount = internal->threadCount;
  260. int modulesLen = internal->modules.size();
  261. // Build ProcessArgs
  262. Module::ProcessArgs processArgs;
  263. processArgs.sampleRate = internal->sampleRate;
  264. processArgs.sampleTime = internal->sampleTime;
  265. processArgs.frame = internal->frame;
  266. // Step each module
  267. while (true) {
  268. // Choose next module
  269. // First-come-first serve module-to-thread allocation algorithm
  270. int i = internal->workerModuleIndex++;
  271. if (i >= modulesLen)
  272. break;
  273. Module* module = internal->modules[i];
  274. module->doProcess(processArgs);
  275. }
  276. }
  277. static void Cable_step(Cable* that) {
  278. Output* output = &that->outputModule->outputs[that->outputId];
  279. Input* input = &that->inputModule->inputs[that->inputId];
  280. // Match number of polyphonic channels to output port
  281. int channels = output->channels;
  282. // Copy all voltages from output to input
  283. for (int c = 0; c < channels; c++) {
  284. float v = output->voltages[c];
  285. // Set 0V if infinite or NaN
  286. if (!std::isfinite(v))
  287. v = 0.f;
  288. input->voltages[c] = v;
  289. }
  290. // Set higher channel voltages to 0
  291. for (int c = channels; c < input->channels; c++) {
  292. input->voltages[c] = 0.f;
  293. }
  294. input->channels = channels;
  295. }
  296. /** Steps a single frame
  297. */
  298. static void Engine_stepFrame(Engine* that) {
  299. Engine::Internal* internal = that->internal;
  300. // Param smoothing
  301. Module* smoothModule = internal->smoothModule;
  302. if (smoothModule) {
  303. int smoothParamId = internal->smoothParamId;
  304. float smoothValue = internal->smoothValue;
  305. Param* smoothParam = &smoothModule->params[smoothParamId];
  306. float value = smoothParam->value;
  307. // Use decay rate of roughly 1 graphics frame
  308. const float smoothLambda = 60.f;
  309. float newValue = value + (smoothValue - value) * smoothLambda * internal->sampleTime;
  310. if (value == newValue) {
  311. // Snap to actual smooth value if the value doesn't change enough (due to the granularity of floats)
  312. smoothParam->setValue(smoothValue);
  313. internal->smoothModule = NULL;
  314. internal->smoothParamId = 0;
  315. }
  316. else {
  317. smoothParam->setValue(newValue);
  318. }
  319. }
  320. // Step cables
  321. for (Cable* cable : that->internal->cables) {
  322. Cable_step(cable);
  323. }
  324. // Flip messages for each module
  325. for (Module* module : that->internal->modules) {
  326. if (module->leftExpander.messageFlipRequested) {
  327. std::swap(module->leftExpander.producerMessage, module->leftExpander.consumerMessage);
  328. module->leftExpander.messageFlipRequested = false;
  329. }
  330. if (module->rightExpander.messageFlipRequested) {
  331. std::swap(module->rightExpander.producerMessage, module->rightExpander.consumerMessage);
  332. module->rightExpander.messageFlipRequested = false;
  333. }
  334. }
  335. // Step modules along with workers
  336. internal->workerModuleIndex = 0;
  337. internal->engineBarrier.wait();
  338. Engine_stepWorker(that, 0);
  339. internal->workerBarrier.wait();
  340. internal->frame++;
  341. }
  342. static void Port_setDisconnected(Port* that) {
  343. that->channels = 0;
  344. for (int c = 0; c < PORT_MAX_CHANNELS; c++) {
  345. that->voltages[c] = 0.f;
  346. }
  347. }
  348. static void Port_setConnected(Port* that) {
  349. if (that->channels > 0)
  350. return;
  351. that->channels = 1;
  352. }
  353. static void Engine_updateConnected(Engine* that) {
  354. // Find disconnected ports
  355. std::set<Port*> disconnectedPorts;
  356. for (Module* module : that->internal->modules) {
  357. for (Input& input : module->inputs) {
  358. disconnectedPorts.insert(&input);
  359. }
  360. for (Output& output : module->outputs) {
  361. disconnectedPorts.insert(&output);
  362. }
  363. }
  364. for (Cable* cable : that->internal->cables) {
  365. // Connect input
  366. Input& input = cable->inputModule->inputs[cable->inputId];
  367. auto inputIt = disconnectedPorts.find(&input);
  368. if (inputIt != disconnectedPorts.end())
  369. disconnectedPorts.erase(inputIt);
  370. Port_setConnected(&input);
  371. // Connect output
  372. Output& output = cable->outputModule->outputs[cable->outputId];
  373. auto outputIt = disconnectedPorts.find(&output);
  374. if (outputIt != disconnectedPorts.end())
  375. disconnectedPorts.erase(outputIt);
  376. Port_setConnected(&output);
  377. }
  378. // Disconnect ports that have no cable
  379. for (Port* port : disconnectedPorts) {
  380. Port_setDisconnected(port);
  381. }
  382. }
  383. static void Engine_refreshParamHandleCache(Engine* that) {
  384. // Clear cache
  385. that->internal->paramHandlesCache.clear();
  386. // Add active ParamHandles to cache
  387. for (ParamHandle* paramHandle : that->internal->paramHandles) {
  388. if (paramHandle->moduleId >= 0) {
  389. that->internal->paramHandlesCache[std::make_tuple(paramHandle->moduleId, paramHandle->paramId)] = paramHandle;
  390. }
  391. }
  392. }
  393. Engine::Engine() {
  394. internal = new Internal;
  395. internal->context = contextGet();
  396. setSuggestedSampleRate(0.f);
  397. }
  398. Engine::~Engine() {
  399. Engine_relaunchWorkers(this, 0);
  400. clear();
  401. // Make sure there are no cables or modules in the rack on destruction.
  402. // If this happens, a module must have failed to remove itself before the RackWidget was destroyed.
  403. assert(internal->cables.empty());
  404. assert(internal->modules.empty());
  405. assert(internal->paramHandles.empty());
  406. assert(internal->modulesCache.empty());
  407. assert(internal->cablesCache.empty());
  408. assert(internal->paramHandlesCache.empty());
  409. delete internal;
  410. }
  411. void Engine::clear() {
  412. WriteLock lock(internal->mutex);
  413. clear_NoLock();
  414. }
  415. void Engine::clear_NoLock() {
  416. // Copy lists because we'll be removing while iterating
  417. std::set<ParamHandle*> paramHandles = internal->paramHandles;
  418. for (ParamHandle* paramHandle : paramHandles) {
  419. removeParamHandle_NoLock(paramHandle);
  420. // Don't delete paramHandle because they're normally owned by Module subclasses
  421. }
  422. std::vector<Cable*> cables = internal->cables;
  423. for (Cable* cable : cables) {
  424. removeCable_NoLock(cable);
  425. delete cable;
  426. }
  427. std::vector<Module*> modules = internal->modules;
  428. for (Module* module : modules) {
  429. removeModule_NoLock(module);
  430. delete module;
  431. }
  432. }
  433. void Engine::stepBlock(int frames) {
  434. std::lock_guard<std::mutex> stepLock(internal->blockMutex);
  435. ReadLock lock(internal->mutex);
  436. // Configure thread
  437. initMXCSR();
  438. random::init();
  439. internal->blockFrame = internal->frame;
  440. internal->blockTime = system::getTime();
  441. internal->blockFrames = frames;
  442. // Update expander pointers
  443. for (Module* module : internal->modules) {
  444. Engine_updateExpander(this, module, false);
  445. Engine_updateExpander(this, module, true);
  446. }
  447. // Launch workers
  448. Engine_relaunchWorkers(this, settings::threadCount);
  449. // Step individual frames
  450. for (int i = 0; i < frames; i++) {
  451. Engine_stepFrame(this);
  452. }
  453. yieldWorkers();
  454. double endTime = system::getTime();
  455. float duration = endTime - internal->blockTime;
  456. float blockDuration = internal->blockFrames * internal->sampleTime;
  457. // DEBUG("%d %f / %f = %f%%", internal->blockFrames, duration, blockDuration, duration / blockDuration * 100.f);
  458. internal->block++;
  459. }
  460. void Engine::setPrimaryModule(Module* module) {
  461. WriteLock lock(internal->mutex);
  462. internal->primaryModule = module;
  463. }
  464. Module* Engine::getPrimaryModule() {
  465. return internal->primaryModule;
  466. }
  467. float Engine::getSampleRate() {
  468. return internal->sampleRate;
  469. }
  470. void Engine::setSampleRate(float sampleRate) {
  471. if (sampleRate == internal->sampleRate)
  472. return;
  473. WriteLock lock(internal->mutex);
  474. internal->sampleRate = sampleRate;
  475. internal->sampleTime = 1.f / sampleRate;
  476. // Trigger SampleRateChangeEvent
  477. Module::SampleRateChangeEvent e;
  478. e.sampleRate = internal->sampleRate;
  479. e.sampleTime = internal->sampleTime;
  480. for (Module* module : internal->modules) {
  481. module->onSampleRateChange(e);
  482. }
  483. }
  484. void Engine::setSuggestedSampleRate(float suggestedSampleRate) {
  485. if (settings::sampleRate > 0) {
  486. setSampleRate(settings::sampleRate);
  487. }
  488. else if (suggestedSampleRate > 0) {
  489. setSampleRate(suggestedSampleRate);
  490. }
  491. else {
  492. // Fallback sample rate
  493. setSampleRate(44100.f);
  494. }
  495. }
  496. float Engine::getSampleTime() {
  497. return internal->sampleTime;
  498. }
  499. void Engine::yieldWorkers() {
  500. internal->workerBarrier.yield = true;
  501. }
  502. int64_t Engine::getBlock() {
  503. return internal->block;
  504. }
  505. int64_t Engine::getFrame() {
  506. return internal->frame;
  507. }
  508. void Engine::setFrame(int64_t frame) {
  509. internal->frame = frame;
  510. }
  511. int64_t Engine::getBlockFrame() {
  512. return internal->blockFrame;
  513. }
  514. double Engine::getBlockTime() {
  515. return internal->blockTime;
  516. }
  517. int Engine::getBlockFrames() {
  518. return internal->blockFrames;
  519. }
  520. double Engine::getBlockDuration() {
  521. return internal->blockFrames * internal->sampleTime;
  522. }
  523. size_t Engine::getNumModules() {
  524. return internal->modules.size();
  525. }
  526. size_t Engine::getModuleIds(int64_t* moduleIds, size_t len) {
  527. ReadLock lock(internal->mutex);
  528. size_t i = 0;
  529. for (Module* m : internal->modules) {
  530. if (i >= len)
  531. break;
  532. moduleIds[i] = m->id;
  533. i++;
  534. }
  535. return i;
  536. }
  537. std::vector<int64_t> Engine::getModuleIds() {
  538. ReadLock lock(internal->mutex);
  539. std::vector<int64_t> moduleIds;
  540. moduleIds.reserve(internal->modules.size());
  541. for (Module* m : internal->modules) {
  542. moduleIds.push_back(m->id);
  543. }
  544. return moduleIds;
  545. }
  546. void Engine::addModule(Module* module) {
  547. WriteLock lock(internal->mutex);
  548. assert(module);
  549. // Check that the module is not already added
  550. auto it = std::find(internal->modules.begin(), internal->modules.end(), module);
  551. assert(it == internal->modules.end());
  552. // Set ID if unset or collides with an existing ID
  553. while (module->id < 0 || internal->modulesCache.find(module->id) != internal->modulesCache.end()) {
  554. // Randomly generate ID
  555. module->id = random::u64() % (1ull << 53);
  556. }
  557. // Add module
  558. internal->modules.push_back(module);
  559. internal->modulesCache[module->id] = module;
  560. // Trigger Add event
  561. Module::AddEvent eAdd;
  562. module->onAdd(eAdd);
  563. // Update ParamHandles' module pointers
  564. for (ParamHandle* paramHandle : internal->paramHandles) {
  565. if (paramHandle->moduleId == module->id)
  566. paramHandle->module = module;
  567. }
  568. }
  569. void Engine::removeModule(Module* module) {
  570. WriteLock lock(internal->mutex);
  571. removeModule_NoLock(module);
  572. }
  573. void Engine::removeModule_NoLock(Module* module) {
  574. assert(module);
  575. // Check that the module actually exists
  576. auto it = std::find(internal->modules.begin(), internal->modules.end(), module);
  577. assert(it != internal->modules.end());
  578. // If a param is being smoothed on this module, stop smoothing it immediately
  579. if (module == internal->smoothModule) {
  580. internal->smoothModule = NULL;
  581. }
  582. // Check that all cables are disconnected
  583. for (Cable* cable : internal->cables) {
  584. assert(cable->inputModule != module);
  585. assert(cable->outputModule != module);
  586. }
  587. // Update ParamHandles' module pointers
  588. for (ParamHandle* paramHandle : internal->paramHandles) {
  589. if (paramHandle->moduleId == module->id)
  590. paramHandle->module = NULL;
  591. }
  592. // Update expander pointers
  593. for (Module* m : internal->modules) {
  594. if (m->leftExpander.module == module) {
  595. m->leftExpander.moduleId = -1;
  596. m->leftExpander.module = NULL;
  597. }
  598. if (m->rightExpander.module == module) {
  599. m->rightExpander.moduleId = -1;
  600. m->rightExpander.module = NULL;
  601. }
  602. }
  603. // Trigger Remove event
  604. Module::RemoveEvent eRemove;
  605. module->onRemove(eRemove);
  606. // Unset primary module
  607. if (internal->primaryModule == module) {
  608. internal->primaryModule = NULL;
  609. }
  610. // Remove module
  611. internal->modulesCache.erase(module->id);
  612. internal->modules.erase(it);
  613. }
  614. bool Engine::hasModule(Module* module) {
  615. ReadLock lock(internal->mutex);
  616. // TODO Performance could be improved by searching modulesCache, but more testing would be needed to make sure it's always valid.
  617. auto it = std::find(internal->modules.begin(), internal->modules.end(), module);
  618. return it != internal->modules.end();
  619. }
  620. Module* Engine::getModule(int64_t moduleId) {
  621. ReadLock lock(internal->mutex);
  622. auto it = internal->modulesCache.find(moduleId);
  623. if (it == internal->modulesCache.end())
  624. return NULL;
  625. return it->second;
  626. }
  627. void Engine::resetModule(Module* module) {
  628. WriteLock lock(internal->mutex);
  629. assert(module);
  630. Module::ResetEvent eReset;
  631. module->onReset(eReset);
  632. }
  633. void Engine::randomizeModule(Module* module) {
  634. WriteLock lock(internal->mutex);
  635. assert(module);
  636. Module::RandomizeEvent eRandomize;
  637. module->onRandomize(eRandomize);
  638. }
  639. void Engine::bypassModule(Module* module, bool bypassed) {
  640. WriteLock lock(internal->mutex);
  641. assert(module);
  642. if (module->isBypassed() == bypassed)
  643. return;
  644. // Clear outputs and set to 1 channel
  645. for (Output& output : module->outputs) {
  646. // This zeros all voltages, but the channel is set to 1 if connected
  647. output.setChannels(0);
  648. }
  649. // Set bypassed state
  650. module->setBypassed(bypassed);
  651. // Trigger event
  652. if (bypassed) {
  653. Module::BypassEvent eBypass;
  654. module->onBypass(eBypass);
  655. }
  656. else {
  657. Module::UnBypassEvent eUnBypass;
  658. module->onUnBypass(eUnBypass);
  659. }
  660. }
  661. json_t* Engine::moduleToJson(Module* module) {
  662. ReadLock lock(internal->mutex);
  663. return module->toJson();
  664. }
  665. void Engine::moduleFromJson(Module* module, json_t* rootJ) {
  666. WriteLock lock(internal->mutex);
  667. module->fromJson(rootJ);
  668. }
  669. size_t Engine::getNumCables() {
  670. return internal->cables.size();
  671. }
  672. size_t Engine::getCableIds(int64_t* cableIds, size_t len) {
  673. ReadLock lock(internal->mutex);
  674. size_t i = 0;
  675. for (Cable* c : internal->cables) {
  676. if (i >= len)
  677. break;
  678. cableIds[i] = c->id;
  679. i++;
  680. }
  681. return i;
  682. }
  683. std::vector<int64_t> Engine::getCableIds() {
  684. ReadLock lock(internal->mutex);
  685. std::vector<int64_t> cableIds;
  686. cableIds.reserve(internal->cables.size());
  687. for (Cable* c : internal->cables) {
  688. cableIds.push_back(c->id);
  689. }
  690. return cableIds;
  691. }
  692. void Engine::addCable(Cable* cable) {
  693. WriteLock lock(internal->mutex);
  694. assert(cable);
  695. // Check cable properties
  696. assert(cable->inputModule);
  697. assert(cable->outputModule);
  698. bool outputWasConnected = false;
  699. for (Cable* cable2 : internal->cables) {
  700. // Check that the cable is not already added
  701. assert(cable2 != cable);
  702. // Check that the input is not already used by another cable
  703. assert(!(cable2->inputModule == cable->inputModule && cable2->inputId == cable->inputId));
  704. // Get connected status of output, to decide whether we need to call a PortChangeEvent.
  705. // It's best to not trust `cable->outputModule->outputs[cable->outputId]->isConnected()`
  706. if (cable2->outputModule == cable->outputModule && cable2->outputId == cable->outputId)
  707. outputWasConnected = true;
  708. }
  709. // Set ID if unset or collides with an existing ID
  710. while (cable->id < 0 || internal->cablesCache.find(cable->id) != internal->cablesCache.end()) {
  711. // Randomly generate ID
  712. cable->id = random::u64() % (1ull << 53);
  713. }
  714. // Add the cable
  715. internal->cables.push_back(cable);
  716. internal->cablesCache[cable->id] = cable;
  717. Engine_updateConnected(this);
  718. // Trigger input port event
  719. {
  720. Module::PortChangeEvent e;
  721. e.connecting = true;
  722. e.type = Port::INPUT;
  723. e.portId = cable->inputId;
  724. cable->inputModule->onPortChange(e);
  725. }
  726. // Trigger output port event if its state went from disconnected to connected.
  727. if (!outputWasConnected) {
  728. Module::PortChangeEvent e;
  729. e.connecting = true;
  730. e.type = Port::OUTPUT;
  731. e.portId = cable->outputId;
  732. cable->outputModule->onPortChange(e);
  733. }
  734. }
  735. void Engine::removeCable(Cable* cable) {
  736. WriteLock lock(internal->mutex);
  737. removeCable_NoLock(cable);
  738. }
  739. void Engine::removeCable_NoLock(Cable* cable) {
  740. assert(cable);
  741. // Check that the cable is already added
  742. auto it = std::find(internal->cables.begin(), internal->cables.end(), cable);
  743. assert(it != internal->cables.end());
  744. // Remove the cable
  745. internal->cablesCache.erase(cable->id);
  746. internal->cables.erase(it);
  747. Engine_updateConnected(this);
  748. bool outputIsConnected = false;
  749. for (Cable* cable2 : internal->cables) {
  750. // Get connected status of output, to decide whether we need to call a PortChangeEvent.
  751. // It's best to not trust `cable->outputModule->outputs[cable->outputId]->isConnected()`
  752. if (cable2->outputModule == cable->outputModule && cable2->outputId == cable->outputId)
  753. outputIsConnected = true;
  754. }
  755. // Trigger input port event
  756. {
  757. Module::PortChangeEvent e;
  758. e.connecting = false;
  759. e.type = Port::INPUT;
  760. e.portId = cable->inputId;
  761. cable->inputModule->onPortChange(e);
  762. }
  763. // Trigger output port event if its state went from connected to disconnected.
  764. if (!outputIsConnected) {
  765. Module::PortChangeEvent e;
  766. e.connecting = false;
  767. e.type = Port::OUTPUT;
  768. e.portId = cable->outputId;
  769. cable->outputModule->onPortChange(e);
  770. }
  771. }
  772. bool Engine::hasCable(Cable* cable) {
  773. ReadLock lock(internal->mutex);
  774. // TODO Performance could be improved by searching cablesCache, but more testing would be needed to make sure it's always valid.
  775. auto it = std::find(internal->cables.begin(), internal->cables.end(), cable);
  776. return it != internal->cables.end();
  777. }
  778. Cable* Engine::getCable(int64_t cableId) {
  779. ReadLock lock(internal->mutex);
  780. auto it = internal->cablesCache.find(cableId);
  781. if (it == internal->cablesCache.end())
  782. return NULL;
  783. return it->second;
  784. }
  785. void Engine::setParam(Module* module, int paramId, float value) {
  786. // If param is being smoothed, cancel smoothing.
  787. if (internal->smoothModule == module && internal->smoothParamId == paramId) {
  788. internal->smoothModule = NULL;
  789. internal->smoothParamId = 0;
  790. }
  791. module->params[paramId].value = value;
  792. }
  793. float Engine::getParam(Module* module, int paramId) {
  794. return module->params[paramId].value;
  795. }
  796. void Engine::setSmoothParam(Module* module, int paramId, float value) {
  797. // If another param is being smoothed, jump value
  798. if (internal->smoothModule && !(internal->smoothModule == module && internal->smoothParamId == paramId)) {
  799. internal->smoothModule->params[internal->smoothParamId].value = internal->smoothValue;
  800. }
  801. internal->smoothParamId = paramId;
  802. internal->smoothValue = value;
  803. // Set this last so the above values are valid as soon as it is set
  804. internal->smoothModule = module;
  805. }
  806. float Engine::getSmoothParam(Module* module, int paramId) {
  807. if (internal->smoothModule == module && internal->smoothParamId == paramId)
  808. return internal->smoothValue;
  809. return module->params[paramId].value;
  810. }
  811. void Engine::addParamHandle(ParamHandle* paramHandle) {
  812. WriteLock lock(internal->mutex);
  813. // New ParamHandles must be blank.
  814. // This means we don't have to refresh the cache.
  815. assert(paramHandle->moduleId < 0);
  816. // Check that the ParamHandle is not already added
  817. auto it = internal->paramHandles.find(paramHandle);
  818. assert(it == internal->paramHandles.end());
  819. // Add it
  820. internal->paramHandles.insert(paramHandle);
  821. // No need to refresh the cache because the moduleId is not set.
  822. }
  823. void Engine::removeParamHandle(ParamHandle* paramHandle) {
  824. WriteLock lock(internal->mutex);
  825. removeParamHandle_NoLock(paramHandle);
  826. }
  827. void Engine::removeParamHandle_NoLock(ParamHandle* paramHandle) {
  828. // Check that the ParamHandle is already added
  829. auto it = internal->paramHandles.find(paramHandle);
  830. assert(it != internal->paramHandles.end());
  831. // Remove it
  832. paramHandle->module = NULL;
  833. internal->paramHandles.erase(it);
  834. Engine_refreshParamHandleCache(this);
  835. }
  836. ParamHandle* Engine::getParamHandle(int64_t moduleId, int paramId) {
  837. ReadLock lock(internal->mutex);
  838. auto it = internal->paramHandlesCache.find(std::make_tuple(moduleId, paramId));
  839. if (it == internal->paramHandlesCache.end())
  840. return NULL;
  841. return it->second;
  842. }
  843. ParamHandle* Engine::getParamHandle(Module* module, int paramId) {
  844. return getParamHandle(module->id, paramId);
  845. }
  846. void Engine::updateParamHandle(ParamHandle* paramHandle, int64_t moduleId, int paramId, bool overwrite) {
  847. ReadLock lock(internal->mutex);
  848. // Check that it exists
  849. auto it = internal->paramHandles.find(paramHandle);
  850. assert(it != internal->paramHandles.end());
  851. // Set IDs
  852. paramHandle->moduleId = moduleId;
  853. paramHandle->paramId = paramId;
  854. paramHandle->module = NULL;
  855. // At this point, the ParamHandle cache might be invalid.
  856. if (paramHandle->moduleId >= 0) {
  857. // Replace old ParamHandle, or reset the current ParamHandle
  858. // TODO Maybe call getParamHandle_NoLock()?
  859. ParamHandle* oldParamHandle = getParamHandle(moduleId, paramId);
  860. if (oldParamHandle) {
  861. if (overwrite) {
  862. oldParamHandle->moduleId = -1;
  863. oldParamHandle->paramId = 0;
  864. oldParamHandle->module = NULL;
  865. }
  866. else {
  867. paramHandle->moduleId = -1;
  868. paramHandle->paramId = 0;
  869. paramHandle->module = NULL;
  870. }
  871. }
  872. }
  873. // Set module pointer if the above block didn't reset it
  874. if (paramHandle->moduleId >= 0) {
  875. // TODO Maybe call getModule_NoLock()?
  876. paramHandle->module = getModule(paramHandle->moduleId);
  877. }
  878. Engine_refreshParamHandleCache(this);
  879. }
  880. json_t* Engine::toJson() {
  881. ReadLock lock(internal->mutex);
  882. json_t* rootJ = json_object();
  883. // modules
  884. json_t* modulesJ = json_array();
  885. for (Module* module : internal->modules) {
  886. // module
  887. json_t* moduleJ = module->toJson();
  888. json_array_append_new(modulesJ, moduleJ);
  889. }
  890. json_object_set_new(rootJ, "modules", modulesJ);
  891. // cables
  892. json_t* cablesJ = json_array();
  893. for (Cable* cable : internal->cables) {
  894. // cable
  895. json_t* cableJ = cable->toJson();
  896. json_array_append_new(cablesJ, cableJ);
  897. }
  898. json_object_set_new(rootJ, "cables", cablesJ);
  899. return rootJ;
  900. }
  901. void Engine::fromJson(json_t* rootJ) {
  902. // Don't write-lock the entire method because most of it doesn't need it.
  903. // Write-locks
  904. clear();
  905. // modules
  906. json_t* modulesJ = json_object_get(rootJ, "modules");
  907. if (!modulesJ)
  908. return;
  909. size_t moduleIndex;
  910. json_t* moduleJ;
  911. json_array_foreach(modulesJ, moduleIndex, moduleJ) {
  912. // Get model
  913. plugin::Model* model;
  914. try {
  915. model = plugin::modelFromJson(moduleJ);
  916. }
  917. catch (Exception& e) {
  918. WARN("Cannot load model: %s", e.what());
  919. APP->patch->log(e.what());
  920. continue;
  921. }
  922. // Create module
  923. Module* module = model->createModule();
  924. assert(module);
  925. try {
  926. // This doesn't need a lock because the Module is not added to the Engine yet.
  927. module->fromJson(moduleJ);
  928. // Before 1.0, the module ID was the index in the "modules" array
  929. if (module->id < 0) {
  930. module->id = moduleIndex;
  931. }
  932. // Write-locks
  933. addModule(module);
  934. }
  935. catch (Exception& e) {
  936. WARN("Cannot load module: %s", e.what());
  937. APP->patch->log(e.what());
  938. delete module;
  939. continue;
  940. }
  941. }
  942. // cables
  943. json_t* cablesJ = json_object_get(rootJ, "cables");
  944. // Before 1.0, cables were called wires
  945. if (!cablesJ)
  946. cablesJ = json_object_get(rootJ, "wires");
  947. if (!cablesJ)
  948. return;
  949. size_t cableIndex;
  950. json_t* cableJ;
  951. json_array_foreach(cablesJ, cableIndex, cableJ) {
  952. // cable
  953. Cable* cable = new Cable;
  954. try {
  955. cable->fromJson(cableJ);
  956. // Before 1.0, the cable ID was the index in the "cables" array
  957. if (cable->id < 0) {
  958. cable->id = cableIndex;
  959. }
  960. // Write-locks
  961. addCable(cable);
  962. }
  963. catch (Exception& e) {
  964. WARN("Cannot load cable: %s", e.what());
  965. delete cable;
  966. // Don't log exceptions because missing modules create unnecessary complaining when cables try to connect to them.
  967. continue;
  968. }
  969. }
  970. }
  971. void EngineWorker::run() {
  972. // Configure thread
  973. contextSet(engine->internal->context);
  974. system::setThreadName(string::f("Worker %d", id));
  975. initMXCSR();
  976. random::init();
  977. while (true) {
  978. engine->internal->engineBarrier.wait();
  979. if (!running)
  980. return;
  981. Engine_stepWorker(engine, id);
  982. engine->internal->workerBarrier.wait();
  983. }
  984. }
  985. } // namespace engine
  986. } // namespace rack