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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
use crate::synthesis::automation::Automation;
use crate::track::PRIORITY_MODULATION;
/// Standard audio sample rate
const DEFAULT_SAMPLE_RATE: f32 = 44100.0;
#[derive(Debug, Clone)]
struct AllPassFilter {
z1: f32,
}
impl AllPassFilter {
fn new() -> Self {
Self { z1: 0.0 }
}
fn process(&mut self, input: f32, delay_samples: f32) -> f32 {
let coefficient = (1.0 - delay_samples) / (1.0 + delay_samples);
let output = -input + self.z1;
self.z1 = input + coefficient * output;
output
}
}
/// Chorus - creates thickness by layering detuned copies
#[derive(Debug, Clone)]
pub struct Chorus {
pub rate: f32, // LFO rate in Hz (typical: 0.5 to 3.0)
pub depth: f32, // Modulation depth in milliseconds (typical: 2.0 to 10.0)
pub mix: f32, // Wet/dry mix (0.0 = dry, 1.0 = wet)
pub priority: u8, // Processing priority (lower = earlier in signal chain)
buffer: Vec<f32>,
write_pos: usize,
buffer_mask: usize, // Bit mask for fast modulo
lfo_phase: f32,
// Automation (optional)
rate_automation: Option<Automation>,
depth_automation: Option<Automation>,
mix_automation: Option<Automation>,
}
impl Chorus {
/// Create a new chorus effect
///
/// # Arguments
/// * `rate` - LFO speed in Hz (0.1 to 5.0, typical: 1.0)
/// * `depth` - Modulation depth in milliseconds (1.0 to 20.0, typical: 5.0)
/// * `mix` - Wet/dry mix (0.0 = dry, 1.0 = wet)
pub fn new(rate: f32, depth: f32, mix: f32) -> Self {
Self::with_sample_rate(rate, depth, mix, DEFAULT_SAMPLE_RATE)
}
/// Create a new chorus effect with custom sample rate
pub fn with_sample_rate(rate: f32, depth: f32, mix: f32, sample_rate: f32) -> Self {
// Buffer size needs to accommodate maximum delay
let max_delay_samples = ((depth * 2.0) * sample_rate / 1000.0) as usize;
// Round up to next power of 2 for fast modulo via bitwise AND
let buffer_size = max_delay_samples.max(1).next_power_of_two();
let buffer_mask = buffer_size - 1;
Self {
rate: rate.clamp(0.1, 10.0),
depth: depth.clamp(0.5, 50.0),
mix: mix.clamp(0.0, 1.0),
priority: PRIORITY_MODULATION, // Modulation effects in middle-late position
buffer: vec![0.0; buffer_size],
write_pos: 0,
buffer_mask,
lfo_phase: 0.0,
rate_automation: None,
depth_automation: None,
mix_automation: None,
}
}
/// Set the processing priority (lower = earlier in signal chain)
pub fn with_priority(mut self, priority: u8) -> Self {
self.priority = priority;
self
}
/// Add automation for the mix parameter
pub fn with_mix_automation(mut self, automation: Automation) -> Self {
self.mix_automation = Some(automation);
self
}
/// Add automation for the rate parameter
pub fn with_rate_automation(mut self, automation: Automation) -> Self {
self.rate_automation = Some(automation);
self
}
/// Add automation for the depth parameter
pub fn with_depth_automation(mut self, automation: Automation) -> Self {
self.depth_automation = Some(automation);
self
}
/// Process a single sample at given sample rate
///
/// # Arguments
/// * `input` - Input sample
/// * `sample_rate` - Sample rate in Hz
/// * `time` - Current time in seconds (for automation)
/// * `sample_count` - Global sample counter (for quantized automation lookups)
#[inline]
pub fn process(&mut self, input: f32, sample_rate: f32, time: f32, sample_count: u64) -> f32 {
// Quantized automation lookups (every 64 samples = 1.45ms @ 44.1kHz)
// Use bitwise AND instead of modulo for power-of-2
if sample_count & 63 == 0 {
if let Some(auto) = &self.mix_automation {
self.mix = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.rate_automation {
self.rate = auto.value_at(time).clamp(0.1, 10.0);
}
if let Some(auto) = &self.depth_automation {
self.depth = auto.value_at(time).clamp(0.5, 50.0);
}
}
if self.mix < 0.0001 {
return input;
}
// Write input to buffer
self.buffer[self.write_pos] = input;
// Calculate modulated delay time using sine LFO
let lfo = (self.lfo_phase * 2.0 * std::f32::consts::PI).sin();
let delay_ms = self.depth.mul_add(0.5 + 0.5 * lfo, 0.0);
let delay_samples = ((delay_ms * sample_rate / 1000.0) as usize) & self.buffer_mask;
// Read from delayed position using bitwise AND (~10x faster!)
let read_pos = (self.write_pos + self.buffer.len() - delay_samples) & self.buffer_mask;
let delayed = self.buffer[read_pos];
// Advance LFO phase
self.lfo_phase += self.rate / sample_rate;
if self.lfo_phase >= 1.0 {
self.lfo_phase -= 1.0;
}
// Advance write position using bitwise AND (~10x faster!)
self.write_pos = (self.write_pos + 1) & self.buffer_mask;
// Mix dry and wet using FMA
input.mul_add(1.0 - self.mix, delayed * self.mix)
}
/// Process a block of samples with optimized buffer processing
///
/// # Arguments
/// * `buffer` - Buffer of samples to process in-place
/// * `sample_rate` - Sample rate in Hz
/// * `time` - Starting time in seconds (for automation)
/// * `sample_count` - Starting sample counter (for quantized automation lookups)
#[inline]
pub fn process_block(
&mut self,
buffer: &mut [f32],
sample_rate: f32,
time: f32,
sample_count: u64,
) {
// Update automation parameters once at buffer start (quantized to 64-sample blocks)
if sample_count & 63 == 0 {
if let Some(auto) = &self.mix_automation {
self.mix = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.rate_automation {
self.rate = auto.value_at(time).clamp(0.1, 10.0);
}
if let Some(auto) = &self.depth_automation {
self.depth = auto.value_at(time).clamp(0.5, 50.0);
}
}
// Early exit if effect is bypassed
if self.mix < 0.0001 {
return;
}
// Pre-calculate constants once for entire buffer
let mix_wet = self.mix;
let mix_dry = 1.0 - self.mix;
let lfo_phase_increment = self.rate / sample_rate;
let two_pi = 2.0 * std::f32::consts::PI;
let depth = self.depth;
let sample_rate_ms = sample_rate / 1000.0;
// Process entire buffer
for sample in buffer.iter_mut() {
let input = *sample;
// Write input to buffer
self.buffer[self.write_pos] = input;
// Calculate modulated delay time using sine LFO
let lfo = (self.lfo_phase * two_pi).sin();
let delay_ms = depth.mul_add(0.5 + 0.5 * lfo, 0.0);
let delay_samples = ((delay_ms * sample_rate_ms) as usize) & self.buffer_mask;
// Read from delayed position using bitwise AND (~10x faster!)
let read_pos = (self.write_pos + self.buffer.len() - delay_samples) & self.buffer_mask;
let delayed = self.buffer[read_pos];
// Advance LFO phase
self.lfo_phase += lfo_phase_increment;
if self.lfo_phase >= 1.0 {
self.lfo_phase -= 1.0;
}
// Advance write position using bitwise AND (~10x faster!)
self.write_pos = (self.write_pos + 1) & self.buffer_mask;
// Mix dry and wet using FMA
*sample = input.mul_add(mix_dry, delayed * mix_wet);
}
}
/// Reset the chorus state
pub fn reset(&mut self) {
self.buffer.fill(0.0);
self.write_pos = 0;
self.lfo_phase = 0.0;
}
// ========== PRESETS ==========
/// Subtle chorus - gentle thickening
pub fn subtle() -> Self {
Self::new(0.5, 3.0, 0.3)
}
/// Classic chorus - 80s style chorus effect
pub fn classic() -> Self {
Self::new(1.5, 5.0, 0.5)
}
/// Wide chorus - expansive stereo spread
pub fn wide() -> Self {
Self::new(0.8, 8.0, 0.6)
}
/// Vibrato - 100% wet for pitch modulation
pub fn vibrato() -> Self {
Self::new(5.0, 3.0, 1.0)
}
/// Thick - dense, layered sound
pub fn thick() -> Self {
Self::new(2.0, 7.0, 0.7)
}
}
/// Phaser - creates sweeping notches in the frequency spectrum
#[derive(Debug, Clone)]
pub struct Phaser {
pub rate: f32, // LFO rate in Hz (typical: 0.1 to 5.0)
pub depth: f32, // Modulation depth (0.0 to 1.0)
pub feedback: f32, // Feedback amount (0.0 to 0.95)
pub mix: f32, // Wet/dry mix (0.0 = dry, 1.0 = wet)
pub stages: usize, // Number of all-pass filter stages (2, 4, 6, or 8)
pub priority: u8, // Processing priority (lower = earlier in signal chain)
allpass_states: Vec<AllPassFilter>,
lfo_phase: f32,
// Automation (optional)
rate_automation: Option<Automation>,
depth_automation: Option<Automation>,
feedback_automation: Option<Automation>,
mix_automation: Option<Automation>,
}
impl Phaser {
/// Create a new phaser effect
///
/// # Arguments
/// * `rate` - LFO speed in Hz (0.1 to 5.0, typical: 0.5)
/// * `depth` - Modulation depth (0.0 to 1.0, typical: 0.7)
/// * `feedback` - Feedback amount (0.0 to 0.95, typical: 0.5)
/// * `stages` - Number of stages (2, 4, 6, or 8, typical: 4)
/// * `mix` - Wet/dry mix (0.0 = dry, 1.0 = wet, typical: 0.5)
pub fn new(rate: f32, depth: f32, feedback: f32, stages: usize, mix: f32) -> Self {
Self::with_sample_rate(rate, depth, feedback, stages, mix, DEFAULT_SAMPLE_RATE)
}
/// Create a new phaser effect
///
/// Note: sample_rate parameter is ignored (kept for API compatibility).
/// The actual sample rate is provided during processing.
pub fn with_sample_rate(
rate: f32,
depth: f32,
feedback: f32,
stages: usize,
mix: f32,
_sample_rate: f32,
) -> Self {
let stages = stages.clamp(2, 8);
Self {
rate,
depth: depth.clamp(0.0, 1.0),
feedback: feedback.clamp(0.0, 0.95),
mix: mix.clamp(0.0, 1.0),
stages,
priority: PRIORITY_MODULATION, // Modulation effects in middle-late position
allpass_states: vec![AllPassFilter::new(); stages],
lfo_phase: 0.0,
rate_automation: None,
depth_automation: None,
feedback_automation: None,
mix_automation: None,
}
}
/// Set the processing priority (lower = earlier in signal chain)
pub fn with_priority(mut self, priority: u8) -> Self {
self.priority = priority;
self
}
/// Add automation for the mix parameter
pub fn with_mix_automation(mut self, automation: Automation) -> Self {
self.mix_automation = Some(automation);
self
}
/// Add automation for the rate parameter
pub fn with_rate_automation(mut self, automation: Automation) -> Self {
self.rate_automation = Some(automation);
self
}
/// Add automation for the depth parameter
pub fn with_depth_automation(mut self, automation: Automation) -> Self {
self.depth_automation = Some(automation);
self
}
/// Add automation for the feedback parameter
pub fn with_feedback_automation(mut self, automation: Automation) -> Self {
self.feedback_automation = Some(automation);
self
}
/// Process a single sample
///
/// # Arguments
/// * `input` - Input sample
/// * `sample_rate` - Sample rate in Hz
/// * `time` - Current time in seconds (for automation)
/// * `sample_count` - Global sample counter (for quantized automation lookups)
#[inline]
pub fn process(&mut self, input: f32, sample_rate: f32, time: f32, sample_count: u64) -> f32 {
// Quantized automation lookups (every 64 samples = 1.45ms @ 44.1kHz)
if sample_count & 63 == 0 {
if let Some(auto) = &self.mix_automation {
self.mix = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.rate_automation {
self.rate = auto.value_at(time).clamp(0.1, 10.0);
}
if let Some(auto) = &self.depth_automation {
self.depth = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.feedback_automation {
self.feedback = auto.value_at(time).clamp(0.0, 0.95);
}
}
if self.mix < 0.0001 || self.depth < 0.0001 {
return input;
}
// Generate LFO
let lfo = (self.lfo_phase * 2.0 * std::f32::consts::PI).sin();
// Map LFO to delay range (affects frequency of notches) using FMA
let min_delay = 0.5;
let max_delay = 5.0;
let delay = (0.5 + 0.5 * lfo * self.depth).mul_add(max_delay - min_delay, min_delay);
// Process through all-pass filter stages
let mut output = input;
for filter in &mut self.allpass_states {
output = filter.process(output, delay);
}
// Apply feedback using FMA
let feedback_sample = output * self.feedback;
output = input + feedback_sample;
// Advance LFO phase
self.lfo_phase += self.rate / sample_rate;
if self.lfo_phase >= 1.0 {
self.lfo_phase -= 1.0;
}
// Mix dry and wet using FMA
input.mul_add(1.0 - self.mix, output * self.mix)
}
/// Process a block of samples with optimized buffer processing
///
/// # Arguments
/// * `buffer` - Buffer of samples to process in-place
/// * `sample_rate` - Sample rate in Hz
/// * `time` - Starting time in seconds (for automation)
/// * `sample_count` - Starting sample counter (for quantized automation lookups)
#[inline]
pub fn process_block(
&mut self,
buffer: &mut [f32],
sample_rate: f32,
time: f32,
sample_count: u64,
) {
// Update automation parameters once at buffer start (quantized to 64-sample blocks)
if sample_count & 63 == 0 {
if let Some(auto) = &self.mix_automation {
self.mix = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.rate_automation {
self.rate = auto.value_at(time).clamp(0.1, 10.0);
}
if let Some(auto) = &self.depth_automation {
self.depth = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.feedback_automation {
self.feedback = auto.value_at(time).clamp(0.0, 0.95);
}
}
// Early exit if effect is bypassed
if self.mix < 0.0001 || self.depth < 0.0001 {
return;
}
// Pre-calculate constants once for entire buffer
let mix_wet = self.mix;
let mix_dry = 1.0 - self.mix;
let lfo_phase_increment = self.rate / sample_rate;
let two_pi = 2.0 * std::f32::consts::PI;
let depth = self.depth;
let feedback = self.feedback;
let min_delay = 0.5;
let max_delay = 5.0;
let delay_range = max_delay - min_delay;
// Process entire buffer
for sample in buffer.iter_mut() {
let input = *sample;
// Generate LFO
let lfo = (self.lfo_phase * two_pi).sin();
// Map LFO to delay range (affects frequency of notches) using FMA
let delay = (0.5 + 0.5 * lfo * depth).mul_add(delay_range, min_delay);
// Process through all-pass filter stages
let mut output = input;
for filter in &mut self.allpass_states {
output = filter.process(output, delay);
}
// Apply feedback using FMA
let feedback_sample = output * feedback;
output = input + feedback_sample;
// Advance LFO phase
self.lfo_phase += lfo_phase_increment;
if self.lfo_phase >= 1.0 {
self.lfo_phase -= 1.0;
}
// Mix dry and wet using FMA
*sample = input.mul_add(mix_dry, output * mix_wet);
}
}
/// Reset the phaser state
pub fn reset(&mut self) {
self.allpass_states = vec![AllPassFilter::new(); self.stages];
self.lfo_phase = 0.0;
}
// ========== PRESETS ==========
/// Slow phaser - gentle sweep (0.3 Hz)
pub fn slow() -> Self {
Self::new(0.3, 0.7, 0.5, 4, 0.5)
}
/// Classic phaser - 70s style phasing (0.5 Hz, 4 stages)
pub fn classic() -> Self {
Self::new(0.5, 0.8, 0.6, 4, 0.6)
}
/// Fast phaser - intense modulation (2.0 Hz, 6 stages)
pub fn fast() -> Self {
Self::new(2.0, 0.9, 0.7, 6, 0.7)
}
/// Subtle phaser - barely-there swoosh (0.4 Hz, mild depth)
pub fn subtle() -> Self {
Self::new(0.4, 0.5, 0.3, 4, 0.4)
}
/// Deep phaser - thick, resonant sweep (0.6 Hz, 8 stages)
pub fn deep() -> Self {
Self::new(0.6, 1.0, 0.8, 8, 0.8)
}
}
/// Flanger - creates jet-plane/swoosh effects with very short delays
#[derive(Debug, Clone)]
pub struct Flanger {
pub rate: f32, // LFO rate in Hz (typical: 0.1 to 2.0)
pub depth: f32, // Modulation depth in milliseconds (typical: 1.0 to 5.0)
pub feedback: f32, // Feedback amount (0.0 to 0.95)
pub mix: f32, // Wet/dry mix (0.0 = dry, 1.0 = wet)
pub priority: u8, // Processing priority (lower = earlier in signal chain)
buffer: Vec<f32>,
write_pos: usize,
buffer_mask: usize, // Bit mask for fast modulo
lfo_phase: f32,
// Automation (optional)
rate_automation: Option<Automation>,
depth_automation: Option<Automation>,
feedback_automation: Option<Automation>,
mix_automation: Option<Automation>,
}
impl Flanger {
/// Create a new flanger effect
///
/// # Arguments
/// * `rate` - LFO speed in Hz (0.1 to 2.0, typical: 0.5)
/// * `depth` - Modulation depth in milliseconds (1.0 to 10.0, typical: 3.0)
/// * `feedback` - Feedback amount (0.0 to 0.95, typical: 0.6)
/// * `mix` - Wet/dry mix (0.0 = dry, 1.0 = wet, typical: 0.5)
pub fn new(rate: f32, depth: f32, feedback: f32, mix: f32) -> Self {
Self::with_sample_rate(rate, depth, feedback, mix, DEFAULT_SAMPLE_RATE)
}
/// Create a new flanger effect
///
/// Note: sample_rate parameter is used only to estimate buffer size.
/// The actual sample rate for processing is provided during process().
pub fn with_sample_rate(
rate: f32,
depth: f32,
feedback: f32,
mix: f32,
sample_rate: f32,
) -> Self {
// Buffer size needs to accommodate maximum delay (in samples)
// Use provided sample_rate for initial buffer sizing
let max_delay_samples = ((depth * 2.0) * sample_rate / 1000.0) as usize;
// Round up to next power of 2 for fast modulo via bitwise AND
let buffer_size = max_delay_samples.max(1).next_power_of_two();
let buffer_mask = buffer_size - 1;
Self {
rate,
depth,
feedback: feedback.clamp(0.0, 0.95),
mix: mix.clamp(0.0, 1.0),
priority: PRIORITY_MODULATION, // Modulation effects in middle-late position
buffer: vec![0.0; buffer_size],
write_pos: 0,
buffer_mask,
lfo_phase: 0.0,
rate_automation: None,
depth_automation: None,
feedback_automation: None,
mix_automation: None,
}
}
/// Set the processing priority (lower = earlier in signal chain)
pub fn with_priority(mut self, priority: u8) -> Self {
self.priority = priority;
self
}
/// Add automation for the mix parameter
pub fn with_mix_automation(mut self, automation: Automation) -> Self {
self.mix_automation = Some(automation);
self
}
/// Add automation for the rate parameter
pub fn with_rate_automation(mut self, automation: Automation) -> Self {
self.rate_automation = Some(automation);
self
}
/// Add automation for the depth parameter
pub fn with_depth_automation(mut self, automation: Automation) -> Self {
self.depth_automation = Some(automation);
self
}
/// Add automation for the feedback parameter
pub fn with_feedback_automation(mut self, automation: Automation) -> Self {
self.feedback_automation = Some(automation);
self
}
/// Process a single sample
///
/// # Arguments
/// * `input` - Input sample
/// * `sample_rate` - Sample rate in Hz
/// * `time` - Current time in seconds (for automation)
/// * `sample_count` - Global sample counter (for quantized automation lookups)
#[inline]
pub fn process(&mut self, input: f32, sample_rate: f32, time: f32, sample_count: u64) -> f32 {
// Quantized automation lookups (every 64 samples = 1.45ms @ 44.1kHz)
if sample_count & 63 == 0 {
if let Some(auto) = &self.mix_automation {
self.mix = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.rate_automation {
self.rate = auto.value_at(time).clamp(0.1, 10.0);
}
if let Some(auto) = &self.depth_automation {
self.depth = auto.value_at(time).clamp(0.5, 50.0);
}
if let Some(auto) = &self.feedback_automation {
self.feedback = auto.value_at(time).clamp(0.0, 0.95);
}
}
// Safety check: if buffer is empty, just pass through
if self.buffer.is_empty() || self.mix < 0.0001 {
return input;
}
// Calculate modulated delay time using sine LFO with FMA
let lfo = (self.lfo_phase * 2.0 * std::f32::consts::PI).sin();
let delay_ms = self.depth.mul_add(0.5 + 0.5 * lfo, 0.0); // 0 to depth milliseconds
let delay_samples = ((delay_ms * sample_rate / 1000.0) as usize) & self.buffer_mask;
// Read from delayed position using bitwise AND (no branches!)
let read_pos = (self.write_pos + self.buffer.len() - delay_samples) & self.buffer_mask;
let delayed = self.buffer[read_pos];
// Write to buffer with feedback using FMA
self.buffer[self.write_pos] = delayed.mul_add(self.feedback, input);
// Advance LFO phase
self.lfo_phase += self.rate / sample_rate;
if self.lfo_phase >= 1.0 {
self.lfo_phase -= 1.0;
}
// Advance write position using bitwise AND (~10x faster!)
self.write_pos = (self.write_pos + 1) & self.buffer_mask;
// Mix dry and wet using FMA
input.mul_add(1.0 - self.mix, delayed * self.mix)
}
/// Process a block of samples with optimized buffer processing
///
/// # Arguments
/// * `buffer` - Buffer of samples to process in-place
/// * `sample_rate` - Sample rate in Hz
/// * `time` - Starting time in seconds (for automation)
/// * `sample_count` - Starting sample counter (for quantized automation lookups)
#[inline]
pub fn process_block(
&mut self,
buffer: &mut [f32],
sample_rate: f32,
time: f32,
sample_count: u64,
) {
// Update automation parameters once at buffer start (quantized to 64-sample blocks)
if sample_count & 63 == 0 {
if let Some(auto) = &self.mix_automation {
self.mix = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.rate_automation {
self.rate = auto.value_at(time).clamp(0.1, 10.0);
}
if let Some(auto) = &self.depth_automation {
self.depth = auto.value_at(time).clamp(0.5, 50.0);
}
if let Some(auto) = &self.feedback_automation {
self.feedback = auto.value_at(time).clamp(0.0, 0.95);
}
}
// Safety check: if buffer is empty, just pass through
if self.buffer.is_empty() || self.mix < 0.0001 {
return;
}
// Pre-calculate constants once for entire buffer
let mix_wet = self.mix;
let mix_dry = 1.0 - self.mix;
let lfo_phase_increment = self.rate / sample_rate;
let two_pi = 2.0 * std::f32::consts::PI;
let depth = self.depth;
let feedback = self.feedback;
let sample_rate_ms = sample_rate / 1000.0;
// Process entire buffer
for sample in buffer.iter_mut() {
let input = *sample;
// Calculate modulated delay time using sine LFO with FMA
let lfo = (self.lfo_phase * two_pi).sin();
let delay_ms = depth.mul_add(0.5 + 0.5 * lfo, 0.0);
let delay_samples = ((delay_ms * sample_rate_ms) as usize) & self.buffer_mask;
// Read from delayed position using bitwise AND (no branches!)
let read_pos = (self.write_pos + self.buffer.len() - delay_samples) & self.buffer_mask;
let delayed = self.buffer[read_pos];
// Write to buffer with feedback using FMA
self.buffer[self.write_pos] = delayed.mul_add(feedback, input);
// Advance LFO phase
self.lfo_phase += lfo_phase_increment;
if self.lfo_phase >= 1.0 {
self.lfo_phase -= 1.0;
}
// Advance write position using bitwise AND (~10x faster!)
self.write_pos = (self.write_pos + 1) & self.buffer_mask;
// Mix dry and wet using FMA
*sample = input.mul_add(mix_dry, delayed * mix_wet);
}
}
/// Reset the flanger state
pub fn reset(&mut self) {
self.buffer.fill(0.0);
self.write_pos = 0;
self.lfo_phase = 0.0;
}
// ========== PRESETS ==========
/// Subtle flanger - gentle swoosh (0.5 Hz)
pub fn subtle() -> Self {
Self::new(0.5, 2.0, 0.3, 0.4)
}
/// Classic flanger - balanced flanging effect (1.0 Hz)
pub fn classic() -> Self {
Self::new(1.0, 3.0, 0.5, 0.6)
}
/// Jet flanger - dramatic jet-plane effect (2.0 Hz, high feedback)
pub fn jet() -> Self {
Self::new(2.0, 5.0, 0.8, 0.8)
}
/// Through-zero flanger - authentic through-zero sound (1.0 Hz)
pub fn through_zero() -> Self {
Self::new(1.0, 4.0, 0.9, 1.0)
}
/// Metallic flanger - sharp, resonant (1.5 Hz, high feedback)
pub fn metallic() -> Self {
Self::new(1.5, 4.5, 0.85, 0.85)
}
}
/// Ring Modulator - creates metallic/robotic inharmonic tones
#[derive(Debug, Clone)]
pub struct RingModulator {
pub carrier_freq: f32, // Carrier frequency in Hz (typical: 50 to 5000)
pub mix: f32, // Wet/dry mix (0.0 = dry, 1.0 = wet)
pub priority: u8, // Processing priority (lower = earlier in signal chain)
phase: f32,
// Pre-allocated buffers for SIMD processing (grow once, then reused)
modulation_buffer: Vec<f32>,
dry_buffer: Vec<f32>,
// Automation (optional)
carrier_freq_automation: Option<Automation>,
mix_automation: Option<Automation>,
}
impl RingModulator {
/// Create a new ring modulator effect
///
/// # Arguments
/// * `carrier_freq` - Carrier frequency in Hz (50 to 5000, typical: 440)
/// * `mix` - Wet/dry mix (0.0 = dry, 1.0 = wet, typical: 0.7)
pub fn new(carrier_freq: f32, mix: f32) -> Self {
Self::with_sample_rate(carrier_freq, mix, DEFAULT_SAMPLE_RATE)
}
/// Create a new ring modulator effect with custom sample rate
/// Note: sample_rate parameter is kept for API compatibility but ignored.
/// The actual sample rate is provided at runtime during processing.
pub fn with_sample_rate(carrier_freq: f32, mix: f32, _sample_rate: f32) -> Self {
Self {
carrier_freq,
mix: mix.clamp(0.0, 1.0),
priority: PRIORITY_MODULATION, // Modulation effects in middle-late position
phase: 0.0,
modulation_buffer: Vec::new(),
dry_buffer: Vec::new(),
carrier_freq_automation: None,
mix_automation: None,
}
}
/// Set the processing priority (lower = earlier in signal chain)
pub fn with_priority(mut self, priority: u8) -> Self {
self.priority = priority;
self
}
/// Add automation for the mix parameter
pub fn with_mix_automation(mut self, automation: Automation) -> Self {
self.mix_automation = Some(automation);
self
}
/// Add automation for the carrier frequency parameter
pub fn with_carrier_freq_automation(mut self, automation: Automation) -> Self {
self.carrier_freq_automation = Some(automation);
self
}
/// Process a single sample
///
/// # Arguments
/// * `input` - Input sample
/// * `sample_rate` - Audio sample rate in Hz (provided by the engine at runtime)
/// * `time` - Current time in seconds (for automation)
/// * `sample_count` - Global sample counter (for quantized automation lookups)
#[inline]
pub fn process(&mut self, input: f32, sample_rate: f32, time: f32, sample_count: u64) -> f32 {
// Quantized automation lookups (every 64 samples = 1.45ms @ 44.1kHz)
if sample_count & 63 == 0 {
if let Some(auto) = &self.mix_automation {
self.mix = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.carrier_freq_automation {
self.carrier_freq = auto.value_at(time).clamp(20.0, 10000.0);
}
}
if self.mix < 0.0001 {
return input;
}
// Generate carrier sine wave using fast wavetable lookup
let carrier = crate::synthesis::wavetable::WAVETABLE.sample(self.phase);
// Ring modulation = multiplication
let modulated = input * carrier;
// Advance phase
self.phase += self.carrier_freq / sample_rate;
if self.phase >= 1.0 {
self.phase -= 1.0;
}
// Mix dry and wet using FMA
input.mul_add(1.0 - self.mix, modulated * self.mix)
}
/// Process a block of samples with SIMD acceleration
///
/// # Arguments
/// * `buffer` - Buffer of samples to process in-place
/// * `sample_rate` - Sample rate in Hz
/// * `time` - Starting time in seconds (for automation)
/// * `sample_count` - Starting sample counter (for quantized automation lookups)
#[inline]
pub fn process_block(
&mut self,
buffer: &mut [f32],
sample_rate: f32,
time: f32,
sample_count: u64,
) {
use crate::synthesis::simd::SIMD;
// Update automation params if needed
if sample_count & 63 == 0 {
if let Some(auto) = &self.mix_automation {
self.mix = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.carrier_freq_automation {
self.carrier_freq = auto.value_at(time).clamp(20.0, 10000.0);
}
}
// Early exit if no effect
if self.mix < 0.0001 {
return;
}
// TRUE SIMD implementation using multiply_buffers()
let phase_increment = self.carrier_freq / sample_rate;
let mix = self.mix;
// Reuse pre-allocated buffers (grow once, then reused)
self.modulation_buffer.clear();
self.modulation_buffer.reserve(buffer.len());
self.dry_buffer.clear();
self.dry_buffer.extend_from_slice(buffer);
// Generate carrier wave (scalar - can't vectorize wavetable lookup)
for _ in 0..buffer.len() {
let carrier = crate::synthesis::wavetable::WAVETABLE.sample(self.phase);
self.modulation_buffer.push(carrier);
self.phase += phase_increment;
if self.phase >= 1.0 {
self.phase -= 1.0;
}
}
// Apply ring modulation using TRUE SIMD
SIMD.multiply_buffers(buffer, &self.modulation_buffer);
// Wet/dry mix: output = dry * (1-mix) + wet * mix
// Currently in buffer: wet signal
// In dry_buffer: dry signal
let wet_gain = mix;
let dry_gain = 1.0 - mix;
// SIMD-optimized wet/dry mix
SIMD.multiply_const(buffer, wet_gain);
for (output, &dry_sample) in buffer.iter_mut().zip(self.dry_buffer.iter()) {
*output = dry_sample.mul_add(dry_gain, *output);
}
}
/// Reset the ring modulator state
pub fn reset(&mut self) {
self.phase = 0.0;
}
// ========== PRESETS ==========
/// Metallic - classic ring mod tone (440 Hz carrier)
pub fn metallic() -> Self {
Self::new(440.0, 0.7)
}
/// Robotic - mid-range carrier for voice effects (220 Hz)
pub fn robotic() -> Self {
Self::new(220.0, 0.8)
}
/// Bell-like - high carrier for bell tones (880 Hz)
pub fn bell() -> Self {
Self::new(880.0, 0.6)
}
/// Deep - low carrier for sub-bass effects (110 Hz)
pub fn deep() -> Self {
Self::new(110.0, 0.75)
}
/// Harsh - high carrier for aggressive tones (1760 Hz)
pub fn harsh() -> Self {
Self::new(1760.0, 0.9)
}
/// Subtle - gentle inharmonic color (330 Hz)
pub fn subtle() -> Self {
Self::new(330.0, 0.4)
}
}
/// Tremolo - rhythmic amplitude modulation
///
/// Creates periodic volume changes, adding rhythmic movement to the signal.
/// Lower frequency rates (< 10 Hz) create a pulsing effect, while higher rates
/// can create vibrato-like timbral changes.
#[derive(Debug, Clone)]
pub struct Tremolo {
pub rate: f32, // LFO rate in Hz (typically 1-20 Hz)
pub depth: f32, // Modulation depth 0.0 to 1.0
pub priority: u8, // Processing priority
phase: f32, // LFO phase (0.0 to 1.0)
// Pre-allocated buffer for SIMD processing (grows once, then reused)
modulation_buffer: Vec<f32>,
// Automation (optional)
rate_automation: Option<Automation>,
depth_automation: Option<Automation>,
}
impl Tremolo {
/// Create a new tremolo effect
///
/// # Arguments
/// * `rate` - LFO frequency in Hz (typically 1-20 Hz)
/// * `depth` - Modulation depth 0.0 (no effect) to 1.0 (full tremolo)
/// * `sample_rate` - Audio sample rate in Hz (kept for API compatibility but ignored)
///
/// **Note:** The actual sample rate is provided at runtime during processing.
pub fn with_sample_rate(rate: f32, depth: f32, _sample_rate: f32) -> Self {
Self {
rate: rate.max(0.01),
depth: depth.clamp(0.0, 1.0),
priority: PRIORITY_MODULATION,
phase: 0.0,
modulation_buffer: Vec::new(),
rate_automation: None,
depth_automation: None,
}
}
/// Create a tremolo with default sample rate (44100 Hz)
pub fn new(rate: f32, depth: f32) -> Self {
Self::with_sample_rate(rate, depth, DEFAULT_SAMPLE_RATE)
}
/// Set the processing priority (lower = earlier in signal chain)
pub fn with_priority(mut self, priority: u8) -> Self {
self.priority = priority;
self
}
/// Add automation for the rate parameter
pub fn with_rate_automation(mut self, automation: Automation) -> Self {
self.rate_automation = Some(automation);
self
}
/// Add automation for the depth parameter
pub fn with_depth_automation(mut self, automation: Automation) -> Self {
self.depth_automation = Some(automation);
self
}
/// Process a single sample
///
/// # Arguments
/// * `input` - Input sample
/// * `sample_rate` - Audio sample rate in Hz (provided by the engine at runtime)
/// * `time` - Current time in seconds (for automation)
/// * `sample_count` - Global sample counter (for quantized automation lookups)
#[inline]
pub fn process(&mut self, input: f32, sample_rate: f32, time: f32, sample_count: u64) -> f32 {
// Quantized automation lookups (every 64 samples)
if sample_count & 63 == 0 {
if let Some(auto) = &self.rate_automation {
self.rate = auto.value_at(time).max(0.01);
}
if let Some(auto) = &self.depth_automation {
self.depth = auto.value_at(time).clamp(0.0, 1.0);
}
}
// Early out if no modulation
if self.depth < 0.0001 {
return input;
}
// Generate LFO (sine wave)
let lfo = (self.phase * 2.0 * std::f32::consts::PI).sin();
// Convert bipolar LFO (-1 to 1) to unipolar modulation
// depth controls how much the volume varies
let modulation = 1.0 - (self.depth * (1.0 - lfo) * 0.5);
// Advance phase
self.phase += self.rate / sample_rate;
if self.phase >= 1.0 {
self.phase -= 1.0;
}
input * modulation
}
/// Process a block of samples with SIMD acceleration
///
/// # Arguments
/// * `buffer` - Buffer of samples to process in-place
/// * `sample_rate` - Sample rate in Hz
/// * `time` - Starting time in seconds (for automation)
/// * `sample_count` - Starting sample counter (for quantized automation lookups)
#[inline]
pub fn process_block(
&mut self,
buffer: &mut [f32],
sample_rate: f32,
time: f32,
sample_count: u64,
) {
use crate::synthesis::simd::SIMD;
// Update automation params if needed
if sample_count & 63 == 0 {
if let Some(auto) = &self.rate_automation {
self.rate = auto.value_at(time).clamp(0.1, 100.0);
}
if let Some(auto) = &self.depth_automation {
self.depth = auto.value_at(time).clamp(0.0, 1.0);
}
}
// Early exit if no effect
if self.depth < 0.0001 {
return;
}
// TRUE SIMD implementation using multiply_buffers()
use std::f32::consts::PI;
let phase_increment = self.rate / sample_rate;
let depth = self.depth;
let two_pi = 2.0 * PI;
// Reuse pre-allocated buffer (grows once, then reused)
self.modulation_buffer.clear();
self.modulation_buffer.reserve(buffer.len());
// Generate LFO modulation values (scalar - can't vectorize sin())
for _ in 0..buffer.len() {
let lfo = (self.phase * two_pi).sin();
// Convert bipolar LFO (-1 to 1) to unipolar amplitude modulation
let modulation = 1.0 - (depth * (1.0 - lfo) * 0.5);
self.modulation_buffer.push(modulation);
self.phase += phase_increment;
if self.phase >= 1.0 {
self.phase -= 1.0;
}
}
// Apply tremolo using TRUE SIMD
SIMD.multiply_buffers(buffer, &self.modulation_buffer);
}
/// Reset the tremolo state
pub fn reset(&mut self) {
self.phase = 0.0;
}
// ========== PRESETS ==========
/// Slow tremolo - gentle, pulsing effect (2 Hz)
pub fn slow() -> Self {
Self::new(2.0, 0.5)
}
/// Classic tremolo - standard rock/blues tremolo (4 Hz)
pub fn classic() -> Self {
Self::new(4.0, 0.6)
}
/// Fast tremolo - intense modulation (8 Hz)
pub fn fast() -> Self {
Self::new(8.0, 0.7)
}
/// Subtle tremolo - barely noticeable pulse (3 Hz)
pub fn subtle() -> Self {
Self::new(3.0, 0.3)
}
/// Helicopter - extreme, rhythmic chop (12 Hz)
pub fn helicopter() -> Self {
Self::new(12.0, 0.9)
}
}