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
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
use crate::synthesis::automation::Automation;
use crate::track::{
PRIORITY_EARLY, PRIORITY_LAST, TrackId, BusId,
};
/// Standard audio sample rate
const DEFAULT_SAMPLE_RATE: f32 = 44100.0;
/// Sidechain source for dynamic effects
///
/// Specifies which external signal should control a dynamic effect (e.g., compressor).
/// The sidechain source's envelope is monitored to trigger compression/gating on the
/// target signal.
///
/// # Example
/// ```
/// # use tunes::synthesis::effects::{Compressor, SidechainSource};
/// // Bass compressor ducks when kick hits
/// let compressor = Compressor::new(0.6, 4.0, 0.01, 0.1, 44100.0)
/// .with_sidechain_track("kick");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum SidechainSource {
/// Sidechain from a specific track by name
Track(String),
/// Sidechain from an entire bus by name
Bus(String),
}
/// Resolved sidechain source using integer IDs for performance
///
/// This is an internal type used during audio rendering. The user-facing API uses
/// `SidechainSource` with string names, which are resolved to integer IDs when
/// converting a Composition to a Mixer.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ResolvedSidechainSource {
/// Sidechain from a specific track by ID
Track(TrackId),
/// Sidechain from an entire bus by ID
Bus(BusId),
}
/// Frequency band for multiband compression
///
/// Defines a frequency range and its associated compressor settings.
/// Used with `Compressor::with_multiband()` or `Compressor::with_multibands()`.
#[derive(Debug, Clone)]
pub struct CompressorBand {
pub low_freq: f32, // Lower frequency bound in Hz
pub high_freq: f32, // Upper frequency bound in Hz
pub compressor: Compressor, // Compressor settings for this band
// Bandpass filter state (Butterworth 2nd order)
low_z1: f32,
low_z2: f32,
high_z1: f32,
high_z2: f32,
}
impl CompressorBand {
/// Create a new frequency band with compressor settings
///
/// # Arguments
/// * `low_freq` - Lower frequency bound in Hz (e.g., 80.0 for bass)
/// * `high_freq` - Upper frequency bound in Hz (e.g., 200.0 for bass)
/// * `compressor` - Compressor to apply to this frequency band
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # use tunes::synthesis::effects::{Compressor, CompressorBand};
/// let bass_band = CompressorBand::new(
/// 40.0, // Low freq
/// 150.0, // High freq
/// Compressor::new(0.3, 4.0, 0.005, 0.05, 1.0) // Tight compression
/// );
/// ```
pub fn new(low_freq: f32, high_freq: f32, compressor: Compressor) -> Self {
Self {
low_freq,
high_freq,
compressor,
low_z1: 0.0,
low_z2: 0.0,
high_z1: 0.0,
high_z2: 0.0,
}
}
/// Process a sample through this band's filter and compressor
#[inline]
fn process_sample(&mut self, input: f32, sample_rate: f32, time: f32, sample_count: u64) -> f32 {
// Apply bandpass filter (highpass then lowpass)
let filtered = self.bandpass(input, sample_rate);
// Compress the filtered signal
self.compressor.process(filtered, sample_rate, time, sample_count, None)
}
/// Simple 2nd-order Butterworth bandpass filter
#[inline]
fn bandpass(&mut self, input: f32, sample_rate: f32) -> f32 {
// Highpass at low_freq
let omega_low = 2.0 * std::f32::consts::PI * self.low_freq / sample_rate;
let cos_omega_low = omega_low.cos();
let alpha_low = omega_low.sin() / (2.0 * 0.707); // Q = 0.707 for Butterworth
let b0_low = (1.0 + cos_omega_low) / 2.0;
let b1_low = -(1.0 + cos_omega_low);
let b2_low = (1.0 + cos_omega_low) / 2.0;
let a0_low = 1.0 + alpha_low;
let a1_low = -2.0 * cos_omega_low;
let a2_low = 1.0 - alpha_low;
let high_passed = (b0_low * input + b1_low * self.low_z1 + b2_low * self.low_z2
- a1_low * self.low_z1 - a2_low * self.low_z2) / a0_low;
self.low_z2 = self.low_z1;
self.low_z1 = high_passed;
// Lowpass at high_freq
let omega_high = 2.0 * std::f32::consts::PI * self.high_freq / sample_rate;
let cos_omega_high = omega_high.cos();
let alpha_high = omega_high.sin() / (2.0 * 0.707);
let b0_high = (1.0 - cos_omega_high) / 2.0;
let b1_high = 1.0 - cos_omega_high;
let b2_high = (1.0 - cos_omega_high) / 2.0;
let a0_high = 1.0 + alpha_high;
let a1_high = -2.0 * cos_omega_high;
let a2_high = 1.0 - alpha_high;
let band_passed = (b0_high * high_passed + b1_high * self.high_z1 + b2_high * self.high_z2
- a1_high * self.high_z1 - a2_high * self.high_z2) / a0_high;
self.high_z2 = self.high_z1;
self.high_z1 = band_passed;
band_passed
}
}
/// Compressor - dynamic range compression
#[derive(Debug, Clone)]
pub struct Compressor {
pub threshold: f32, // Threshold in amplitude 0.0-1.0 (NOT dB! 0.3 ≈ -10dB, 0.5 ≈ -6dB)
pub ratio: f32, // Compression ratio (1.0 = no compression, 10.0 = heavy)
pub attack: f32, // Attack time in seconds
pub release: f32, // Release time in seconds
pub makeup_gain: f32, // Makeup gain to compensate for volume reduction
pub priority: u8, // Processing priority (lower = earlier in signal chain)
envelope: f32,
// Cached coefficients (avoid expensive exp() calls)
cached_attack_coeff: f32,
cached_release_coeff: f32,
cached_sample_rate: f32,
// Sidechaining support (user-facing API)
pub sidechain_source: Option<SidechainSource>, // External signal to trigger compression (by name)
// Resolved sidechain source (internal, used during rendering)
pub(crate) resolved_sidechain_source: Option<ResolvedSidechainSource>,
// Multiband compression support
bands: Option<Vec<CompressorBand>>,
// Automation (optional)
threshold_automation: Option<Automation>,
ratio_automation: Option<Automation>,
attack_automation: Option<Automation>,
release_automation: Option<Automation>,
makeup_gain_automation: Option<Automation>,
}
impl Compressor {
/// Create a new compressor
///
/// # Arguments
/// * `threshold` - Level above which compression starts in amplitude (0.0 to 1.0, NOT dB!)
/// Typical values: 0.5 = gentle, 0.3 = moderate, 0.2 = aggressive
/// * `ratio` - Compression ratio (2.0 = gentle, 10.0 = heavy limiting)
/// * `attack` - Attack time in seconds (typical: 0.001 to 0.1)
/// * `release` - Release time in seconds (typical: 0.05 to 0.5)
/// * `makeup_gain` - Output gain multiplier (1.0 to 4.0)
pub fn new(threshold: f32, ratio: f32, attack: f32, release: f32, makeup_gain: f32) -> Self {
let attack = attack.max(0.001);
let release = release.max(0.001);
// Pre-compute coefficients for default sample rate
let cached_attack_coeff = (-1.0 / (attack * DEFAULT_SAMPLE_RATE)).exp();
let cached_release_coeff = (-1.0 / (release * DEFAULT_SAMPLE_RATE)).exp();
Self {
threshold: threshold.clamp(0.0, 1.0),
ratio: ratio.max(1.0),
attack,
release,
makeup_gain: makeup_gain.max(0.1),
priority: PRIORITY_EARLY, // Compressor typically early in chain
envelope: 0.0,
cached_attack_coeff,
cached_release_coeff,
cached_sample_rate: DEFAULT_SAMPLE_RATE,
sidechain_source: None,
resolved_sidechain_source: None,
bands: None,
threshold_automation: None,
ratio_automation: None,
attack_automation: None,
release_automation: None,
makeup_gain_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 threshold parameter
pub fn with_threshold_automation(mut self, automation: Automation) -> Self {
self.threshold_automation = Some(automation);
self
}
/// Add automation for the ratio parameter
pub fn with_ratio_automation(mut self, automation: Automation) -> Self {
self.ratio_automation = Some(automation);
self
}
/// Add automation for the attack parameter
pub fn with_attack_automation(mut self, automation: Automation) -> Self {
self.attack_automation = Some(automation);
self
}
/// Add automation for the release parameter
pub fn with_release_automation(mut self, automation: Automation) -> Self {
self.release_automation = Some(automation);
self
}
/// Add automation for the makeup gain parameter
pub fn with_makeup_gain_automation(mut self, automation: Automation) -> Self {
self.makeup_gain_automation = Some(automation);
self
}
/// Configure sidechain from a specific track
///
/// Duck this signal when the specified track is loud. The compressor will
/// monitor the sidechain track's envelope instead of its own signal to
/// decide when to compress.
///
/// Common use: Duck bass when kick hits.
///
/// # Arguments
/// * `track_name` - Name of the track to use as sidechain source
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # use tunes::synthesis::effects::Compressor;
/// # let mut comp = Composition::new(Tempo::new(120.0));
/// comp.track("kick")
/// .bus("drums")
/// .drum(DrumType::Kick, 0.0);
///
/// comp.track("bass")
/// .bus("bass")
/// .notes(&[C2], 0.5);
///
/// let mut mixer = comp.into_mixer();
///
/// // Bass ducks when kick hits
/// mixer.bus("bass")
/// .compressor(
/// Compressor::new(0.6, 4.0, 0.01, 0.1, 1.0)
/// .with_sidechain_track("kick")
/// );
/// ```
pub fn with_sidechain_track(mut self, track_name: &str) -> Self {
self.sidechain_source = Some(SidechainSource::Track(track_name.to_string()));
self
}
/// Configure sidechain from an entire bus
///
/// Duck this signal when the specified bus is loud. Useful for ducking
/// a bus based on another bus (e.g., duck synths when drums bus is active).
///
/// # Arguments
/// * `bus_name` - Name of the bus to use as sidechain source
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # use tunes::synthesis::effects::Compressor;
/// # let mut mixer = tunes::track::Mixer::new(Tempo::new(120.0));
/// // Synths duck when entire drums bus is loud
/// mixer.bus("synths")
/// .compressor(
/// Compressor::new(0.5, 3.0, 0.005, 0.05, 1.0)
/// .with_sidechain_bus("drums")
/// );
/// ```
pub fn with_sidechain_bus(mut self, bus_name: &str) -> Self {
self.sidechain_source = Some(SidechainSource::Bus(bus_name.to_string()));
self
}
/// Add a single frequency band for multiband compression
///
/// Splits the signal into frequency bands and applies different compression
/// to each band independently. Perfect for mastering and frequency-specific dynamics.
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # use tunes::synthesis::effects::{Compressor, CompressorBand};
/// let comp = Compressor::new(0.5, 3.0, 0.01, 0.1, 1.0)
/// .with_multiband(CompressorBand::new(
/// 80.0, // Low freq
/// 200.0, // High freq
/// Compressor::new(0.3, 4.0, 0.005, 0.05, 1.0) // Tight bass comp
/// ));
/// ```
pub fn with_multiband(mut self, band: CompressorBand) -> Self {
if self.bands.is_none() {
self.bands = Some(Vec::new());
}
self.bands.as_mut().unwrap().push(band);
self
}
/// Add multiple frequency bands for multiband compression
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # use tunes::synthesis::effects::{Compressor, CompressorBand};
/// let bands = vec![
/// CompressorBand::new(0.0, 200.0,
/// Compressor::new(0.3, 4.0, 0.005, 0.05, 1.0)), // Bass
/// CompressorBand::new(200.0, 2000.0,
/// Compressor::new(0.5, 2.5, 0.01, 0.1, 1.0)), // Mids
/// CompressorBand::new(2000.0, 20000.0,
/// Compressor::new(0.6, 2.0, 0.01, 0.1, 1.0)), // Highs
/// ];
///
/// let comp = Compressor::new(0.5, 1.0, 0.01, 0.1, 1.0)
/// .with_multibands(bands);
/// ```
pub fn with_multibands(mut self, bands: Vec<CompressorBand>) -> Self {
self.bands = Some(bands);
self
}
/// Convenience: Create a 3-band multiband compressor (low/mid/high)
///
/// Creates a standard 3-way split with default compression settings.
/// Use `.with_band_low()`, `.with_band_mid()`, and `.with_band_high()`
/// to customize each band's compression.
///
/// # Example
/// ```
/// # use tunes::prelude::*;
/// # use tunes::synthesis::effects::Compressor;
/// let comp = Compressor::multiband_3way(200.0, 2000.0)
/// .with_band_low(0.3, 4.0) // Tight bass control
/// .with_band_mid(0.5, 2.5) // Gentle mids
/// .with_band_high(0.6, 2.0); // Transparent highs
/// ```
pub fn multiband_3way(low_mid_crossover: f32, mid_high_crossover: f32) -> Self {
let bands = vec![
CompressorBand::new(
0.0,
low_mid_crossover,
Compressor::new(0.5, 3.0, 0.01, 0.1, 1.0),
),
CompressorBand::new(
low_mid_crossover,
mid_high_crossover,
Compressor::new(0.5, 3.0, 0.01, 0.1, 1.0),
),
CompressorBand::new(
mid_high_crossover,
20000.0,
Compressor::new(0.5, 3.0, 0.01, 0.1, 1.0),
),
];
let attack = 0.01;
let release = 0.1;
Self {
threshold: 0.5,
ratio: 1.0, // Disabled when using bands
attack,
release,
makeup_gain: 1.0,
priority: PRIORITY_EARLY,
envelope: 0.0,
cached_attack_coeff: (-1.0 / (attack * DEFAULT_SAMPLE_RATE)).exp(),
cached_release_coeff: (-1.0 / (release * DEFAULT_SAMPLE_RATE)).exp(),
cached_sample_rate: DEFAULT_SAMPLE_RATE,
sidechain_source: None,
resolved_sidechain_source: None,
bands: Some(bands),
threshold_automation: None,
ratio_automation: None,
attack_automation: None,
release_automation: None,
makeup_gain_automation: None,
}
}
/// Adjust low band compression (for use with `multiband_3way`)
pub fn with_band_low(mut self, threshold: f32, ratio: f32) -> Self {
if let Some(bands) = &mut self.bands {
if let Some(band) = bands.get_mut(0) {
band.compressor.threshold = threshold;
band.compressor.ratio = ratio;
}
}
self
}
/// Adjust mid band compression (for use with `multiband_3way`)
pub fn with_band_mid(mut self, threshold: f32, ratio: f32) -> Self {
if let Some(bands) = &mut self.bands {
if let Some(band) = bands.get_mut(1) {
band.compressor.threshold = threshold;
band.compressor.ratio = ratio;
}
}
self
}
/// Adjust high band compression (for use with `multiband_3way`)
pub fn with_band_high(mut self, threshold: f32, ratio: f32) -> Self {
if let Some(bands) = &mut self.bands {
if let Some(band) = bands.get_mut(2) {
band.compressor.threshold = threshold;
band.compressor.ratio = ratio;
}
}
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)
/// * `sidechain_envelope` - Optional external envelope for sidechaining (overrides input level detection)
#[inline]
pub fn process(&mut self, input: f32, sample_rate: f32, time: f32, sample_count: u64, sidechain_envelope: Option<f32>) -> f32 {
// If multiband is enabled, process through bands instead
if let Some(bands) = &mut self.bands {
let mut output = 0.0;
for band in bands.iter_mut() {
output += band.process_sample(input, sample_rate, time, sample_count);
}
return output.clamp(-2.0, 2.0);
}
// Standard single-band compression below
// 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.threshold_automation {
self.threshold = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.ratio_automation {
self.ratio = auto.value_at(time).max(1.0);
}
if let Some(auto) = &self.attack_automation {
self.attack = auto.value_at(time).max(0.001);
}
if let Some(auto) = &self.release_automation {
self.release = auto.value_at(time).max(0.001);
}
if let Some(auto) = &self.makeup_gain_automation {
self.makeup_gain = auto.value_at(time).max(0.1);
}
}
// Use sidechain envelope if provided, otherwise use input level
let input_level = sidechain_envelope.unwrap_or_else(|| input.abs());
// Update cached coefficients if sample rate changed or automation updated attack/release
if (sample_rate - self.cached_sample_rate).abs() > 0.1
|| (sample_count & 63 == 0 && (self.attack_automation.is_some() || self.release_automation.is_some()))
{
self.cached_attack_coeff = (-1.0 / (self.attack * sample_rate)).exp();
self.cached_release_coeff = (-1.0 / (self.release * sample_rate)).exp();
self.cached_sample_rate = sample_rate;
}
// Use FMA for envelope calculation with cached coefficients
let coeff = if input_level > self.envelope {
self.cached_attack_coeff
} else {
self.cached_release_coeff
};
self.envelope = self.envelope.mul_add(coeff, input_level * (1.0 - coeff));
// Clamp envelope to prevent runaway values
self.envelope = self.envelope.clamp(0.0, 2.0);
// Calculate gain reduction
let gain = if self.envelope > self.threshold {
let over_threshold = self.envelope / self.threshold.max(0.001); // Prevent division by zero
let compressed = over_threshold.powf(1.0 / self.ratio);
(compressed * self.threshold / self.envelope).clamp(0.0, 1.0)
} else {
1.0
};
// Apply compression and makeup gain using FMA, clamp output to prevent clipping
let output = input * gain * self.makeup_gain;
output.clamp(-2.0, 2.0)
}
/// Process a stereo sample with properly linked compression
///
/// Uses the maximum level of both channels for gain detection, then applies
/// the same gain reduction to both channels. This prevents stereo image shifts.
///
/// # Arguments
/// * `left` - Left channel input
/// * `right` - Right channel input
/// * `sample_rate` - Sample rate in Hz
/// * `time` - Current time in seconds (for automation)
/// * `sample_count` - Global sample counter (for quantized automation lookups)
/// * `sidechain_envelope` - Optional external envelope for sidechaining
///
/// # Returns
/// Tuple of (left_output, right_output)
#[inline]
pub fn process_stereo_linked(
&mut self,
left: f32,
right: f32,
sample_rate: f32,
time: f32,
sample_count: u64,
sidechain_envelope: Option<f32>,
) -> (f32, f32) {
// Quantized automation lookups (every 64 samples = 1.45ms @ 44.1kHz)
if sample_count & 63 == 0 {
if let Some(auto) = &self.threshold_automation {
self.threshold = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.ratio_automation {
self.ratio = auto.value_at(time).max(1.0);
}
if let Some(auto) = &self.attack_automation {
self.attack = auto.value_at(time).max(0.001);
}
if let Some(auto) = &self.release_automation {
self.release = auto.value_at(time).max(0.001);
}
if let Some(auto) = &self.makeup_gain_automation {
self.makeup_gain = auto.value_at(time).max(0.1);
}
}
// Use sidechain envelope if provided, otherwise use max of both channels for detection
let input_level = sidechain_envelope.unwrap_or_else(|| left.abs().max(right.abs()));
// Update cached coefficients if sample rate changed or automation updated attack/release
if (sample_rate - self.cached_sample_rate).abs() > 0.1
|| (sample_count & 63 == 0 && (self.attack_automation.is_some() || self.release_automation.is_some()))
{
self.cached_attack_coeff = (-1.0 / (self.attack * sample_rate)).exp();
self.cached_release_coeff = (-1.0 / (self.release * sample_rate)).exp();
self.cached_sample_rate = sample_rate;
}
// Use FMA for envelope calculation with cached coefficients
let coeff = if input_level > self.envelope {
self.cached_attack_coeff
} else {
self.cached_release_coeff
};
self.envelope = self.envelope.mul_add(coeff, input_level * (1.0 - coeff));
// Clamp envelope to prevent runaway values
self.envelope = self.envelope.clamp(0.0, 2.0);
// Calculate gain reduction (same for both channels)
let gain = if self.envelope > self.threshold {
let over_threshold = self.envelope / self.threshold.max(0.001);
let compressed = over_threshold.powf(1.0 / self.ratio);
(compressed * self.threshold / self.envelope).clamp(0.0, 1.0)
} else {
1.0
};
// Apply same gain to both channels with makeup gain
let left_out = (left * gain * self.makeup_gain).clamp(-2.0, 2.0);
let right_out = (right * gain * self.makeup_gain).clamp(-2.0, 2.0);
(left_out, right_out)
}
/// Process a block of samples
///
/// # 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)
/// * `sidechain_envelope` - Optional external envelope for sidechaining
#[inline]
pub fn process_block(&mut self, buffer: &mut [f32], sample_rate: f32, time: f32, sample_count: u64, sidechain_envelope: Option<f32>) {
// If multiband is enabled, fall back to per-sample processing
if self.bands.is_some() {
let time_delta = 1.0 / sample_rate;
for (i, sample) in buffer.iter_mut().enumerate() {
let current_time = time + (i as f32 * time_delta);
let current_sample_count = sample_count + i as u64;
*sample = self.process(*sample, sample_rate, current_time, current_sample_count, sidechain_envelope);
}
return;
}
// Optimized single-band compression buffer processing
// Update automation parameters once at buffer start (quantized to 64-sample blocks)
if sample_count & 63 == 0 {
if let Some(auto) = &self.threshold_automation {
self.threshold = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.ratio_automation {
self.ratio = auto.value_at(time).max(1.0);
}
if let Some(auto) = &self.attack_automation {
self.attack = auto.value_at(time).max(0.001);
}
if let Some(auto) = &self.release_automation {
self.release = auto.value_at(time).max(0.001);
}
if let Some(auto) = &self.makeup_gain_automation {
self.makeup_gain = auto.value_at(time).max(0.1);
}
// Update cached coefficients
self.cached_attack_coeff = (-1.0 / (self.attack * sample_rate)).exp();
self.cached_release_coeff = (-1.0 / (self.release * sample_rate)).exp();
self.cached_sample_rate = sample_rate;
}
// Pre-calculate constants once for entire buffer
let threshold = self.threshold;
let ratio = self.ratio;
let makeup_gain = self.makeup_gain;
let cached_attack_coeff = self.cached_attack_coeff;
let cached_release_coeff = self.cached_release_coeff;
let threshold_max = threshold.max(0.001); // Prevent division by zero
let inv_ratio = 1.0 / ratio;
// Process entire buffer
for sample in buffer.iter_mut() {
let input = *sample;
// Use sidechain envelope if provided, otherwise use input level
let input_level = sidechain_envelope.unwrap_or_else(|| input.abs());
// Use FMA for envelope calculation with cached coefficients
let coeff = if input_level > self.envelope {
cached_attack_coeff
} else {
cached_release_coeff
};
self.envelope = self.envelope.mul_add(coeff, input_level * (1.0 - coeff));
// Clamp envelope to prevent runaway values
self.envelope = self.envelope.clamp(0.0, 2.0);
// Calculate gain reduction
let gain = if self.envelope > threshold {
let over_threshold = self.envelope / threshold_max;
let compressed = over_threshold.powf(inv_ratio);
(compressed * threshold / self.envelope).clamp(0.0, 1.0)
} else {
1.0
};
// Apply compression and makeup gain using FMA, clamp output to prevent clipping
let output = input * gain * makeup_gain;
*sample = output.clamp(-2.0, 2.0);
}
}
/// Process an interleaved stereo block with stereo-linked compression
///
/// # Arguments
/// * `buffer` - Interleaved stereo buffer [L0, R0, L1, R1, ...] 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)
/// * `sidechain_envelope` - Optional external envelope for sidechaining
#[inline]
pub fn process_stereo_block(&mut self, buffer: &mut [f32], sample_rate: f32, time: f32, sample_count: u64, sidechain_envelope: Option<f32>) {
// If multiband is enabled, fall back to per-sample processing
if self.bands.is_some() {
for (i, frame) in buffer.chunks_mut(2).enumerate() {
if frame.len() == 2 {
let (left, right) = self.process_stereo_linked(
frame[0],
frame[1],
sample_rate,
time,
sample_count + i as u64,
sidechain_envelope,
);
frame[0] = left;
frame[1] = right;
}
}
return;
}
// Optimized single-band stereo-linked compression
// Update automation parameters once at buffer start
if sample_count & 63 == 0 {
if let Some(auto) = &self.threshold_automation {
self.threshold = auto.value_at(time).clamp(0.0, 1.0);
}
if let Some(auto) = &self.ratio_automation {
self.ratio = auto.value_at(time).max(1.0);
}
if let Some(auto) = &self.attack_automation {
self.attack = auto.value_at(time).max(0.001);
}
if let Some(auto) = &self.release_automation {
self.release = auto.value_at(time).max(0.001);
}
if let Some(auto) = &self.makeup_gain_automation {
self.makeup_gain = auto.value_at(time).max(0.1);
}
// Update cached coefficients
self.cached_attack_coeff = (-1.0 / (self.attack * sample_rate)).exp();
self.cached_release_coeff = (-1.0 / (self.release * sample_rate)).exp();
self.cached_sample_rate = sample_rate;
}
// Pre-calculate constants once for entire buffer
let threshold = self.threshold;
let ratio = self.ratio;
let makeup_gain = self.makeup_gain;
let cached_attack_coeff = self.cached_attack_coeff;
let cached_release_coeff = self.cached_release_coeff;
let threshold_max = threshold.max(0.001);
let inv_ratio = 1.0 / ratio;
// Process entire interleaved stereo buffer
for frame in buffer.chunks_mut(2) {
if frame.len() == 2 {
let left = frame[0];
let right = frame[1];
// Use sidechain envelope if provided, otherwise use max of both channels
let input_level = sidechain_envelope.unwrap_or_else(|| left.abs().max(right.abs()));
// Envelope follower with cached coefficients
let coeff = if input_level > self.envelope {
cached_attack_coeff
} else {
cached_release_coeff
};
self.envelope = self.envelope.mul_add(coeff, input_level * (1.0 - coeff));
self.envelope = self.envelope.clamp(0.0, 2.0);
// Calculate gain reduction (same for both channels)
let gain = if self.envelope > threshold {
let over_threshold = self.envelope / threshold_max;
let compressed = over_threshold.powf(inv_ratio);
(compressed * threshold / self.envelope).clamp(0.0, 1.0)
} else {
1.0
};
// Apply same gain to both channels with makeup gain
frame[0] = (left * gain * makeup_gain).clamp(-2.0, 2.0);
frame[1] = (right * gain * makeup_gain).clamp(-2.0, 2.0);
}
}
}
/// Reset the compressor state
pub fn reset(&mut self) {
self.envelope = 0.0;
}
// ========== PRESETS ==========
/// Gentle compression - transparent, barely noticeable (2:1 ratio)
pub fn gentle() -> Self {
Self::new(0.5, 2.0, 0.01, 0.1, DEFAULT_SAMPLE_RATE)
}
/// Vocal compression - fast attack for controlling vocals (4:1 ratio)
pub fn vocal() -> Self {
Self::new(0.4, 4.0, 0.005, 0.05, DEFAULT_SAMPLE_RATE)
}
/// Drum bus compression - punchy, adds glue to drums (4:1 ratio)
pub fn drum_bus() -> Self {
Self::new(0.6, 4.0, 0.01, 0.15, DEFAULT_SAMPLE_RATE)
}
/// Bass compression - evens out bass notes (6:1 ratio)
pub fn bass() -> Self {
Self::new(0.5, 6.0, 0.02, 0.2, DEFAULT_SAMPLE_RATE)
}
/// Master compression - gentle glue for final mix (2.5:1 ratio)
pub fn master() -> Self {
Self::new(0.6, 2.5, 0.01, 0.1, DEFAULT_SAMPLE_RATE)
}
/// Limiter - brick wall limiting (20:1 ratio)
pub fn limiter() -> Self {
Self::new(0.8, 20.0, 0.001, 0.05, DEFAULT_SAMPLE_RATE)
}
/// Aggressive compression - heavy squashing (8:1 ratio)
pub fn aggressive() -> Self {
Self::new(0.3, 8.0, 0.005, 0.08, DEFAULT_SAMPLE_RATE)
}
}
/// Gate - noise gate / expander
///
/// Reduces the level of signals below a threshold, useful for removing
/// background noise or creating rhythmic gating effects.
#[derive(Debug, Clone)]
pub struct Gate {
pub threshold: f32, // Threshold in dB (e.g., -40.0)
pub ratio: f32, // Expansion ratio (typically 10:1 to ∞:1, where ∞ = hard gate)
pub attack: f32, // Attack time in seconds
pub release: f32, // Release time in seconds
pub priority: u8, // Processing priority
envelope: f32, // Current envelope value (0.0 to 1.0)
_sample_rate: f32,
// Automation (optional)
threshold_automation: Option<Automation>,
ratio_automation: Option<Automation>,
}
impl Gate {
/// Create a new gate effect
///
/// # Arguments
/// * `threshold` - Threshold in dB (signals below this are reduced)
/// * `ratio` - Expansion ratio (10.0 = 10:1, f32::INFINITY = hard gate)
/// * `attack` - Attack time in seconds (how quickly gate opens)
/// * `release` - Release time in seconds (how quickly gate closes)
/// * `sample_rate` - Audio sample rate in Hz
pub fn with_sample_rate(
threshold: f32,
ratio: f32,
attack: f32,
release: f32,
sample_rate: f32,
) -> Self {
Self {
threshold,
ratio: ratio.max(1.0),
attack: attack.max(0.0001),
release: release.max(0.001),
priority: PRIORITY_EARLY, // Gates typically go early in the chain
envelope: 0.0,
_sample_rate: sample_rate,
threshold_automation: None,
ratio_automation: None,
}
}
/// Create a gate with default sample rate (44100 Hz)
pub fn new(threshold: f32, ratio: f32, attack: f32, release: f32) -> Self {
Self::with_sample_rate(threshold, ratio, attack, release, 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 threshold parameter
pub fn with_threshold_automation(mut self, automation: Automation) -> Self {
self.threshold_automation = Some(automation);
self
}
/// Add automation for the ratio parameter
pub fn with_ratio_automation(mut self, automation: Automation) -> Self {
self.ratio_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)
if sample_count & 63 == 0 {
if let Some(auto) = &self.threshold_automation {
self.threshold = auto.value_at(time);
}
if let Some(auto) = &self.ratio_automation {
self.ratio = auto.value_at(time).max(1.0);
}
}
// Convert input to dB
let input_db = if input.abs() > 0.0001 {
20.0 * input.abs().log10()
} else {
-100.0 // Very quiet = -100 dB
};
// Determine target envelope based on threshold
let target_envelope = if input_db > self.threshold {
1.0 // Above threshold: gate open
} else {
// Below threshold: apply expansion/gating
let db_below = self.threshold - input_db;
let expansion = db_below * (self.ratio - 1.0) / self.ratio;
10.0_f32.powf(-expansion / 20.0) // Convert back to linear
};
// Smooth envelope with attack/release
let coeff = if target_envelope > self.envelope {
// Attack (gate opening)
(-1.0 / (self.attack * sample_rate)).exp()
} else {
// Release (gate closing)
(-1.0 / (self.release * sample_rate)).exp()
};
self.envelope = target_envelope + coeff * (self.envelope - target_envelope);
// Apply gating
input * self.envelope
}
/// 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.threshold_automation {
self.threshold = auto.value_at(time);
}
if let Some(auto) = &self.ratio_automation {
self.ratio = auto.value_at(time).max(1.0);
}
}
// Pre-calculate constants once for entire buffer
let threshold = self.threshold;
let ratio = self.ratio;
let attack_coeff = (-1.0 / (self.attack * sample_rate)).exp();
let release_coeff = (-1.0 / (self.release * sample_rate)).exp();
let ratio_inv = (ratio - 1.0) / ratio;
// Process entire buffer
for sample in buffer.iter_mut() {
let input = *sample;
// Convert input to dB
let input_db = if input.abs() > 0.0001 {
20.0 * input.abs().log10()
} else {
-100.0 // Very quiet = -100 dB
};
// Determine target envelope based on threshold
let target_envelope = if input_db > threshold {
1.0 // Above threshold: gate open
} else {
// Below threshold: apply expansion/gating
let db_below = threshold - input_db;
let expansion = db_below * ratio_inv;
10.0_f32.powf(-expansion / 20.0) // Convert back to linear
};
// Smooth envelope with attack/release
let coeff = if target_envelope > self.envelope {
attack_coeff
} else {
release_coeff
};
self.envelope = target_envelope + coeff * (self.envelope - target_envelope);
// Apply gating
*sample = input * self.envelope;
}
}
/// Reset the gate state
pub fn reset(&mut self) {
self.envelope = 0.0;
}
// ========== PRESETS ==========
/// Gentle gate - subtle noise reduction (-35 dB threshold)
pub fn gentle() -> Self {
Self::with_sample_rate(-35.0, 4.0, 0.001, 0.05, DEFAULT_SAMPLE_RATE)
}
/// Standard gate - balanced noise control (-40 dB threshold)
pub fn standard() -> Self {
Self::with_sample_rate(-40.0, 10.0, 0.001, 0.05, DEFAULT_SAMPLE_RATE)
}
/// Aggressive gate - hard gating for dramatic effect (-30 dB, high ratio)
pub fn aggressive() -> Self {
Self::with_sample_rate(-30.0, f32::INFINITY, 0.0001, 0.02, DEFAULT_SAMPLE_RATE)
}
/// Drum gate - fast attack/release for drums (-45 dB)
pub fn drum() -> Self {
Self::with_sample_rate(-45.0, 20.0, 0.0001, 0.03, DEFAULT_SAMPLE_RATE)
}
/// Vocal gate - moderate gating for vocals (-38 dB)
pub fn vocal() -> Self {
Self::with_sample_rate(-38.0, 8.0, 0.002, 0.08, DEFAULT_SAMPLE_RATE)
}
}
/// Limiter - brick-wall peak limiter
///
/// Prevents signal from exceeding a threshold, acting as a safety net
/// against clipping. Typically used as the final stage in the signal chain.
#[derive(Debug, Clone)]
pub struct Limiter {
pub threshold: f32, // Threshold in dB (e.g., -0.1 dB)
pub release: f32, // Release time in seconds
pub priority: u8, // Processing priority
gain_reduction: f32, // Current gain reduction (0.0 to 1.0)
_sample_rate: f32,
// Automation (optional)
threshold_automation: Option<Automation>,
}
impl Limiter {
/// Create a new limiter effect
///
/// # Arguments
/// * `threshold` - Threshold in dB (signals above this are limited)
/// * `release` - Release time in seconds (how quickly limiter recovers)
/// * `sample_rate` - Audio sample rate in Hz
pub fn with_sample_rate(threshold: f32, release: f32, sample_rate: f32) -> Self {
Self {
threshold,
release: release.max(0.001),
priority: PRIORITY_LAST, // Limiters go last to catch peaks
gain_reduction: 1.0,
_sample_rate: sample_rate,
threshold_automation: None,
}
}
/// Create a limiter with default sample rate (44100 Hz)
pub fn new(threshold: f32, release: f32) -> Self {
Self::with_sample_rate(threshold, release, 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 threshold parameter
pub fn with_threshold_automation(mut self, automation: Automation) -> Self {
self.threshold_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)
if sample_count & 63 == 0 {
if let Some(auto) = &self.threshold_automation {
self.threshold = auto.value_at(time);
}
}
// Convert threshold from dB to linear
let threshold_linear = 10.0_f32.powf(self.threshold / 20.0);
// Detect peak
let input_abs = input.abs();
// Calculate required gain reduction
let target_gain = if input_abs > threshold_linear {
threshold_linear / input_abs
} else {
1.0
};
// Apply gain reduction with instant attack and release envelope
// Instant attack (0 ms) for true peak limiting
if target_gain < self.gain_reduction {
self.gain_reduction = target_gain;
} else {
// Smooth release
let release_coeff = (-1.0 / (self.release * sample_rate)).exp();
self.gain_reduction = target_gain + release_coeff * (self.gain_reduction - target_gain);
}
// Apply limiting
input * self.gain_reduction
}
/// Process a stereo sample with properly linked limiting
///
/// Uses the maximum level of both channels for peak detection, then applies
/// the same gain reduction to both channels. This prevents stereo image shifts.
///
/// # Arguments
/// * `left` - Left channel input
/// * `right` - Right channel input
/// * `sample_rate` - Sample rate in Hz
/// * `time` - Current time in seconds (for automation)
/// * `sample_count` - Global sample counter (for quantized automation lookups)
///
/// # Returns
/// Tuple of (left_output, right_output)
#[inline]
pub fn process_stereo_linked(
&mut self,
left: f32,
right: f32,
sample_rate: f32,
time: f32,
sample_count: u64,
) -> (f32, f32) {
// Quantized automation lookups (every 64 samples)
if sample_count & 63 == 0 {
if let Some(auto) = &self.threshold_automation {
self.threshold = auto.value_at(time);
}
}
// Convert threshold from dB to linear
let threshold_linear = 10.0_f32.powf(self.threshold / 20.0);
// Detect peak from both channels
let peak = left.abs().max(right.abs());
// Calculate required gain reduction
let target_gain = if peak > threshold_linear {
threshold_linear / peak
} else {
1.0
};
// Apply gain reduction with instant attack and release envelope
if target_gain < self.gain_reduction {
self.gain_reduction = target_gain;
} else {
// Smooth release
let release_coeff = (-1.0 / (self.release * sample_rate)).exp();
self.gain_reduction = target_gain + release_coeff * (self.gain_reduction - target_gain);
}
// Apply same limiting gain to both channels
(left * self.gain_reduction, right * self.gain_reduction)
}
/// Process a block of samples
///
/// # 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.threshold_automation {
self.threshold = auto.value_at(time);
}
}
// Pre-calculate constants once for entire buffer
let threshold_linear = 10.0_f32.powf(self.threshold / 20.0);
let release_coeff = (-1.0 / (self.release * sample_rate)).exp();
// Process entire buffer
for sample in buffer.iter_mut() {
let input = *sample;
// Detect peak
let input_abs = input.abs();
// Calculate required gain reduction
let target_gain = if input_abs > threshold_linear {
threshold_linear / input_abs
} else {
1.0
};
// Apply gain reduction with instant attack and release envelope
// Instant attack (0 ms) for true peak limiting
if target_gain < self.gain_reduction {
self.gain_reduction = target_gain;
} else {
// Smooth release
self.gain_reduction = target_gain + release_coeff * (self.gain_reduction - target_gain);
}
// Apply limiting
*sample = input * self.gain_reduction;
}
}
/// Process an interleaved stereo block with stereo-linked limiting
///
/// # Arguments
/// * `buffer` - Interleaved stereo buffer [L0, R0, L1, R1, ...] 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_stereo_block(&mut self, buffer: &mut [f32], sample_rate: f32, time: f32, sample_count: u64) {
// Update automation parameters once at buffer start
if sample_count & 63 == 0 {
if let Some(auto) = &self.threshold_automation {
self.threshold = auto.value_at(time);
}
}
// Pre-calculate constants once for entire buffer
let threshold_linear = 10.0_f32.powf(self.threshold / 20.0);
let release_coeff = (-1.0 / (self.release * sample_rate)).exp();
// Process entire interleaved stereo buffer
for frame in buffer.chunks_mut(2) {
if frame.len() == 2 {
let left = frame[0];
let right = frame[1];
// Detect peak from both channels (use maximum)
let peak = left.abs().max(right.abs());
// Calculate required gain reduction
let target_gain = if peak > threshold_linear {
threshold_linear / peak
} else {
1.0
};
// Apply gain reduction with instant attack and release envelope
if target_gain < self.gain_reduction {
self.gain_reduction = target_gain;
} else {
self.gain_reduction = target_gain + release_coeff * (self.gain_reduction - target_gain);
}
// Apply same limiting to both channels
frame[0] = left * self.gain_reduction;
frame[1] = right * self.gain_reduction;
}
}
}
/// Get the current gain reduction in dB
///
/// Useful for metering how much limiting is occurring
pub fn get_gain_reduction_db(&self) -> f32 {
if self.gain_reduction > 0.0 {
20.0 * self.gain_reduction.log10()
} else {
-100.0
}
}
/// Reset the limiter state
pub fn reset(&mut self) {
self.gain_reduction = 1.0;
}
// ========== PRESETS ==========
/// Transparent limiter - very light limiting (-0.5 dB)
pub fn transparent() -> Self {
Self::with_sample_rate(-0.5, 0.1, DEFAULT_SAMPLE_RATE)
}
/// Standard limiter - balanced protection (-0.3 dB)
pub fn standard() -> Self {
Self::with_sample_rate(-0.3, 0.05, DEFAULT_SAMPLE_RATE)
}
/// Brick wall - maximum protection (-0.1 dB, fast release)
pub fn brick_wall() -> Self {
Self::with_sample_rate(-0.1, 0.005, DEFAULT_SAMPLE_RATE)
}
/// Mastering limiter - professional mastering (-0.2 dB)
pub fn mastering() -> Self {
Self::with_sample_rate(-0.2, 0.08, DEFAULT_SAMPLE_RATE)
}
/// Safety limiter - emergency protection (0.0 dB)
pub fn safety() -> Self {
Self::with_sample_rate(0.0, 0.01, DEFAULT_SAMPLE_RATE)
}
}