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.

1148 lines
28KB

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