-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOsc.h
More file actions
1498 lines (1352 loc) · 53 KB
/
Osc.h
File metadata and controls
1498 lines (1352 loc) · 53 KB
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
/*
* Osc.h
*
* A waveTable oscillator class. Contains generators for common wavetables.
*
* by Andrew R. Brown 2021
*
* Based on the Mozzi audio library by Tim Barrass 2012
*
* This file is part of the M16 audio library. Relies on M16.h
*
* M16 is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
*/
#ifndef OSC_H_
#define OSC_H_
class Osc {
public:
// ============== Dual-core phase synchronization (RP2040) ==============
#if IS_RP2040()
static constexpr int MAX_REGISTERED_OSCS = 32;
static Osc* registeredOscs[MAX_REGISTERED_OSCS];
static int numRegisteredOscs;
// Per-core phase storage for synchronized dual-core operation
uint32_t storedPhase[2] = {0, 0};
bool useStoredPhase[2] = {false, false}; // Per-core flag to prevent race conditions
/** Register this oscillator for dual-core phase sync */
void registerForDualCore() {
if (numRegisteredOscs < MAX_REGISTERED_OSCS) {
// Check if already registered
for (int i = 0; i < numRegisteredOscs; i++) {
if (registeredOscs[i] == this) return;
}
registeredOscs[numRegisteredOscs++] = this;
}
}
/** Advance phases for all registered oscillators (call under mutex) */
static void advanceAllPhases(int coreNum) {
for (int i = 0; i < numRegisteredOscs; i++) {
Osc* osc = registeredOscs[i];
if (osc) {
// Store current phase for this core, then advance
osc->storedPhase[coreNum] = osc->phase_fractional;
osc->phase_fractional += osc->phase_increment_fractional;
osc->useStoredPhase[coreNum] = true; // Only set flag for this core
}
}
}
/** Mark this core's oscillators as done with stored phase */
static void clearStoredPhaseFlag(int coreNum) {
for (int i = 0; i < numRegisteredOscs; i++) {
if (registeredOscs[i]) {
registeredOscs[i]->useStoredPhase[coreNum] = false; // Only clear this core's flag
}
}
}
#endif
// ========================================================================
/** Constructor.
* Has no table specified - make sure to use setTable() after initialising
*/
Osc() {
#if IS_RP2040()
registerForDualCore();
#endif
}
/** Updates the phase according to the current frequency and returns the sample at the new phase position.
* @return outSamp The next sample.
*/
inline
int16_t next() {
int32_t sampVal;
// Fast path: atomic phase increment for thread-safe dual-core operation
#if IS_RP2040()
// Pico dual-core: use pre-acquired phase if available (set by advanceAllPhases)
if (isDualCore && !pulseWidthOn) {
int coreNum = get_core_num();
// Check this core's flag - prevents race where other core clears our flag
if (useStoredPhase[coreNum]) {
int16_t* cachedBandPtr = (int16_t*)__atomic_load_n((uintptr_t*)&bandPtr, __ATOMIC_RELAXED);
if (cachedBandPtr == nullptr) return 0;
// Use the phase that was stored for this core (already advanced under mutex)
uint32_t myPhase = storedPhase[coreNum];
int idx;
if (isNoise && !isCrackle) {
uint32_t scrambled = myPhase * 2654435761u;
idx = (scrambled >> 16) & (TABLE_SIZE - 1);
} else {
idx = (myPhase >> 16) & (TABLE_SIZE - 1);
}
sampVal = cachedBandPtr[idx];
if (spreadActive) {
sampVal = doSpreadAtomic(sampVal);
}
return sampVal;
}
}
#endif
#if IS_ESP32() || IS_RP2040()
if (!pulseWidthOn && !isNoise && !isCrackle) {
// Cache volatile values atomically to prevent torn reads during setFreq()
uint32_t cachedIncrement = __atomic_load_n(&phase_increment_fractional, __ATOMIC_RELAXED);
int16_t* cachedBandPtr = (int16_t*)__atomic_load_n((uintptr_t*)&bandPtr, __ATOMIC_RELAXED);
// Safety check: if bandPtr is null or increment is zero, return silence
if (cachedBandPtr == nullptr || cachedIncrement == 0) {
return 0;
}
// Atomic fetch-and-add: each core gets a unique phase value
uint32_t myPhase = __atomic_fetch_add(&phase_fractional, cachedIncrement, __ATOMIC_RELAXED);
int idx = (myPhase >> 16) & (TABLE_SIZE - 1);
sampVal = cachedBandPtr[idx];
if (spreadActive) {
sampVal = doSpreadAtomic(sampVal);
}
return sampVal;
}
// Atomic path for noise and crackle oscillators
if ((isNoise || isCrackle) && !pulseWidthOn) {
uint32_t cachedIncrement = __atomic_load_n(&phase_increment_fractional, __ATOMIC_RELAXED);
int16_t* cachedBandPtr = (int16_t*)__atomic_load_n((uintptr_t*)&bandPtr, __ATOMIC_RELAXED);
if (cachedBandPtr == nullptr || cachedIncrement == 0) return 0;
uint32_t myPhase = __atomic_fetch_add(&phase_fractional, cachedIncrement, __ATOMIC_RELAXED);
int idx;
if (isCrackle) {
// Crackle: normal index, sparse impulses in table
idx = (myPhase >> 16) & (TABLE_SIZE - 1);
} else {
// Noise: scramble phase via multiplicative hash to avoid periodicity
// Replaces the non-atomic random-jump-on-wrap with a deterministic scatter
// that maps sequential phases to pseudo-random table positions
uint32_t scrambled = myPhase * 2654435761u; // Knuth multiplicative hash
idx = (scrambled >> 16) & (TABLE_SIZE - 1);
}
sampVal = cachedBandPtr[idx];
if (spreadActive) {
sampVal = doSpreadAtomic(sampVal);
}
return sampVal;
}
#endif
// Non-atomic fallback for pulse width mode (or single-core platforms)
int idx = phase_fractional >> 16;
sampVal = bandPtr[idx];
incrementPhase();
if (spreadActive) {
sampVal = doSpread(sampVal);
}
return sampVal;
}
/** Updates the phase and returns the next sample with interpolation.
* Uses cubic interpolation for high band (>831Hz), linear for mid band (>208Hz),
* smoothing for low band. Thresholds match band selection in setFreq().
* Higher quality than next() at ~5-15% more CPU cost.
* @return sampVal The next sample.
*/
inline
int16_t next2() {
int32_t sampVal;
uint32_t myPhase;
int idx;
// Fast path: atomic phase increment for thread-safe dual-core operation
#if IS_ESP32() || IS_RP2040()
if (!pulseWidthOn && !isNoise && !isCrackle) {
// Cache volatile values atomically to prevent torn reads during setFreq()
uint32_t cachedIncrement = __atomic_load_n(&phase_increment_fractional, __ATOMIC_RELAXED);
int16_t* cachedBandPtr = (int16_t*)__atomic_load_n((uintptr_t*)&bandPtr, __ATOMIC_RELAXED);
float cachedFreq = frequency; // Used for band selection decision
// Safety check: if bandPtr is null or increment is zero, return silence
if (cachedBandPtr == nullptr || cachedIncrement == 0) {
return 0;
}
// Atomic fetch-and-add: each core gets a unique phase value
myPhase = __atomic_fetch_add(&phase_fractional, cachedIncrement, __ATOMIC_RELAXED);
idx = (myPhase >> 16) & (TABLE_SIZE - 1);
if (cachedFreq > 831.0f) {
// Cubic interpolation for high frequencies (4-point Hermite)
float t = (float)(myPhase & 0xFFFF) * (1.0f / 65536.0f);
float t2 = t * t;
float t3 = t2 * t;
int16_t sm1 = cachedBandPtr[(idx - 1) & (TABLE_SIZE - 1)];
int16_t s0 = cachedBandPtr[idx];
int16_t s1 = cachedBandPtr[(idx + 1) & (TABLE_SIZE - 1)];
int16_t s2 = cachedBandPtr[(idx + 2) & (TABLE_SIZE - 1)];
float a0 = -0.5f * sm1 + 1.5f * s0 - 1.5f * s1 + 0.5f * s2;
float a1 = sm1 - 2.5f * s0 + 2.0f * s1 - 0.5f * s2;
float a2 = -0.5f * sm1 + 0.5f * s1;
float a3 = s0;
sampVal = (int32_t)(a0 * t3 + a1 * t2 + a2 * t + a3);
if (sampVal > MAX_16) sampVal = MAX_16;
else if (sampVal < MIN_16) sampVal = MIN_16;
} else if (cachedFreq > 208.0f) {
// Linear interpolation for mid frequencies
int frac = (myPhase >> 6) & 0x3FF;
int16_t s0 = cachedBandPtr[idx];
int16_t s1 = cachedBandPtr[(idx + 1) & (TABLE_SIZE - 1)];
sampVal = s0 + (((s1 - s0) * frac) >> 10);
} else {
// Low-frequency: direct lookup (smoothing handled at output stage)
sampVal = cachedBandPtr[idx];
}
if (spreadActive) {
sampVal = doSpreadAtomic(sampVal);
}
return sampVal;
}
#endif
// Non-atomic path for pulse width, noise, crackle modes (or single-core platforms)
idx = (phase_fractional >> 16) & (TABLE_SIZE - 1);
if (frequency > 831.0f) {
float t = (float)(phase_fractional & 0xFFFF) * (1.0f / 65536.0f);
float t2 = t * t;
float t3 = t2 * t;
int16_t sm1 = bandPtr[(idx - 1) & (TABLE_SIZE - 1)];
int16_t s0 = bandPtr[idx];
int16_t s1 = bandPtr[(idx + 1) & (TABLE_SIZE - 1)];
int16_t s2 = bandPtr[(idx + 2) & (TABLE_SIZE - 1)];
float a0 = -0.5f * sm1 + 1.5f * s0 - 1.5f * s1 + 0.5f * s2;
float a1 = sm1 - 2.5f * s0 + 2.0f * s1 - 0.5f * s2;
float a2 = -0.5f * sm1 + 0.5f * s1;
float a3 = s0;
sampVal = (int32_t)(a0 * t3 + a1 * t2 + a2 * t + a3);
if (sampVal > MAX_16) sampVal = MAX_16;
else if (sampVal < MIN_16) sampVal = MIN_16;
} else if (frequency > 208.0f) {
int frac = (phase_fractional >> 6) & 0x3FF;
int16_t s0 = bandPtr[idx];
int16_t s1 = bandPtr[(idx + 1) & (TABLE_SIZE - 1)];
sampVal = s0 + (((s1 - s0) * frac) >> 10);
} else {
sampVal = bandPtr[idx];
if (bandPtr == waveTable) {
sampVal = (sampVal + prevSampVal) >> 1;
prevSampVal = sampVal;
}
}
incrementPhase();
if (spreadActive) {
sampVal = doSpread(sampVal);
}
return sampVal;
}
/** Returns the sample at a specified time in milliseconds.
* Used for LFOs. Assumes the Osc started at time = 0;
* @return outSamp The sample value at the calculated phase position - range MIN_16 to MAX_16.
*/
inline
int16_t atTime(unsigned long ms) {
unsigned long indexAtTime = ms * cycleLengthPerMS * TABLE_SIZE;
int index = indexAtTime & (TABLE_SIZE - 1); //indexAtTime % TABLE_SIZE; assuming index is a power of 2
int16_t outSamp = waveTable[index];
return outSamp;
}
/** Returns the normalised oscillator value at specified time in milliseconds.
* Used for LFOs. Assumes the Osc started at time = 0;
* @return outVal The osc value at the calculated phase position normalised between 0.0 and 1.0.
*/
inline
float atTimeNormal(unsigned long ms) {
int16_t outSamp = atTime(ms);
return max(0.0, outSamp * MAX_16_INV * 0.5 + 0.5);
}
/** Change the sound table which will be played by the Oscil.
* @param TABLE_NAME is the name of the array. Must be the same size as the original table used when instantiated.
*/
inline
void setTable(int16_t * TABLE_NAME) { // const
waveTable = TABLE_NAME;
// Update bandPtr based on current frequency
if (frequency > 831) {
bandPtr = waveTable + TABLE_SIZE * 2;
} else if (frequency > 208) {
bandPtr = waveTable + TABLE_SIZE;
} else {
bandPtr = waveTable;
}
}
/** Set the phase of the Oscil. Phase ranges from 0.0 - 1.0 */
inline
void setPhase(float phase) {
// Convert 0.0-1.0 to 16.16 fixed-point (0 to TABLE_SIZE << 16)
phase_fractional = (uint32_t)(phase * TABLE_SIZE * 65536.0f);
// Spread phases also 16.16
phase_fractional_s1 = phase_fractional;
phase_fractional_s2 = phase_fractional;
}
/** Get the phase of the Oscil in fractional format (0.0 - 1.0). */
inline
float getPhase() {
// Convert 16.16 fixed-point back to 0.0-1.0
return (float)phase_fractional / (TABLE_SIZE * 65536.0f);
}
/** Set the spread value of the Oscil.
* @newVal A multiplyer of the base freq, from 0 to 1.0, values near zero are best for phasing effects
*/
inline
void setSpread(float newVal) {
spread1 = 1.0f + newVal;
spread2 = 1.0f - newVal * 0.5002;
if (newVal > 0) {
spreadActive = true;
} else spreadActive = false;
setFreq(getFreq());
}
/** Set the spread value of each detuned Oscilator instance. Ranges > 0
* @val1 The first spread value
* @val2 The second spread value
*/
inline
void setSpread(int val1, int val2) {
spread1 = intervalRatios[val1 + 12]; //intervalFreq(frequency, val1);
spread2 = intervalRatios[val2 + 12]; //intervalFreq(frequency, val2);
}
/** Return the spread value of the Oscil. */
float getSpread() {
return spread1 - 1.0;
}
/** Return the current value of the Oscil. */
int16_t getValue() {
int idx = phase_fractional >> 16; // 16.16 fixed-point
return bandPtr[idx];
}
/** Get a blend of this Osc and another.
* @param secondWaveTable - an waveTable array to morph with
* @param morphAmount - The balance (mix) of the second wavetable, 0.0 - 1.0
*/
inline
int16_t nextMorph(int16_t * secondWaveTable, float morphAmount) {
if (morphAmount <= 0) return next(); // identical to next() when not morphing
int intMorphAmount = max(0, min (1024, (int)(1024 * morphAmount)));
int32_t sampVal;
#if IS_ESP32() || IS_RP2040()
{
uint32_t cachedIncrement = __atomic_load_n(&phase_increment_fractional, __ATOMIC_RELAXED);
int16_t* cachedBandPtr = (int16_t*)__atomic_load_n((uintptr_t*)&bandPtr, __ATOMIC_RELAXED);
if (cachedBandPtr == nullptr || cachedIncrement == 0) return 0;
uint32_t myPhase = __atomic_fetch_add(&phase_fractional, cachedIncrement, __ATOMIC_RELAXED);
int idx = (myPhase >> 16) & (TABLE_SIZE - 1);
int bandOffset = (int)(cachedBandPtr - waveTable);
int32_t sampVal1 = cachedBandPtr[idx];
int32_t sampVal2 = secondWaveTable[bandOffset + idx];
sampVal = (((sampVal2 * intMorphAmount) >> 10) +
((sampVal1 * (1024 - intMorphAmount)) >> 10));
if (spreadActive) {
sampVal = doSpreadAtomic(sampVal);
}
return sampVal;
}
#endif
// Non-atomic fallback for single-core platforms
int idx = (phase_fractional >> 16) & (TABLE_SIZE - 1);
int bandOffset = (int)(bandPtr - waveTable);
int32_t sampVal1 = bandPtr[idx];
int32_t sampVal2 = secondWaveTable[bandOffset + idx];
sampVal = (((sampVal2 * intMorphAmount) >> 10) +
((sampVal1 * (1024 - intMorphAmount)) >> 10));
incrementPhase();
if (spreadActive) {
sampVal = doSpread(sampVal);
}
return sampVal;
}
/** Get a blend of this Osc and another, without incrementing the waveTable lookup.
* @param secondWaveTable - a waveTable array to morph with
* @param morphAmount - The balance (mix) of the second waveTable , 0.0 - 1.0
*/
inline
int16_t currentMorph(int16_t * secondWaveTable, float morphAmount) {
if (morphAmount <= 0) {
// Read current sample without morphing
#if IS_ESP32() || IS_RP2040()
int16_t* cachedBandPtr = (int16_t*)__atomic_load_n((uintptr_t*)&bandPtr, __ATOMIC_RELAXED);
if (cachedBandPtr == nullptr) return 0;
uint32_t myPhase = __atomic_load_n(&phase_fractional, __ATOMIC_RELAXED);
int idx = (myPhase >> 16) & (TABLE_SIZE - 1);
prevSampVal = cachedBandPtr[idx];
#else
int idx = (phase_fractional >> 16) & (TABLE_SIZE - 1);
prevSampVal = bandPtr[idx];
#endif
return prevSampVal;
}
int intMorphAmount = max(0, min(1024, (int)(1024 * morphAmount)));
int32_t sampVal;
#if IS_ESP32() || IS_RP2040()
{
int16_t* cachedBandPtr = (int16_t*)__atomic_load_n((uintptr_t*)&bandPtr, __ATOMIC_RELAXED);
if (cachedBandPtr == nullptr) return 0;
uint32_t myPhase = __atomic_load_n(&phase_fractional, __ATOMIC_RELAXED);
int idx = (myPhase >> 16) & (TABLE_SIZE - 1);
int bandOffset = (int)(cachedBandPtr - waveTable);
int32_t sampVal1 = cachedBandPtr[idx];
int32_t sampVal2 = secondWaveTable[bandOffset + idx];
sampVal = (((sampVal2 * intMorphAmount) >> 10) +
((sampVal1 * (1024 - intMorphAmount)) >> 10));
prevSampVal = sampVal;
if (spreadActive) {
sampVal = doSpreadAtomic(sampVal);
}
return sampVal;
}
#endif
int idx = (phase_fractional >> 16) & (TABLE_SIZE - 1);
int bandOffset = (int)(bandPtr - waveTable);
int32_t sampVal1 = bandPtr[idx];
int32_t sampVal2 = secondWaveTable[bandOffset + idx];
sampVal = (((sampVal2 * intMorphAmount) >> 10) +
((sampVal1 * (1024 - intMorphAmount)) >> 10));
prevSampVal = sampVal;
if (spreadActive) {
sampVal = doSpread(sampVal);
}
return sampVal;
}
/** Get a window transform between this Osc and another waveTable .
* Inspired by the Window Transform Function by Dove Audio
* @param secondWaveTable - an waveTable array to transform with
* @param windowSize - The amount (mix) of the second waveTable to let through, 0.0 - 1.0
* @param duel - Use a duel window that can increase harmonicity
* @param invert - Invert the second wavefrom that can increase harmonicity
*/
inline
int16_t nextWTrans(int16_t * secondWaveTable, float windowSize, bool duel, bool invert) {
// see https://dove-audio.com/wtf-module/
int halfTable = HALF_TABLE_SIZE;
int portion12 = halfTable * windowSize;
int quarterTable = TABLE_SIZE * 0.25;
int threeQuarterTable = quarterTable * 3;
int portion14 = quarterTable * windowSize;
int32_t sampVal = 0;
int phaseIdx = phase_fractional >> 16; // 16.16: extract integer index for comparisons
if (duel) {
if (phaseIdx < (quarterTable - portion14) || (phaseIdx > (quarterTable + portion14) &&
phaseIdx < (threeQuarterTable - portion14)) || phaseIdx > (threeQuarterTable + portion14)) {
int idx = phaseIdx;
if (frequency > 831) { // midi pitch ~80 // high
sampVal = waveTable[idx + TABLE_SIZE + TABLE_SIZE];
} else if (frequency > 208) { // midi pitch ~56 // mid
sampVal = waveTable[idx + TABLE_SIZE];
} else {
sampVal = (waveTable[idx] + prevSampVal)>>1; // low
prevSampVal = sampVal;
}
if (spreadActive) {
sampVal = doSpread(sampVal);
}
} else {
sampVal = secondWaveTable[phaseIdx];
if (invert) sampVal *= -1;
if (spreadActive) {
int32_t spreadSamp1 = secondWaveTable[phaseIdx];
sampVal = (sampVal + spreadSamp1)>>1;
int32_t spreadSamp2 = secondWaveTable[phaseIdx];
sampVal = (sampVal + spreadSamp2)>>1;
incrementSpreadPhase();
}
}
} else {
if (phaseIdx < (halfTable - portion12) || phaseIdx > (halfTable + portion12)) {
int idx = phaseIdx;
if (frequency > 831) { // midi pitch ~80 // high
sampVal = waveTable[idx + TABLE_SIZE + TABLE_SIZE];
} else if (frequency > 208) { // midi pitch ~56 // mid
sampVal = waveTable[idx + TABLE_SIZE];
} else {
sampVal = (waveTable[idx] + prevSampVal)>>1; // low
prevSampVal = sampVal;
}
if (spreadActive) {
sampVal = doSpread(sampVal);
}
} else {
sampVal = secondWaveTable[phaseIdx];
if (invert) sampVal *= -1;
if (spreadActive) {
int32_t spreadSamp1 = secondWaveTable[phaseIdx];
sampVal = (sampVal + spreadSamp1)>>1;
int32_t spreadSamp2 = secondWaveTable[phaseIdx];
sampVal = (sampVal + spreadSamp2)>>1;
incrementSpreadPhase();
}
}
}
sampVal = (sampVal + prevSampVal)>>1; // smooth joins
prevSampVal = sampVal;
incrementPhase();
return sampVal;
}
/** Phase Modulation (FM)
* @param modulator - The next sample from the modulating waveform (int16_t)
* @param modIndex - Modulation depth, 0.0 to ~10.0 typical
* 0.5-1.0: Subtle FM shimmer
* 2.0-4.0: Classic FM tones
* 5.0-10.0: Aggressive FM
*/
inline int16_t phMod(int16_t modulator, float modIndex) {
// Calculate phase offset in 16.16 format
int32_t modOffset = (int32_t)((float)modulator * modIndex * 8.0f);
// Anti-aliasing: reduce mod depth at high carrier frequencies
modOffset = (modOffset * modDepthScale) >> 10;
modOffset <<= 8; // Scale to 16.16 format
#if IS_ESP32() || IS_RP2040()
if (!pulseWidthOn && !isNoise && !isCrackle) {
// Atomic path: each core gets a unique phase value (matches next() pattern)
uint32_t cachedIncrement = __atomic_load_n(&phase_increment_fractional, __ATOMIC_RELAXED);
int16_t* cachedBandPtr = (int16_t*)__atomic_load_n((uintptr_t*)&bandPtr, __ATOMIC_RELAXED);
if (cachedBandPtr == nullptr || cachedIncrement == 0) return 0;
uint32_t myPhase = __atomic_fetch_add(&phase_fractional, cachedIncrement, __ATOMIC_RELAXED);
// Add modulation offset to this core's phase
uint32_t p = myPhase + modOffset;
int idx = (p >> 16) & (TABLE_SIZE - 1);
int frac = (p >> 6) & 0x3FF;
int16_t s0 = cachedBandPtr[idx];
int16_t s1 = cachedBandPtr[(idx + 1) & (TABLE_SIZE - 1)];
int32_t sampVal = s0 + (((s1 - s0) * frac) >> 10);
if (spreadActive) {
sampVal = doSpreadAtomic(sampVal);
}
return sampVal;
}
#endif
// Non-atomic fallback for pulse width, noise, crackle, or single-core platforms
uint32_t p = phase_fractional + modOffset;
int idx = (p >> 16) & (TABLE_SIZE - 1);
int frac = (p >> 6) & 0x3FF; // 10-bit fractional (0-1023)
int16_t* cachedBandPtr = bandPtr;
int16_t s0 = cachedBandPtr[idx];
int16_t s1 = cachedBandPtr[(idx + 1) & (TABLE_SIZE - 1)];
int32_t sampVal = s0 + (((s1 - s0) * frac) >> 10);
incrementPhase();
if (spreadActive) {
sampVal = doSpread(sampVal);
}
return sampVal;
}
/** Phase Modulation using pre-scaled integer mod index (avoids per-sample float math)
*
* Equivalent to phMod() but replaces two per-sample float multiplies with one
* integer multiply + shift. Pre-compute the scaled value at parameter-change time
* (e.g., in loop() or at note trigger), then pass it here in audioUpdate().
*
* Pre-scaling formula:
* int32_t modIndexScaled = (int32_t)(modIndex * 2048.0f);
* // where 2048 = 8.0 * 256.0 (the internal scaling factors)
*
* Example usage:
* // At parameter-change time (loop, envelope update, note trigger):
* float modIndex = fmDepth * envelopeFollow; // 0.0 to ~10.0
* int32_t scaledMod = (int32_t)(modIndex * 2048.0f);
*
* // In audioUpdate() (called at sample rate):
* int16_t sample = osc.phModInt(fmOsc.next(), scaledMod);
*
* @param modulator - The next sample from the modulating waveform (int16_t)
* @param modIndexScaled - Pre-scaled mod index: (int32_t)(modIndex * 2048.0f)
*/
inline int16_t phModInt(int16_t modulator, int32_t modIndexScaled) {
// modOffset = modulator * modIndex * 8.0f, pre-scaled by 256
int32_t modOffset = ((int32_t)modulator * modIndexScaled) >> 8;
// Anti-aliasing: reduce mod depth at high carrier frequencies
modOffset = (modOffset * modDepthScale) >> 10;
modOffset <<= 8; // Scale to 16.16 format
#if IS_ESP32() || IS_RP2040()
if (!pulseWidthOn && !isNoise && !isCrackle) {
uint32_t cachedIncrement = __atomic_load_n(&phase_increment_fractional, __ATOMIC_RELAXED);
int16_t* cachedBandPtr = (int16_t*)__atomic_load_n((uintptr_t*)&bandPtr, __ATOMIC_RELAXED);
if (cachedBandPtr == nullptr || cachedIncrement == 0) return 0;
uint32_t myPhase = __atomic_fetch_add(&phase_fractional, cachedIncrement, __ATOMIC_RELAXED);
uint32_t p = myPhase + modOffset;
int idx = (p >> 16) & (TABLE_SIZE - 1);
int frac = (p >> 6) & 0x3FF;
int16_t s0 = cachedBandPtr[idx];
int16_t s1 = cachedBandPtr[(idx + 1) & (TABLE_SIZE - 1)];
int32_t sampVal = s0 + (((s1 - s0) * frac) >> 10);
if (spreadActive) {
sampVal = doSpreadAtomic(sampVal);
}
return sampVal;
}
#endif
uint32_t p = phase_fractional + modOffset;
int idx = (p >> 16) & (TABLE_SIZE - 1);
int frac = (p >> 6) & 0x3FF;
int16_t* cachedBandPtr = bandPtr;
int16_t s0 = cachedBandPtr[idx];
int16_t s1 = cachedBandPtr[(idx + 1) & (TABLE_SIZE - 1)];
int32_t sampVal = s0 + (((s1 - s0) * frac) >> 10);
incrementPhase();
if (spreadActive) {
sampVal = doSpread(sampVal);
}
return sampVal;
}
/** Set cached mod index for use with single-argument phMod
* @param modIndex - The depth value (0.0 - 10.0 typical)
*/
inline void setModIndex(float modIndex) {
cachedModIndexF = modIndex;
}
/** Phase Modulation using cached mod index
* Call setModIndex() first, then use this in the audio loop
*/
inline int16_t phMod(int16_t modulator) {
return phMod(modulator, cachedModIndexF);
}
/** Phase Modulation with 2x oversampling (FM)
* Higher quality anti-aliasing at ~2x CPU cost
* @param modulator - The next sample from the modulating waveform (int16_t)
* @param modIndex - Modulation depth, 0.0 to ~10.0 typical
*/
inline int16_t phMod2(int16_t modulator, float modIndex) {
// Calculate phase offset in 16.16 format
int32_t modOffset = (int32_t)((float)modulator * modIndex * 8.0f);
// Anti-aliasing: reduce mod depth at high carrier frequencies
modOffset = (modOffset * modDepthScale) >> 10;
modOffset <<= 8; // Scale to 16.16 format
#if IS_ESP32() || IS_RP2040()
if (!pulseWidthOn && !isNoise && !isCrackle) {
// Atomic path: advance full increment atomically, compute two lookups from it
uint32_t cachedIncrement = __atomic_load_n(&phase_increment_fractional, __ATOMIC_RELAXED);
int16_t* cachedBandPtr = (int16_t*)__atomic_load_n((uintptr_t*)&bandPtr, __ATOMIC_RELAXED);
if (cachedBandPtr == nullptr || cachedIncrement == 0) return 0;
uint32_t myPhase = __atomic_fetch_add(&phase_fractional, cachedIncrement, __ATOMIC_RELAXED);
uint32_t halfInc = cachedIncrement >> 1;
// --- Sample 1: at start of this core's phase slice ---
uint32_t p1 = myPhase + modOffset;
int idx1 = (p1 >> 16) & (TABLE_SIZE - 1);
int frac1 = (p1 >> 6) & 0x3FF;
int16_t s0 = cachedBandPtr[idx1];
int16_t s1 = cachedBandPtr[(idx1 + 1) & (TABLE_SIZE - 1)];
int32_t samp1 = s0 + (((s1 - s0) * frac1) >> 10);
// --- Sample 2: at half-step within this core's phase slice ---
uint32_t p2 = (myPhase + halfInc) + modOffset;
int idx2 = (p2 >> 16) & (TABLE_SIZE - 1);
int frac2 = (p2 >> 6) & 0x3FF;
s0 = cachedBandPtr[idx2];
s1 = cachedBandPtr[(idx2 + 1) & (TABLE_SIZE - 1)];
int32_t samp2 = s0 + (((s1 - s0) * frac2) >> 10);
int32_t sampVal = (samp1 + samp2) >> 1;
if (spreadActive) {
sampVal = doSpreadAtomic(sampVal);
}
return sampVal;
}
#endif
// Non-atomic fallback for pulse width, noise, crackle, or single-core platforms
uint32_t halfInc = phase_increment_fractional >> 1;
// --- Sample 1: at current phase ---
uint32_t p1 = phase_fractional + modOffset;
int idx1 = (p1 >> 16) & (TABLE_SIZE - 1);
int frac1 = (p1 >> 6) & 0x3FF;
int16_t s0 = bandPtr[idx1];
int16_t s1 = bandPtr[(idx1 + 1) & (TABLE_SIZE - 1)];
int32_t samp1 = s0 + (((s1 - s0) * frac1) >> 10);
// Advance phase by half increment
phase_fractional += halfInc;
phase_fractional &= TABLE_SIZE_FP_MASK;
// --- Sample 2: at half-step advanced phase ---
uint32_t p2 = phase_fractional + modOffset;
int idx2 = (p2 >> 16) & (TABLE_SIZE - 1);
int frac2 = (p2 >> 6) & 0x3FF;
s0 = bandPtr[idx2];
s1 = bandPtr[(idx2 + 1) & (TABLE_SIZE - 1)];
int32_t samp2 = s0 + (((s1 - s0) * frac2) >> 10);
// Advance phase by remaining half increment
phase_fractional += halfInc;
phase_fractional &= TABLE_SIZE_FP_MASK;
// Average the two samples (simple 2-tap lowpass)
int32_t sampVal = (samp1 + samp2) >> 1;
if (spreadActive) {
sampVal = doSpread(sampVal);
}
return sampVal;
}
/** Phase Modulation with 2x oversampling using cached mod index */
inline int16_t phMod2(int16_t modulator) {
return phMod2(modulator, cachedModIndexF);
}
/** Ring Modulation
* Pass in a second oscillator and multiply its value to change mod depth
* Multiplying incomming oscillator amplitude between 0.5 - 2.0 is best.
*/
inline
int16_t ringMod(int audioIn) {
incrementPhase();
int idx = phase_fractional >> 16; // 16.16 fixed-point
int32_t currSamp = waveTable[idx];
int16_t sampVal = (currSamp * audioIn)>>15;
if (spreadActive) {
sampVal = doSpread(sampVal);
}
return sampVal;
}
/** PhISM Shaker model
* Designed for Osc being set to a noise waveTable .
* @param thresh The amount of aparent particles. Ty cally 0.9 - 0.999
* Envelope output and pass to one or more band pass filters or other resonator.
*/
inline
int16_t particle(float thresh) {
int idx = phase_fractional >> 16; // 16.16 fixed-point
int32_t noiseVal = waveTable[idx];
if (noiseVal > (MAX_16 * thresh)) {
particleEnv = noiseVal - (MAX_16 - noiseVal) - (MAX_16 - noiseVal);
} else particleEnv *= particleEnvReleaseRate;
incrementPhase();
noiseVal = (prevParticle + noiseVal + noiseVal)/3;
return (noiseVal * particleEnv) >> 16;
}
/** PhISM Shaker model
* Designed for Osc being set to a noise wavetable.
* Uses some private hard coded params.
* Envelope output and pass to one or more band pass filters or other resonator.
*/
inline
int16_t particle() {
return particle(particleThreshold);
}
/** Frequency Modulation Feedback
* Designed for Osc being set to a sine waveform, but works with any waveform.
* @modIndex amount of feedback applied, >=0 and useful < 100
* Credit to description in The CMT (Roads 1996).
*/
inline
int16_t feedback(int32_t modIndex) {
// Read feedback sample using 16.16 index
int16_t y = waveTable[feedback_phase_fractional >> 16] >> 3;
int16_t s = waveTable[y & (TABLE_SIZE - 1)];
// Calculate feedback offset and convert to 16.16
int32_t f_fp = ((modIndex * (int32_t)s) >> 16) << 16;
// Update phase with feedback (signed arithmetic then fast wrap)
phase_fractional = (uint32_t)((int32_t)phase_fractional + f_fp + (int32_t)phase_increment_fractional);
phase_fractional &= TABLE_SIZE_FP_MASK; // Fast wrap
// Increment feedback phase with fast wrap
feedback_phase_fractional += phase_increment_fractional;
feedback_phase_fractional &= TABLE_SIZE_FP_MASK;
// Return sample at current phase
int16_t out = waveTable[(phase_fractional >> 16) & (TABLE_SIZE - 1)];
return out;
}
/** Glide toward the frequency of the oscillator in Hz.
* @freq The desired final value
* @amnt The percentage toward target (0.0 - 1.0)
*/
inline
void slewFreq(float freq, float amnt) {
if (freq == frequency) return;
if (amnt == 0) {
setFreq(freq);
} else if (freq >= 0 && amnt > 0 && amnt <= 1) {
float tempFreq = frequency;
setFreq(slew(frequency, freq, amnt));
prevFrequency = tempFreq;
}
}
/** Set the frequency of the oscillator.
* @freq The desired frequency in Hz
*/
inline
void setFreq(float freq) {
if (freq > 0) {
frequency = freq;
// 16.16 fixed-point: phase_inc = (freq * TABLE_SIZE / SAMPLE_RATE) * 65536
uint32_t newIncrement = (uint32_t)(freq * TABLE_SIZE * 65536.0f / SAMPLE_RATE);
// Calculate new band pointer before atomic update
int16_t* newBandPtr = bandPtr;
if (waveTable != nullptr) {
if (freq > 831) {
newBandPtr = waveTable + TABLE_SIZE * 2; // high band
} else if (freq > 208) {
newBandPtr = waveTable + TABLE_SIZE; // mid band
} else {
newBandPtr = waveTable; // low band
}
}
// Atomic stores for thread-safety with next() on dual-core systems
#if IS_ESP32() || IS_RP2040()
// Update bandPtr first, then increment (next() reads increment first, then bandPtr)
__atomic_store_n((uintptr_t*)&bandPtr, (uintptr_t)newBandPtr, __ATOMIC_RELEASE);
__atomic_store_n(&phase_increment_fractional, newIncrement, __ATOMIC_RELEASE);
#else
bandPtr = newBandPtr;
phase_increment_fractional = newIncrement;
#endif
if (pulseWidthOn) {
// Calculate pulse width variants in 16.16
uint32_t halfInc = newIncrement >> 1;
phase_increment_fractional_w1 = (uint32_t)(halfInc / pulseWidth);
phase_increment_fractional_w2 = (uint32_t)(halfInc / (1.0f - pulseWidth));
}
if (spreadActive) {
// 16.16 spread increments
phase_increment_fractional_s1 = (uint32_t)(newIncrement * spread1);
phase_increment_fractional_s2 = (uint32_t)(newIncrement * spread2);
} else {
phase_increment_fractional_s1 = newIncrement;
phase_increment_fractional_s2 = newIncrement;
}
cycleLengthPerMS = frequency * 0.001f;
// Frequency-adaptive mod depth scaling for anti-aliasing in phMod
// Below 1500Hz: full depth. Above: reduce proportionally to headroom to Nyquist.
// This reduces FM sidebands that would alias at higher carrier frequencies.
const float nyquist = SAMPLE_RATE * 0.5f;
const float thresholdFreq = 1500.0f;
if (freq <= thresholdFreq) {
modDepthScale = 1024; // Full depth
} else {
// Scale down based on remaining headroom: (nyquist - freq) / (nyquist - threshold)
float headroom = (nyquist - freq) / (nyquist - thresholdFreq);
modDepthScale = (int32_t)(1024.0f * fmaxf(0.05f, fminf(1.0f, headroom)));
}
}
}
/** Return the frequency of the oscillator in Hz. */
inline
float getFreq() {
return frequency;
}
/** Set the frequency via a MIDI pitch
* @midiPitch The pitch, value 0 - 127
*/
inline
void setPitch(float midi_pitch) {
midiPitch = midi_pitch;
setFreq(mtof(min(127.0f, max(0.0f, midi_pitch * (1 + (audioRand(6) * 0.00001f))))));
prevFrequency = frequency;
}
/** Return the pitch as a MIDI pitch
* @midiPitch The pitch, value 0 - 127
*/
inline
float getPitch() {
return midiPitch;
}
/** Set a specific phase increment in 16.16 fixed-point format.
* @phaseinc_fractional 16.16 fixed-point increment value
* For reference: 65536 = 1 table index per sample
*/
inline
void setPhaseInc(uint32_t phaseinc_fractional) {
phase_increment_fractional = phaseinc_fractional;
}
/** Set using noise waveform flag.
* @val Is true or false
*/
inline
void setNoise(bool val) {
isNoise = val;
}
/** Set using crackle waveform flag.
* @val Is true or false
*/
inline
void setCrackle(bool val) {
setNoise(true);
isCrackle = val;
}
/** Set using crackle waveform flag.
* @val Is true or false
* @amnt Spareness of impulse in samples, from 1 to MAX_16
*/
inline
void setCrackle(bool val, int amnt) {
setNoise(true);
isCrackle = val;
crackleAmnt = max(1, min(MAX_16, amnt));
}
/** Set using pulse width for the waveform
* @width The cycle amount for the first half of the wave - 0.0 to 1.0
*/
inline
void setPulseWidth(float width) {
pulseWidthOn = true;
pulseWidth = max(0.05f, min(0.95f, width));
// Calculate 16.16 pulse width increments
uint32_t halfPhaseInc = phase_increment_fractional >> 1;
phase_increment_fractional_w1 = (uint32_t)(halfPhaseInc / pulseWidth);
phase_increment_fractional_w2 = (uint32_t)(halfPhaseInc / (1.0f - pulseWidth));
}
/** Set using pulse width for the waveform
* @width The cycle amount for the first half of the wave - 0.0 to 1.0
*/
inline
float getPulseWidth() {
return pulseWidth;
}
/** Below are helper methods for generating waveforms into existing arrays.
* Call from class not instance. e.g. Osc::triGen(myWaveTableArray);
* While it might be simpler to have each instance have its own wavetable,
* it's more memory effcient for wavetables to be shared. So create them in the
* main program file and reference them from instances of this class.
*/