Skip to main content

qualia_audio/features/filters/
allpass.rs

1//! RBJ Audio-EQ-Cookbook all-pass biquad coefficient design.
2//!
3//! Flat magnitude, frequency-dependent phase — used for phase alignment and
4//! dispersion, not tone shaping.
5
6use super::biquad::BiquadCoeffs;
7use core::f32::consts::PI;
8
9/// Design a 2nd-order all-pass (RBJ cookbook `APF`).
10///
11/// `center_hz` sets the frequency of maximum phase shift; `q` sets transition
12/// sharpness. Inputs are clamped so coefficients stay finite.
13pub fn design_allpass(sample_rate: f32, center_hz: f32, q: f32) -> BiquadCoeffs {
14    let (cos_w0, alpha) = rbj_params(sample_rate, center_hz, q);
15    let b0 = 1.0 - alpha;
16    let b1 = -2.0 * cos_w0;
17    let b2 = 1.0 + alpha;
18    let a0 = 1.0 + alpha;
19    let a1 = -2.0 * cos_w0;
20    let a2 = 1.0 - alpha;
21    BiquadCoeffs::from_raw(b0, b1, b2, a0, a1, a2)
22}
23
24/// Shared RBJ intermediate terms `(cos(w0), alpha)` with input clamping.
25fn rbj_params(sample_rate: f32, center_hz: f32, q: f32) -> (f32, f32) {
26    let sr = if sample_rate > 1.0 { sample_rate } else { 1.0 };
27    let nyq = sr * 0.5;
28    let f0 = center_hz.clamp(1.0e-4, nyq * 0.999);
29    let q = if q > 1.0e-4 { q } else { 1.0e-4 };
30    let w0 = 2.0 * PI * f0 / sr;
31    let alpha = w0.sin() / (2.0 * q);
32    (w0.cos(), alpha)
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38    use crate::features::filters::biquad::{BiquadCoeffs, BiquadState};
39
40    fn run_sine(sr: f32, freq: f32, c: &BiquadCoeffs) -> f32 {
41        let n = 16384usize;
42        let skip = 4096usize;
43        let mut st = BiquadState::new();
44        let mut acc_in = 0.0f32;
45        let mut acc_out = 0.0f32;
46        let mut cnt = 0.0f32;
47        for i in 0..n {
48            let x = (2.0 * core::f32::consts::PI * freq * i as f32 / sr).sin();
49            let y = st.process_sample(c, x);
50            if i >= skip {
51                acc_in += x * x;
52                acc_out += y * y;
53                cnt += 1.0;
54            }
55        }
56        (acc_out / cnt).sqrt() / (acc_in / cnt).sqrt()
57    }
58
59    #[test]
60    fn magnitude_flat_across_band() {
61        let c = design_allpass(48_000.0, 1_000.0, 0.707);
62        // All-pass keeps magnitude ~unity at every frequency.
63        for &f in &[100.0, 1_000.0, 5_000.0, 15_000.0] {
64            let ratio = run_sine(48_000.0, f, &c);
65            assert!(ratio > 0.9 && ratio < 1.1, "f={f} ratio={ratio}");
66        }
67    }
68}