idsp/
filter.rs

1/// Single inpout single output i32 filter
2pub trait Filter {
3    /// Filter configuration type.
4    ///
5    /// While the filter struct owns the state,
6    /// the configuration is decoupled to allow sharing.
7    type Config;
8    /// Update the filter with a new sample.
9    ///
10    /// # Args
11    /// * `x`: Input data.
12    /// * `k`: Filter configuration.
13    ///
14    /// # Return
15    /// Filtered output y.
16    fn update(&mut self, x: i32, k: &Self::Config) -> i32;
17    /// Return the current filter output
18    fn get(&self) -> i32;
19    /// Update the filter so that it outputs the provided value.
20    /// This does not completely define the state of the filter.
21    fn set(&mut self, x: i32);
22}
23
24/// Nyquist zero
25///
26/// Filter with a flat transfer function and a transfer function zero at Nyquist.
27#[derive(Copy, Clone, Default)]
28pub struct Nyquist(i32);
29impl Filter for Nyquist {
30    type Config = ();
31    fn update(&mut self, x: i32, _k: &Self::Config) -> i32 {
32        let x = x >> 1; // x/2 for less bias but more distortion
33        let y = x.wrapping_add(self.0);
34        self.0 = x;
35        y
36    }
37    fn get(&self) -> i32 {
38        self.0
39    }
40    fn set(&mut self, x: i32) {
41        self.0 = x;
42    }
43}
44
45/// Repeat another filter
46#[derive(Copy, Clone)]
47pub struct Repeat<const N: usize, T>([T; N]);
48impl<const N: usize, T: Filter> Filter for Repeat<N, T> {
49    type Config = T::Config;
50    fn update(&mut self, x: i32, k: &Self::Config) -> i32 {
51        self.0.iter_mut().fold(x, |x, stage| stage.update(x, k))
52    }
53    fn get(&self) -> i32 {
54        self.0[N - 1].get()
55    }
56    fn set(&mut self, x: i32) {
57        self.0.iter_mut().for_each(|stage| stage.set(x));
58    }
59}
60impl<const N: usize, T: Default + Copy> Default for Repeat<N, T> {
61    fn default() -> Self {
62        Self([T::default(); N])
63    }
64}
65
66/// Combine two different filters in cascade
67#[derive(Copy, Clone, Default)]
68pub struct Cascade<T, U>(T, U);
69impl<T: Filter, U: Filter> Filter for Cascade<T, U> {
70    type Config = (T::Config, U::Config);
71    fn update(&mut self, x: i32, k: &Self::Config) -> i32 {
72        self.1.update(self.0.update(x, &k.0), &k.1)
73    }
74    fn get(&self) -> i32 {
75        self.1.get()
76    }
77    fn set(&mut self, x: i32) {
78        self.1.set(x)
79    }
80}