Skip to main content

lib_jsl_dsp/discrete/resampling/
polyphase_arbitrary_resampling.rs

1//! Streaming resampling by an integer up rate and a real down rate.
2//!
3//! See the book entry [Resampling: polyphase, half-band and CIC filters](https://jwkunz.github.io/lib_jsl/book/spectral/resampling.html#arbitrary-ratios).
4
5
6use crate::{
7    dsp::discrete::{
8        filters::firwin::{FirwinPassZero, firwin},
9        resampling::polyphase_integer_resampling::PolyphaseEngine,
10        stream_operator::{StreamOperator, StreamOperatorManagement},
11        windows::{WindowType, kaiser_beta, kaiser_estimate_numtaps},
12    },
13    prelude::{ErrorsJSL, IsAnalytic},
14};
15
16/// Streaming resampler by an integer `up_rate` and a real `down_rate`.
17///
18/// Output `m` is taken from the upsampled, filtered signal at position `⌊m · down_rate⌋`, so the
19/// output times are rounded to the nearest-below point of the `up_rate` grid: the timing error is
20/// at most one upsampled sample, and shrinks as `up_rate` grows. With an integer `down_rate` the
21/// result equals [`PolyphaseIntegerResampler`](super::polyphase_integer_resampling::PolyphaseIntegerResampler)'s.
22pub struct PolyphaseArbitraryResampler<T: IsAnalytic> {
23    engine: PolyphaseEngine<T>,
24}
25
26impl<T: IsAnalytic> PolyphaseArbitraryResampler<T> {
27    pub fn new(
28        up_rate: usize,
29        down_rate: f64,
30        fir_taps: Option<&[f64]>,
31    ) -> Result<Self, ErrorsJSL> {
32        if up_rate == 0 {
33            return Err(ErrorsJSL::InvalidInputRange("up_rate must be > 0"));
34        }
35        if !down_rate.is_finite() || down_rate <= 0.0 {
36            return Err(ErrorsJSL::InvalidInputRange(
37                "down_rate must be finite and > 0",
38            ));
39        }
40        let max_rate = up_rate.max(down_rate.ceil() as usize);
41        let mut taps = if let Some(t) = fir_taps {
42            if t.is_empty() {
43                return Err(ErrorsJSL::InvalidInputRange("fir_taps must be non-empty"));
44            }
45            t.to_vec()
46        } else {
47            let cut_off = 0.5 / max_rate as f64;
48            let mut numtaps = kaiser_estimate_numtaps(60.0, cut_off).max(max_rate);
49            numtaps = ((numtaps as f64) / up_rate as f64).ceil() as usize * up_rate; // Round up to a multiple of up_rate for better efficiency
50            let beta = kaiser_beta(60.0);
51            firwin(
52                numtaps,
53                &[cut_off],
54                None,
55                WindowType::Kaiser { beta },
56                FirwinPassZero::True,
57                true,
58                1.0,
59            )?
60        };
61
62        while taps.len() < max_rate {
63            taps.push(0.0);
64        }
65
66        for h in &mut taps {
67            *h *= up_rate as f64;
68        }
69        Ok(Self { engine: PolyphaseEngine::new(up_rate, down_rate, taps) })
70    }
71}
72
73impl<T: IsAnalytic> StreamOperatorManagement for PolyphaseArbitraryResampler<T> {
74    fn reset(&mut self) -> Result<(), ErrorsJSL> {
75        self.engine.reset();
76        Ok(())
77    }
78
79    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
80        Ok(())
81    }
82}
83
84impl<T: IsAnalytic> StreamOperator<T, T> for PolyphaseArbitraryResampler<T> {
85    fn process(&mut self, data_in: &[T]) -> Result<Option<Vec<T>>, ErrorsJSL> {
86        let out = self.engine.process(data_in);
87        Ok(if out.is_empty() { None } else { Some(out) })
88    }
89
90    fn flush(&mut self) -> Result<Option<Vec<T>>, ErrorsJSL> {
91        let out = self.engine.flush();
92        Ok(if out.is_empty() { None } else { Some(out) })
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use crate::discrete::resampling::polyphase_integer_resampling::PolyphaseIntegerResampler;
100
101    #[test]
102    fn decimation_with_a_unit_filter_keeps_every_third_sample() {
103        let mut resampler = PolyphaseArbitraryResampler::new(1, 3.0, Some(&[1.0])).unwrap();
104        let input = (0..10).map(|x| x as f64).collect::<Vec<f64>>();
105        assert_eq!(resampler.process(&input).unwrap().unwrap(), vec![0.0, 3.0, 6.0, 9.0]);
106    }
107
108    #[test]
109    fn integer_ratios_agree_with_the_integer_resampler_and_fractional_ones_track_a_sine() {
110        let x: Vec<f64> = (0..400).map(|n| (0.05 * n as f64).sin()).collect();
111        let mut a = PolyphaseArbitraryResampler::new(4, 3.0, None).unwrap();
112        let mut b = PolyphaseIntegerResampler::new(4, 3, None).unwrap();
113        assert_eq!(a.process(&x).unwrap(), b.process(&x).unwrap());
114        // Resample by 32/45.7: output m sits at input time ⌊45.7 m⌋ / 32, minus the filter delay.
115        let up = 32;
116        let down = 45.7;
117        let mut r = PolyphaseArbitraryResampler::new(up, down, None).unwrap();
118        let y = r.process(&x).unwrap().unwrap();
119        let delay = (r.engine.taps.len() - 1) as f64 / 2.0;
120        let worst = y.iter().enumerate().skip(20).take(y.len() - 40).map(|(m, v)| {
121            let t = ((m as f64 * down).floor() - delay) / up as f64;
122            (v - (0.05 * t).sin()).abs()
123        }).fold(0.0, f64::max);
124        assert!(worst < 2e-3, "{worst}");
125    }
126}