oximedia-effects 0.1.5

Professional audio effects suite for OxiMedia
Documentation
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
//! Multiband dynamics compressor.
//!
//! Splits the input signal into three frequency bands using crossover filters
//! and applies independent compression to each band before summing them back.
//!
//! # Architecture
//!
//! ```text
//!              ┌─── LP1 ─────────────────────────────────── COMP_LOW ──┐
//! input ───────┤    LP(f1)                                             ├─── Σ ─── output
//!              │                                                        │
//!              ├─── HP1→LP2 ─────────────────────────────── COMP_MID ──┤
//!              │    HP(f1) → LP(f2)                                    │
//!              │                                                        │
//!              └─── HP2 ─────────────────────────────────── COMP_HIGH─┘
//!                   HP(f2)
//! ```
//!
//! Default crossover frequencies: **250 Hz** (low/mid) and **4 000 Hz** (mid/high).
//!
//! # Example
//!
//! ```
//! use oximedia_effects::multiband_compressor::{MultibandCompressor, BandConfig};
//!
//! let mut comp = MultibandCompressor::new(48_000.0);
//!
//! let mut buf = vec![0.3f32; 512];
//! comp.process(&mut buf);
//! ```

#![allow(clippy::cast_precision_loss)]

use std::f32::consts::PI;

// ---------------------------------------------------------------------------
// BandConfig
// ---------------------------------------------------------------------------

/// Per-band compression parameters.
#[derive(Debug, Clone, PartialEq)]
pub struct BandConfig {
    /// Threshold in dBFS above which compression starts.
    pub threshold_db: f32,
    /// Compression ratio (e.g. `4.0` = 4:1).
    pub ratio: f32,
    /// Attack time in milliseconds.
    pub attack_ms: f32,
    /// Release time in milliseconds.
    pub release_ms: f32,
    /// Knee width in dB (0 = hard knee).
    pub knee_db: f32,
    /// Makeup gain in dB applied after compression.
    pub makeup_gain_db: f32,
}

impl Default for BandConfig {
    fn default() -> Self {
        Self {
            threshold_db: -18.0,
            ratio: 4.0,
            attack_ms: 10.0,
            release_ms: 100.0,
            knee_db: 6.0,
            makeup_gain_db: 0.0,
        }
    }
}

impl BandConfig {
    /// Create a gentle compression band.
    #[must_use]
    pub fn gentle() -> Self {
        Self {
            threshold_db: -12.0,
            ratio: 2.0,
            attack_ms: 20.0,
            release_ms: 200.0,
            knee_db: 6.0,
            makeup_gain_db: 0.0,
        }
    }

    /// Create an aggressive limiting band.
    #[must_use]
    pub fn limiting() -> Self {
        Self {
            threshold_db: -6.0,
            ratio: 20.0,
            attack_ms: 1.0,
            release_ms: 50.0,
            knee_db: 0.0,
            makeup_gain_db: 0.0,
        }
    }

    /// Validate parameters.
    pub fn validate(&self) -> Result<(), String> {
        if self.ratio < 1.0 {
            return Err(format!("ratio must be >= 1.0, got {}", self.ratio));
        }
        if self.attack_ms <= 0.0 {
            return Err(format!("attack_ms must be > 0, got {}", self.attack_ms));
        }
        if self.release_ms <= 0.0 {
            return Err(format!("release_ms must be > 0, got {}", self.release_ms));
        }
        if self.knee_db < 0.0 {
            return Err(format!("knee_db must be >= 0, got {}", self.knee_db));
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Biquad filter (direct form II transposed)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
struct Biquad {
    b0: f32,
    b1: f32,
    b2: f32,
    a1: f32,
    a2: f32,
    s1: f32,
    s2: f32,
}

impl Biquad {
    fn process(&mut self, x: f32) -> f32 {
        let y = self.b0 * x + self.s1;
        self.s1 = self.b1 * x - self.a1 * y + self.s2;
        self.s2 = self.b2 * x - self.a2 * y;
        y
    }

    fn reset(&mut self) {
        self.s1 = 0.0;
        self.s2 = 0.0;
    }

    /// Linkwitz-Riley 2nd-order lowpass (Q = 0.5).
    fn lr_lowpass(freq_hz: f32, sample_rate: f32) -> Self {
        let w0 = 2.0 * PI * freq_hz / sample_rate;
        let cos_w0 = w0.cos();
        let sin_w0 = w0.sin();
        let q = 0.5_f32.sqrt(); // Butterworth Q
        let alpha = sin_w0 / (2.0 * q);
        let a0 = 1.0 + alpha;
        Self {
            b0: ((1.0 - cos_w0) / 2.0) / a0,
            b1: (1.0 - cos_w0) / a0,
            b2: ((1.0 - cos_w0) / 2.0) / a0,
            a1: (-2.0 * cos_w0) / a0,
            a2: (1.0 - alpha) / a0,
            s1: 0.0,
            s2: 0.0,
        }
    }

    /// Linkwitz-Riley 2nd-order highpass (Q = 0.5).
    fn lr_highpass(freq_hz: f32, sample_rate: f32) -> Self {
        let w0 = 2.0 * PI * freq_hz / sample_rate;
        let cos_w0 = w0.cos();
        let sin_w0 = w0.sin();
        let q = 0.5_f32.sqrt();
        let alpha = sin_w0 / (2.0 * q);
        let a0 = 1.0 + alpha;
        Self {
            b0: ((1.0 + cos_w0) / 2.0) / a0,
            b1: -(1.0 + cos_w0) / a0,
            b2: ((1.0 + cos_w0) / 2.0) / a0,
            a1: (-2.0 * cos_w0) / a0,
            a2: (1.0 - alpha) / a0,
            s1: 0.0,
            s2: 0.0,
        }
    }
}

// ---------------------------------------------------------------------------
// Single-band compressor
// ---------------------------------------------------------------------------

/// State for one compression band.
#[derive(Debug, Clone)]
struct BandCompressor {
    config: BandConfig,
    /// Envelope follower state (dBFS).
    envelope_db: f32,
    /// Precomputed attack coefficient.
    attack_coeff: f32,
    /// Precomputed release coefficient.
    release_coeff: f32,
    /// Precomputed makeup gain (linear).
    makeup_linear: f32,
}

impl BandCompressor {
    fn new(config: BandConfig, sample_rate: f32) -> Self {
        let attack_coeff = compute_time_coeff(config.attack_ms, sample_rate);
        let release_coeff = compute_time_coeff(config.release_ms, sample_rate);
        let makeup_linear = db_to_linear(config.makeup_gain_db);
        Self {
            config,
            envelope_db: -144.0,
            attack_coeff,
            release_coeff,
            makeup_linear,
        }
    }

    fn process_sample(&mut self, x: f32) -> f32 {
        let input_db = linear_to_db(x.abs());

        // Level detection (peak with attack/release smoothing)
        if input_db > self.envelope_db {
            self.envelope_db =
                self.attack_coeff * self.envelope_db + (1.0 - self.attack_coeff) * input_db;
        } else {
            self.envelope_db =
                self.release_coeff * self.envelope_db + (1.0 - self.release_coeff) * input_db;
        }

        // Gain computer with soft knee
        let gain_db = self.compute_gain(self.envelope_db);

        // Apply gain and makeup
        x * db_to_linear(gain_db) * self.makeup_linear
    }

    fn compute_gain(&self, level_db: f32) -> f32 {
        let threshold = self.config.threshold_db;
        let ratio = self.config.ratio;
        let knee = self.config.knee_db;

        let excess = level_db - threshold;

        if knee > 0.0 {
            let half_knee = knee / 2.0;
            if excess < -half_knee {
                // Below knee: no compression
                0.0
            } else if excess < half_knee {
                // In the knee: smooth transition
                let t = (excess + half_knee) / knee;
                let slope = (1.0 / ratio - 1.0) * t * t / 2.0;
                slope * knee / 2.0 // gain reduction in dB
            } else {
                // Above knee: full compression
                (1.0 / ratio - 1.0) * excess + (1.0 / ratio - 1.0) * half_knee / 2.0
            }
        } else if excess > 0.0 {
            // Hard knee
            (1.0 / ratio - 1.0) * excess
        } else {
            0.0
        }
    }

    fn reset(&mut self) {
        self.envelope_db = -144.0;
    }

    #[allow(dead_code)]
    fn update_sample_rate(&mut self, sample_rate: f32) {
        self.attack_coeff = compute_time_coeff(self.config.attack_ms, sample_rate);
        self.release_coeff = compute_time_coeff(self.config.release_ms, sample_rate);
    }
}

// ---------------------------------------------------------------------------
// MultibandCompressor
// ---------------------------------------------------------------------------

/// Three-band multiband compressor.
pub struct MultibandCompressor {
    /// Crossover frequency between low and mid bands (Hz).
    crossover_low_hz: f32,
    /// Crossover frequency between mid and high bands (Hz).
    crossover_high_hz: f32,
    /// Lowpass filter for low band (LP1).
    lp1: Biquad,
    /// Highpass filter for mid band (HP1).
    hp1: Biquad,
    /// Lowpass filter for mid band upper edge (LP2).
    lp2: Biquad,
    /// Highpass filter for high band (HP2).
    hp2: Biquad,
    /// Low band compressor.
    comp_low: BandCompressor,
    /// Mid band compressor.
    comp_mid: BandCompressor,
    /// High band compressor.
    comp_high: BandCompressor,
    #[allow(dead_code)]
    sample_rate: f32,
}

impl MultibandCompressor {
    /// Create a new `MultibandCompressor` with default band configurations.
    ///
    /// Default crossovers: 250 Hz (low/mid) and 4 000 Hz (mid/high).
    #[must_use]
    pub fn new(sample_rate: f32) -> Self {
        let crossover_low = 250.0f32;
        let crossover_high = 4_000.0f32;
        Self::new_with_bands(
            BandConfig::default(),
            BandConfig::default(),
            BandConfig::default(),
            crossover_low,
            crossover_high,
            sample_rate,
        )
    }

    /// Create a `MultibandCompressor` with custom per-band configurations.
    ///
    /// * `low`            – compression config for the low band (<= `crossover_low_hz`)
    /// * `mid`            – compression config for the mid band
    /// * `high`           – compression config for the high band (>= `crossover_high_hz`)
    /// * `crossover_low_hz`  – crossover between low and mid bands (Hz)
    /// * `crossover_high_hz` – crossover between mid and high bands (Hz)
    /// * `sample_rate`    – audio sample rate (Hz)
    #[must_use]
    pub fn new_with_bands(
        low: BandConfig,
        mid: BandConfig,
        high: BandConfig,
        crossover_low_hz: f32,
        crossover_high_hz: f32,
        sample_rate: f32,
    ) -> Self {
        let xover_low = crossover_low_hz.clamp(20.0, sample_rate * 0.45);
        let xover_high = crossover_high_hz.clamp(xover_low + 1.0, sample_rate * 0.49);

        Self {
            crossover_low_hz: xover_low,
            crossover_high_hz: xover_high,
            lp1: Biquad::lr_lowpass(xover_low, sample_rate),
            hp1: Biquad::lr_highpass(xover_low, sample_rate),
            lp2: Biquad::lr_lowpass(xover_high, sample_rate),
            hp2: Biquad::lr_highpass(xover_high, sample_rate),
            comp_low: BandCompressor::new(low, sample_rate),
            comp_mid: BandCompressor::new(mid, sample_rate),
            comp_high: BandCompressor::new(high, sample_rate),
            sample_rate,
        }
    }

    /// Return the low/mid crossover frequency.
    #[must_use]
    pub fn crossover_low_hz(&self) -> f32 {
        self.crossover_low_hz
    }

    /// Return the mid/high crossover frequency.
    #[must_use]
    pub fn crossover_high_hz(&self) -> f32 {
        self.crossover_high_hz
    }

    /// Process a single sample through all three bands.
    pub fn process_sample(&mut self, input: f32) -> f32 {
        // Split into bands
        let low = self.lp1.process(input);
        let mid_hp = self.hp1.process(input);
        let mid = self.lp2.process(mid_hp);
        let high = self.hp2.process(mid_hp);

        // Compress each band
        let low_out = self.comp_low.process_sample(low);
        let mid_out = self.comp_mid.process_sample(mid);
        let high_out = self.comp_high.process_sample(high);

        // Sum bands
        low_out + mid_out + high_out
    }

    /// Process a buffer of samples in-place.
    pub fn process(&mut self, buffer: &mut [f32]) {
        for sample in buffer.iter_mut() {
            *sample = self.process_sample(*sample);
        }
    }

    /// Reset all filter and compressor states.
    pub fn reset(&mut self) {
        self.lp1.reset();
        self.hp1.reset();
        self.lp2.reset();
        self.hp2.reset();
        self.comp_low.reset();
        self.comp_mid.reset();
        self.comp_high.reset();
    }

    /// Return a reference to the low band configuration.
    #[must_use]
    pub fn low_config(&self) -> &BandConfig {
        &self.comp_low.config
    }

    /// Return a reference to the mid band configuration.
    #[must_use]
    pub fn mid_config(&self) -> &BandConfig {
        &self.comp_mid.config
    }

    /// Return a reference to the high band configuration.
    #[must_use]
    pub fn high_config(&self) -> &BandConfig {
        &self.comp_high.config
    }
}

// ---------------------------------------------------------------------------
// DSP utility functions
// ---------------------------------------------------------------------------

/// Compute a smoothing coefficient for an attack/release time in ms.
/// Uses the standard `exp(-1/(time_s * sample_rate))` formula.
fn compute_time_coeff(time_ms: f32, sample_rate: f32) -> f32 {
    if time_ms <= 0.0 || sample_rate <= 0.0 {
        return 0.0;
    }
    let time_samples = time_ms * 0.001 * sample_rate;
    (-1.0 / time_samples).exp()
}

/// Convert linear amplitude to dBFS. Returns –144 dB for zero/near-zero input.
fn linear_to_db(x: f32) -> f32 {
    if x < 1e-7 {
        -144.0
    } else {
        20.0 * x.log10()
    }
}

/// Convert dBFS to linear amplitude.
fn db_to_linear(db: f32) -> f32 {
    10.0_f32.powf(db / 20.0)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // ---- BandConfig tests --------------------------------------------------

    #[test]
    fn test_band_config_default() {
        let c = BandConfig::default();
        assert!(c.validate().is_ok());
        assert!(c.ratio >= 1.0);
        assert!(c.attack_ms > 0.0);
        assert!(c.release_ms > 0.0);
    }

    #[test]
    fn test_band_config_gentle() {
        let c = BandConfig::gentle();
        assert!(c.validate().is_ok());
    }

    #[test]
    fn test_band_config_limiting() {
        let c = BandConfig::limiting();
        assert!(c.validate().is_ok());
        assert!(c.ratio >= 10.0);
    }

    #[test]
    fn test_band_config_validate_bad_ratio() {
        let c = BandConfig {
            ratio: 0.5,
            ..Default::default()
        };
        assert!(c.validate().is_err());
    }

    #[test]
    fn test_band_config_validate_zero_attack() {
        let c = BandConfig {
            attack_ms: 0.0,
            ..Default::default()
        };
        assert!(c.validate().is_err());
    }

    #[test]
    fn test_band_config_validate_zero_release() {
        let c = BandConfig {
            release_ms: 0.0,
            ..Default::default()
        };
        assert!(c.validate().is_err());
    }

    #[test]
    fn test_band_config_validate_negative_knee() {
        let c = BandConfig {
            knee_db: -1.0,
            ..Default::default()
        };
        assert!(c.validate().is_err());
    }

    // ---- MultibandCompressor construction ----------------------------------

    #[test]
    fn test_new_default_crossovers() {
        let comp = MultibandCompressor::new(48_000.0);
        assert!((comp.crossover_low_hz() - 250.0).abs() < 1.0);
        assert!((comp.crossover_high_hz() - 4_000.0).abs() < 1.0);
    }

    #[test]
    fn test_new_with_bands_custom_crossovers() {
        let comp = MultibandCompressor::new_with_bands(
            BandConfig::default(),
            BandConfig::default(),
            BandConfig::default(),
            300.0,
            3_000.0,
            48_000.0,
        );
        assert!((comp.crossover_low_hz() - 300.0).abs() < 1.0);
        assert!((comp.crossover_high_hz() - 3_000.0).abs() < 1.0);
    }

    // ---- Processing --------------------------------------------------------

    #[test]
    fn test_process_sample_finite() {
        let mut comp = MultibandCompressor::new(48_000.0);
        for i in 0..1024 {
            let s = (i as f32 * 0.02).sin() * 0.4;
            let out = comp.process_sample(s);
            assert!(out.is_finite(), "non-finite output at sample {i}");
        }
    }

    #[test]
    fn test_process_silent_input() {
        let mut comp = MultibandCompressor::new(48_000.0);
        let out = comp.process_sample(0.0);
        assert!(out.abs() < 1e-6);
    }

    #[test]
    fn test_process_buffer_length_preserved() {
        let mut comp = MultibandCompressor::new(48_000.0);
        let mut buf = vec![0.2f32; 512];
        comp.process(&mut buf);
        assert_eq!(buf.len(), 512);
    }

    #[test]
    fn test_process_buffer_all_finite() {
        let mut comp = MultibandCompressor::new(48_000.0);
        let mut buf: Vec<f32> = (0..1024).map(|i| (i as f32 * 0.05).sin() * 0.5).collect();
        comp.process(&mut buf);
        for &v in &buf {
            assert!(v.is_finite());
        }
    }

    #[test]
    fn test_reset_clears_state() {
        let mut comp = MultibandCompressor::new(48_000.0);
        let mut buf = vec![0.8f32; 512];
        comp.process(&mut buf);
        comp.reset();
        // After reset, processing a quiet signal should behave like a fresh instance
        let mut comp2 = MultibandCompressor::new(48_000.0);
        let input = 0.1f32;
        let out1 = comp.process_sample(input);
        let out2 = comp2.process_sample(input);
        assert!((out1 - out2).abs() < 1e-4);
    }

    // ---- Compression behaviour ---------------------------------------------

    #[test]
    fn test_compression_reduces_loud_signal() {
        // With high ratio and low threshold, loud signals should be attenuated
        let low = BandConfig {
            threshold_db: -30.0,
            ratio: 10.0,
            attack_ms: 1.0,
            release_ms: 50.0,
            knee_db: 0.0,
            makeup_gain_db: 0.0,
        };
        let mut comp = MultibandCompressor::new_with_bands(
            low,
            BandConfig::default(),
            BandConfig::default(),
            200.0,
            5_000.0,
            48_000.0,
        );
        // Feed loud signal to build up envelope
        let input = 0.9f32;
        let mut outputs = Vec::new();
        for _ in 0..500 {
            outputs.push(comp.process_sample(input));
        }
        let last = *outputs.last().unwrap_or(&0.0);
        // Output should be reduced significantly below input in the steady state
        assert!(
            last.abs() <= input.abs() + 0.05,
            "Compression did not reduce level: {last}"
        );
    }

    #[test]
    fn test_makeup_gain_increases_output() {
        let band_no_makeup = BandConfig {
            makeup_gain_db: 0.0,
            threshold_db: -6.0,
            ratio: 4.0,
            attack_ms: 1.0,
            release_ms: 50.0,
            knee_db: 0.0,
        };
        let band_with_makeup = BandConfig {
            makeup_gain_db: 6.0,
            ..band_no_makeup.clone()
        };

        let mut comp1 = MultibandCompressor::new_with_bands(
            band_no_makeup,
            BandConfig::default(),
            BandConfig::default(),
            250.0,
            4_000.0,
            48_000.0,
        );
        let mut comp2 = MultibandCompressor::new_with_bands(
            band_with_makeup,
            BandConfig::default(),
            BandConfig::default(),
            250.0,
            4_000.0,
            48_000.0,
        );

        let input = 0.1f32; // Below threshold, so gain computer neutral, but makeup still applies
                            // Warm up
        for _ in 0..100 {
            comp1.process_sample(input);
            comp2.process_sample(input);
        }
        let out1 = comp1.process_sample(input);
        let out2 = comp2.process_sample(input);

        assert!(
            out2.abs() >= out1.abs(),
            "Makeup gain should increase output level"
        );
    }

    // ---- Utility function tests --------------------------------------------

    #[test]
    fn test_db_to_linear_roundtrip() {
        let db = -12.0f32;
        let linear = db_to_linear(db);
        let back = linear_to_db(linear);
        assert!((back - db).abs() < 0.01);
    }

    #[test]
    fn test_linear_to_db_zero() {
        let db = linear_to_db(0.0);
        assert!(db <= -100.0, "Zero amplitude should give very low dB");
    }

    #[test]
    fn test_compute_time_coeff_range() {
        let coeff = compute_time_coeff(10.0, 48_000.0);
        assert!(coeff > 0.0 && coeff < 1.0);
    }
}