idsp/
dsm.rs

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