Skip to main content

lib_jsl_dsp/discrete/resampling/
polyphase_integer_resampling.rs

1//! Streaming rational-ratio resampling by polyphase filtering.
2//!
3//! See the book entry [Resampling: polyphase, half-band and CIC filters](https://jwkunz.github.io/lib_jsl/book/spectral/resampling.html#polyphase-resampling).
4
5use std::collections::VecDeque;
6
7use crate::{
8    dsp::discrete::{
9        filters::firwin::{FirwinPassZero, firwin},
10        stream_operator::{StreamOperator, StreamOperatorManagement},
11        windows::{WindowType, kaiser_beta, kaiser_estimate_numtaps},
12    },
13    number_theory::greatest_common_divisor::gcd,
14    prelude::{ErrorsJSL, IsAnalytic},
15};
16
17/// The streaming polyphase engine shared by the integer and arbitrary-ratio resamplers.
18///
19/// It computes `y[m] = Σ_j h[p_m − j·up] x[j]` with `p_m = ⌊m · down⌋`: the input upsampled by
20/// `up` (zeros between samples), filtered by `h`, and sampled every `down` positions, exactly as
21/// SciPy's `upfirdn` but without forming the zero-stuffed signal. Only the taps that meet real
22/// samples are multiplied, so each output costs about `len(h) / up` multiply-adds.
23#[derive(Debug, Clone)]
24pub(crate) struct PolyphaseEngine<T: IsAnalytic> {
25    up: usize,
26    down: f64,
27    pub(crate) taps: Vec<f64>,
28    /// The most recent inputs, oldest first; `history[0]` is input number `first`.
29    history: VecDeque<T>,
30    first: usize,
31    /// Inputs received so far.
32    received: usize,
33    /// Index of the next output.
34    next: usize,
35}
36
37impl<T: IsAnalytic> PolyphaseEngine<T> {
38    pub(crate) fn new(up: usize, down: f64, taps: Vec<f64>) -> Self {
39        PolyphaseEngine { up, down, taps, history: VecDeque::new(), first: 0, received: 0, next: 0 }
40    }
41
42    /// The upsampled-domain position of output `m`.
43    fn position(&self, m: usize) -> usize {
44        (m as f64 * self.down + 1e-9).floor() as usize
45    }
46
47    /// Emits every output whose inputs are all available, considering only positions below `end`.
48    // ANCHOR: polyphase
49    fn drain(&mut self, end: usize, out: &mut Vec<T>) {
50        let len = self.taps.len();
51        loop {
52            let p = self.position(self.next);
53            if p >= end || self.received == 0 || p / self.up > self.received - 1 {
54                break;
55            }
56            // Inputs j with 0 <= p − j·up < len.
57            let hi = p / self.up;
58            let lo = if p + 1 > len { (p + 1 - len).div_ceil(self.up) } else { 0 };
59            let mut acc = T::zero();
60            for j in lo..=hi {
61                acc += self.history[j - self.first].f_scale(self.taps[p - j * self.up]);
62            }
63            out.push(acc);
64            self.next += 1;
65        }
66    // ANCHOR_END: polyphase
67        // Forget inputs that no future output can reach.
68        let p = self.position(self.next);
69        let needed_from = if p + 1 > len { (p + 1 - len).div_ceil(self.up) } else { 0 };
70        while self.first < needed_from && !self.history.is_empty() {
71            self.history.pop_front();
72            self.first += 1;
73        }
74    }
75
76    pub(crate) fn process(&mut self, data_in: &[T]) -> Vec<T> {
77        let mut out = Vec::new();
78        for &x in data_in {
79            self.history.push_back(x);
80            self.received += 1;
81            self.drain(usize::MAX, &mut out);
82        }
83        out
84    }
85
86    /// The remaining outputs of the full filtered signal (up to position `(N − 1)·up + len(h)`),
87    /// after which the engine is reset.
88    pub(crate) fn flush(&mut self) -> Vec<T> {
89        let mut out = Vec::new();
90        if self.received > 0 {
91            let end = (self.received - 1) * self.up + self.taps.len();
92            while self.position(self.next) < end {
93                self.history.push_back(T::zero());
94                self.received += 1;
95                self.drain(end, &mut out);
96            }
97        }
98        self.reset();
99        out
100    }
101
102    pub(crate) fn reset(&mut self) {
103        self.history.clear();
104        self.first = 0;
105        self.received = 0;
106        self.next = 0;
107    }
108}
109
110/// Streaming rational-ratio polyphase resampler: upsample by `up_rate`, low-pass filter, keep every
111/// `down_rate`-th sample (`up_rate / down_rate` is reduced to lowest terms). The output equals
112/// SciPy's `upfirdn(up · h, x, up, down)`, the core of `resample_poly`, and arrives as soon as the
113/// inputs it needs have; `flush` emits the rest of the filter's tail. Without explicit taps a
114/// Kaiser-window low-pass filter with cutoff `1 / max(up, down)` of Nyquist and 60 dB attenuation
115/// is designed.
116pub struct PolyphaseIntegerResampler<T: IsAnalytic> {
117    engine: PolyphaseEngine<T>,
118}
119
120impl<T: IsAnalytic> PolyphaseIntegerResampler<T> {
121    /// The `new` method initializes a `PolyphaseIntegerResampler` instance with the specified upsampling rate, downsampling rate, and optional FIR filter taps.
122    /// If FIR filter taps are not provided, it designs a low-pass FIR filter using the Kaiser window method, with a cutoff frequency determined by the maximum of the upsampling and downsampling rates.
123    /// The number of taps is estimated based on the desired attenuation and the width of the transition band,
124    pub fn new(
125        up_rate: usize,
126        down_rate: usize,
127        fir_taps: Option<&[f64]>,
128    ) -> Result<Self, ErrorsJSL> {
129        if up_rate == 0 || down_rate == 0 {
130            return Err(ErrorsJSL::InvalidInputRange(
131                "up_rate and down_rate must both be > 0",
132            ));
133        }
134
135        let g = gcd(up_rate as i128, down_rate as i128) as usize;
136        let up = up_rate / g;
137        let down = down_rate / g;
138        let max_rate = up.max(down);
139        let mut taps = if let Some(t) = fir_taps {
140            if t.is_empty() {
141                return Err(ErrorsJSL::InvalidInputRange("fir_taps must be non-empty"));
142            }
143            t.to_vec()
144        } else {
145            let cut_off = 0.5 / max_rate as f64;
146            let mut numtaps = kaiser_estimate_numtaps(60.0, cut_off).max(max_rate);
147            numtaps = ((numtaps as f64) / up as f64).ceil() as usize * up; // Round up to a multiple of up_rate for better efficiency
148            let beta = kaiser_beta(60.0);
149            firwin(
150                numtaps,
151                &[cut_off],
152                None,
153                WindowType::Kaiser { beta },
154                FirwinPassZero::True,
155                true,
156                1.0,
157            )?
158        };
159
160        // Match resample_poly: scale the taps by the upsampling factor to keep unit gain.
161        for h in &mut taps {
162            *h *= up as f64;
163        }
164        Ok(Self { engine: PolyphaseEngine::new(up, down as f64, taps) })
165    }
166
167}
168
169impl<T: IsAnalytic> StreamOperatorManagement for PolyphaseIntegerResampler<T> {
170    fn reset(&mut self) -> Result<(), ErrorsJSL> {
171        self.engine.reset();
172        Ok(())
173    }
174
175    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
176        Ok(())
177    }
178}
179
180impl<T: IsAnalytic> StreamOperator<T, T> for PolyphaseIntegerResampler<T> {
181    fn process(&mut self, data_in: &[T]) -> Result<Option<Vec<T>>, ErrorsJSL> {
182        let out = self.engine.process(data_in);
183        Ok(if out.is_empty() { None } else { Some(out) })
184    }
185
186    fn flush(&mut self) -> Result<Option<Vec<T>>, ErrorsJSL> {
187        let out = self.engine.flush();
188        Ok(if out.is_empty() { None } else { Some(out) })
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    /// SciPy's upfirdn, written out directly.
197    fn upfirdn(h: &[f64], x: &[f64], up: usize, down: usize) -> Vec<f64> {
198        let total = (x.len() - 1) * up + h.len();
199        (0..total.div_ceil(down))
200            .map(|m| {
201                let p = m * down;
202                (0..x.len()).filter(|&j| j * up <= p && p - j * up < h.len()).map(|j| h[p - j * up] * x[j]).sum()
203            })
204            .collect()
205    }
206
207    #[test]
208    fn decimation_with_a_unit_filter_keeps_every_third_sample() {
209        let mut resampler = PolyphaseIntegerResampler::new(3, 9, Some(&[1.0])).unwrap();
210        let input = (0..10).map(|x| x as f64).collect::<Vec<f64>>();
211        assert_eq!(resampler.process(&input).unwrap().unwrap(), vec![0.0, 3.0, 6.0, 9.0]);
212    }
213
214    #[test]
215    fn interpolates_between_samples_and_matches_upfirdn_in_any_chunking() {
216        // Linear interpolation by 3 (triangular taps; the resampler multiplies them by 3).
217        let taps = [1.0 / 9.0, 2.0 / 9.0, 3.0 / 9.0, 2.0 / 9.0, 1.0 / 9.0];
218        let mut r = PolyphaseIntegerResampler::new(3, 1, Some(&taps)).unwrap();
219        let y = r.process(&[0.0, 3.0, 6.0, 9.0]).unwrap().unwrap();
220        // After the two-sample delay of the filter, the ramp 0, 1, 2, … appears.
221        assert_eq!(y.len(), 12);
222        assert!(y[2..].iter().enumerate().all(|(i, v)| (v - i as f64).abs() < 1e-12), "{y:?}");
223        // 3/2 resampling of a longer signal, fed in uneven chunks, equals upfirdn exactly.
224        let x: Vec<f64> = (0..50).map(|n| (0.3 * n as f64).sin() + 0.01 * (n * n) as f64).collect();
225        let h: Vec<f64> = (0..17).map(|k| 1.0 / (1.0 + (k as f64 - 8.0).powi(2))).collect();
226        let mut r = PolyphaseIntegerResampler::new(3, 2, Some(&h)).unwrap();
227        let mut got = Vec::new();
228        for chunk in x.chunks(7) {
229            got.extend(r.process(chunk).unwrap().unwrap_or_default());
230        }
231        got.extend(r.flush().unwrap().unwrap_or_default());
232        let scaled: Vec<f64> = h.iter().map(|v| 3.0 * v).collect();
233        let want = upfirdn(&scaled, &x, 3, 2);
234        assert_eq!(got.len(), want.len());
235        assert!(got.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-12));
236    }
237}