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.

768 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. // Swap messages of all modules
  250. for (Module *module : that->internal->modules) {
  251. std::swap(module->leftProducerMessage, module->leftConsumerMessage);
  252. std::swap(module->rightProducerMessage, module->rightConsumerMessage);
  253. }
  254. }
  255. static void Engine_updateAdjacent(Engine *that, Module *m) {
  256. // Sync leftModule
  257. if (m->leftModuleId >= 0) {
  258. if (!m->leftModule || m->leftModule->id != m->leftModuleId) {
  259. m->leftModule = that->getModule(m->leftModuleId);
  260. }
  261. }
  262. else {
  263. if (m->leftModule) {
  264. m->leftModule = NULL;
  265. }
  266. }
  267. // Sync rightModule
  268. if (m->rightModuleId >= 0) {
  269. if (!m->rightModule || m->rightModule->id != m->rightModuleId) {
  270. m->rightModule = that->getModule(m->rightModuleId);
  271. }
  272. }
  273. else {
  274. if (m->rightModule) {
  275. m->rightModule = NULL;
  276. }
  277. }
  278. }
  279. static void Engine_relaunchWorkers(Engine *that) {
  280. Engine::Internal *internal = that->internal;
  281. assert(1 <= internal->threadCount);
  282. // Stop all workers
  283. for (EngineWorker &worker : internal->workers) {
  284. worker.stop();
  285. }
  286. internal->engineBarrier.wait();
  287. // Destroy all workers
  288. for (EngineWorker &worker : internal->workers) {
  289. worker.join();
  290. }
  291. internal->workers.resize(0);
  292. // Configure main thread
  293. system::setThreadRealTime(internal->realTime);
  294. // Set barrier counts
  295. internal->engineBarrier.total = internal->threadCount;
  296. internal->workerBarrier.total = internal->threadCount;
  297. // Create workers
  298. internal->workers.resize(internal->threadCount - 1);
  299. for (int id = 1; id < internal->threadCount; id++) {
  300. EngineWorker &worker = internal->workers[id - 1];
  301. worker.id = id;
  302. worker.engine = that;
  303. worker.start();
  304. }
  305. }
  306. static void Engine_run(Engine *that) {
  307. Engine::Internal *internal = that->internal;
  308. // Set up thread
  309. system::setThreadName("Engine");
  310. // system::setThreadRealTime();
  311. disableDenormals();
  312. // Every time the that waits and locks a mutex, it steps this many frames
  313. const int mutexSteps = 128;
  314. // Time in seconds that the that is rushing ahead of the estimated clock time
  315. double aheadTime = 0.0;
  316. auto lastTime = std::chrono::high_resolution_clock::now();
  317. while (internal->running) {
  318. internal->vipMutex.wait();
  319. // Set sample rate
  320. if (internal->sampleRate != settings::sampleRate) {
  321. internal->sampleRate = settings::sampleRate;
  322. internal->sampleTime = 1 / internal->sampleRate;
  323. for (Module *module : internal->modules) {
  324. module->onSampleRateChange();
  325. }
  326. aheadTime = 0.0;
  327. }
  328. // Launch workers
  329. if (internal->threadCount != settings::threadCount || internal->realTime != settings::realTime) {
  330. internal->threadCount = settings::threadCount;
  331. internal->realTime = settings::realTime;
  332. Engine_relaunchWorkers(that);
  333. }
  334. if (!internal->paused) {
  335. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  336. for (Module *module : internal->modules) {
  337. Engine_updateAdjacent(that, module);
  338. }
  339. // Step modules
  340. for (int i = 0; i < mutexSteps; i++) {
  341. Engine_step(that);
  342. }
  343. }
  344. double stepTime = mutexSteps * internal->sampleTime;
  345. aheadTime += stepTime;
  346. auto currTime = std::chrono::high_resolution_clock::now();
  347. const double aheadFactor = 2.0;
  348. aheadTime -= aheadFactor * std::chrono::duration<double>(currTime - lastTime).count();
  349. lastTime = currTime;
  350. aheadTime = std::fmax(aheadTime, 0.0);
  351. // Avoid pegging the CPU at 100% when there are no "blocking" modules like AudioInterface, but still step audio at a reasonable rate
  352. // The number of steps to wait before possibly sleeping
  353. const double aheadMax = 1.0; // seconds
  354. if (aheadTime > aheadMax) {
  355. std::this_thread::sleep_for(std::chrono::duration<double>(stepTime));
  356. }
  357. }
  358. // Stop workers
  359. internal->threadCount = 1;
  360. Engine_relaunchWorkers(that);
  361. }
  362. void Engine::start() {
  363. internal->running = true;
  364. internal->thread = std::thread([&] {
  365. random::init();
  366. Engine_run(this);
  367. });
  368. }
  369. void Engine::stop() {
  370. internal->running = false;
  371. internal->thread.join();
  372. }
  373. void Engine::setPaused(bool paused) {
  374. VIPLock vipLock(internal->vipMutex);
  375. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  376. internal->paused = paused;
  377. }
  378. bool Engine::isPaused() {
  379. // No lock
  380. return internal->paused;
  381. }
  382. float Engine::getSampleRate() {
  383. return internal->sampleRate;
  384. }
  385. float Engine::getSampleTime() {
  386. return internal->sampleTime;
  387. }
  388. void Engine::yieldWorkers() {
  389. internal->workerBarrier.yield = true;
  390. }
  391. void Engine::addModule(Module *module) {
  392. assert(module);
  393. VIPLock vipLock(internal->vipMutex);
  394. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  395. // Check that the module is not already added
  396. auto it = std::find(internal->modules.begin(), internal->modules.end(), module);
  397. assert(it == internal->modules.end());
  398. // Set ID
  399. if (module->id < 0) {
  400. // Automatically assign ID
  401. module->id = internal->nextModuleId++;
  402. }
  403. else {
  404. // Manual ID
  405. // Check that the ID is not already taken
  406. for (Module *m : internal->modules) {
  407. assert(module->id != m->id);
  408. }
  409. if (module->id >= internal->nextModuleId) {
  410. internal->nextModuleId = module->id + 1;
  411. }
  412. }
  413. // Add module
  414. internal->modules.push_back(module);
  415. module->onAdd();
  416. // Update ParamHandles
  417. for (ParamHandle *paramHandle : internal->paramHandles) {
  418. if (paramHandle->moduleId == module->id)
  419. paramHandle->module = module;
  420. }
  421. }
  422. void Engine::removeModule(Module *module) {
  423. assert(module);
  424. VIPLock vipLock(internal->vipMutex);
  425. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  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 adjacent modules
  441. for (Module *m : internal->modules) {
  442. if (m->leftModule == module) {
  443. m->leftModuleId = -1;
  444. m->leftModule = NULL;
  445. }
  446. if (m->rightModule == module) {
  447. m->rightModuleId = -1;
  448. m->rightModule = NULL;
  449. }
  450. }
  451. // Check that the module actually exists
  452. auto it = std::find(internal->modules.begin(), internal->modules.end(), module);
  453. assert(it != internal->modules.end());
  454. // Remove the module
  455. module->onRemove();
  456. internal->modules.erase(it);
  457. }
  458. Module *Engine::getModule(int moduleId) {
  459. VIPLock vipLock(internal->vipMutex);
  460. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  461. // Find module
  462. for (Module *module : internal->modules) {
  463. if (module->id == moduleId)
  464. return module;
  465. }
  466. return NULL;
  467. }
  468. void Engine::resetModule(Module *module) {
  469. assert(module);
  470. VIPLock vipLock(internal->vipMutex);
  471. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  472. module->onReset();
  473. }
  474. void Engine::randomizeModule(Module *module) {
  475. assert(module);
  476. VIPLock vipLock(internal->vipMutex);
  477. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  478. module->onRandomize();
  479. }
  480. void Engine::bypassModule(Module *module, bool bypass) {
  481. assert(module);
  482. VIPLock vipLock(internal->vipMutex);
  483. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  484. if (bypass) {
  485. for (Output &output : module->outputs) {
  486. // This also zeros all voltages
  487. output.setChannels(0);
  488. }
  489. module->cpuTime = 0.f;
  490. }
  491. else {
  492. // Set all outputs to 1 channel
  493. for (Output &output : module->outputs) {
  494. output.setChannels(1);
  495. }
  496. }
  497. module->bypass = bypass;
  498. }
  499. static void Engine_updateConnected(Engine *that) {
  500. // Set everything to unconnected
  501. for (Module *module : that->internal->modules) {
  502. for (Input &input : module->inputs) {
  503. input.active = false;
  504. }
  505. for (Output &output : module->outputs) {
  506. output.active = false;
  507. }
  508. }
  509. // Set inputs/outputs to active
  510. for (Cable *cable : that->internal->cables) {
  511. cable->outputModule->outputs[cable->outputId].active = true;
  512. cable->inputModule->inputs[cable->inputId].active = true;
  513. }
  514. }
  515. void Engine::addCable(Cable *cable) {
  516. assert(cable);
  517. VIPLock vipLock(internal->vipMutex);
  518. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  519. // Check cable properties
  520. assert(cable->outputModule);
  521. assert(cable->inputModule);
  522. // Check that the cable is not already added, and that the input is not already used by another cable
  523. for (Cable *cable2 : internal->cables) {
  524. assert(cable2 != cable);
  525. assert(!(cable2->inputModule == cable->inputModule && cable2->inputId == cable->inputId));
  526. }
  527. // Set ID
  528. if (cable->id < 0) {
  529. // Automatically assign ID
  530. cable->id = internal->nextCableId++;
  531. }
  532. else {
  533. // Manual ID
  534. // Check that the ID is not already taken
  535. for (Cable *w : internal->cables) {
  536. assert(cable->id != w->id);
  537. }
  538. if (cable->id >= internal->nextCableId) {
  539. internal->nextCableId = cable->id + 1;
  540. }
  541. }
  542. // Add the cable
  543. internal->cables.push_back(cable);
  544. Engine_updateConnected(this);
  545. }
  546. void Engine::removeCable(Cable *cable) {
  547. assert(cable);
  548. VIPLock vipLock(internal->vipMutex);
  549. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  550. // Check that the cable is already added
  551. auto it = std::find(internal->cables.begin(), internal->cables.end(), cable);
  552. assert(it != internal->cables.end());
  553. // Set input to inactive
  554. Input &input = cable->inputModule->inputs[cable->inputId];
  555. input.setChannels(0);
  556. // Remove the cable
  557. internal->cables.erase(it);
  558. Engine_updateConnected(this);
  559. }
  560. void Engine::setParam(Module *module, int paramId, float value) {
  561. // TODO Does this need to be thread-safe?
  562. // If being smoothed, cancel smoothing
  563. if (internal->smoothModule == module && internal->smoothParamId == paramId) {
  564. internal->smoothModule = NULL;
  565. internal->smoothParamId = 0;
  566. }
  567. module->params[paramId].value = value;
  568. }
  569. float Engine::getParam(Module *module, int paramId) {
  570. return module->params[paramId].value;
  571. }
  572. void Engine::setSmoothParam(Module *module, int paramId, float value) {
  573. // If another param is being smoothed, jump value
  574. if (internal->smoothModule && !(internal->smoothModule == module && internal->smoothParamId == paramId)) {
  575. internal->smoothModule->params[internal->smoothParamId].value = internal->smoothValue;
  576. }
  577. internal->smoothParamId = paramId;
  578. internal->smoothValue = value;
  579. // Set this last so the above values are valid as soon as it is set
  580. internal->smoothModule = module;
  581. }
  582. float Engine::getSmoothParam(Module *module, int paramId) {
  583. if (internal->smoothModule == module && internal->smoothParamId == paramId)
  584. return internal->smoothValue;
  585. return getParam(module, paramId);
  586. }
  587. void Engine::addParamHandle(ParamHandle *paramHandle) {
  588. VIPLock vipLock(internal->vipMutex);
  589. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  590. // Check that the ParamHandle is not already added
  591. auto it = std::find(internal->paramHandles.begin(), internal->paramHandles.end(), paramHandle);
  592. assert(it == internal->paramHandles.end());
  593. // New ParamHandles must be blank
  594. assert(paramHandle->moduleId < 0);
  595. internal->paramHandles.push_back(paramHandle);
  596. }
  597. void Engine::removeParamHandle(ParamHandle *paramHandle) {
  598. VIPLock vipLock(internal->vipMutex);
  599. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  600. paramHandle->module = NULL;
  601. // Check that the ParamHandle is already added
  602. auto it = std::find(internal->paramHandles.begin(), internal->paramHandles.end(), paramHandle);
  603. assert(it != internal->paramHandles.end());
  604. internal->paramHandles.erase(it);
  605. }
  606. ParamHandle *Engine::getParamHandle(Module *module, int paramId) {
  607. // VIPLock vipLock(internal->vipMutex);
  608. // std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  609. for (ParamHandle *paramHandle : internal->paramHandles) {
  610. if (paramHandle->module == module && paramHandle->paramId == paramId)
  611. return paramHandle;
  612. }
  613. return NULL;
  614. }
  615. void Engine::updateParamHandle(ParamHandle *paramHandle, int moduleId, int paramId, bool overwrite) {
  616. VIPLock vipLock(internal->vipMutex);
  617. std::lock_guard<std::recursive_mutex> lock(internal->mutex);
  618. // Set IDs
  619. paramHandle->moduleId = moduleId;
  620. paramHandle->paramId = paramId;
  621. paramHandle->module = NULL;
  622. auto it = std::find(internal->paramHandles.begin(), internal->paramHandles.end(), paramHandle);
  623. if (it != internal->paramHandles.end() && paramHandle->moduleId >= 0) {
  624. // Remove existing ParamHandles pointing to the same param
  625. for (ParamHandle *p : internal->paramHandles) {
  626. if (p != paramHandle && p->moduleId == moduleId && p->paramId == paramId) {
  627. if (overwrite)
  628. p->reset();
  629. else
  630. paramHandle->reset();
  631. }
  632. }
  633. // Find module with same moduleId
  634. for (Module *module : internal->modules) {
  635. if (module->id == paramHandle->moduleId) {
  636. paramHandle->module = module;
  637. }
  638. }
  639. }
  640. }
  641. void EngineWorker::run() {
  642. system::setThreadName("Engine worker");
  643. system::setThreadRealTime(engine->internal->realTime);
  644. disableDenormals();
  645. while (1) {
  646. engine->internal->engineBarrier.wait();
  647. if (!running)
  648. return;
  649. Engine_stepModules(engine, id);
  650. engine->internal->workerBarrier.wait();
  651. }
  652. }
  653. } // namespace engine
  654. } // namespace rack