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.

1322 lines
32KB

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