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.

766 lines
19KB

  1. #include "engine/Engine.hpp"
  2. #include "settings.hpp"
  3. #include "system.hpp"
  4. #include "random.hpp"
  5. #include <algorithm>
  6. #include <chrono>
  7. #include <thread>
  8. #include <condition_variable>
  9. #include <mutex>
  10. #include <atomic>
  11. #include <x86intrin.h>
  12. namespace rack {
  13. namespace engine {
  14. static void disableDenormals() {
  15. // Set CPU to flush-to-zero (FTZ) and denormals-are-zero (DAZ) mode
  16. // https://software.intel.com/en-us/node/682949
  17. _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
  18. _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
  19. }
  20. /** Threads which obtain a VIPLock will cause wait() to block for other less important threads.
  21. This does not provide the VIPs with an exclusive lock. That should be left up to another mutex shared between the less important thread.
  22. */
  23. struct VIPMutex {
  24. int count = 0;
  25. std::condition_variable cv;
  26. std::mutex countMutex;
  27. /** Blocks until there are no remaining VIPLocks */
  28. void wait() {
  29. std::unique_lock<std::mutex> lock(countMutex);
  30. while (count > 0)
  31. cv.wait(lock);
  32. }
  33. };
  34. struct VIPLock {
  35. VIPMutex &m;
  36. VIPLock(VIPMutex &m) : m(m) {
  37. std::unique_lock<std::mutex> lock(m.countMutex);
  38. m.count++;
  39. }
  40. ~VIPLock() {
  41. std::unique_lock<std::mutex> lock(m.countMutex);
  42. m.count--;
  43. lock.unlock();
  44. m.cv.notify_all();
  45. }
  46. };
  47. struct Barrier {
  48. std::mutex mutex;
  49. std::condition_variable cv;
  50. int count = 0;
  51. int total = 0;
  52. void wait() {
  53. // Waiting on one thread is trivial.
  54. if (total <= 1)
  55. return;
  56. std::unique_lock<std::mutex> lock(mutex);
  57. int id = ++count;
  58. if (id == total) {
  59. count = 0;
  60. cv.notify_all();
  61. }
  62. else {
  63. cv.wait(lock);
  64. }
  65. }
  66. };
  67. struct SpinBarrier {
  68. std::atomic<int> count{0};
  69. int total = 0;
  70. void wait() {
  71. int id = ++count;
  72. if (id == total) {
  73. count = 0;
  74. }
  75. else {
  76. while (count != 0) {
  77. _mm_pause();
  78. }
  79. }
  80. }
  81. };
  82. /** Spinlocks until all `total` threads are waiting.
  83. If `yield` is set to true at any time, all threads will switch to waiting on a mutex instead.
  84. All threads must return before beginning a new phase. Alternating between two barriers solves this problem.
  85. */
  86. struct HybridBarrier {
  87. std::atomic<int> count {0};
  88. int total = 0;
  89. std::mutex mutex;
  90. std::condition_variable cv;
  91. std::atomic<bool> yield {false};
  92. void wait() {
  93. int id = ++count;
  94. // End and reset phase if this is the last thread
  95. if (id == total) {
  96. count = 0;
  97. if (yield) {
  98. std::unique_lock<std::mutex> lock(mutex);
  99. cv.notify_all();
  100. yield = false;
  101. }
  102. return;
  103. }
  104. // Spinlock
  105. while (!yield) {
  106. if (count == 0)
  107. return;
  108. _mm_pause();
  109. }
  110. // Wait on mutex
  111. {
  112. std::unique_lock<std::mutex> lock(mutex);
  113. cv.wait(lock, [&]{
  114. return count == 0;
  115. });
  116. }
  117. }
  118. };
  119. struct EngineWorker {
  120. Engine *engine;
  121. int id;
  122. std::thread thread;
  123. bool running = true;
  124. void start() {
  125. thread = std::thread([&] {
  126. random::init();
  127. run();
  128. });
  129. }
  130. void stop() {
  131. running = false;
  132. }
  133. void join() {
  134. thread.join();
  135. }
  136. void run();
  137. };
  138. struct Engine::Internal {
  139. std::vector<Module*> modules;
  140. std::vector<Cable*> cables;
  141. std::vector<ParamHandle*> paramHandles;
  142. bool paused = false;
  143. bool running = false;
  144. float sampleRate;
  145. float sampleTime;
  146. int nextModuleId = 0;
  147. int nextCableId = 0;
  148. // Parameter smoothing
  149. Module *smoothModule = NULL;
  150. int smoothParamId;
  151. float smoothValue;
  152. std::recursive_mutex mutex;
  153. std::thread thread;
  154. VIPMutex vipMutex;
  155. bool realTime = false;
  156. int threadCount = 1;
  157. std::vector<EngineWorker> workers;
  158. HybridBarrier engineBarrier;
  159. HybridBarrier workerBarrier;
  160. std::atomic<int> workerModuleIndex;
  161. };
  162. Engine::Engine() {
  163. internal = new Internal;
  164. internal->engineBarrier.total = 1;
  165. internal->workerBarrier.total = 1;
  166. internal->sampleRate = 44100.f;
  167. internal->sampleTime = 1 / internal->sampleRate;
  168. system::setThreadRealTime(false);
  169. }
  170. Engine::~Engine() {
  171. // Make sure there are no cables or modules in the rack on destruction.
  172. // If this happens, a module must have failed to remove itself before the RackWidget was destroyed.
  173. assert(internal->cables.empty());
  174. assert(internal->modules.empty());
  175. assert(internal->paramHandles.empty());
  176. delete internal;
  177. }
  178. static void Engine_stepModules(Engine *that, int threadId) {
  179. Engine::Internal *internal = that->internal;
  180. // int threadCount = internal->threadCount;
  181. int modulesLen = internal->modules.size();
  182. float sampleTime = internal->sampleTime;
  183. Module::ProcessArgs processCtx;
  184. processCtx.sampleRate = internal->sampleRate;
  185. processCtx.sampleTime = internal->sampleTime;
  186. // Step each module
  187. // for (int i = threadId; i < modulesLen; i += threadCount) {
  188. while (true) {
  189. // Choose next module
  190. int i = internal->workerModuleIndex++;
  191. if (i >= modulesLen)
  192. break;
  193. Module *module = internal->modules[i];
  194. if (!module->bypass) {
  195. // Step module
  196. if (settings::cpuMeter) {
  197. auto startTime = std::chrono::high_resolution_clock::now();
  198. module->process(processCtx);
  199. auto stopTime = std::chrono::high_resolution_clock::now();
  200. float cpuTime = std::chrono::duration<float>(stopTime - startTime).count();
  201. // Smooth CPU time
  202. const float cpuTau = 2.f /* seconds */;
  203. module->cpuTime += (cpuTime - module->cpuTime) * sampleTime / cpuTau;
  204. }
  205. else {
  206. module->process(processCtx);
  207. }
  208. }
  209. // Iterate ports to step plug lights
  210. for (Input &input : module->inputs) {
  211. input.process(sampleTime);
  212. }
  213. for (Output &output : module->outputs) {
  214. output.process(sampleTime);
  215. }
  216. }
  217. }
  218. static void Engine_step(Engine *that) {
  219. Engine::Internal *internal = that->internal;
  220. // Param smoothing
  221. Module *smoothModule = internal->smoothModule;
  222. int smoothParamId = internal->smoothParamId;
  223. float smoothValue = internal->smoothValue;
  224. if (smoothModule) {
  225. Param *param = &smoothModule->params[smoothParamId];
  226. float value = param->value;
  227. // Decay rate is 1 graphics frame
  228. const float smoothLambda = 60.f;
  229. float newValue = value + (smoothValue - value) * smoothLambda * internal->sampleTime;
  230. if (value == newValue) {
  231. // Snap to actual smooth value if the value doesn't change enough (due to the granularity of floats)
  232. param->setValue(smoothValue);
  233. internal->smoothModule = NULL;
  234. internal->smoothParamId = 0;
  235. }
  236. else {
  237. param->value = newValue;
  238. }
  239. }
  240. // Step modules along with workers
  241. internal->workerModuleIndex = 0;
  242. internal->engineBarrier.wait();
  243. Engine_stepModules(that, 0);
  244. internal->workerBarrier.wait();
  245. // Step cables
  246. for (Cable *cable : that->internal->cables) {
  247. cable->step();
  248. }
  249. // Flip messages for each module
  250. for (Module *module : that->internal->modules) {
  251. if (module->leftExpander.messageFlipRequested) {
  252. std::swap(module->leftExpander.producerMessage, module->leftExpander.consumerMessage);
  253. module->leftExpander.messageFlipRequested = false;
  254. }
  255. if (module->rightExpander.messageFlipRequested) {
  256. std::swap(module->rightExpander.producerMessage, module->rightExpander.consumerMessage);
  257. module->rightExpander.messageFlipRequested = false;
  258. }
  259. }
  260. }
  261. static void Engine_updateExpander(Engine *that, Module::Expander *expander) {
  262. if (expander->moduleId >= 0) {
  263. if (!expander->module || expander->module->id != expander->moduleId) {
  264. expander->module = that->getModule(expander->moduleId);
  265. }
  266. }
  267. else {
  268. if (expander->module) {
  269. expander->module = NULL;
  270. }
  271. }
  272. }
  273. static void Engine_relaunchWorkers(Engine *that) {
  274. Engine::Internal *internal = that->internal;
  275. assert(1 <= internal->threadCount);
  276. // Stop all workers
  277. for (EngineWorker &worker : internal->workers) {
  278. worker.stop();
  279. }
  280. internal->engineBarrier.wait();
  281. // Destroy all workers
  282. for (EngineWorker &worker : internal->workers) {
  283. worker.join();
  284. }
  285. internal->workers.resize(0);
  286. // Configure main thread
  287. system::setThreadRealTime(internal->realTime);
  288. // Set barrier counts
  289. internal->engineBarrier.total = internal->threadCount;
  290. internal->workerBarrier.total = internal->threadCount;
  291. // Create workers
  292. internal->workers.resize(internal->threadCount - 1);
  293. for (int id = 1; id < internal->threadCount; id++) {
  294. EngineWorker &worker = internal->workers[id - 1];
  295. worker.id = id;
  296. worker.engine = that;
  297. worker.start();
  298. }
  299. }
  300. static void Engine_run(Engine *that) {
  301. Engine::Internal *internal = that->internal;
  302. // Set up thread
  303. system::setThreadName("Engine");
  304. // system::setThreadRealTime();
  305. disableDenormals();
  306. // Every time the that waits and locks a mutex, it steps this many frames
  307. const int mutexSteps = 128;
  308. // Time in seconds that the that is rushing ahead of the estimated clock time
  309. double aheadTime = 0.0;
  310. auto lastTime = std::chrono::high_resolution_clock::now();
  311. while (internal->running) {
  312. internal->vipMutex.wait();
  313. // Set sample rate
  314. if (internal->sampleRate != settings::sampleRate) {
  315. internal->sampleRate = settings::sampleRate;
  316. internal->sampleTime = 1 / internal->sampleRate;
  317. for (Module *module : internal->modules) {
  318. module->onSampleRateChange();
  319. }
  320. aheadTime = 0.0;
  321. }
  322. // Launch workers
  323. if (internal->threadCount != settings::threadCount || internal->realTime != settings::realTime) {
  324. internal->threadCount = settings::threadCount;
  325. internal->realTime = settings::realTime;
  326. Engine_relaunchWorkers(that);
  327. }
  328. if (!internal->paused) {
  329. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  330. // Update expander pointers
  331. for (Module *module : internal->modules) {
  332. Engine_updateExpander(that, &module->leftExpander);
  333. Engine_updateExpander(that, &module->rightExpander);
  334. }
  335. // Step modules
  336. for (int i = 0; i < mutexSteps; i++) {
  337. Engine_step(that);
  338. }
  339. }
  340. double stepTime = mutexSteps * internal->sampleTime;
  341. aheadTime += stepTime;
  342. auto currTime = std::chrono::high_resolution_clock::now();
  343. const double aheadFactor = 2.0;
  344. aheadTime -= aheadFactor * std::chrono::duration<double>(currTime - lastTime).count();
  345. lastTime = currTime;
  346. aheadTime = std::fmax(aheadTime, 0.0);
  347. // Avoid pegging the CPU at 100% when there are no "blocking" modules like AudioInterface, but still step audio at a reasonable rate
  348. // The number of steps to wait before possibly sleeping
  349. const double aheadMax = 1.0; // seconds
  350. if (aheadTime > aheadMax) {
  351. std::this_thread::sleep_for(std::chrono::duration<double>(stepTime));
  352. }
  353. }
  354. // Stop workers
  355. internal->threadCount = 1;
  356. Engine_relaunchWorkers(that);
  357. }
  358. void Engine::start() {
  359. internal->running = true;
  360. internal->thread = std::thread([&] {
  361. random::init();
  362. Engine_run(this);
  363. });
  364. }
  365. void Engine::stop() {
  366. internal->running = false;
  367. internal->thread.join();
  368. }
  369. void Engine::setPaused(bool paused) {
  370. VIPLock vipLock(internal->vipMutex);
  371. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  372. internal->paused = paused;
  373. }
  374. bool Engine::isPaused() {
  375. // No lock
  376. return internal->paused;
  377. }
  378. float Engine::getSampleRate() {
  379. return internal->sampleRate;
  380. }
  381. float Engine::getSampleTime() {
  382. return internal->sampleTime;
  383. }
  384. void Engine::yieldWorkers() {
  385. internal->workerBarrier.yield = true;
  386. }
  387. void Engine::addModule(Module *module) {
  388. assert(module);
  389. VIPLock vipLock(internal->vipMutex);
  390. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  391. // Check that the module is not already added
  392. auto it = std::find(internal->modules.begin(), internal->modules.end(), module);
  393. assert(it == internal->modules.end());
  394. // Set ID
  395. if (module->id < 0) {
  396. // Automatically assign ID
  397. module->id = internal->nextModuleId++;
  398. }
  399. else {
  400. // Manual ID
  401. // Check that the ID is not already taken
  402. for (Module *m : internal->modules) {
  403. assert(module->id != m->id);
  404. }
  405. if (module->id >= internal->nextModuleId) {
  406. internal->nextModuleId = module->id + 1;
  407. }
  408. }
  409. // Add module
  410. internal->modules.push_back(module);
  411. // Trigger Add event
  412. module->onAdd();
  413. // Update ParamHandles
  414. for (ParamHandle *paramHandle : internal->paramHandles) {
  415. if (paramHandle->moduleId == module->id)
  416. paramHandle->module = module;
  417. }
  418. }
  419. void Engine::removeModule(Module *module) {
  420. assert(module);
  421. VIPLock vipLock(internal->vipMutex);
  422. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  423. // Check that the module actually exists
  424. auto it = std::find(internal->modules.begin(), internal->modules.end(), module);
  425. assert(it != internal->modules.end());
  426. // If a param is being smoothed on this module, stop smoothing it immediately
  427. if (module == internal->smoothModule) {
  428. internal->smoothModule = NULL;
  429. }
  430. // Check that all cables are disconnected
  431. for (Cable *cable : internal->cables) {
  432. assert(cable->outputModule != module);
  433. assert(cable->inputModule != module);
  434. }
  435. // Update ParamHandles
  436. for (ParamHandle *paramHandle : internal->paramHandles) {
  437. if (paramHandle->moduleId == module->id)
  438. paramHandle->module = NULL;
  439. }
  440. // Update expander pointers
  441. for (Module *m : internal->modules) {
  442. if (m->leftExpander.module == module) {
  443. m->leftExpander.moduleId = -1;
  444. m->leftExpander.module = NULL;
  445. }
  446. if (m->rightExpander.module == module) {
  447. m->rightExpander.moduleId = -1;
  448. m->rightExpander.module = NULL;
  449. }
  450. }
  451. // Trigger Remove event
  452. module->onRemove();
  453. // Remove module
  454. internal->modules.erase(it);
  455. }
  456. Module *Engine::getModule(int moduleId) {
  457. VIPLock vipLock(internal->vipMutex);
  458. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  459. // Find module
  460. for (Module *module : internal->modules) {
  461. if (module->id == moduleId)
  462. return module;
  463. }
  464. return NULL;
  465. }
  466. void Engine::resetModule(Module *module) {
  467. assert(module);
  468. VIPLock vipLock(internal->vipMutex);
  469. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  470. module->onReset();
  471. }
  472. void Engine::randomizeModule(Module *module) {
  473. assert(module);
  474. VIPLock vipLock(internal->vipMutex);
  475. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  476. module->onRandomize();
  477. }
  478. void Engine::bypassModule(Module *module, bool bypass) {
  479. assert(module);
  480. VIPLock vipLock(internal->vipMutex);
  481. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  482. if (bypass) {
  483. for (Output &output : module->outputs) {
  484. // This also zeros all voltages
  485. output.setChannels(0);
  486. }
  487. module->cpuTime = 0.f;
  488. }
  489. else {
  490. // Set all outputs to 1 channel
  491. for (Output &output : module->outputs) {
  492. output.setChannels(1);
  493. }
  494. }
  495. module->bypass = bypass;
  496. }
  497. static void Engine_updateConnected(Engine *that) {
  498. // Set everything to unconnected
  499. for (Module *module : that->internal->modules) {
  500. for (Input &input : module->inputs) {
  501. input.active = false;
  502. }
  503. for (Output &output : module->outputs) {
  504. output.active = false;
  505. }
  506. }
  507. // Set inputs/outputs to active
  508. for (Cable *cable : that->internal->cables) {
  509. cable->outputModule->outputs[cable->outputId].active = true;
  510. cable->inputModule->inputs[cable->inputId].active = true;
  511. }
  512. }
  513. void Engine::addCable(Cable *cable) {
  514. assert(cable);
  515. VIPLock vipLock(internal->vipMutex);
  516. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  517. // Check cable properties
  518. assert(cable->outputModule);
  519. assert(cable->inputModule);
  520. // Check that the cable is not already added, and that the input is not already used by another cable
  521. for (Cable *cable2 : internal->cables) {
  522. assert(cable2 != cable);
  523. assert(!(cable2->inputModule == cable->inputModule && cable2->inputId == cable->inputId));
  524. }
  525. // Set ID
  526. if (cable->id < 0) {
  527. // Automatically assign ID
  528. cable->id = internal->nextCableId++;
  529. }
  530. else {
  531. // Manual ID
  532. // Check that the ID is not already taken
  533. for (Cable *w : internal->cables) {
  534. assert(cable->id != w->id);
  535. }
  536. if (cable->id >= internal->nextCableId) {
  537. internal->nextCableId = cable->id + 1;
  538. }
  539. }
  540. // Add the cable
  541. internal->cables.push_back(cable);
  542. Engine_updateConnected(this);
  543. }
  544. void Engine::removeCable(Cable *cable) {
  545. assert(cable);
  546. VIPLock vipLock(internal->vipMutex);
  547. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  548. // Check that the cable is already added
  549. auto it = std::find(internal->cables.begin(), internal->cables.end(), cable);
  550. assert(it != internal->cables.end());
  551. // Set input to inactive
  552. Input &input = cable->inputModule->inputs[cable->inputId];
  553. input.setChannels(0);
  554. // Remove the cable
  555. internal->cables.erase(it);
  556. Engine_updateConnected(this);
  557. }
  558. void Engine::setParam(Module *module, int paramId, float value) {
  559. // TODO Does this need to be thread-safe?
  560. // If being smoothed, cancel smoothing
  561. if (internal->smoothModule == module && internal->smoothParamId == paramId) {
  562. internal->smoothModule = NULL;
  563. internal->smoothParamId = 0;
  564. }
  565. module->params[paramId].value = value;
  566. }
  567. float Engine::getParam(Module *module, int paramId) {
  568. return module->params[paramId].value;
  569. }
  570. void Engine::setSmoothParam(Module *module, int paramId, float value) {
  571. // If another param is being smoothed, jump value
  572. if (internal->smoothModule && !(internal->smoothModule == module && internal->smoothParamId == paramId)) {
  573. internal->smoothModule->params[internal->smoothParamId].value = internal->smoothValue;
  574. }
  575. internal->smoothParamId = paramId;
  576. internal->smoothValue = value;
  577. // Set this last so the above values are valid as soon as it is set
  578. internal->smoothModule = module;
  579. }
  580. float Engine::getSmoothParam(Module *module, int paramId) {
  581. if (internal->smoothModule == module && internal->smoothParamId == paramId)
  582. return internal->smoothValue;
  583. return getParam(module, paramId);
  584. }
  585. void Engine::addParamHandle(ParamHandle *paramHandle) {
  586. VIPLock vipLock(internal->vipMutex);
  587. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  588. // Check that the ParamHandle is not already added
  589. auto it = std::find(internal->paramHandles.begin(), internal->paramHandles.end(), paramHandle);
  590. assert(it == internal->paramHandles.end());
  591. // New ParamHandles must be blank
  592. assert(paramHandle->moduleId < 0);
  593. internal->paramHandles.push_back(paramHandle);
  594. }
  595. void Engine::removeParamHandle(ParamHandle *paramHandle) {
  596. VIPLock vipLock(internal->vipMutex);
  597. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  598. paramHandle->module = NULL;
  599. // Check that the ParamHandle is already added
  600. auto it = std::find(internal->paramHandles.begin(), internal->paramHandles.end(), paramHandle);
  601. assert(it != internal->paramHandles.end());
  602. internal->paramHandles.erase(it);
  603. }
  604. ParamHandle *Engine::getParamHandle(Module *module, int paramId) {
  605. // VIPLock vipLock(internal->vipMutex);
  606. // std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  607. for (ParamHandle *paramHandle : internal->paramHandles) {
  608. if (paramHandle->module == module && paramHandle->paramId == paramId)
  609. return paramHandle;
  610. }
  611. return NULL;
  612. }
  613. void Engine::updateParamHandle(ParamHandle *paramHandle, int moduleId, int paramId, bool overwrite) {
  614. VIPLock vipLock(internal->vipMutex);
  615. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  616. // Set IDs
  617. paramHandle->moduleId = moduleId;
  618. paramHandle->paramId = paramId;
  619. paramHandle->module = NULL;
  620. auto it = std::find(internal->paramHandles.begin(), internal->paramHandles.end(), paramHandle);
  621. if (it != internal->paramHandles.end() && paramHandle->moduleId >= 0) {
  622. // Remove existing ParamHandles pointing to the same param
  623. for (ParamHandle *p : internal->paramHandles) {
  624. if (p != paramHandle && p->moduleId == moduleId && p->paramId == paramId) {
  625. if (overwrite)
  626. p->reset();
  627. else
  628. paramHandle->reset();
  629. }
  630. }
  631. // Find module with same moduleId
  632. for (Module *module : internal->modules) {
  633. if (module->id == paramHandle->moduleId) {
  634. paramHandle->module = module;
  635. }
  636. }
  637. }
  638. }
  639. void EngineWorker::run() {
  640. system::setThreadName("Engine worker");
  641. system::setThreadRealTime(engine->internal->realTime);
  642. disableDenormals();
  643. while (1) {
  644. engine->internal->engineBarrier.wait();
  645. if (!running)
  646. return;
  647. Engine_stepModules(engine, id);
  648. engine->internal->workerBarrier.wait();
  649. }
  650. }
  651. } // namespace engine
  652. } // namespace rack