weirdnet-dsp 0.2.0

Weirdnet DSP building blocks: RBJ biquad filters, level helpers (dB, peak, RMS) and fades. Pure functions over slices, no I/O, no allocation per block.
Documentation
//! Biquad filters from the RBJ audio-EQ cookbook (direct form II transposed, `f64` state).
//!
//! Design with [`BiquadCoeffs::design`], run with [`Biquad`] (one channel) or [`MultiBiquad`] (interleaved, one state per
//! channel). [`BiquadCoeffs::response_db`] gives the exact frequency response, which the tests and the plugins' golden checks use.

use std::f64::consts::TAU;

/// What a filter does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterKind {
    /// Passes below the cutoff (`-3 dB` at the cutoff when `Q = 1/sqrt(2)`).
    LowPass,
    /// Passes above the cutoff.
    HighPass,
    /// Passes around the cutoff, constant `0 dB` peak gain; `Q` sets the narrowness.
    BandPass,
    /// Boosts or cuts `gain_db` around the cutoff, `Q` sets the width. With `gain_db = 0` it is an identity.
    Peaking,
}

/// Why a filter could not be designed.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DspError {
    /// The sample rate is zero.
    InvalidSampleRate,
    /// The cutoff is not above zero and below the Nyquist frequency (half the sample rate).
    CutoffOutOfRange { cutoff_hz: f64, nyquist_hz: f64 },
    /// `Q` is not a positive, finite number.
    InvalidQ(f64),
    /// A parameter is NaN or infinite.
    NotFinite(&'static str),
}

impl std::fmt::Display for DspError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DspError::InvalidSampleRate => write!(f, "the sample rate must be above zero"),
            DspError::CutoffOutOfRange { cutoff_hz, nyquist_hz } => {
                write!(f, "the cutoff {cutoff_hz} Hz must be above 0 and below the Nyquist frequency {nyquist_hz} Hz")
            }
            DspError::InvalidQ(q) => write!(f, "Q must be above zero and finite, got {q}"),
            DspError::NotFinite(what) => write!(f, "{what} is not a finite number"),
        }
    }
}

impl std::error::Error for DspError {}

/// Normalised biquad coefficients (`a0 = 1`): `y = b0 x + b1 x1 + b2 x2 - a1 y1 - a2 y2`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BiquadCoeffs {
    pub b0: f64,
    pub b1: f64,
    pub b2: f64,
    pub a1: f64,
    pub a2: f64,
}

impl BiquadCoeffs {
    /// The identity filter.
    pub const IDENTITY: BiquadCoeffs = BiquadCoeffs { b0: 1.0, b1: 0.0, b2: 0.0, a1: 0.0, a2: 0.0 };

    /// Designs a filter. `gain_db` only matters for [`FilterKind::Peaking`].
    pub fn design(kind: FilterKind, sample_rate: u32, cutoff_hz: f64, q: f64, gain_db: f64) -> Result<Self, DspError> {
        if sample_rate == 0 {
            return Err(DspError::InvalidSampleRate);
        }
        if !cutoff_hz.is_finite() {
            return Err(DspError::NotFinite("the cutoff"));
        }
        if !gain_db.is_finite() {
            return Err(DspError::NotFinite("the gain"));
        }
        let nyquist = f64::from(sample_rate) / 2.0;
        if cutoff_hz <= 0.0 || cutoff_hz >= nyquist {
            return Err(DspError::CutoffOutOfRange { cutoff_hz, nyquist_hz: nyquist });
        }
        if !q.is_finite() || q <= 0.0 {
            return Err(DspError::InvalidQ(q));
        }
        let w0 = TAU * cutoff_hz / f64::from(sample_rate);
        let (sin, cos) = w0.sin_cos();
        let alpha = sin / (2.0 * q);
        let (b0, b1, b2, a0, a1, a2) = match kind {
            FilterKind::LowPass => ((1.0 - cos) / 2.0, 1.0 - cos, (1.0 - cos) / 2.0, 1.0 + alpha, -2.0 * cos, 1.0 - alpha),
            FilterKind::HighPass => ((1.0 + cos) / 2.0, -(1.0 + cos), (1.0 + cos) / 2.0, 1.0 + alpha, -2.0 * cos, 1.0 - alpha),
            FilterKind::BandPass => (alpha, 0.0, -alpha, 1.0 + alpha, -2.0 * cos, 1.0 - alpha),
            FilterKind::Peaking => {
                let a = 10f64.powf(gain_db / 40.0);
                (1.0 + alpha * a, -2.0 * cos, 1.0 - alpha * a, 1.0 + alpha / a, -2.0 * cos, 1.0 - alpha / a)
            }
        };
        Ok(BiquadCoeffs { b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: a1 / a0, a2: a2 / a0 })
    }

    /// The gain in dB at `freq_hz` for a signal sampled at `sample_rate`.
    pub fn response_db(&self, freq_hz: f64, sample_rate: u32) -> f64 {
        let w = TAU * freq_hz / f64::from(sample_rate);
        let (s1, c1) = w.sin_cos();
        let (s2, c2) = (2.0 * w).sin_cos();
        // H(e^jw) = (b0 + b1 e^-jw + b2 e^-2jw) / (1 + a1 e^-jw + a2 e^-2jw)
        let num_re = self.b0 + self.b1 * c1 + self.b2 * c2;
        let num_im = -(self.b1 * s1 + self.b2 * s2);
        let den_re = 1.0 + self.a1 * c1 + self.a2 * c2;
        let den_im = -(self.a1 * s1 + self.a2 * s2);
        let num = num_re * num_re + num_im * num_im;
        let den = den_re * den_re + den_im * den_im;
        10.0 * (num / den).log10()
    }

    /// Whether the poles are inside the unit circle (the filter is stable).
    pub fn is_stable(&self) -> bool {
        self.a2.abs() < 1.0 && self.a1.abs() < 1.0 + self.a2
    }
}

/// One channel of a biquad.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Biquad {
    coeffs: BiquadCoeffs,
    z1: f64,
    z2: f64,
}

impl Biquad {
    /// A filter with clear state.
    pub fn new(coeffs: BiquadCoeffs) -> Self {
        Biquad { coeffs, z1: 0.0, z2: 0.0 }
    }

    /// Clears the state.
    pub fn reset(&mut self) {
        self.z1 = 0.0;
        self.z2 = 0.0;
    }

    /// Filters one sample.
    #[inline]
    pub fn process_sample(&mut self, x: f32) -> f32 {
        let x = f64::from(x);
        let c = &self.coeffs;
        let y = c.b0 * x + self.z1;
        self.z1 = c.b1 * x - c.a1 * y + self.z2;
        self.z2 = c.b2 * x - c.a2 * y;
        y as f32
    }

    /// Filters a block in place. No allocation.
    pub fn process(&mut self, block: &mut [f32]) {
        for s in block {
            *s = self.process_sample(*s);
        }
    }
}

/// A biquad per channel over interleaved audio.
#[derive(Debug, Clone)]
pub struct MultiBiquad {
    channels: Vec<Biquad>,
}

impl MultiBiquad {
    /// `channels` filters with the same coefficients. Allocates once, here.
    pub fn new(channels: u16, coeffs: BiquadCoeffs) -> Self {
        MultiBiquad { channels: vec![Biquad::new(coeffs); usize::from(channels.max(1))] }
    }

    /// Clears every channel's state.
    pub fn reset(&mut self) {
        self.channels.iter_mut().for_each(Biquad::reset);
    }

    /// Filters interleaved audio in place. A trailing partial frame is filtered on its own channels. No allocation.
    pub fn process_interleaved(&mut self, samples: &mut [f32]) {
        let n = self.channels.len();
        for (i, s) in samples.iter_mut().enumerate() {
            *s = self.channels[i % n].process_sample(*s);
        }
    }
}

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

    const FS: u32 = 48_000;
    const BUTTERWORTH_Q: f64 = std::f64::consts::FRAC_1_SQRT_2;

    fn design(kind: FilterKind, cutoff: f64, q: f64, gain: f64) -> BiquadCoeffs {
        BiquadCoeffs::design(kind, FS, cutoff, q, gain).unwrap()
    }

    #[test]
    fn low_pass_is_minus_3_db_at_the_cutoff_and_flat_below() {
        let c = design(FilterKind::LowPass, 1000.0, BUTTERWORTH_Q, 0.0);
        assert!((c.response_db(1000.0, FS) + 3.0103).abs() < 0.01);
        assert!(c.response_db(10.0, FS).abs() < 0.01, "flat well below the cutoff");
        assert!(c.response_db(10_000.0, FS) < -38.0, "a decade above a second-order filter is about -40 dB");
        assert!(c.is_stable());
    }

    #[test]
    fn high_pass_mirrors_the_low_pass() {
        let c = design(FilterKind::HighPass, 1000.0, BUTTERWORTH_Q, 0.0);
        assert!((c.response_db(1000.0, FS) + 3.0103).abs() < 0.01);
        assert!(c.response_db(10.0, FS) < -78.0);
        assert!(c.response_db(20_000.0, FS).abs() < 0.2);
    }

    #[test]
    fn band_pass_peaks_at_0_db_on_the_cutoff() {
        let c = design(FilterKind::BandPass, 2000.0, 4.0, 0.0);
        assert!(c.response_db(2000.0, FS).abs() < 1e-6);
        assert!(c.response_db(200.0, FS) < -20.0);
        assert!(c.response_db(20_000.0, FS) < -20.0);
        let narrow = design(FilterKind::BandPass, 2000.0, 16.0, 0.0);
        assert!(narrow.response_db(2400.0, FS) < c.response_db(2400.0, FS), "higher Q is narrower");
    }

    #[test]
    fn peaking_gain_lands_on_the_cutoff() {
        for gain in [-12.0, -3.0, 6.0, 12.0] {
            let c = design(FilterKind::Peaking, 1500.0, 1.0, gain);
            assert!((c.response_db(1500.0, FS) - gain).abs() < 1e-6, "{gain} dB");
            assert!(c.response_db(30.0, FS).abs() < 0.2, "away from the cutoff it is flat");
            assert!(c.response_db(22_000.0, FS).abs() < 0.5);
        }
    }

    #[test]
    fn peaking_with_zero_gain_is_the_identity() {
        let c = design(FilterKind::Peaking, 1500.0, 1.0, 0.0);
        for f in [50.0, 1500.0, 15_000.0] {
            assert!(c.response_db(f, FS).abs() < 1e-9);
        }
    }

    #[test]
    fn rejects_bad_parameters() {
        let ok = |c: f64, q: f64, g: f64, fs: u32| BiquadCoeffs::design(FilterKind::LowPass, fs, c, q, g);
        assert_eq!(ok(1000.0, 1.0, 0.0, 0), Err(DspError::InvalidSampleRate));
        assert!(matches!(ok(24_000.0, 1.0, 0.0, FS), Err(DspError::CutoffOutOfRange { .. })), "Nyquist itself is out");
        assert!(matches!(ok(30_000.0, 1.0, 0.0, FS), Err(DspError::CutoffOutOfRange { .. })));
        assert!(matches!(ok(0.0, 1.0, 0.0, FS), Err(DspError::CutoffOutOfRange { .. })));
        assert!(matches!(ok(-5.0, 1.0, 0.0, FS), Err(DspError::CutoffOutOfRange { .. })));
        assert_eq!(ok(1000.0, 0.0, 0.0, FS), Err(DspError::InvalidQ(0.0)));
        assert!(matches!(ok(1000.0, f64::NAN, 0.0, FS), Err(DspError::InvalidQ(_))));
        assert!(matches!(ok(f64::NAN, 1.0, 0.0, FS), Err(DspError::NotFinite(_))));
        assert!(matches!(ok(1000.0, 1.0, f64::INFINITY, FS), Err(DspError::NotFinite(_))));
        assert!(ok(23_999.0, 1.0, 0.0, FS).is_ok());
        assert!(!DspError::InvalidQ(0.0).to_string().is_empty());
    }

    fn sine(hz: f32, frames: usize) -> Vec<f32> {
        (0..frames).map(|i| (std::f32::consts::TAU * hz * i as f32 / FS as f32).sin()).collect()
    }

    fn settled_peak(samples: &[f32]) -> f32 {
        crate::peak(&samples[samples.len() / 2..])
    }

    /// The amplitude of a settled sine from its RMS, which is more exact than the sampled peak.
    fn settled_amplitude(samples: &[f32]) -> f32 {
        crate::rms(&samples[samples.len() / 2..]) * std::f32::consts::SQRT_2
    }

    #[test]
    fn filtering_a_sine_matches_the_designed_response() {
        let c = design(FilterKind::LowPass, 1000.0, BUTTERWORTH_Q, 0.0);
        for (hz, expect_db) in [(250.0f32, c.response_db(250.0, FS)), (1000.0, -3.0103), (4000.0, c.response_db(4000.0, FS))] {
            let mut s = sine(hz, 48_000);
            Biquad::new(c).process(&mut s);
            let measured = 20.0 * settled_amplitude(&s).log10();
            assert!((f64::from(measured) - expect_db).abs() < 0.05, "{hz} Hz: {measured} vs {expect_db}");
        }
    }

    #[test]
    fn impulse_response_decays() {
        let c = design(FilterKind::BandPass, 500.0, 8.0, 0.0);
        let mut b = Biquad::new(c);
        let mut block = vec![0.0f32; 48_000];
        block[0] = 1.0;
        b.process(&mut block);
        assert!(crate::peak(&block[40_000..]) < 1e-6, "a stable filter rings out");
        assert!(crate::peak(&block[..100]) > 0.003);
    }

    #[test]
    fn identity_coefficients_leave_audio_alone() {
        let mut s = sine(440.0, 256);
        let before = s.clone();
        Biquad::new(BiquadCoeffs::IDENTITY).process(&mut s);
        assert_eq!(s, before);
    }

    #[test]
    fn multi_channel_filters_each_channel_with_its_own_state() {
        let c = design(FilterKind::LowPass, 500.0, BUTTERWORTH_Q, 0.0);
        let left = sine(100.0, 4800);
        let right = sine(8000.0, 4800);
        let mut inter: Vec<f32> = left.iter().zip(&right).flat_map(|(l, r)| [*l, *r]).collect();
        MultiBiquad::new(2, c).process_interleaved(&mut inter);
        let l: Vec<f32> = inter.iter().step_by(2).copied().collect();
        let r: Vec<f32> = inter.iter().skip(1).step_by(2).copied().collect();
        let mut solo_left = left.clone();
        Biquad::new(c).process(&mut solo_left);
        assert_eq!(l, solo_left, "the channels do not leak into each other");
        assert!(settled_peak(&l) > 0.9, "100 Hz passes");
        assert!(settled_peak(&r) < 0.01, "8 kHz is cut");
    }

    #[test]
    fn reset_clears_the_ringing() {
        let c = design(FilterKind::LowPass, 200.0, 4.0, 0.0);
        let mut b = Biquad::new(c);
        for _ in 0..100 {
            b.process_sample(1.0);
        }
        b.reset();
        assert_eq!(b.process_sample(0.0), 0.0);
        let mut m = MultiBiquad::new(2, c);
        m.process_interleaved(&mut [1.0, 1.0, 1.0, 1.0]);
        m.reset();
        let mut z = [0.0f32; 4];
        m.process_interleaved(&mut z);
        assert_eq!(z, [0.0; 4]);
    }

    #[test]
    fn stable_over_a_wide_sweep() {
        for cutoff in [20.0, 100.0, 1000.0, 10_000.0, 20_000.0, 23_900.0] {
            for q in [0.1, 0.5, 0.71, 2.0, 10.0, 18.0] {
                for kind in [FilterKind::LowPass, FilterKind::HighPass, FilterKind::BandPass, FilterKind::Peaking] {
                    let c = design(kind, cutoff, q, 6.0);
                    assert!(c.is_stable(), "{kind:?} {cutoff} Hz Q {q}");
                    assert!(c.b0.is_finite() && c.a1.is_finite());
                }
            }
        }
    }
}