Skip to main content

qualia_core_db/audio/dsp/
biquad_df2t.rs

1//! Direct Form II Transposed (DF2T) 3-Band Parametric Biquad Filter.
2//!
3//! Designed for the Webizen AudioWorklet real-time audio thread:
4//! - **DF2T Topology**: 2 state variables per biquad, superior numerical stability
5//!   against low-frequency pole quantization (200 Hz low-shelf anchor).
6//! - **Denormal Prevention**: Injects $10^{-24}$ DC offset into raw samples, preventing
7//!   subnormal stall penalties (up to 100x) on mobile ARM NEON FPUs.
8//! - **128-Sample Quantum Ramping**: Trigonometric coefficient updates occur strictly
9//!   at quantum boundaries (2.67 ms @ 48 kHz). Inner sample loop linearly ramps coefficients
10//!   using 5 scalar additions per sample, eliminating zipper noise and audio clicks.
11//! - **Zero-Heap Hot Path**: Evaluates directly into caller-supplied slices, delegating
12//!   RBJ Audio EQ Cookbook synthesis and DF2T recurrence math to `etalon_signal::filter`.
13
14use etalon_signal::filter::{
15    df2t_step_f32, rbj_high_shelf, rbj_low_shelf, rbj_peaking_eq,
16    BiquadCoeffs as EtalonBiquadCoeffs,
17};
18
19/// AudioWorklet render quantum — coefficient updates and ramping occur at
20/// these boundaries (2.67 ms @ 48 kHz).
21pub const QUANTUM_SIZE: usize = 128;
22/// DC offset injected per sample to prevent subnormal-FPU stall penalties.
23pub const DENORMAL_DC_OFFSET: f32 = 1e-24;
24
25/// Low-frequency shelf anchor (Hz).
26pub const ANCHOR_LOW_HZ: f32 = 200.0;
27/// Mid-frequency peaking band anchor (Hz).
28pub const ANCHOR_MID_HZ: f32 = 1000.0;
29/// High-frequency shelf anchor (Hz).
30pub const ANCHOR_HIGH_HZ: f32 = 8000.0;
31
32/// Normalized biquad filter coefficients $H(z) = \frac{b_0 + b_1 z^{-1} + b_2 z^{-2}}{1 + a_1 z^{-1} + a_2 z^{-2}}$.
33#[repr(C)]
34#[derive(Debug, Clone, Copy, PartialEq)]
35pub struct BiquadCoeffs {
36    /// Feed-forward coefficient for `x[n]`.
37    pub b0: f32,
38    /// Feed-forward coefficient for `x[n-1]`.
39    pub b1: f32,
40    /// Feed-forward coefficient for `x[n-2]`.
41    pub b2: f32,
42    /// Feedback coefficient for `y[n-1]`.
43    pub a1: f32,
44    /// Feedback coefficient for `y[n-2]`.
45    pub a2: f32,
46}
47
48impl Default for BiquadCoeffs {
49    fn default() -> Self {
50        Self {
51            b0: 1.0,
52            b1: 0.0,
53            b2: 0.0,
54            a1: 0.0,
55            a2: 0.0,
56        }
57    }
58}
59
60impl BiquadCoeffs {
61    /// Convert to double-precision `etalon_signal::filter::BiquadCoeffs`.
62    #[inline]
63    pub fn to_etalon(self) -> EtalonBiquadCoeffs {
64        EtalonBiquadCoeffs::from_f32(self.b0, self.b1, self.b2, self.a1, self.a2)
65    }
66
67    /// Convert from double-precision `etalon_signal::filter::BiquadCoeffs`.
68    #[inline]
69    pub fn from_etalon(c: EtalonBiquadCoeffs) -> Self {
70        Self {
71            b0: c.b0 as f32,
72            b1: c.b1 as f32,
73            b2: c.b2 as f32,
74            a1: c.a1 as f32,
75            a2: c.a2 as f32,
76        }
77    }
78
79    /// Verify Jury stability ($|a_2| < 1$ and $|a_1| < 1 + a_2$) via `etalon_signal`.
80    #[inline]
81    pub fn is_stable(&self) -> bool {
82        self.to_etalon().is_stable()
83    }
84}
85
86/// Direct Form II Transposed filter state registers.
87#[repr(C)]
88#[derive(Debug, Clone, Copy, PartialEq, Default)]
89pub struct Df2tState {
90    /// First state register (`s1[n-1]`).
91    pub s1: f32,
92    /// Second state register (`s2[n-1]`).
93    pub s2: f32,
94}
95
96impl Df2tState {
97    /// Clear both state registers.
98    #[inline]
99    pub fn reset(&mut self) {
100        self.s1 = 0.0;
101        self.s2 = 0.0;
102    }
103}
104
105/// Single DF2T biquad filter with linear coefficient ramping.
106#[derive(Debug, Clone)]
107pub struct Df2tBiquad {
108    /// DF2T state registers.
109    pub state: Df2tState,
110    /// Coefficients in use this sample (ramped per-sample toward `target`).
111    pub active: BiquadCoeffs,
112    /// Coefficients being ramped toward over the current quantum.
113    pub target: BiquadCoeffs,
114    /// Per-sample increment derived in `set_target_quantum`.
115    pub delta: BiquadCoeffs,
116}
117
118impl Default for Df2tBiquad {
119    fn default() -> Self {
120        Self {
121            state: Df2tState::default(),
122            active: BiquadCoeffs::default(),
123            target: BiquadCoeffs::default(),
124            delta: BiquadCoeffs {
125                b0: 0.0,
126                b1: 0.0,
127                b2: 0.0,
128                a1: 0.0,
129                a2: 0.0,
130            },
131        }
132    }
133}
134
135impl Df2tBiquad {
136    /// Prepare ramping step towards new target coefficients over the next 128-sample quantum.
137    #[inline]
138    pub fn set_target_quantum(&mut self, target: BiquadCoeffs) {
139        self.target = target;
140        let inv_q = 1.0 / (QUANTUM_SIZE as f32);
141        self.delta = BiquadCoeffs {
142            b0: (target.b0 - self.active.b0) * inv_q,
143            b1: (target.b1 - self.active.b1) * inv_q,
144            b2: (target.b2 - self.active.b2) * inv_q,
145            a1: (target.a1 - self.active.a1) * inv_q,
146            a2: (target.a2 - self.active.a2) * inv_q,
147        };
148    }
149
150    /// Process a single sample using DF2T transposed topology with 5-addition coefficient ramp.
151    #[inline]
152    pub fn process_sample(&mut self, input: f32) -> f32 {
153        // Step coefficients
154        self.active.b0 += self.delta.b0;
155        self.active.b1 += self.delta.b1;
156        self.active.b2 += self.delta.b2;
157        self.active.a1 += self.delta.a1;
158        self.active.a2 += self.delta.a2;
159
160        df2t_step_f32(
161            self.active.b0,
162            self.active.b1,
163            self.active.b2,
164            self.active.a1,
165            self.active.a2,
166            &mut self.state.s1,
167            &mut self.state.s2,
168            input,
169        )
170    }
171}
172
173/// 3-Band Parametric Equalizer consisting of cascaded DF2T biquads:
174/// 1. Low Shelf (200 Hz anchor)
175/// 2. Mid Peaking (1000 Hz anchor)
176/// 3. High Shelf (8000 Hz anchor)
177#[derive(Debug, Clone)]
178pub struct ThreeBandParametricBiquad {
179    /// Sample rate the coefficients were computed for (clamped to ≥ 8 kHz).
180    pub sample_rate: f32,
181    /// Low shelf stage at `ANCHOR_LOW_HZ` (200 Hz).
182    pub low_shelf: Df2tBiquad,
183    /// Mid peaking stage at `ANCHOR_MID_HZ` (1 kHz).
184    pub mid_peak: Df2tBiquad,
185    /// High shelf stage at `ANCHOR_HIGH_HZ` (8 kHz).
186    pub high_shelf: Df2tBiquad,
187}
188
189impl ThreeBandParametricBiquad {
190    /// Create an EQ at flat unity response (0 dB on all bands), coefficients
191    /// snapped to target so no ramping occurs on the first quantum.
192    pub fn new(sample_rate: f32) -> Self {
193        let mut eq = Self {
194            sample_rate: sample_rate.max(8000.0),
195            low_shelf: Df2tBiquad::default(),
196            mid_peak: Df2tBiquad::default(),
197            high_shelf: Df2tBiquad::default(),
198        };
199        // Initialize at flat unity response
200        eq.set_band_gains_db(0.0, 0.0, 0.0);
201        eq.snap_to_target();
202        eq
203    }
204
205    /// Snap active coefficients directly to target (useful on init or seek).
206    pub fn snap_to_target(&mut self) {
207        self.low_shelf.active = self.low_shelf.target;
208        self.low_shelf.delta = BiquadCoeffs {
209            b0: 0.0,
210            b1: 0.0,
211            b2: 0.0,
212            a1: 0.0,
213            a2: 0.0,
214        };
215        self.mid_peak.active = self.mid_peak.target;
216        self.mid_peak.delta = BiquadCoeffs {
217            b0: 0.0,
218            b1: 0.0,
219            b2: 0.0,
220            a1: 0.0,
221            a2: 0.0,
222        };
223        self.high_shelf.active = self.high_shelf.target;
224        self.high_shelf.delta = BiquadCoeffs {
225            b0: 0.0,
226            b1: 0.0,
227            b2: 0.0,
228            a1: 0.0,
229            a2: 0.0,
230        };
231    }
232
233    /// Reset internal filter state registers (clear delay lines).
234    pub fn reset_states(&mut self) {
235        self.low_shelf.state.reset();
236        self.mid_peak.state.reset();
237        self.high_shelf.state.reset();
238    }
239
240    /// Configure band gains in decibels for the next 128-sample quantum.
241    pub fn set_band_gains_db(&mut self, low_gain_db: f32, mid_gain_db: f32, high_gain_db: f32) {
242        let low_coeffs =
243            calc_low_shelf_coeffs(self.sample_rate, ANCHOR_LOW_HZ, 0.7071, low_gain_db);
244        let mid_coeffs = calc_peaking_coeffs(self.sample_rate, ANCHOR_MID_HZ, 1.0, mid_gain_db);
245        let high_coeffs =
246            calc_high_shelf_coeffs(self.sample_rate, ANCHOR_HIGH_HZ, 0.7071, high_gain_db);
247
248        self.low_shelf.set_target_quantum(low_coeffs);
249        self.mid_peak.set_target_quantum(mid_coeffs);
250        self.high_shelf.set_target_quantum(high_coeffs);
251    }
252
253    /// Map continuous Jakob & Hanika spectral polynomial coefficients $(c_0, c_1, c_2)$
254    /// directly to the 3-band acoustic parameters.
255    pub fn set_from_spectral_coeffs(&mut self, c0: f32, c1: f32, c2: f32) {
256        // Map polynomial terms to decibel gains in [-18.0, +18.0] dB
257        let low_db = (c0 * 12.0).clamp(-24.0, 24.0);
258        let mid_db = (c1 * 12.0).clamp(-24.0, 24.0);
259        let high_db = (c2 * 12.0).clamp(-24.0, 24.0);
260        self.set_band_gains_db(low_db, mid_db, high_db);
261    }
262
263    /// Process a single 128-sample quantum in-place with zero allocations.
264    /// Injects $10^{-24}$ DC offset into each sample to prevent mobile ARM NEON denormal stalls.
265    #[inline]
266    pub fn process_quantum(&mut self, buffer: &mut [f32; QUANTUM_SIZE]) {
267        for sample in buffer.iter_mut() {
268            // Anti-denormal offset
269            let clean_in = *sample + DENORMAL_DC_OFFSET;
270
271            // Cascade: Low Shelf -> Mid Peak -> High Shelf
272            let y1 = self.low_shelf.process_sample(clean_in);
273            let y2 = self.mid_peak.process_sample(y1);
274            let y3 = self.high_shelf.process_sample(y2);
275
276            *sample = y3;
277        }
278    }
279
280    /// Process a caller-supplied slice of arbitrary length (multiple of 128 recommended).
281    /// Zero heap allocation.
282    pub fn process_slice(&mut self, input: &[f32], output: &mut [f32]) {
283        let n = input.len().min(output.len());
284        let mut i = 0;
285        while i < n {
286            let chunk_len = (n - i).min(QUANTUM_SIZE);
287            for k in 0..chunk_len {
288                let clean_in = input[i + k] + DENORMAL_DC_OFFSET;
289                let y1 = self.low_shelf.process_sample(clean_in);
290                let y2 = self.mid_peak.process_sample(y1);
291                let y3 = self.high_shelf.process_sample(y2);
292                output[i + k] = y3;
293            }
294            i += chunk_len;
295        }
296    }
297}
298
299// ───────────────────────────────────────────────────────────────────────────
300//  Cookbook Biquad Coefficient Calculators (delegated to etalon_signal::filter)
301// ───────────────────────────────────────────────────────────────────────────
302
303#[inline]
304fn sanitize_rbj_params(sr: f32, f0: f32, q: f32) -> (f64, f64, f64) {
305    let sr_f64 = f64::from(sr.max(8000.0));
306    let f0_f64 = f64::from(f0).clamp(1.0, 0.499 * sr_f64);
307    let q_f64 = f64::from(q).max(1e-4);
308    (sr_f64, f0_f64, q_f64)
309}
310
311#[inline]
312fn calc_low_shelf_coeffs(sr: f32, f0: f32, q: f32, gain_db: f32) -> BiquadCoeffs {
313    let (sr_f64, f0_f64, q_f64) = sanitize_rbj_params(sr, f0, q);
314    rbj_low_shelf(sr_f64, f0_f64, q_f64, f64::from(gain_db))
315        .map(BiquadCoeffs::from_etalon)
316        .unwrap_or_default()
317}
318
319#[inline]
320fn calc_peaking_coeffs(sr: f32, f0: f32, q: f32, gain_db: f32) -> BiquadCoeffs {
321    let (sr_f64, f0_f64, q_f64) = sanitize_rbj_params(sr, f0, q);
322    rbj_peaking_eq(sr_f64, f0_f64, q_f64, f64::from(gain_db))
323        .map(BiquadCoeffs::from_etalon)
324        .unwrap_or_default()
325}
326
327#[inline]
328fn calc_high_shelf_coeffs(sr: f32, f0: f32, q: f32, gain_db: f32) -> BiquadCoeffs {
329    let (sr_f64, f0_f64, q_f64) = sanitize_rbj_params(sr, f0, q);
330    rbj_high_shelf(sr_f64, f0_f64, q_f64, f64::from(gain_db))
331        .map(BiquadCoeffs::from_etalon)
332        .unwrap_or_default()
333}
334
335/// Standalone JavaScript snippet for standard AudioWorkletProcessor registration.
336pub const AUDIO_WORKLET_DF2T_JS: &str = r#"
337class ThreeBandBiquadProcessor extends AudioWorkletProcessor {
338  constructor() {
339    super();
340    this.s1 = [0, 0, 0];
341    this.s2 = [0, 0, 0];
342    this.active = [
343      { b0: 1, b1: 0, b2: 0, a1: 0, a2: 0 },
344      { b0: 1, b1: 0, b2: 0, a1: 0, a2: 0 },
345      { b0: 1, b1: 0, b2: 0, a1: 0, a2: 0 }
346    ];
347  }
348
349  process(inputs, outputs, parameters) {
350    const input = inputs[0];
351    const output = outputs[0];
352    if (!input || !input[0]) return true;
353
354    const inChannel = input[0];
355    const outChannel = output[0];
356    const len = inChannel.length;
357
358    for (let i = 0; i < len; i++) {
359      // Inject 1e-24 DC offset to prevent subnormal ARM NEON stalls
360      let x = inChannel[i] + 1e-24;
361      for (let b = 0; b < 3; b++) {
362        const c = this.active[b];
363        const y = c.b0 * x + this.s1[b];
364        this.s1[b] = c.b1 * x - c.a1 * y + this.s2[b];
365        this.s2[b] = c.b2 * x - c.a2 * y;
366        x = y;
367      }
368      outChannel[i] = x;
369    }
370    return true;
371  }
372}
373registerProcessor('three-band-biquad-processor', ThreeBandBiquadProcessor);
374"#;
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379
380    #[test]
381    fn df2t_zero_input_decay_stays_bounded() {
382        let mut eq = ThreeBandParametricBiquad::new(48000.0);
383        eq.set_band_gains_db(6.0, -3.0, 4.0);
384        eq.snap_to_target();
385        assert!(eq.low_shelf.active.is_stable());
386        assert!(eq.mid_peak.active.is_stable());
387        assert!(eq.high_shelf.active.is_stable());
388
389        let mut block = [0.0f32; QUANTUM_SIZE];
390        block[0] = 1.0; // Impulse
391        eq.process_quantum(&mut block);
392
393        // Subsequent silence blocks
394        for _ in 0..10 {
395            let mut silence = [0.0f32; QUANTUM_SIZE];
396            eq.process_quantum(&mut silence);
397            // Verify no NaN or Inf
398            for s in silence.iter() {
399                assert!(!s.is_nan());
400                assert!(!s.is_infinite());
401            }
402        }
403        // State should not enter denormal zero due to DC offset
404        assert!(eq.low_shelf.state.s1.abs() > 0.0);
405    }
406
407    #[test]
408    fn df2t_coefficient_ramping_eliminates_steps() {
409        let mut eq = ThreeBandParametricBiquad::new(48000.0);
410        eq.set_band_gains_db(0.0, 0.0, 0.0);
411        eq.snap_to_target();
412
413        // Introduce large step change
414        eq.set_band_gains_db(12.0, -12.0, 6.0);
415
416        // Process first quantum
417        let mut block = [0.5f32; QUANTUM_SIZE];
418        eq.process_quantum(&mut block);
419
420        // Verify coefficients smoothly interpolated
421        let active_b0 = eq.low_shelf.active.b0;
422        let target_b0 = eq.low_shelf.target.b0;
423        assert!((active_b0 - target_b0).abs() < 1e-4);
424    }
425
426    #[test]
427    fn spectral_coefficient_mapping_produces_stable_response() {
428        let mut eq = ThreeBandParametricBiquad::new(48000.0);
429        eq.set_from_spectral_coeffs(0.85, 0.32, 0.15);
430        eq.snap_to_target();
431
432        let mut block = [0.25f32; QUANTUM_SIZE];
433        eq.process_quantum(&mut block);
434        for s in block.iter() {
435            assert!(s.is_finite());
436        }
437    }
438}