Skip to main content

qualia_audio/features/filters/
biquad.rs

1//! Biquad (second-order IIR) engine — the shared core all EQ designs feed.
2//!
3//! `BiquadCoeffs` are normalized (a0 folded to 1). `BiquadState` runs Direct
4//! Form I via [`etalon_signal::filter::df1_step_f32`]: it keeps two input and
5//! two output history taps on the stack, so the hot path allocates nothing.
6
7use crate::types::AudioError;
8
9/// Normalized biquad coefficients (transfer function with `a0 == 1`).
10///
11/// `y[n] = b0*x[n] + b1*x[n-1] + b2*x[n-2] - a1*y[n-1] - a2*y[n-2]`
12#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct BiquadCoeffs {
14    pub b0: f32,
15    pub b1: f32,
16    pub b2: f32,
17    pub a1: f32,
18    pub a2: f32,
19}
20
21impl BiquadCoeffs {
22    /// Identity (pass-through) filter: `y[n] = x[n]`.
23    pub const fn identity() -> Self {
24        Self {
25            b0: 1.0,
26            b1: 0.0,
27            b2: 0.0,
28            a1: 0.0,
29            a2: 0.0,
30        }
31    }
32
33    /// Convert from `f64` [`etalon_signal::filter::BiquadCoeffs`].
34    #[inline]
35    pub const fn from_etalon(c: etalon_signal::filter::BiquadCoeffs) -> Self {
36        Self {
37            b0: c.b0 as f32,
38            b1: c.b1 as f32,
39            b2: c.b2 as f32,
40            a1: c.a1 as f32,
41            a2: c.a2 as f32,
42        }
43    }
44
45    /// Design a 2nd-order peaking EQ filter via `etalon_signal::filter::rbj_peaking_eq`.
46    pub fn design_peaking_eq(sample_rate: f32, center_hz: f32, q: f32, gain_db: f32) -> Self {
47        let sr = f64::from(if sample_rate > 1.0 { sample_rate } else { 1.0 });
48        let f0 = f64::from(center_hz).clamp(1.0e-4, sr * 0.5 * 0.999);
49        let q64 = f64::from(if q > 1.0e-4 { q } else { 1.0e-4 });
50        etalon_signal::filter::rbj_peaking_eq(sr, f0, q64, f64::from(gain_db))
51            .map(Self::from_etalon)
52            .unwrap_or_else(|_| Self::identity())
53    }
54
55    /// Build from raw (un-normalized) cookbook coefficients by dividing through
56    /// by `a0`. Falls back to identity if `a0` is not finite/non-zero.
57    pub(crate) fn from_raw(b0: f32, b1: f32, b2: f32, a0: f32, a1: f32, a2: f32) -> Self {
58        if a0 == 0.0 || !a0.is_finite() {
59            return Self::identity();
60        }
61        let inv = 1.0 / a0;
62        Self {
63            b0: b0 * inv,
64            b1: b1 * inv,
65            b2: b2 * inv,
66            a1: a1 * inv,
67            a2: a2 * inv,
68        }
69    }
70}
71
72/// Running filter state (two-tap history). Direct Form I — one instance per
73/// mono channel. Zero-heap: all state lives inline on the stack.
74#[derive(Debug, Clone, Copy, Default)]
75pub struct BiquadState {
76    x1: f32,
77    x2: f32,
78    y1: f32,
79    y2: f32,
80}
81
82impl BiquadState {
83    /// Fresh state with all history taps at zero.
84    pub const fn new() -> Self {
85        Self {
86            x1: 0.0,
87            x2: 0.0,
88            y1: 0.0,
89            y2: 0.0,
90        }
91    }
92
93    /// Clear history taps (e.g. on discontinuity / seek).
94    pub fn reset(&mut self) {
95        self.x1 = 0.0;
96        self.x2 = 0.0;
97        self.y1 = 0.0;
98        self.y2 = 0.0;
99    }
100
101    /// Process one sample; advances history. No allocation.
102    #[inline]
103    pub fn process_sample(&mut self, c: &BiquadCoeffs, x: f32) -> f32 {
104        etalon_signal::filter::df1_step_f32(
105            c.b0,
106            c.b1,
107            c.b2,
108            c.a1,
109            c.a2,
110            &mut self.x1,
111            &mut self.x2,
112            &mut self.y1,
113            &mut self.y2,
114            x,
115        )
116    }
117
118    /// Process a whole block into a caller-supplied output buffer.
119    ///
120    /// `out` must be at least as long as `x`; extra `out` slots are untouched.
121    pub fn process(
122        &mut self,
123        c: &BiquadCoeffs,
124        x: &[f32],
125        out: &mut [f32],
126    ) -> Result<(), AudioError> {
127        if out.len() < x.len() {
128            return Err(AudioError::OutputBufferTooSmall);
129        }
130        for (i, &xi) in x.iter().enumerate() {
131            out[i] = self.process_sample(c, xi);
132        }
133        Ok(())
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn zero_input_stays_zero() {
143        let c = BiquadCoeffs {
144            b0: 0.5,
145            b1: -0.3,
146            b2: 0.2,
147            a1: -1.1,
148            a2: 0.4,
149        };
150        let mut st = BiquadState::new();
151        let x = [0.0f32; 16];
152        let mut out = [9.0f32; 16];
153        st.process(&c, &x, &mut out).expect("buffer big enough");
154        for &y in &out {
155            assert_eq!(y, 0.0);
156        }
157    }
158
159    #[test]
160    fn impulse_response_first_taps_fir() {
161        // Pure FIR (a1=a2=0): impulse response is exactly [b0, b1, b2, 0, ...].
162        let c = BiquadCoeffs {
163            b0: 0.25,
164            b1: 0.5,
165            b2: -0.125,
166            a1: 0.0,
167            a2: 0.0,
168        };
169        let mut st = BiquadState::new();
170        let mut x = [0.0f32; 6];
171        x[0] = 1.0;
172        let mut out = [0.0f32; 6];
173        st.process(&c, &x, &mut out).expect("buffer big enough");
174        assert!((out[0] - 0.25).abs() < 1e-6);
175        assert!((out[1] - 0.5).abs() < 1e-6);
176        assert!((out[2] - (-0.125)).abs() < 1e-6);
177        assert!((out[3]).abs() < 1e-6);
178        assert!((out[4]).abs() < 1e-6);
179    }
180
181    #[test]
182    fn impulse_response_with_feedback() {
183        // y[n] = b0*x + b1*x1 - a1*y1.  Impulse: y0=b0, y1=b1-a1*b0,
184        // y2 = -a1*y1, y3 = -a1*y2 ...
185        let c = BiquadCoeffs {
186            b0: 1.0,
187            b1: 0.5,
188            b2: 0.0,
189            a1: -0.5,
190            a2: 0.0,
191        };
192        let mut st = BiquadState::new();
193        let mut x = [0.0f32; 5];
194        x[0] = 1.0;
195        let mut out = [0.0f32; 5];
196        st.process(&c, &x, &mut out).expect("buffer big enough");
197        let y0 = 1.0f32;
198        let y1 = 0.5 - (-0.5) * y0; // = 1.0
199        let y2 = -(-0.5) * y1; // = 0.5
200        let y3 = -(-0.5) * y2; // = 0.25
201        assert!((out[0] - y0).abs() < 1e-6);
202        assert!((out[1] - y1).abs() < 1e-6);
203        assert!((out[2] - y2).abs() < 1e-6);
204        assert!((out[3] - y3).abs() < 1e-6);
205    }
206
207    #[test]
208    fn short_output_buffer_errors() {
209        let c = BiquadCoeffs::identity();
210        let mut st = BiquadState::new();
211        let x = [1.0f32; 8];
212        let mut out = [0.0f32; 4];
213        assert_eq!(
214            st.process(&c, &x, &mut out),
215            Err(AudioError::OutputBufferTooSmall)
216        );
217    }
218
219    #[test]
220    fn identity_passes_through() {
221        let c = BiquadCoeffs::identity();
222        let mut st = BiquadState::new();
223        let x = [0.1, -0.4, 0.7, -0.9, 0.2];
224        let mut out = [0.0f32; 5];
225        st.process(&c, &x, &mut out).expect("buffer big enough");
226        for i in 0..x.len() {
227            assert!((out[i] - x[i]).abs() < 1e-6);
228        }
229    }
230}