idsp/
svf.rs

1//! State variable filter
2
3use num_traits::{Float, FloatConst};
4use serde::{Deserialize, Serialize};
5
6/// Second order state variable filter state
7pub struct State<T> {
8    /// Lowpass output
9    pub lp: T,
10    /// Highpass output
11    pub hp: T,
12    /// Bandpass output
13    pub bp: T,
14}
15
16impl<T: Float> State<T> {
17    /// Bandreject (notch) output
18    pub fn br(&self) -> T {
19        self.hp + self.lp
20    }
21}
22
23/// State variable filter
24///
25/// <https://www.earlevel.com/main/2003/03/02/the-digital-state-variable-filter/>
26#[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, PartialOrd)]
27pub struct Svf<T> {
28    f: T,
29    q: T,
30}
31
32impl<T: Float + FloatConst> Svf<T> {
33    /// Set the critical frequency
34    ///
35    /// In units of the sample frequency.
36    pub fn set_frequency(&mut self, f0: T) {
37        self.f = (T::one() + T::one()) * (T::PI() * f0).sin();
38    }
39
40    /// Set the Q parameter
41    pub fn set_q(&mut self, q: T) {
42        self.q = T::one() / q;
43    }
44
45    /// Update the filter
46    ///
47    /// Ingest an input sample and update state correspondingly.
48    /// Selected output(s) are available from [`State`].
49    pub fn update(&self, s: &mut State<T>, x0: T) {
50        s.lp = s.bp * self.f + s.lp;
51        s.hp = x0 - s.lp - s.bp * self.q;
52        s.bp = s.hp * self.f + s.bp;
53    }
54}