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