idsp/
dsm.rs

1/// Delta-sigma modulator
2///
3/// * MASH-(1)^K architecture
4/// * `0 <= K <= 8` (`K=0` is valid but the output will be the constant quantized 0)
5/// * The output range is `1 - (1 << K - 1)..=(1 << K - 1)`.
6/// * Given constant input `x0`, the average output is `x0/(1 << 32)`.
7/// * The noise goes up as `K * 20 dB/decade`.
8///
9/// ```
10/// # use idsp::Dsm;
11/// let mut d = Dsm::<3>::default();
12/// let x = 0x87654321;
13/// let n = 1 << 20;
14/// let y = (0..n).map(|_| d.update(x) as f32).sum::<f32>() / n as f32;
15/// let m = x as f32 / (1u64 << 32) as f32;
16/// assert!((y / m - 1.0).abs() < (1.0 / n as f32).sqrt(), "{y} != {m}");
17/// ```
18#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd)]
19pub struct Dsm<const K: usize> {
20    a: [u32; K],
21    c: [i8; K],
22}
23
24impl<const K: usize> Default for Dsm<K> {
25    fn default() -> Self {
26        Self {
27            a: [0; K],
28            c: [0; K],
29        }
30    }
31}
32
33impl<const K: usize> Dsm<K> {
34    /// Ingest input sample, emit new output.
35    ///
36    /// # Arguments
37    /// * `x`: New input sample
38    ///
39    /// # Returns
40    /// New output
41    pub fn update(&mut self, x: u32) -> i8 {
42        let mut d = 0i8;
43        let mut c = false;
44        self.a.iter_mut().fold(x, |x, a| {
45            (*a, c) = a.overflowing_add(x);
46            d = (d << 1) | c as i8;
47            *a
48        });
49        self.c.iter_mut().take(K - 1).fold(d & 1, |mut y, c| {
50            d >>= 1;
51            (y, *c) = ((d & 1) + y - *c, y);
52            y
53        })
54    }
55}