-
Notifications
You must be signed in to change notification settings - Fork 7
/
extras.h
682 lines (595 loc) · 22.8 KB
/
extras.h
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
/*
This C++ layer on top of the audio-engine defines the
notion of instruments and uses locks to protect concurrent accesses to
instruments containers. These locks are acquired
according to the same global order, everywhere in the code, so as to
ensure that no deadlock will ever occur.
These locks are not taken by the audio realtime thread,
which remains lock-free unless IMJ_AUDIO_MASTERGLOBALLOCK is used.
*/
#include "compiler.prepro.h"
#include "cpp.audio/include/public.h"
#ifdef __cplusplus
namespace imajuscule::audio {
namespace audioelement {
using AudioFloat = double;
// in sync with the corresponding Haskel Enum instance
enum class OscillatorType {
Sweep = -2,
Noise = -1,
// values >= 0 are in sync with the corresponding Haskell enum
SinusLoudnessVolumeAdjusted,
Sinus,
Saw,
Square,
Triangle
};
std::ostream & operator << (std::ostream &, OscillatorType);
template<template<OscillatorType> typename F>
void foreachOscillatorType() {
F<OscillatorType::SinusLoudnessVolumeAdjusted>{}();
F<OscillatorType::Sinus>{}();
F<OscillatorType::Saw>{}();
F<OscillatorType::Square>{}();
F<OscillatorType::Triangle>{}();
F<OscillatorType::Noise>{}();
F<OscillatorType::Sweep>{}();
}
template<OscillatorType o>
struct ToFOsc;
template <>
struct ToFOsc<OscillatorType::Saw> {
static constexpr auto convert = FOscillator::SAW;
};
template <>
struct ToFOsc<OscillatorType::Square> {
static constexpr auto convert = FOscillator::SQUARE;
};
template <>
struct ToFOsc<OscillatorType::Triangle> {
static constexpr auto convert = FOscillator::TRIANGLE;
};
template <>
struct ToFOsc<OscillatorType::Sinus> {
// never used
static constexpr auto convert = FOscillator::SAW;
};
template <>
struct ToFOsc<OscillatorType::SinusLoudnessVolumeAdjusted> {
// never used
static constexpr auto convert = FOscillator::SAW;
};
template <>
struct ToFOsc<OscillatorType::Noise> {
// never used
static constexpr auto convert = FOscillator::SAW;
};
template <>
struct ToFOsc<OscillatorType::Sweep> {
// never used
static constexpr auto convert = FOscillator::SAW;
};
template<OscillatorType O, typename FPT>
struct GenericOscillator {
using type =
std::conditional_t<
O == OscillatorType::SinusLoudnessVolumeAdjusted,
LoudnessVolumeAdjusted< SineOscillatorAlgo< FPT, eNormalizePolicy::FAST > >,
std::conditional_t<
O == OscillatorType::Sinus,
SineOscillatorAlgo< FPT, eNormalizePolicy::FAST >,
std::conditional_t<
O == OscillatorType::Noise,
PinkNoiseAlgo,
std::conditional_t<
O == OscillatorType::Sweep,
FreqSingleRampAlgo< FPT >,
FOscillatorAlgo< FPT, ToFOsc<O>::convert, OscillatorUsage::Raw >
>
>
>
>;
};
template<OscillatorType O, typename FPT>
using genericOscillator = typename GenericOscillator<O, FPT>::type;
template<OscillatorType O, typename Env>
struct AudioElementOf {
using type =
StereoPanned<
VolumeAdjusted<
MultiEnveloped<
genericOscillator<O, typename Env::FPT>
, Env
>
>
>;
};
template<OscillatorType O, typename Env>
using audioElementOf = typename AudioElementOf<O, Env>::type;
struct SweepSetup {
int durationSamples;
float freq;
Extremity freq_extremity;
itp::interpolation interp;
bool operator ==(SweepSetup const & o) const {
if (durationSamples != o.durationSamples) {
return false;
}
if (freq != o.freq) {
return false;
}
if (freq_extremity != o.freq_extremity) {
return false;
}
if (interp != o.interp) {
return false;
}
return true;
}
bool operator != (SweepSetup const & o) const {
return !this->operator ==(o);
}
std::size_t combine_hash(std::size_t h) const {
hash_combine(h, durationSamples);
hash_combine(h, freq);
hash_combine(h, freq_extremity);
hash_combine(h, interp);
return h;
}
};
template<OscillatorType Osc>
struct ExtraParams {
std::size_t combine_hash(std::size_t h) const { return h; }
};
template<>
struct ExtraParams<OscillatorType::Sweep> {
SweepSetup const & sweep;
std::size_t combine_hash(std::size_t h) const {
return sweep.combine_hash(h);
}
};
template<OscillatorType Osc>
struct ExtraParamsSummary {
ExtraParamsSummary(ExtraParams<Osc> const &)
{}
bool operator != (ExtraParamsSummary const & o) const {
return !this->operator ==(o);
}
bool operator == (ExtraParamsSummary const & o) const { return true; }
};
template<>
struct ExtraParamsSummary<OscillatorType::Sweep> {
ExtraParamsSummary(ExtraParams<OscillatorType::Sweep> const & p)
: sweep(p.sweep)
{}
bool operator != (ExtraParamsSummary const & o) const {
return !this->operator ==(o);
}
bool operator == (ExtraParamsSummary const & o) const {
if (sweep != o.sweep) {
return false;
}
return true;
}
private:
SweepSetup const sweep;
};
template<typename EnvelParamT, typename HarmonicsArray, OscillatorType Osc>
struct ParamsFor {
HarmonicsArray const & har;
EnvelParamT const & env;
ExtraParams<Osc> params;
std::size_t hash() const {
std::size_t h = audioelement::hashHarmonics(har);
return params.combine_hash(env.combine_hash(h));
}
};
// 'ParamsSummary' is a lightweight version of 'ParamsFor':
// - If in 'ParamsFor' we have a reference, in 'ParamsSummary' we have the object
// - If in 'ParamsFor' we have a dynamically allocated object, in 'ParamsSummary' we have the hash of this object
// - and we have a global hash
template<typename EnvelParamT, audioelement::OscillatorType Osc>
struct ParamsSummary {
template<typename Har>
ParamsSummary(ParamsFor<EnvelParamT, Har, Osc> const & p)
: hash_harmonics(audioelement::hashHarmonics(p.har))
, env(p.env)
, params_summary(p.params) {
hash = p.params.combine_hash(env.combine_hash(hash_harmonics));
}
bool operator == (ParamsSummary const & o) const {
if (hash != o.hash) {
return false;
}
if (hash_harmonics != o.hash_harmonics) {
return false;
}
if (env != o.env) {
return false;
}
if (params_summary != o.params_summary) {
return false;
}
return true;
}
std::size_t getHash() const { return hash; }
private:
// for equality test:
std::size_t const hash_harmonics;
EnvelParamT const env;
ExtraParamsSummary<Osc> const params_summary;
// global hash
std::size_t hash;
};
template<typename EnvelParamT, OscillatorType Osc>
struct SetParam {
template<typename HarmonicsArray, typename B>
static void set(int sample_rate, ParamsFor<EnvelParamT, HarmonicsArray, Osc> const & p, B & b) {
b.forEachElem([&p, sample_rate](auto & e) {
// the order is important, maybe we need a single method.
e.elem.getOsc().getOsc().setHarmonics(p.har, sample_rate);
e.elem.editEnvelope().setAHDSR(p.env, sample_rate);
});
}
};
template<typename EnvelParamT>
struct SetParam<EnvelParamT, OscillatorType::Sweep> {
template<typename HarmonicsArray, typename B>
static void set(int sample_rate, ParamsFor<EnvelParamT, HarmonicsArray, OscillatorType::Sweep> const & p, B & b) {
b.forEachElem([&p, sample_rate](auto & e) {
// the order is important, maybe we need a single method.
e.elem.getOsc().getOsc().setHarmonics(p.har, sample_rate);
e.elem.editEnvelope().setAHDSR(p.env, sample_rate);
// Side note : for a sweep, MultiEnveloped is overkill because there is a single harmonic.
e.elem.getOsc().getOsc().forEachHarmonic([&p, sample_rate](auto & h) {
h.getAlgo().getCtrl().setup(p.params.sweep.freq_extremity,
freq_to_angle_increment(p.params.sweep.freq, sample_rate),
p.params.sweep.durationSamples,
p.params.sweep.interp);
});
});
}
};
template<typename Env>
std::pair<std::vector<double>, int>
envelopeGraphVec(int sample_rate, typename Env::Param const & envParams) {
Env e;
e.setAHDSR(envParams, sample_rate);
// emulate a key-press
e.onKeyPressed(0);
int splitAt = -1;
std::vector<double> v;
v.reserve(10000);
for(int i=0; e.getRelaxedState() != EnvelopeState::EnvelopeDone1; ++i) {
e.step();
v.push_back(e.value());
if(!e.afterAttackBeforeSustain()) {
splitAt = v.size();
if constexpr (Env::Release == EnvelopeRelease::WaitForKeyRelease) {
// emulate a key-release
e.onKeyReleased(0);
}
break;
}
}
while(e.getRelaxedState() != EnvelopeState::EnvelopeDone1) {
e.step();
v.push_back(e.value());
}
return {std::move(v),splitAt};
}
}
#ifdef IMJ_AUDIO_MASTERGLOBALLOCK
#pragma message "IMJ_AUDIO_MASTERGLOBALLOCK mode is not recommended, it will lead to audio glitches under contention."
static constexpr auto audioEnginePolicy = AudioOutPolicy::MasterGlobalLock;
#else
// This lockfree mode is recommended, it reduces the likelyhood of audio glitches.
static constexpr auto audioEnginePolicy = AudioOutPolicy::MasterLockFree;
#endif
static constexpr int nAudioOut = 2;
using Stepper = SimpleAudioOutContext<
nAudioOut,
audioEnginePolicy
>;
Stepper & getStepper();
using Ctxt = Context<
AudioPlatform::PortAudio,
Features::JustOut
>;
Ctxt & getAudioContext();
using Reverb = ReverbPost<ReverbType::Realtime_Synchronous, nAudioOut, nAudioOut>;
Reverb & getReverb();
Limiter<double> & getLimiter();
constexpr SynchronizePhase syncPhase(audioelement::OscillatorType o){
using audioelement::OscillatorType;
switch(o) {
case OscillatorType::Saw:
case OscillatorType::Square:
case OscillatorType::Triangle:
case OscillatorType::Sinus:
case OscillatorType::SinusLoudnessVolumeAdjusted:
return SynchronizePhase::Yes;
case OscillatorType::Noise:
case OscillatorType::Sweep:
return SynchronizePhase::No;
}
}
constexpr DefaultStartPhase defaultStartPhase(audioelement::OscillatorType o){
using audioelement::OscillatorType;
switch(o) {
case OscillatorType::Saw:
case OscillatorType::Square:
case OscillatorType::Triangle:
case OscillatorType::Sinus:
case OscillatorType::SinusLoudnessVolumeAdjusted:
return DefaultStartPhase::Random;
case OscillatorType::Noise:
case OscillatorType::Sweep:
return DefaultStartPhase::Zero;
}
}
// TODO like in ResynthElementInitializer, we should handle more aspects here
// instead of hardcoding them per synth.
struct ElementInitializer {
ElementInitializer(float const stereo)
: m_stereo(stereo)
{}
template<typename Elt>
void operator()(Elt & e) const {
// panning (except for note changes)
//if (t==InitializationType::NewNote) {
e.setStereoGain(stereo(m_stereo));
//}
}
bool operator ==(ElementInitializer const& o) const {
return
std::make_tuple(m_stereo) ==
std::make_tuple(o.m_stereo);
}
bool operator !=(ElementInitializer const& o) const {
return !this->operator ==(o);
}
private:
float m_stereo; // -1 (left) 1 (right)
};
template <typename Env, audioelement::OscillatorType Osc>
using synthOf = sine::Synth < // the name of the namespace is misleading : it can handle all kinds of oscillators
nAudioOut
, audioelement::audioElementOf<Osc, Env>
, syncPhase(Osc)
, defaultStartPhase(Osc)
, HandleNoteOff::Yes
, 32 // maybe 32 voices is not enough?
, ElementInitializer
>;
template<typename T>
struct withChannels {
withChannels()
: gen(150) // max number of simultaneously played pitches on a single synth
{}
~withChannels() {
std::lock_guard<std::mutex> l(isUsed); // see 'Using'
}
auto onEvent(int const sample_rate, Event e, Optional<MIDITimestampAndSource> const & maybeMts) {
return obj.onEvent(sample_rate,
e,
getStepper(),
getStepper(),
maybeMts);
}
void convertNoteId(int voice, Event & e) {
return convertKeyToNoteId(gen, voice, e);
}
T obj;
std::mutex isUsed;
private:
NoteIdsGenerator gen;
};
// a 'Using' instance gives the guarantee that the object 'o' passed to its constructor
// won't be destroyed during the entire lifetime of the instance, iff the following conditions hold:
// (1) 'protectsDestruction' passed to the constructor is currently locked
// (2) T::~T() locks, then unlocks 'o.isUsed', so that 'o' cannot be destroyed
// until 'protectsDestruction' is unlocked
template<typename T>
struct Using {
T & o; // this reference makes the object move-only, which is what we want
Using(std::lock_guard<std::mutex> && protectsDestruction, T&o) : o(o) {
o.isUsed.lock();
// NOTE here, both the instrument lock (isUsed) and the 'protectsDestruction' lock
// are taken.
//
// The order in which we take the locks is important to avoid deadlocks:
// it is OK to take multiple locks at the same time, /only/ if, everywhere in the program,
// we take them respecting a global order on the locks of the program.
//
// Hence, here the global order is:
// map lock (protectsDestruction) -> instrument lock (isUsed)
}
~Using() {
o.isUsed.unlock();
}
};
struct tryScopedLock {
tryScopedLock(std::mutex&m) : m(m) {
success = m.try_lock();
}
operator bool () const {
return success;
}
~tryScopedLock() {
if(success) {
m.unlock();
}
}
private:
std::mutex & m;
bool success;
};
template<typename T>
struct Hash {
std::size_t operator ()(T const & p) const {
return p.getHash();
}
};
template <typename Envel, audioelement::OscillatorType Osc>
struct Synths {
using T = synthOf<Envel, Osc>;
using EnvelParamT = typename Envel::Param;
template<typename HarmonicsArray>
using Params = audioelement::ParamsFor<EnvelParamT, HarmonicsArray, Osc>;
// used as key in a map
using StaticParamsSummary = audioelement::ParamsSummary<EnvelParamT, Osc>;
// NOTE the 'Using' is constructed while we hold the lock to the map.
// Hence, while garbage collecting / recycling, if we take the map lock,
// and if the instrument lock is not taken, we have the guarantee that
// the instrument lock won't be taken until we release the map lock.
template<typename HarmonicsArray>
static Using<withChannels<T>> get(int sample_rate, Params<HarmonicsArray> const ¶ms) {
using namespace audioelement;
StaticParamsSummary summary(params);
// we use a global lock because we can concurrently modify and lookup the map.
std::lock_guard<std::mutex> l(map_mutex());
auto & synths = map();
auto it = synths.find(summary);
if(it != synths.end()) {
return Using(std::move(l), *(it->second));
}
if(auto * p = recycleInstrument(sample_rate, synths, params, summary)) {
return Using(std::move(l), *p);
}
auto p = std::make_unique<withChannels<T>>();
SetParam<EnvelParamT, Osc>::set(sample_rate, params, p->obj);
if(!p->obj.initialize(getStepper())) {
auto oneSynth = synths.begin();
if(oneSynth != synths.end()) {
LG(ERR, "a preexisting synth is returned");
return Using(std::move(l), *(oneSynth->second.get()));
}
LG(ERR, "an uninitialized synth is returned");
}
return Using(
std::move(l)
, *(synths.emplace(summary, std::move(p)).first->second));
}
static void finalize() {
std::lock_guard<std::mutex> l(map_mutex());
for(auto & s : map()) {
s.second->obj.finalize(getStepper());
}
map().clear();
}
private:
using Map = std::unordered_map<
StaticParamsSummary,
std::unique_ptr<withChannels<T>>,
Hash<StaticParamsSummary>>;
static auto & map() {
static Map m;
return m;
}
static auto & map_mutex() {
static std::mutex m;
return m;
}
/* The caller is expected to take the map mutex. */
template<typename HarmonicsArray>
static withChannels<T> * recycleInstrument(int const sample_rate, Map & synths, Params<HarmonicsArray> const & params, StaticParamsSummary const summary) {
for(auto it = synths.begin(), end = synths.end(); it != end; ++it) {
auto & i = it->second;
if(!i) {
LG(ERR,"inconsistent map");
continue;
}
auto & o = *i;
if(auto scoped = tryScopedLock(o.isUsed)) {
if(!o.obj.allEnvelopesFinished()) {
continue;
}
// All enveloppes are finished, and the map mutex has been taken
// so no note is being started
/*
auto node = synths.extract(it);
node.key() = envelParam;
auto [inserted, isNew] = synths.insert(std::move(node));
*/
// the code above uses C++17 features not present in clang yet, it is
// replaced by the code below.
std::unique_ptr<withChannels<T>> new_p;
new_p.swap(it->second);
synths.erase(it);
auto [inserted, isNew] = synths.emplace(summary, std::move(new_p));
Assert(isNew); // because prior to calling this function, we did a lookup
using namespace audioelement;
SetParam<EnvelParamT, Osc>::set(sample_rate, params, inserted->second->obj);
return inserted->second.get();
}
else {
// a note is being started or stopped, we can't recycle this instrument.
}
}
return nullptr;
}
};
template<audioelement::OscillatorType O>
struct FinalizeSynths {
void operator ()() {
using namespace audioelement;
static constexpr auto A = getAtomicity<audioEnginePolicy>();
Synths<AHDSREnvelope<A, AudioFloat, EnvelopeRelease::WaitForKeyRelease>, O>::finalize();
Synths<AHDSREnvelope<A, AudioFloat, EnvelopeRelease::ReleaseAfterDecay>, O>::finalize();
}
};
template<typename Env, audioelement::OscillatorType Osc, typename HarmonicsArray, typename... Args>
onEventResult midiEvent(int voice, float stereo, HarmonicsArray const & harmonics, typename Env::Param const & env, Event e, Optional<MIDITimestampAndSource> maybeMts, Args... args) {
audioelement::ParamsFor<typename Env::Param, HarmonicsArray, Osc> params{harmonics, env, std::forward<Args>(args)...};
std::optional<int> sr = getAudioContext().getSampleRate();
auto using_synth = Synths<Env, Osc>::get(*sr, params);
using_synth.o.obj.setSynchronousElementInitializer({stereo}); // ok because we own the lock in using_synth
// note id in 'e' is the pitch. we need to convert it:
using_synth.o.convertNoteId(voice, e);
return using_synth.o.onEvent(*sr, e, maybeMts);
}
template<typename Env, typename HarmonicsArray>
onEventResult midiEvent_(int voice, float stereo, audioelement::OscillatorType osc, HarmonicsArray const & harmonics, typename Env::Param const & p, Event n, Optional<MIDITimestampAndSource> maybeMts) {
using namespace audioelement;
switch(osc) {
case OscillatorType::Saw:
return midiEvent<Env, OscillatorType::Saw, HarmonicsArray>(voice, stereo, harmonics, p, n, maybeMts);
case OscillatorType::Square:
return midiEvent<Env, OscillatorType::Square, HarmonicsArray>(voice, stereo, harmonics, p, n, maybeMts);
case OscillatorType::Triangle:
return midiEvent<Env, OscillatorType::Triangle, HarmonicsArray>(voice, stereo, harmonics, p, n, maybeMts);
case OscillatorType::Sinus:
return midiEvent<Env, OscillatorType::Sinus, HarmonicsArray>(voice, stereo, harmonics, p, n, maybeMts);
case OscillatorType::SinusLoudnessVolumeAdjusted:
return midiEvent<Env, OscillatorType::SinusLoudnessVolumeAdjusted, HarmonicsArray>(voice, stereo, harmonics, p, n, maybeMts);
case OscillatorType::Noise:
return midiEvent<Env, OscillatorType::Noise, HarmonicsArray>(voice, stereo, harmonics, p, n, maybeMts);
default:
std::cerr << "not a standard oscillator" << std::endl;
throw(std::runtime_error("not a standard oscillator"));
}
}
template<typename Env, typename HarmonicsArray>
onEventResult midiEventSweep_(int voice, float stereo,
audioelement::OscillatorType osc,
HarmonicsArray const & harmonics,
typename Env::Param const & p,
audioelement::SweepSetup const & sweep,
Event n,
Optional<MIDITimestampAndSource> maybeMts) {
using namespace audioelement;
switch(osc) {
case OscillatorType::Sweep:
return midiEvent<Env, OscillatorType::Sweep, HarmonicsArray>(voice, stereo, harmonics, p, n, maybeMts, sweep);
default:
std::cerr << "not a sweep oscillator" << std::endl;
throw(std::runtime_error("not a sweep oscillator"));
}
}
using VoiceWindImpl = Voice<audioEnginePolicy, nAudioOut, audioelement::SoundEngineMode::WIND, HandleNoteOff::Yes>;
std::mutex & windVoiceMutex();
VoiceWindImpl & windVoice();
NoteIdsGenerator & windVoiceNoteIdsGen();
} // NS imajuscule::audio
#endif