oximedia-effects 0.1.1

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
//! Multi-band filter bank for spectral shaping and analysis.
//!
//! Provides a configurable bank of second-order band-pass filters
//! for graphic EQ, spectral analysis, and crossover applications.

#![allow(dead_code)]

/// Shape of a filter band.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BandShape {
    /// Resonant band-pass filter.
    BandPass,
    /// Low-shelf filter.
    LowShelf,
    /// High-shelf filter.
    HighShelf,
    /// Parametric (peaking) EQ band.
    Peaking,
    /// Notch (band-reject) filter.
    Notch,
}

impl BandShape {
    /// Human-readable label.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            BandShape::BandPass => "Band-Pass",
            BandShape::LowShelf => "Low-Shelf",
            BandShape::HighShelf => "High-Shelf",
            BandShape::Peaking => "Peaking",
            BandShape::Notch => "Notch",
        }
    }
}

/// A single filter band in the bank.
#[derive(Debug, Clone)]
pub struct FilterBand {
    /// Centre frequency in Hz.
    pub center_hz: f32,
    /// Bandwidth in Hz (Q-derived).
    pub bandwidth_hz_val: f32,
    /// Gain in dB (used by peaking and shelf types).
    pub gain_db: f32,
    /// Filter shape.
    pub shape: BandShape,
    /// Whether this band is active.
    pub enabled: bool,
    // Biquad state variables (transposed direct-form II)
    s1: f32,
    s2: f32,
    // Biquad coefficients: b0, b1, b2, a1, a2
    b0: f32,
    b1: f32,
    b2: f32,
    a1: f32,
    a2: f32,
}

impl FilterBand {
    /// Create a peaking band at `center_hz` with `bandwidth_hz` and `gain_db`.
    #[allow(clippy::cast_precision_loss)]
    #[must_use]
    pub fn peaking(center_hz: f32, bandwidth_hz: f32, gain_db: f32, sample_rate: f32) -> Self {
        let mut band = Self {
            center_hz,
            bandwidth_hz_val: bandwidth_hz,
            gain_db,
            shape: BandShape::Peaking,
            enabled: true,
            s1: 0.0,
            s2: 0.0,
            b0: 1.0,
            b1: 0.0,
            b2: 0.0,
            a1: 0.0,
            a2: 0.0,
        };
        band.recalculate(sample_rate);
        band
    }

    /// Create a band-pass band.
    #[must_use]
    pub fn band_pass(center_hz: f32, bandwidth_hz: f32, sample_rate: f32) -> Self {
        let mut band = Self {
            center_hz,
            bandwidth_hz_val: bandwidth_hz,
            gain_db: 0.0,
            shape: BandShape::BandPass,
            enabled: true,
            s1: 0.0,
            s2: 0.0,
            b0: 1.0,
            b1: 0.0,
            b2: 0.0,
            a1: 0.0,
            a2: 0.0,
        };
        band.recalculate(sample_rate);
        band
    }

    /// Bandwidth in Hz.
    #[must_use]
    pub fn bandwidth_hz(&self) -> f32 {
        self.bandwidth_hz_val
    }

    /// Q factor derived from centre frequency and bandwidth.
    #[must_use]
    pub fn q(&self) -> f32 {
        if self.bandwidth_hz_val > 0.0 {
            self.center_hz / self.bandwidth_hz_val
        } else {
            1.0
        }
    }

    /// Recalculate biquad coefficients.
    pub fn recalculate(&mut self, sample_rate: f32) {
        use std::f32::consts::PI;
        let w0 = 2.0 * PI * self.center_hz / sample_rate;
        let cos_w0 = w0.cos();
        let sin_w0 = w0.sin();
        let q = self.q().max(0.01);
        let alpha = sin_w0 / (2.0 * q);

        match self.shape {
            BandShape::Peaking => {
                let a = 10.0_f32.powf(self.gain_db / 40.0);
                self.b0 = 1.0 + alpha * a;
                self.b1 = -2.0 * cos_w0;
                self.b2 = 1.0 - alpha * a;
                let a0 = 1.0 + alpha / a;
                self.a1 = -2.0 * cos_w0 / a0;
                self.a2 = (1.0 - alpha / a) / a0;
                self.b0 /= a0;
                self.b1 /= a0;
                self.b2 /= a0;
            }
            BandShape::BandPass => {
                self.b0 = alpha;
                self.b1 = 0.0;
                self.b2 = -alpha;
                let a0 = 1.0 + alpha;
                self.b0 /= a0;
                self.b1 /= a0;
                self.b2 /= a0;
                self.a1 = -2.0 * cos_w0 / a0;
                self.a2 = (1.0 - alpha) / a0;
            }
            BandShape::Notch => {
                self.b0 = 1.0;
                self.b1 = -2.0 * cos_w0;
                self.b2 = 1.0;
                let a0 = 1.0 + alpha;
                self.b0 /= a0;
                self.b1 /= a0;
                self.b2 /= a0;
                self.a1 = -2.0 * cos_w0 / a0;
                self.a2 = (1.0 - alpha) / a0;
            }
            BandShape::LowShelf | BandShape::HighShelf => {
                // Flat pass-through for shelf (simplified)
                self.b0 = 1.0;
                self.b1 = 0.0;
                self.b2 = 0.0;
                self.a1 = 0.0;
                self.a2 = 0.0;
            }
        }
    }

    /// Process a single sample through this band.
    pub fn process_sample(&mut self, input: f32) -> f32 {
        if !self.enabled {
            return input;
        }
        let output = self.b0 * input + self.s1;
        self.s1 = self.b1 * input - self.a1 * output + self.s2;
        self.s2 = self.b2 * input - self.a2 * output;
        output
    }

    /// Reset filter state.
    pub fn reset(&mut self) {
        self.s1 = 0.0;
        self.s2 = 0.0;
    }
}

/// Configuration snapshot for a filter bank.
#[derive(Debug, Clone, Default)]
pub struct FilterBankConfig {
    /// Number of bands.
    pub band_count: usize,
    /// Sample rate.
    pub sample_rate: f32,
    /// Global bypass switch.
    pub bypassed: bool,
}

impl FilterBankConfig {
    /// Create a config for `band_count` bands at `sample_rate`.
    #[must_use]
    pub fn new(band_count: usize, sample_rate: f32) -> Self {
        Self {
            band_count,
            sample_rate,
            bypassed: false,
        }
    }

    /// Number of bands in this configuration.
    #[must_use]
    pub fn band_count(&self) -> usize {
        self.band_count
    }
}

/// A bank of filter bands operating in series.
pub struct FilterBank {
    bands: Vec<FilterBand>,
    sample_rate: f32,
}

impl FilterBank {
    /// Create an empty filter bank.
    #[must_use]
    pub fn new(sample_rate: f32) -> Self {
        Self {
            bands: Vec::new(),
            sample_rate,
        }
    }

    /// Add a band to the bank.
    pub fn add_band(&mut self, band: FilterBand) {
        self.bands.push(band);
    }

    /// Process a single sample through all enabled bands in series.
    pub fn process_sample(&mut self, mut input: f32) -> f32 {
        for band in &mut self.bands {
            input = band.process_sample(input);
        }
        input
    }

    /// Centre frequencies of all registered bands.
    #[must_use]
    pub fn center_frequencies(&self) -> Vec<f32> {
        self.bands.iter().map(|b| b.center_hz).collect()
    }

    /// Number of bands in the bank.
    #[must_use]
    pub fn band_count(&self) -> usize {
        self.bands.len()
    }

    /// Reset all band states.
    pub fn reset(&mut self) {
        for band in &mut self.bands {
            band.reset();
        }
    }

    /// Sample rate.
    #[must_use]
    pub fn sample_rate(&self) -> f32 {
        self.sample_rate
    }
}

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

    #[test]
    fn test_band_shape_labels() {
        assert_eq!(BandShape::BandPass.label(), "Band-Pass");
        assert_eq!(BandShape::Peaking.label(), "Peaking");
        assert_eq!(BandShape::Notch.label(), "Notch");
    }

    #[test]
    fn test_filter_band_bandwidth_hz() {
        let band = FilterBand::peaking(1000.0, 200.0, 0.0, 48000.0);
        assert!((band.bandwidth_hz() - 200.0).abs() < 0.01);
    }

    #[test]
    fn test_filter_band_q() {
        let band = FilterBand::peaking(1000.0, 200.0, 0.0, 48000.0);
        let q = band.q();
        assert!((q - 5.0).abs() < 0.01, "expected q=5, got {q}");
    }

    #[test]
    fn test_filter_band_pass_through_when_disabled() {
        let mut band = FilterBand::band_pass(1000.0, 200.0, 48000.0);
        band.enabled = false;
        let out = band.process_sample(0.5);
        assert!((out - 0.5).abs() < 1e-6);
    }

    #[test]
    fn test_filter_band_reset() {
        let mut band = FilterBand::band_pass(500.0, 100.0, 48000.0);
        // Process a sample to dirty state
        band.process_sample(1.0);
        band.reset();
        assert_eq!(band.s1, 0.0);
        assert_eq!(band.s2, 0.0);
    }

    #[test]
    fn test_filter_bank_add_and_count() {
        let mut bank = FilterBank::new(48000.0);
        assert_eq!(bank.band_count(), 0);
        bank.add_band(FilterBand::band_pass(500.0, 100.0, 48000.0));
        bank.add_band(FilterBand::band_pass(1000.0, 200.0, 48000.0));
        assert_eq!(bank.band_count(), 2);
    }

    #[test]
    fn test_filter_bank_center_frequencies() {
        let mut bank = FilterBank::new(48000.0);
        bank.add_band(FilterBand::band_pass(500.0, 100.0, 48000.0));
        bank.add_band(FilterBand::band_pass(2000.0, 400.0, 48000.0));
        let freqs = bank.center_frequencies();
        assert_eq!(freqs.len(), 2);
        assert!((freqs[0] - 500.0).abs() < 0.01);
        assert!((freqs[1] - 2000.0).abs() < 0.01);
    }

    #[test]
    fn test_filter_bank_process_silence() {
        let mut bank = FilterBank::new(48000.0);
        bank.add_band(FilterBand::peaking(1000.0, 200.0, 6.0, 48000.0));
        // Silence should remain silence
        let out = bank.process_sample(0.0);
        assert!(out.abs() < 1e-6);
    }

    #[test]
    fn test_filter_bank_reset() {
        let mut bank = FilterBank::new(48000.0);
        bank.add_band(FilterBand::peaking(500.0, 100.0, 3.0, 48000.0));
        bank.process_sample(1.0);
        bank.reset();
        // After reset, silence input should yield near-zero output
        let out = bank.process_sample(0.0);
        assert!(
            out.abs() < 1e-5,
            "expected near zero after reset, got {out}"
        );
    }

    #[test]
    fn test_filter_bank_config_band_count() {
        let cfg = FilterBankConfig::new(10, 48000.0);
        assert_eq!(cfg.band_count(), 10);
        assert!(!cfg.bypassed);
    }

    #[test]
    fn test_filter_bank_sample_rate() {
        let bank = FilterBank::new(44100.0);
        assert!((bank.sample_rate() - 44100.0).abs() < 0.01);
    }

    #[test]
    fn test_band_pass_attenuates_off_frequency() {
        let mut band = FilterBand::band_pass(10000.0, 500.0, 48000.0);
        // Feed a low-frequency pulse and check that DC is attenuated
        let out = band.process_sample(1.0);
        // Band-pass at 10kHz should pass very little DC energy
        assert!(out.abs() < 0.5, "expected attenuation of DC, got {out}");
    }

    #[test]
    fn test_notch_reduces_signal() {
        // Create a notch band manually by using recalculate
        let mut band = FilterBand {
            center_hz: 1000.0,
            bandwidth_hz_val: 100.0,
            gain_db: 0.0,
            shape: BandShape::Notch,
            enabled: true,
            s1: 0.0,
            s2: 0.0,
            b0: 1.0,
            b1: 0.0,
            b2: 0.0,
            a1: 0.0,
            a2: 0.0,
        };
        band.recalculate(48000.0);
        // Just verify it processes without panic
        let _ = band.process_sample(0.5);
    }
}