use core::f32::consts::PI;
use nalgebra::Complex;
use super::biquad::{Biquad, Section};
use super::{InvalidConfig, check};
const MAX_CENTER_SHARE: f32 = 0.48;
const MIN_CENTER_PER_BANDWIDTH: f32 = 0.52;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NotchConfig {
pub center_hz: f32,
pub bandwidth_hz: f32,
pub attenuation_db: f32,
}
impl Default for NotchConfig {
fn default() -> Self {
Self {
center_hz: 0.0,
bandwidth_hz: 40.0,
attenuation_db: 40.0,
}
}
}
impl NotchConfig {
pub fn is_on(&self) -> bool {
self.center_hz > 0.0
}
pub fn validate(&self) -> Result<(), InvalidConfig> {
check(
"center_hz",
self.center_hz >= 0.0 && self.center_hz.is_finite(),
"non-negative and finite",
)?;
check(
"bandwidth_hz",
self.bandwidth_hz >= 0.0 && self.bandwidth_hz.is_finite(),
"non-negative and finite",
)?;
check(
"attenuation_db",
self.attenuation_db > 0.0 && self.attenuation_db.is_finite(),
"positive and finite",
)
}
pub fn response(&self, dt_s: f32, unit_delay: Complex<f32>) -> Complex<f32> {
let one = Complex::new(1.0, 0.0);
let Some(Coefficients { b, a }) = Coefficients::new(self, dt_s) else {
return one;
};
let z1 = unit_delay;
(one * b[0] + z1 * b[1] + z1 * z1 * b[2]) / (one + z1 * a[0] + z1 * z1 * a[1])
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct Notch(Biquad<Coefficients>);
impl Notch {
pub(crate) fn apply(&mut self, value: f32, dt: f32, config: &NotchConfig) -> f32 {
self.0.apply(value, dt, config)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Coefficients {
b: [f32; 3],
a: [f32; 2],
}
impl Section for Coefficients {
type Settings = NotchConfig;
fn new(config: &NotchConfig, dt_s: f32) -> Option<Self> {
let center_hz = config
.center_hz
.max(MIN_CENTER_PER_BANDWIDTH * config.bandwidth_hz);
let center_share = center_hz * dt_s;
let cuts = config.is_on()
&& config.bandwidth_hz > 0.0
&& center_share < MAX_CENTER_SHARE
&& config.validate().is_ok();
if !cuts {
return None;
}
let lower_hz = center_hz - 0.5 * config.bandwidth_hz;
let octaves = 2.0 * libm::log2f(center_hz / lower_hz);
let ratio = libm::exp2f(octaves);
let q = libm::sqrtf(ratio) / (ratio - 1.0);
let omega = 2.0 * PI * center_share;
let alpha = libm::sinf(omega) / (2.0 * q);
let depth = libm::powf(10.0, -config.attenuation_db / 20.0);
let cos_omega = libm::cosf(omega);
let a0 = 1.0 + alpha;
Some(Self {
b: [1.0 + alpha * depth, -2.0 * cos_omega, 1.0 - alpha * depth].map(|b| b / a0),
a: [-2.0 * cos_omega, 1.0 - alpha].map(|a| a / a0),
})
}
fn step(&self, value: f32, inputs: [f32; 2], outputs: [f32; 2]) -> f32 {
let Self { b, a } = *self;
b[0] * value + b[1] * inputs[0] + b[2] * inputs[1] - a[0] * outputs[0] - a[1] * outputs[1]
}
}
#[cfg(test)]
mod tests;