use core::f32::consts::{PI, SQRT_2};
use nalgebra::Complex;
use super::biquad::{Biquad, Section};
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct LowPass(Biquad<Coefficients>);
impl LowPass {
pub(crate) fn apply(&mut self, value: f32, dt: f32, cutoff_hz: f32) -> f32 {
self.0.apply(value, dt, &cutoff_hz)
}
pub(crate) fn response(cutoff_hz: f32, dt_s: f32, unit_delay: Complex<f32>) -> Complex<f32> {
let one = Complex::new(1.0, 0.0);
let Some(Coefficients { b0, a1, a2 }) = Coefficients::new(&cutoff_hz, dt_s) else {
return one;
};
let z1 = unit_delay;
(one + z1 * 2.0 + z1 * z1) * b0 / (one + z1 * a1 + z1 * z1 * a2)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Coefficients {
b0: f32,
a1: f32,
a2: f32,
}
impl Section for Coefficients {
type Settings = f32;
fn new(cutoff_hz: &f32, dt_s: f32) -> Option<Self> {
let cutoff_hz = *cutoff_hz;
let passes = !(cutoff_hz > 0.0 && cutoff_hz * dt_s < 0.5 && cutoff_hz.is_finite());
if passes {
return None;
}
let k = libm::tanf(PI * cutoff_hz * dt_s);
let k_squared = k * k;
let norm = 1.0 / (1.0 + SQRT_2 * k + k_squared);
Some(Self {
b0: k_squared * norm,
a1: 2.0 * (k_squared - 1.0) * norm,
a2: (1.0 - SQRT_2 * k + k_squared) * norm,
})
}
fn step(&self, value: f32, inputs: [f32; 2], outputs: [f32; 2]) -> f32 {
let Self { b0, a1, a2 } = *self;
b0 * (value + 2.0 * inputs[0] + inputs[1]) - a1 * outputs[0] - a2 * outputs[1]
}
}
#[cfg(test)]
mod tests;