Skip to main content

qualia_audio/features/filters/
lowpass.rs

1//! RBJ Audio-EQ-Cookbook low-pass biquad coefficient design.
2
3use super::biquad::BiquadCoeffs;
4
5/// Design a 2nd-order low-pass (RBJ cookbook `LPF`).
6///
7/// `sample_rate` Hz, `cutoff_hz` corner frequency, `q` resonance
8/// (0.707 ≈ Butterworth). Inputs are clamped to a safe range so the returned
9/// coefficients are always finite.
10pub fn design_lowpass(sample_rate: f32, cutoff_hz: f32, q: f32) -> BiquadCoeffs {
11    let sr = f64::from(if sample_rate > 1.0 { sample_rate } else { 1.0 });
12    let f0 = f64::from(cutoff_hz).clamp(1.0e-4, sr * 0.5 * 0.999);
13    let q64 = f64::from(if q > 1.0e-4 { q } else { 1.0e-4 });
14    etalon_signal::filter::rbj_lowpass(sr, f0, q64)
15        .map(BiquadCoeffs::from_etalon)
16        .unwrap_or_else(|_| BiquadCoeffs::identity())
17}
18
19#[cfg(test)]
20mod tests {
21    use super::*;
22    use crate::features::filters::biquad::BiquadState;
23
24    fn rms(xs: &[f32]) -> f32 {
25        let s: f32 = xs.iter().map(|v| v * v).sum();
26        (s / xs.len() as f32).sqrt()
27    }
28
29    fn run_sine(sr: f32, freq: f32, c: &BiquadCoeffs) -> f32 {
30        let n = 8192usize;
31        let skip = 2048usize; // discard transient, measure steady state
32        let mut st = BiquadState::new();
33        let mut acc_in = 0.0f32;
34        let mut acc_out = 0.0f32;
35        let mut cnt = 0.0f32;
36        for i in 0..n {
37            let x = (2.0 * core::f32::consts::PI * freq * i as f32 / sr).sin();
38            let y = st.process_sample(c, x);
39            if i >= skip {
40                acc_in += x * x;
41                acc_out += y * y;
42                cnt += 1.0;
43            }
44        }
45        let rms_in = (acc_in / cnt).sqrt();
46        let rms_out = (acc_out / cnt).sqrt();
47        rms_out / rms_in
48    }
49
50    #[test]
51    fn passband_preserves_rms() {
52        let c = design_lowpass(48_000.0, 1_000.0, 0.707);
53        let ratio = run_sine(48_000.0, 150.0, &c); // well below cutoff
54        assert!(ratio > 0.9 && ratio < 1.1, "passband ratio {ratio}");
55    }
56
57    #[test]
58    fn stopband_attenuates() {
59        let c = design_lowpass(48_000.0, 1_000.0, 0.707);
60        let ratio = run_sine(48_000.0, 12_000.0, &c); // well above cutoff
61        assert!(ratio < 0.3, "stopband ratio {ratio}");
62    }
63
64    #[test]
65    fn coeffs_finite() {
66        let c = design_lowpass(44_100.0, 2_000.0, 0.5);
67        assert!(rms(&[c.b0, c.b1, c.b2, c.a1, c.a2]).is_finite());
68    }
69}