-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFX.h
More file actions
1209 lines (1107 loc) · 48.4 KB
/
FX.h
File metadata and controls
1209 lines (1107 loc) · 48.4 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
/*
* FX.h
*
* A class of various DSP effects
*
* by Andrew R. Brown 2021
*
* This file is part of the M16 audio library
* Inspired by the Mozzi audio library by Tim Barrass 2012
*
* M16 is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
*/
#ifndef FX_H_
#define FX_H_
#include "Del.h"
#include "Osc.h"
#include "All.h"
#include "SVF.h"
#include "EMA.h"
#if IS_RP2040()
#include "pico/mutex.h"
#endif
class FX {
public:
#if IS_ESP32() || IS_RP2040()
std::atomic<bool> _fxLock{false};
#endif
/** Constructor. */
FX() {}
/** Wave Folding
* Fold clipped values
* Pass in a signal and an amount to multiply its value by
* @param sample_in The next sample value
* @param amount The degree of amplifcation which is then folded; 1.0 +
*/
inline
int16_t waveFold(int32_t sample_in, float amount) {
if (amount <= 1) return sample_in;
sample_in *= amount;
while(abs(sample_in) > MAX_16) {
if (sample_in > 0) sample_in = MAX_16 - (sample_in + MIN_16);
if (sample_in <= 0) sample_in = MIN_16 - (sample_in + MAX_16);
}
return clip16(sample_in);
}
// clip16() in M16.h does hard clipping
/* Soft Clipping default
* Distort sound based on input level and depth amount
* Pass in a signal and depth amount.
* Output level can vary, so best to mix with original signal.
* @param sample_in The next sample value
* @param amount The degree of clipping to be applied - 1 to 400 is a reasonable range
* From amount of 1.0 (neutral) upward to about 25.0
*/
inline
int16_t softClip(int32_t sample_in, float amount) {
return softClipTube(sample_in, amount);
}
/** Soft Clipping (atan)
* Distort sound based on input level and depth amount
* Pass in a signal and depth amount.
* Output level can vary, so best to mix with original signal.
* @param sample_in The next sample value
* @param amount The degree of clipping to be applied - 1 to 400 is a reasonable range
* From amount of 1.0 (neutral) upward to about 2.0 for some compression to
* about 3.0 for mild drive, to about 4 - 6 for noticiable overdrive, to 7 - 10 for distortion
* Note: Uses atan() which is warm but can sound dull. See alternatives below.
*/
inline
int16_t softClipAtan(int32_t sample_in, float amount) {
int32_t samp = 38000 * atan(amount * (sample_in * (float)MAX_16_INV)); // 20831
return clip16(samp);
}
/** Cubic Soft Clipping
* Faster and brighter than atan soft clip.
* Uses polynomial x - x³/6.75 which has a sharper knee, preserving more harmonics.
* @param sample_in The next sample value
* @param amount The degree of clipping, 1.0 (neutral) to ~10.0 (heavy distortion)
*/
inline
int16_t softClipCubic(int32_t sample_in, float amount) {
float x = amount * sample_in * (float)MAX_16_INV;
float out;
if (x > 1.5f) out = 1.0f;
else if (x < -1.5f) out = -1.0f;
else out = x - (x * x * x) * 0.148148f; // x - x³/6.75
return clip16((int32_t)(out * MAX_16));
}
/** Fast Tanh Soft Clipping
* Balanced tone between warm and bright using Pade approximant.
* ~5x faster than real tanh, smooth curve with good harmonic balance.
* @param sample_in The next sample value
* @param amount The degree of clipping, 1.0 (neutral) to ~10.0 (heavy distortion)
*/
inline
int16_t softClipTanh(int32_t sample_in, float amount) {
float x = amount * sample_in * (float)MAX_16_INV;
float x2 = x * x;
float out = x * (27.0f + x2) / (27.0f + 9.0f * x2);
return clip16((int32_t)(out * MAX_16));
}
/** Tube-Style Asymmetric Saturation
* Emulates tube amplifier characteristics with asymmetric clipping.
* Adds even harmonics for warmth with presence, not dull.
* @param sample_in The next sample value
* @param amount The degree of saturation, 1.0 (mild) to ~10.0 (heavy)
*/
inline
int16_t softClipTube(int32_t sample_in, float amount) {
float x = amount * sample_in * (float)MAX_16_INV;
float out;
if (x >= 0) {
// Fast exp approximation: e^x ≈ (1 + x/8)^8 for small x, else clamp
float ex = (x > 4.0f) ? 0.0f : fastExpNeg(x);
out = 1.0f - ex;
} else {
float ex = (x < -4.0f) ? 0.0f : fastExpNeg(-x);
out = ex - 1.0f;
}
return clip16((int32_t)(out * MAX_16));
}
/** Integer-only Soft Clipping (no floats)
* Warm approximation of tube saturation using only integer math.
* Uses rational function: out = x / (1 + |x|/threshold)
* Optimized to avoid int64 division for better ESP32 performance.
* @param sample_in The next sample value
* @param amount The drive amount as integer, 1024 = unity, 2048 = 2x drive, etc.
* Useful range: 1024 (mild) to 10240 (heavy distortion)
*/
inline
int16_t softClipInt(int32_t sample_in, int32_t amount) {
// Scale input by amount (amount is 10-bit fixed point, 1024 = 1.0)
int32_t x = (sample_in * amount) >> 10;
// Clamp input to prevent overflow
if (x > 98304) x = 98304; // 3x MAX_16
else if (x < -98304) x = -98304;
// Rational soft clip: out = x * threshold / (threshold + |x|)
// Use threshold = 32768, scaled math to stay in 32-bit
int32_t absX = (x >= 0) ? x : -x;
// Scale down, compute, scale back up to avoid overflow
// out = x * 32768 / (32768 + absX)
// Rewrite as: out = x / (1 + absX/32768) = x / (1 + absX>>15)
int32_t denom = 32768 + (absX >> 1); // Approximate: threshold + absX/2
int32_t out = (x << 14) / (denom >> 1); // Scaled 32-bit division
// Final clamp to valid 16-bit range
if (out > MAX_16) out = MAX_16;
else if (out < MIN_16) out = MIN_16;
return (int16_t)out;
}
/** Foldback Soft Clipping
* Folds the waveform back instead of clipping, creating bright harmonics.
* More aggressive/synth-like character than traditional soft clip.
* @param sample_in The next sample value
* @param amount The degree of folding, 1.0 (neutral) to ~4.0 (heavy fold)
*/
inline
int16_t softClipFold(int32_t sample_in, float amount) {
float x = amount * sample_in * (float)MAX_16_INV;
// Single fold at ±1 threshold
if (x > 1.0f) x = 2.0f - x;
else if (x < -1.0f) x = -2.0f - x;
// Clamp result in case of extreme values
if (x > 1.0f) x = 1.0f;
else if (x < -1.0f) x = -1.0f;
return (int16_t)(x * MAX_16);
}
/** Bit Crusher
* Reduces bit depth for lo-fi digital distortion effect.
* Quantizes the sample to fewer bits, creating stepped/grainy artifacts.
* @param sample_in The next sample value
* @param bits Bit depth from 1 (extreme) to 16 (clean). Typical range 4-12.
*/
inline
int16_t bitCrush(int32_t sample_in, int bits) {
if (bits >= 16) return clip16(sample_in);
if (bits < 1) bits = 1;
int shift = 16 - bits;
// Add half-step offset before truncation for rounding (reduces DC offset)
int32_t halfStep = 1 << (shift - 1);
// Quantize by shifting right then left (truncates lower bits)
int32_t out = ((sample_in + halfStep) >> shift) << shift;
return clip16(out);
}
/** Bit Crusher with Sample Rate Reduction
* Combines bit depth reduction with sample-and-hold for classic lo-fi sound.
* @param sample_in The next sample value
* @param bits Bit depth from 1 (extreme) to 16 (clean). Typical range 4-12.
* @param holdSamples Number of samples to hold (1 = no reduction, higher = more aliasing)
* Values 1-16 typical. Creates staircase/aliasing artifacts.
*/
inline
int16_t bitCrush(int32_t sample_in, int bits, int holdSamples) {
// Sample rate reduction via sample-and-hold
if (holdSamples > 1) {
crushHoldCounter++;
if (crushHoldCounter >= holdSamples) {
crushHoldCounter = 0;
crushHoldValue = bitCrush(sample_in, bits);
}
return crushHoldValue;
}
return bitCrush(sample_in, bits);
}
/** Bit Crusher (float interface)
* Reduces bit depth for lo-fi digital distortion effect.
* @param sample_in The next sample value
* @param amount Crush amount from 0.0 (clean) to 1.0 (extreme, ~2 bits)
* Maps logarithmically for more usable range in the middle.
*/
inline
int16_t bitCrushF(int32_t sample_in, float amount) {
amount = max(0.0f, min(1.0f, amount));
// Map 0-1 to 16-2 bits with curve for better control in sweet spot
// amount=0 -> 16 bits, amount=0.5 -> ~6 bits, amount=1.0 -> 2 bits
int bits = 16 - (int)(amount * amount * 14.0f);
return bitCrush(sample_in, bits);
}
/** Overdrive
* Distort sound based on input level and depth amount
* Pass in a signal and depth amount.
* Output level can vary, so best to mix with original signal.
* @param sample_in The next sample value
* @param amount The degree of clipping to be applied, from 1 to 4 is a reasonable range
* Amounts less than 1.0 (neutral) will reduce the signal
*/
inline
int16_t overdrive(int32_t sample_in, float amount) {
// filter input
aveFilter.setFreq(10000); // htz approx 1/4 of sample rate
sample_in = aveFilter.next(sample_in);
amount *= 0.72; // scale so 1.0 is neutral
// clipper
sample_in = sample_in * amount;
float sample = sample_in * MAX_16_INV * amount;
float absSampIn = abs(sample);
float clippedSampIn = (sample > 0) ? 1.0f : -1.0f;
float clippedSampIn16 = (sample_in > 0) ? MAX_16 : MIN_16;
float clipOut = 0;
float thresh = 0.33; //10922; //MAX_16 * 0.33;
if (absSampIn < thresh) {
clipOut = 2.0f * sample;
} else if (absSampIn < 2 * thresh) {
clipOut = clippedSampIn * (3.0f - (2.0f - 3.0f * absSampIn) * (2.0f - 3.0f * absSampIn)) / 3.0f;
} else {
clipOut = clippedSampIn;
}
return clip16(clipOut * MAX_16);
}
/** Set compression parameters (call when parameters change, not every sample)
* @param threshold is the threshold value between 0.0 and 1.0
* @param ratio is the ratio value, > 1.0, typically 2 to 4
* @param attackMs is attack time in milliseconds (default 5ms for percussive)
* @param releaseMs is release time in milliseconds (default 100ms for percussive)
*/
inline
void setCompression(float threshold, float ratio, float attackMs = 5.0f, float releaseMs = 100.0f) {
compThreshold = threshold;
compRatio = ratio;
compThresh = (int16_t)(threshold * MAX_16);
compInvRatio = 1.0f / ratio;
compGainCompensation = 1.0f + (1.0f - threshold * (1.0f + compInvRatio));
// Calculate envelope coefficients from time constants
// coeff = exp(-1 / (time_seconds * sample_rate))
float attackSamples = attackMs * 0.001f * SAMPLE_RATE;
float releaseSamples = releaseMs * 0.001f * SAMPLE_RATE;
compAttackCoeff = attackSamples > 0 ? fastExpNeg(1.0f / attackSamples) : 0.0f;
compReleaseCoeff = releaseSamples > 0 ? fastExpNeg(1.0f / releaseSamples) : 0.0f;
}
/** Compressor with gain compensation and attack/release envelope
* @param sample is the input sample value
* Call setCompression() first to set threshold, ratio, attack and release times
*/
inline
int16_t compression(int32_t sample) {
int16_t absSample = sample > 0 ? sample : -sample;
// Calculate target gain reduction
float targetGainReduction = 0.0f;
if (absSample > compThresh) {
// How much over threshold?
float excess = absSample - compThresh;
float compressedExcess = excess * compInvRatio;
// Calc gain reduction needed (as a ratio)
targetGainReduction = (excess - compressedExcess) / (float)absSample;
}
// Apply envelope with attack/release
if (targetGainReduction > compEnvelope) {
compEnvelope = compAttackCoeff * compEnvelope + (1.0f - compAttackCoeff) * targetGainReduction;
} else {
compEnvelope = compReleaseCoeff * compEnvelope + (1.0f - compReleaseCoeff) * targetGainReduction;
}
// Apply gain reduction and makeup gain
float gain = (1.0f - compEnvelope) * compGainCompensation;
int32_t output = (int32_t)(sample * gain);
// Clip to prevent overflow
if (output > MAX_16) output = MAX_16;
if (output < MIN_16) output = MIN_16;
return (int16_t)output;
}
/** Left channel compressor with independent envelope state
* @param sample is the input sample value
* Call setCompression() first to set threshold, ratio, attack and release times
*/
inline
int16_t compressionL(int32_t sample) {
int32_t absSample = sample > 0 ? sample : -sample;
float targetGainReduction = 0.0f;
if (absSample > compThresh) {
float excess = absSample - compThresh;
float compressedExcess = excess * compInvRatio;
targetGainReduction = (excess - compressedExcess) / (float)absSample;
}
if (targetGainReduction > compEnvelopeL) {
compEnvelopeL = compAttackCoeff * compEnvelopeL + (1.0f - compAttackCoeff) * targetGainReduction;
} else {
compEnvelopeL = compReleaseCoeff * compEnvelopeL + (1.0f - compReleaseCoeff) * targetGainReduction;
}
float gain = (1.0f - compEnvelopeL) * compGainCompensation;
int32_t output = (int32_t)(sample * gain);
if (output > MAX_16) output = MAX_16;
if (output < MIN_16) output = MIN_16;
return (int16_t)output;
}
/** Right channel compressor with independent envelope state
* @param sample is the input sample value
* Call setCompression() first to set threshold, ratio, attack and release times
*/
inline
int16_t compressionR(int32_t sample) {
int32_t absSample = sample > 0 ? sample : -sample;
float targetGainReduction = 0.0f;
if (absSample > compThresh) {
float excess = absSample - compThresh;
float compressedExcess = excess * compInvRatio;
targetGainReduction = (excess - compressedExcess) / (float)absSample;
}
if (targetGainReduction > compEnvelopeR) {
compEnvelopeR = compAttackCoeff * compEnvelopeR + (1.0f - compAttackCoeff) * targetGainReduction;
} else {
compEnvelopeR = compReleaseCoeff * compEnvelopeR + (1.0f - compReleaseCoeff) * targetGainReduction;
}
float gain = (1.0f - compEnvelopeR) * compGainCompensation;
int32_t output = (int32_t)(sample * gain);
if (output > MAX_16) output = MAX_16;
if (output < MIN_16) output = MIN_16;
return (int16_t)output;
}
/** Compressor with gain compensation (legacy version - parameters computed every sample)
* @param sample is the input sample value
* @param threshold is the threshold value between 0.0 and 1.0
* @param ratio is the ratio value, > 1.0, typically 2 to 4
*/
inline
int16_t compression(int32_t sample, float threshold, float ratio) {
int16_t thresh = threshold * MAX_16;
float invRatio = 1.0f / ratio;
float gainCompensationRatio = 1.0f + (1.0f - threshold * (1.0f + 1.0f * invRatio));
if (sample >= thresh || sample <= -thresh) {
int32_t compressed_sample;
if (sample > 0) {
compressed_sample = (int32_t)((sample - thresh) * invRatio + thresh);
if (compressed_sample > MAX_16) compressed_sample = MAX_16;
} else {
compressed_sample = (int32_t)((sample + thresh) * invRatio - thresh);
if (compressed_sample < MIN_16) compressed_sample = MIN_16;
}
return compressed_sample * gainCompensationRatio;
}
return sample * gainCompensationRatio;
}
/** Update the wave shaping table
* @param TABLE_NAME is the name of the array. Filled with 16bit values.
* @param tableSize the length in samples, typically a power of 2.
* Size of TABLE_SIZE is suggested, smaller or larger bit sizes will reduce or increase resolution.
*/
inline
void setShapeTable(int16_t * TABLE_NAME, int tableSize) {
if (shapeTable) { delete[] shapeTable; shapeTable = nullptr; }
shapeTableSize = tableSize;
shapeTable = new int16_t[shapeTableSize];
memcpy(shapeTable, TABLE_NAME, shapeTableSize * sizeof(int16_t));
waveShaperStepInc = 65537.0 / shapeTableSize;
waveShaperStepIncInv = 1.0f / waveShaperStepInc;
}
/** Wave Shaper
* Distorts wave input by wave shaping function
* Shaping wave is, like osc wavetables, WAVE_TABLE wide from MIN_16 to MAX_16 values
* @sample_in is the input sample value from the carrier wave
* @amount is the degree of distortion, from 0.0 to 1.0
*/
inline
int16_t waveShaper(int16_t sample_in, float amount) {
int index = sample_in;
if (shapeTableSize > 0) index = min(shapeTableSize-1, (int)max(0.0f, (sample_in + MAX_16) * waveShaperStepIncInv));
int16_t sampVal = shapeTable[index];
if (amount >= 0 && amount < 1.0) sampVal = (sampVal * amount) + (sample_in * (1.0 - amount));
return sampVal;
}
/** Create a dedicated soft clip wave shaper
* Distorts wave input by wave shaping function
* @amount is the degree of distortion, from 1.0 being minimal to ~10.0 being a lot
* It is not efficient to update this in real time,
* if required, then manage wave shape function in your main code
*/
inline
void setShapeTableSoftClip(float amount) {
if (shapeTable) { delete[] shapeTable; shapeTable = nullptr; }
shapeTableSize = TABLE_SIZE;
shapeTable = new int16_t[shapeTableSize]; // create a new waveshape table
waveShaperStepInc = 65537.0 / shapeTableSize;
waveShaperStepIncInv = 1.0f / waveShaperStepInc;
for(int i=0; i<shapeTableSize; i++) {
shapeTable[i] = 20813.0 * atan(amount * ((MIN_16 + i * waveShaperStepInc) * (float)MAX_16_INV));
}
}
/** Create a dedicated s-wave wave shaper
* Distorts wave input by the wave shaping function
* @amount is the degree of distortion, from 0.0 to 1.0
* Smaller values for amount may require gain increase compensation
* It is not efficient to update this in real time,
* if required, then manage wave shape function in your main code
*/
inline
void setShapeTableSigmoidCurve(float amount) {
if (shapeTable) { delete[] shapeTable; shapeTable = nullptr; } // remove any previous memory allocation
shapeTableSize = TABLE_SIZE;
shapeTable = new int16_t[shapeTableSize]; // create a new waveshape table
waveShaperStepInc = 65537.0 / shapeTableSize;
waveShaperStepIncInv = 1.0f / waveShaperStepInc;
float tabInc = 1.0 / shapeTableSize * 2;
for(int i=0; i<shapeTableSize * 0.5f; i++) {
float sVal = pow(i * tabInc, amount);
shapeTable[i] = sVal * MAX_16 - MAX_16;
shapeTable[TABLE_SIZE - i] = MAX_16 - sVal * MAX_16;
}
}
/** Create a randomly varied wave shaper
* Distorts wave input by the wave shaping function
* @amount is the degree of distortion, from 0 to MAX_16;
* Because random values are static and looped, the sound is grainy rather than noisy.
*/
inline
void setShapeTableJitter(float amount) {
if (shapeTable) { delete[] shapeTable; shapeTable = nullptr; } // remove any previous memory allocation
shapeTableSize = TABLE_SIZE;
shapeTable = new int16_t[shapeTableSize]; // create a new waveshape table
waveShaperStepInc = 65537.0 / shapeTableSize;
waveShaperStepIncInv = 1.0f / waveShaperStepInc;
for(int i=0; i<shapeTableSize; i++) {
shapeTable[i] = waveShaperStepInc * i + audioRand(amount * 2) - amount;
}
}
/** Karplus Strong fedback model
* @audioIn Pass in an oscillator or other signal
* @pluckFreq Feedback freq, usually equal to the freq of the incoming osc,
* or desired freq of pluck for signal (noise) bursts. In Hz.
* @depth The level of feedback. Controls the amount of effect or length of pluck tail. 0.0 - 1.0
* Use smaller depth for continuous feedback, and very large depth values for pluck string effect on impulses.
*/
inline
int16_t pluck(int16_t audioIn, float pluckFreq, float depth) {
if (!pluckBufferEstablished) initPluckBuffer();
int16_t result = 0;
M16_ATOMIC_GUARD_BLOCKING(_fxLock, {
// read
//float read_index_fractional = SAMPLE_RATE / pluckFreq;
int pluck_buffer_read_index = pluck_buffer_write_index - SAMPLE_RATE / pluckFreq + 1;
if (pluck_buffer_read_index < 0) pluck_buffer_read_index += PLUCK_BUFFER_SIZE;
int bufferRead = pluckBuffer[pluck_buffer_read_index] * depth;
// update buffer
int32_t output = audioIn + bufferRead;
pluckBuffer[(int)pluck_buffer_write_index] = output; // divide?
int32_t aveOut = (output + prevPluckOutput)>>1;
prevPluckOutput = aveOut;
// increment buffer phase
pluck_buffer_write_index += 1;
if (pluck_buffer_write_index > PLUCK_BUFFER_SIZE) pluck_buffer_write_index -= PLUCK_BUFFER_SIZE;
// send output
result = aveOut;
});
return result;
}
/** A simple reverb using recursive delay lines.
* Mono version that sums left and right channels
* @audioIn A mono audio signal
* Inspired by reverb example G08 in Pure Data.
*/
inline
int16_t reverb(int32_t audioIn) {
// set up first time called
if (!reverbInitiated) {
initReverb(reverbSize);
}
int16_t result = 0;
M16_ATOMIC_GUARD_BLOCKING(_fxLock, {
processReverb(audioIn, audioIn);
result = clip16(((audioIn * (1024 - reverbMix))>>10) + ((revP1 * reverbMix)>>12) + ((revP2 * reverbMix)>>12));
});
return result;
}
/** A simple 'spring' reverb using recursive delay lines.
* Stereo version that takes two inputs (can be the same) and sets left and right channel outs
* @audioInLeft A mono audio signal
* @audioInRight A mono audio signal
* @audioOutLeft A mono audio destination variable for the left channel
* @audioOutRight A mono audio destination variable for the right channel
* Inspired by reverb example G08 in Pure Data.
*/
inline
void reverbStereo(int32_t audioInLeft, int32_t audioInRight, int32_t &audioOutLeft, int32_t &audioOutRight) {
// Thread-safe lazy initialization with mutex (dual-core platforms)
if (!reverbInitiated) {
#if IS_ESP32()
extern SemaphoreHandle_t audioInitMutex;
if (audioInitMutex != NULL && xSemaphoreTake(audioInitMutex, portMAX_DELAY)) {
// Double-check after acquiring mutex
if (!reverbInitiated) {
initReverb(reverbSize);
}
xSemaphoreGive(audioInitMutex);
} else {
initReverb(reverbSize);
}
#elif IS_RP2040()
extern mutex_t picoAudioInitMutex;
extern bool picoMutexInitialized;
if (picoMutexInitialized) {
mutex_enter_blocking(&picoAudioInitMutex);
if (!reverbInitiated) {
initReverb(reverbSize);
}
mutex_exit(&picoAudioInitMutex);
} else {
initReverb(reverbSize);
}
#else
initReverb(reverbSize);
#endif
}
M16_ATOMIC_GUARD_BLOCKING(_fxLock, {
if (reverb2Initiated) {
processReverb((audioInLeft + allpassRevOut)>>1, clip16(audioInRight + allpassRevOut)>>1);
} else {
processReverb(clip16(audioInLeft), clip16(audioInRight));
}
audioOutLeft = clip16(((audioInLeft * (1024 - reverbMix))>>10) + ((revP1 * reverbMix)>>11));
audioOutRight = clip16(((audioInRight * (1024 - reverbMix))>>10) + ((revP2 * reverbMix)>>11));
});
}
/** Half-rate stereo reverb with interpolation for reduced CPU usage.
* Processes reverb every other sample and applies smoothing to reduce artifacts.
* Saves ~40-50% CPU compared to full-rate reverb.
* @audioInLeft A mono audio signal for left channel
* @audioInRight A mono audio signal for right channel
* @audioOutLeft A mono audio destination variable for the left channel
* @audioOutRight A mono audio destination variable for the right channel
*/
inline
void reverbStereoInterp(int32_t audioInLeft, int32_t audioInRight, int32_t &audioOutLeft, int32_t &audioOutRight) {
// Thread-safe lazy initialization with mutex (dual-core platforms)
if (!reverbInitiated) {
#if IS_ESP32()
extern SemaphoreHandle_t audioInitMutex;
if (audioInitMutex != NULL && xSemaphoreTake(audioInitMutex, portMAX_DELAY)) {
if (!reverbInitiated) {
initReverb(reverbSize);
}
xSemaphoreGive(audioInitMutex);
} else {
initReverb(reverbSize);
}
#elif IS_RP2040()
extern mutex_t picoAudioInitMutex;
extern bool picoMutexInitialized;
if (picoMutexInitialized) {
mutex_enter_blocking(&picoAudioInitMutex);
if (!reverbInitiated) {
initReverb(reverbSize);
}
mutex_exit(&picoAudioInitMutex);
} else {
initReverb(reverbSize);
}
#else
initReverb(reverbSize);
#endif
}
// Default to cached smoothed output (used when lock not acquired)
audioOutLeft = reverbInterpSmoothL;
audioOutRight = reverbInterpSmoothR;
// Non-blocking: losing core uses cached output above instead of spinning
M16_ATOMIC_GUARD(_fxLock, {
int32_t outL; int32_t outR;
reverbInterpToggle = !reverbInterpToggle;
if (reverbInterpToggle) {
// Process reverb this sample
if (reverb2Initiated) {
processReverb((audioInLeft + allpassRevOut)>>1, clip16(audioInRight + allpassRevOut)>>1);
} else {
processReverb(clip16(audioInLeft), clip16(audioInRight));
}
outL = clip16(((audioInLeft * (1024 - reverbMix))>>10) + ((revP1 * reverbMix)>>11));
outR = clip16(((audioInRight * (1024 - reverbMix))>>10) + ((revP2 * reverbMix)>>11));
reverbInterpPrevL = outL;
reverbInterpPrevR = outR;
} else {
// Skip reverb processing, use previous output
outL = reverbInterpPrevL;
outR = reverbInterpPrevR;
}
// Smooth output with 1-pole lowpass to reduce half-rate artifacts
reverbInterpSmoothL += (outL - reverbInterpSmoothL) >> 2;
reverbInterpSmoothR += (outR - reverbInterpSmoothR) >> 2;
audioOutLeft = reverbInterpSmoothL;
audioOutRight = reverbInterpSmoothR;
});
}
/** Reset the interpolated reverb smoothing state.
* Call when enabling reverb after it was disabled to avoid transients.
* @seedL Initial value for left channel smoother
* @seedR Initial value for right channel smoother
*/
inline
void resetReverbInterp(int32_t seedL = 0, int32_t seedR = 0) {
reverbInterpSmoothL = seedL;
reverbInterpSmoothR = seedR;
reverbInterpPrevL = seedL;
reverbInterpPrevR = seedR;
}
/** A simple 'Chamberlin' reverb using allpass filter preprocessor and recursive delay lines. */
inline
void reverbStereo2(int32_t audioInLeft, int32_t audioInRight, int32_t &audioOutLeft, int32_t &audioOutRight) {
if (!reverb2Initiated) {
allpass1.setDelayTime(49.6);
allpass1.setFeedbackLevel(0.83);
allpass2.setDelayTime(34.65);
allpass2.setFeedbackLevel(0.79);
reverb2Initiated = true;
}
// Allpass pre-processing under the FX lock (reverbStereo also acquires it,
// but M16_ATOMIC_GUARD_BLOCKING is non-reentrant so we do allpass outside)
// Note: allpass filters have their own Del locks for thread safety
int32_t summedMono = (audioInLeft + audioInRight) >> 1;
allpassRevOut = allpass2.next(allpass1.next(summedMono));
reverbStereo(audioInLeft , audioInRight, audioOutLeft, audioOutRight);
}
/** Set the reverb length
* @rLen The amount of feedback that effects reverb decay time. Values from 0.0 to 1.0.
*/
inline
void setReverbLength(float rLen) {
rLen = max(0.0f, min(1.0f, rLen));
reverbFeedbackLevel = pow(rLen, 0.2f);
// Pre-calculate integer coefficient for optimized path
reverbFeedbackInt = (int16_t)(reverbFeedbackLevel * 1024.0f);
// Update Del objects if using legacy path
if (reverbInitiated && !useOptimizedReverb) {
delay1.setLevel(reverbFeedbackLevel);
delay2.setLevel(reverbFeedbackLevel);
delay3.setLevel(reverbFeedbackLevel);
delay4.setLevel(reverbFeedbackLevel);
}
allpass1.setFeedbackLevel(reverbFeedbackLevel * 0.95);
allpass2.setFeedbackLevel(reverbFeedbackLevel * 0.9);
}
/** Return the reverb length. */
float getReverbLength() {
return reverbFeedbackLevel;
}
/** Set the reverb amount
* @rMix The balance between dry and wet signal, as the amount of wet signal, from 0.0 to 1.0.
*/
inline
void setReverbMix(float rMix) {
reverbMix = max(0, min(1024, (int)(rMix * 1024.0f)));
// Serial.print("reverbMix ");Serial.println(reverbMix);
}
/** Return the reverb amount, 0.0 - 1.0 */
float getReverbMix() {
return reverbMix * 0.0009765625f;
}
/** Set dampening (high frequency absorption)
* @param damp 0.0-1.0, higher = more HF dampening (darker sound)
*/
void setDampening(float damp) {
damp = max(0.0f, min(1.0f, damp));
// Pre-calculate damping coefficient (0.7-1.0 range)
// Higher damp value = lower coefficient = more HF cut
int16_t dampInt = (int16_t)(damp * 1024.0f);
reverbDampCoeff = 717 + (((1024 - dampInt) * 307) >> 10);
}
/** Set the reverb memory size
* @newSize A multiple of the default, >= 1.0
* Larger sizes take up more memory
*/
inline
void setReverbSize(float newSize) {
reverbSize = max(1.0f, newSize);
initReverb(reverbSize);
}
/* This prevents PSRAM detection and memory allocation from happening in ISR context */
inline
void initReverbSafe() {
if (!reverbInitiated) {
// Trigger PSRAM diagnostics if not already done
isPSRAMAvailable();
initReverb(reverbSize);
// Pre-initialize allpass filters to prevent lazy init in audio tasks
allpass1.setDelayTime(49.6);
allpass1.setFeedbackLevel(0.83);
allpass2.setDelayTime(34.65);
allpass2.setFeedbackLevel(0.79);
// Force buffer allocation by calling next() once
allpass1.next(0);
allpass2.next(0);
reverb2Initiated = true;
Serial.println("Reverb and allpass filters pre-initialized");
}
}
/** A mono chorus using a modulated delay line.
* Based on Dattorro, Jon. 1997. Effect design, part 2: Delay line modulation and chorus.
* Journal of the Audio Engineering Society 45(10), 764–788.
* @audioIn A mono audio signal
*/
inline
int16_t chorus(int32_t audioIn) {
// set up first time called
if (!chorusInitiated) {
initChorus();
}
int16_t result = 0;
M16_ATOMIC_GUARD_BLOCKING(_fxLock, {
float chorusLfoVal = chorusLfo.next() * MAX_16_INV;
chorusDelay.setTime(chorusDelayTime + chorusLfoVal * chorusLfoWidth);
int32_t delVal = chorusDelay.next(audioIn);
int32_t inVal = (audioIn * (chorusMixInput))>>10;
delVal = (delVal * chorusMixDelay)>>10;
// Normalize output to prevent clipping
int32_t sum = inVal + delVal;
result = clip16((sum * chorusMixNorm)>>10);
});
return result;
}
/** A stereo chorus using two modulated delay lines.
* @audioInLeft An audio signal
* @audioInRight An audio signal
* @audioOutLeft A variable to receive audio output for the left channel
* @audioOutLeft A variable to receive audio output for the right channel
*/
inline
void chorusStereo(int32_t audioInLeft, int32_t audioInRight, int32_t &audioOutLeft, int32_t &audioOutRight) {
// set up first time called
if (!chorusInitiated) {
initChorus();
}
M16_ATOMIC_GUARD_BLOCKING(_fxLock, {
float chorusLfoVal = chorusLfo.next() * MAX_16_INV;
chorusDelay.setTime(chorusDelayTime + chorusLfoVal * chorusLfoWidth);
chorusDelay2.setTime(chorusDelayTime2 + chorusLfoVal * chorusLfoWidth);
int32_t delVal = chorusDelay.next(audioInLeft);
int32_t delVal2 = chorusDelay2.next(audioInRight);
int32_t inVal = (audioInLeft * (chorusMixInput))>>10;
int32_t inVal2 = (audioInRight * (chorusMixInput))>>10;
delVal = (delVal * chorusMixDelay)>>10;
delVal2 = (delVal2 * chorusMixDelay)>>10;
// Normalize output to prevent clipping
int32_t sumL = inVal + delVal;
int32_t sumR = inVal2 + delVal2;
audioOutLeft = clip16((sumL * chorusMixNorm)>>10);
audioOutRight = clip16((sumR * chorusMixNorm)>>10);
});
}
/** Set the chorus effect depth
* @depth amount of chorus to add to the input signal, 0.0 to 1.0
*/
inline
void setChorusDepth(float depth) {
depth = pow(depth, 0.8) * 0.5;
chorusMixInput = panLeft(depth) * 1024;
chorusMixDelay = panRight(depth) * 1024;
updateChorusMixNorm();
}
/** Set the chorus width
* @depth pitch width of chorus LFO, 0.0 to 1.0
*/
inline
void setChorusWidth(float depth) {
chorusLfoWidth = pow(max(0.0f, depth), 1.5) * 3.0d;
}
/** Set the chorus rate
* @rate pitch frequency of chorus LFO, in hertz. Typically 0.01 to 3.0
*/
inline
void setChorusRate(float rate) {
chorusLfoRate = rate;
chorusLfo.setFreq(chorusLfoRate);
}
/** Set the chorus feedback level
* @val feedback level of the chorus delay line, from 0.0 to 1.0
*/
inline
void setChorusFeedback(float val) {
chorusFeedback = val;
chorusDelay.setFeedback(true);
chorusDelay.setFeedbackLevel(max(0.0f, min(1.0f, chorusFeedback)));
chorusDelay2.setFeedback(true);
chorusDelay2.setFeedbackLevel(max(0.0f, min(1.0f, chorusFeedback)));
}
/** Set the chorus delay time
* @time delay time in ms, typically 20 to 40 ms
*/
inline
void setChorusDelayTime(float time) {
chorusDelayTime = min(40.0f, max(0.0f, time));
chorusDelayTime2 = min(40.0f, max(0.0f, time * 0.74f));
}
/** Smooth input signal using simple 1-pole lowpass filter
* @param input The next input sample value
* @param smoothingFactor Smoothing factor from 0.0 (no smoothing) to 1.0 (max smoothing - no output)
*/
int32_t smooth(int32_t input, float smoothingFactor) {
// Simple 1-pole lowpass filter for smoothing
prevSmoothValue += (int32_t)((input - prevSmoothValue) * (1.0f - smoothingFactor));
return prevSmoothValue;
}
/** Smooth left channel with separate state
* @param input The next input sample value
* @param smoothingFactor Smoothing factor from 0.0 (no smoothing) to 1.0 (max smoothing)
*/
int32_t smoothL(int32_t input, float smoothingFactor) {
prevSmoothValueL += (int32_t)((input - prevSmoothValueL) * (1.0f - smoothingFactor));
return prevSmoothValueL;
}
/** Smooth right channel with separate state
* @param input The next input sample value
* @param smoothingFactor Smoothing factor from 0.0 (no smoothing) to 1.0 (max smoothing)
*/
int32_t smoothR(int32_t input, float smoothingFactor) {
prevSmoothValueR += (int32_t)((input - prevSmoothValueR) * (1.0f - smoothingFactor));
return prevSmoothValueR;
}
/** Smooth stereo signal with separate state per channel
* @param inputL Left channel input
* @param inputR Right channel input
* @param outputL Reference to left channel output
* @param outputR Reference to right channel output
* @param smoothingFactor Smoothing factor from 0.0 (no smoothing) to 1.0 (max smoothing)
*/
void smoothStereo(int32_t inputL, int32_t inputR, int32_t &outputL, int32_t &outputR, float smoothingFactor) {
float coeff = 1.0f - smoothingFactor;
prevSmoothValueL += (int32_t)((inputL - prevSmoothValueL) * coeff);
prevSmoothValueR += (int32_t)((inputR - prevSmoothValueR) * coeff);
outputL = prevSmoothValueL;
outputR = prevSmoothValueR;
}
private:
/** Fast approximation of e^(-x) for x >= 0
* Uses (1 - x/n)^n approximation, accurate for 0 <= x <= 4
*/
inline float fastExpNeg(float x) {
// Approximate e^(-x) using (1 - x/8)^8
float t = 1.0f - x * 0.125f;
t = t * t; // ^2
t = t * t; // ^4
t = t * t; // ^8
return max(0.0f, t);
}
const static int16_t PLUCK_BUFFER_SIZE = 1500; // lowest MIDI pitch is 24
int * pluckBuffer; // [PLUCK_BUFFER_SIZE];
float pluck_buffer_write_index = 0;
int prevPluckOutput = 0;
bool pluckBufferEstablished = false;
// Bit crusher sample-and-hold state
int16_t crushHoldValue = 0;
int16_t crushHoldCounter = 0;
bool reverbInitiated = false;
float reverbFeedbackLevel = 0.93; // 0.0 to 1.0
int reverbMix = 40; // 0 to 1024
float reverbSize = 4.0; // >= 1, memory allocated to delay lengths
int16_t reverbFeedbackInt = 950; // 0-1024, integer version of feedback level
int16_t reverbDampCoeff = 904; // Pre-calculated dampening coefficient (0.3 default)
int32_t revFilterStore1 = 0, revFilterStore2 = 0, revFilterStore3 = 0, revFilterStore4 = 0;
int32_t revInputHPF_L = 0, revInputHPF_R = 0; // Input highpass filter state
// Optimized reverb delay buffers - power-of-2 sizes for fast modulo via bitwise AND
// Buffer sizes chosen to accommodate delay times up to reverbSize=16
static const int REV_BUF_BITS = 10; // 1024 samples = ~23ms at 44.1kHz
static const int REV_BUF_SIZE = 1 << REV_BUF_BITS; // 1024
static const int REV_BUF_MASK = REV_BUF_SIZE - 1; // 0x3FF for fast wrap
int16_t* revBuf1 = nullptr;
int16_t* revBuf2 = nullptr;
int16_t* revBuf3 = nullptr;
int16_t* revBuf4 = nullptr;
uint16_t revWritePos = 0; // Single write position for all buffers
uint16_t revDelay1 = 0, revDelay2 = 0, revDelay3 = 0, revDelay4 = 0; // Delay offsets in samples
// Legacy Del objects kept for API compatibility (setReverbSize with unusual sizes)
Del delay1, delay2, delay3, delay4;
bool useOptimizedReverb = false; // Flag to use optimized path
int32_t revD1, revD2, revD3, revD4, revP1, revP2, revP3, revP4, revP5, revP6, revM3, revM4, revM5, revM6;
int16_t * shapeTable;
int shapeTableSize = 0;
float waveShaperStepInc = MAX_16 * 2.0 * TABLE_SIZE_INV;
float waveShaperStepIncInv;
bool chorusInitiated = false;
int chorusDelayTime = 38;
int chorusDelayTime2 = 28;
float chorusLfoRate = 0.65; // hz
float chorusLfoWidth = 0.5; // ms
int chorusMixInput = 600; // 0 - 1024
int chorusMixDelay = 800; // 0 - 1024
int chorusMixNorm = 731; // normalization factor to prevent clipping (1024 * 1024 / (600 + 800))
float chorusFeedback = 0.4; // 0.0 to 1.0
int16_t * chorusLfoTable;
Osc chorusLfo;
Del chorusDelay, chorusDelay2;
All allpass1, allpass2;
bool reverb2Initiated = false;
int32_t allpassRevOut = 0;
// Half-rate reverb interpolation state
bool reverbInterpToggle = false;
int32_t reverbInterpPrevL = 0, reverbInterpPrevR = 0;
int32_t reverbInterpSmoothL = 0, reverbInterpSmoothR = 0;
int32_t prevSaturationOutput = 0;
EMA aveFilter;
int32_t prevSmoothValue = 0;
int32_t prevSmoothValueL = 0;