pub(crate) trait Section: Copy {
type Settings: Copy + PartialEq;
fn new(settings: &Self::Settings, dt_s: f32) -> Option<Self>;
fn step(&self, value: f32, inputs: [f32; 2], outputs: [f32; 2]) -> f32;
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Biquad<S: Section> {
weights: Option<(S, S::Settings, f32)>,
history: Option<([f32; 2], [f32; 2])>,
}
impl<S: Section> Default for Biquad<S> {
fn default() -> Self {
Self {
weights: None,
history: None,
}
}
}
impl<S: Section> Biquad<S> {
pub(crate) fn apply(&mut self, value: f32, dt: f32, settings: &S::Settings) -> f32 {
if !value.is_finite() {
return value;
}
let Some(weights) = self.weights(dt, settings) else {
self.history = None;
return value;
};
let (inputs, outputs) = *self.history.get_or_insert(([value; 2], [value; 2]));
let output = weights.step(value, inputs, outputs);
self.history = Some(([value, inputs[0]], [output, outputs[0]]));
output
}
fn weights(&mut self, dt: f32, settings: &S::Settings) -> Option<S> {
match self.weights {
Some((weights, cached, cached_dt)) if cached == *settings && cached_dt == dt => {
Some(weights)
}
_ => {
let weights = S::new(settings, dt)?;
self.weights = Some((weights, *settings, dt));
Some(weights)
}
}
}
}