Skip to main content

usbdac_core/convert/
resample.rs

1//! A polyphase windowed-sinc sample-rate converter for rational ratios.
2//!
3//! Written from the textbook design, with nothing borrowed from another converter.
4//!
5//! ### Design
6//!
7//! For rates `fi` (input) and `fo` (output) let `g = gcd(fi, fo)`, `L = fo / g` and `M = fi / g`.
8//! Output sample `n` sits at input time `t = n * M / L`, that is between input samples `k` and
9//! `k + 1` with `k = floor(n * M / L)` and fraction `p / L`, `p = (n * M) mod L`. It is
10//!
11//! ```text
12//! y[n] = sum_j x[k - (T/2 - 1) + j] * c[p][j]      c[p][j] = h((T/2 - 1) - j + p / L)
13//! ```
14//!
15//! where `h` is a windowed sinc evaluated at the exact fractional offset: the response of the
16//! ideal low-pass filter `2 fc sinc(2 fc t)` (time in input samples, `fc` in cycles per input
17//! sample) times a Kaiser window of half-width `T/2` input samples. The coefficients are computed
18//! once, for the `L` phases, and each phase is normalised to sum to exactly 1, so the gain at DC is
19//! 1 for every phase. There are `L * T` of them (at most 4.5 million), and an output costs `T`
20//! multiply-adds.
21//!
22//! The filter is zero-phase: output `n` is aligned with input time `n * M / L` exactly, with no
23//! group delay to compensate. What it needs is the `T/2` input samples after that instant, so the
24//! converter holds back `T/2` input frames ([`Resampler::delay_frames`]): they are the algorithmic
25//! latency, and they are flushed by feeding `T/2` zeros ([`Resampler::pad_frames`]), which makes
26//! the total output length for `N` input frames exactly `ceil(N * L / M)`.
27//!
28//! ### Quality
29//!
30//! `fp` is the passband edge and `fs` the stopband edge, `Delta = (fs - fp) / fi`, `A` the stopband
31//! attenuation to design for. Kaiser's formulas give the window shape `beta = 0.1102 (A - 8.7)` and the
32//! half-width `W = (A - 7.95) / (28.72 * Delta)` input samples, and the cutoff `fc` is the centre of the
33//! transition band. [`Quality::High`] designs for `fp = 0.91` and `fs = 1.0` times the lower Nyquist
34//! frequency, so nothing above it can alias into the output; [`Quality::Fast`] for `fp = 0.90` and
35//! `fs = 1.10` (content between them aliases into the 10% of the band under the Nyquist
36//! frequency, which the passband does not use), and a lower `A`; it takes about 2.9 times fewer
37//! taps and runs about 2.5 times faster. The tests measure the result and
38//! `docs/API.md` quotes the numbers.
39//!
40//! ### Cost
41//!
42//! The filter is longer the more it downsamples: `T` is about `158 * fi / min(fi, fo)` taps for
43//! [`Quality::High`], so 768 kHz to 44.1 kHz takes about 2800 multiply-adds per output sample
44//! (about 120 million per second per channel). The processing loop allocates nothing.
45
46use super::format::{ConvertError, Quality};
47
48/// The longest filter the converter will build, in taps per phase.
49pub const MAX_TAPS: usize = 8192;
50/// The largest coefficient table the converter will build.
51pub const MAX_COEFFICIENTS: usize = 4_500_000;
52
53/// The design targets of a [`Quality`].
54#[derive(Debug, Clone, Copy)]
55struct Spec {
56    /// Stopband attenuation the Kaiser formulas are given.
57    attenuation_db: f64,
58    /// Passband edge as a fraction of the lower Nyquist frequency.
59    passband: f64,
60    /// Stopband edge as a fraction of the lower Nyquist frequency.
61    stopband: f64,
62}
63
64fn spec(quality: Quality) -> Spec {
65    match quality {
66        Quality::High => Spec {
67            attenuation_db: 110.0,
68            passband: 0.91,
69            stopband: 1.0,
70        },
71        Quality::Fast => Spec {
72            attenuation_db: 84.0,
73            passband: 0.90,
74            stopband: 1.10,
75        },
76    }
77}
78
79/// What the converter built for a pair of rates.
80#[derive(Debug, Clone, Copy, PartialEq)]
81pub struct FilterInfo {
82    /// Upsampling factor of the polyphase structure (and number of phases).
83    pub l: usize,
84    /// Decimation factor.
85    pub m: usize,
86    /// Taps per output sample.
87    pub taps: usize,
88    /// Passband edge in Hz.
89    pub passband_hz: f64,
90    /// Stopband edge in Hz.
91    pub stopband_hz: f64,
92    /// Attenuation the filter was designed for, in dB.
93    pub design_attenuation_db: f64,
94}
95
96fn gcd(mut a: u64, mut b: u64) -> u64 {
97    while b != 0 {
98        (a, b) = (b, a % b);
99    }
100    a
101}
102
103/// Modified Bessel function of the first kind, order 0, by its power series.
104pub(crate) fn bessel_i0(x: f64) -> f64 {
105    let quarter = x * x / 4.0;
106    let mut term = 1.0;
107    let mut sum = 1.0;
108    for k in 1..400 {
109        term *= quarter / (k * k) as f64;
110        sum += term;
111        if term < sum * 1e-18 {
112            break;
113        }
114    }
115    sum
116}
117
118pub(crate) fn kaiser_beta(attenuation_db: f64) -> f64 {
119    if attenuation_db > 50.0 {
120        0.1102 * (attenuation_db - 8.7)
121    } else if attenuation_db >= 21.0 {
122        0.5842 * (attenuation_db - 21.0).powf(0.4) + 0.07886 * (attenuation_db - 21.0)
123    } else {
124        0.0
125    }
126}
127
128fn sinc(x: f64) -> f64 {
129    if x.abs() < 1e-12 {
130        1.0
131    } else {
132        let px = std::f64::consts::PI * x;
133        px.sin() / px
134    }
135}
136
137/// Describes the filter for `from_hz` to `to_hz` without synthesising it: the polyphase ratio and
138/// the number of taps. Fails for a ratio that needs more than [`MAX_COEFFICIENTS`] coefficients.
139pub fn filter_info(from_hz: u32, to_hz: u32, quality: Quality) -> Result<FilterInfo, ConvertError> {
140    if from_hz == 0 || to_hz == 0 {
141        return Err(ConvertError::InvalidArgument(
142            "rates must be positive".into(),
143        ));
144    }
145    let g = gcd(u64::from(from_hz), u64::from(to_hz));
146    let m = (u64::from(from_hz) / g) as usize;
147    let l = (u64::from(to_hz) / g) as usize;
148    let spec = spec(quality);
149
150    let fi = f64::from(from_hz);
151    let nyquist = f64::from(from_hz.min(to_hz)) / 2.0;
152    let passband_hz = spec.passband * nyquist;
153    let stopband_hz = spec.stopband * nyquist;
154    let transition = (stopband_hz - passband_hz) / fi;
155    let half_width = (spec.attenuation_db - 7.95) / (28.72 * transition);
156    let mut taps = 2 * half_width.ceil() as usize;
157    taps = taps.div_ceil(8) * 8;
158    taps = taps.max(16);
159    if taps > MAX_TAPS || l.saturating_mul(taps) > MAX_COEFFICIENTS {
160        return Err(ConvertError::Unsupported(format!(
161            "converting {from_hz} Hz to {to_hz} Hz needs a filter of {taps} taps in {l} phases, \
162             more than the {MAX_COEFFICIENTS} coefficients the converter builds"
163        )));
164    }
165    Ok(FilterInfo {
166        l,
167        m,
168        taps,
169        passband_hz,
170        stopband_hz,
171        design_attenuation_db: spec.attenuation_db,
172    })
173}
174
175/// The filter for `from_hz` to `to_hz`: its description and the `L * T` coefficients, phase after phase.
176fn design(
177    from_hz: u32,
178    to_hz: u32,
179    quality: Quality,
180) -> Result<(FilterInfo, Vec<f64>), ConvertError> {
181    let info = filter_info(from_hz, to_hz, quality)?;
182    let (l, taps) = (info.l, info.taps);
183    let cutoff = (info.passband_hz + info.stopband_hz) / 2.0 / f64::from(from_hz); // cycles per input sample
184    let beta = kaiser_beta(info.design_attenuation_db);
185    let i0_beta = bessel_i0(beta);
186    let half = (taps / 2) as f64;
187    let mut coef = vec![0.0f64; l * taps];
188    for p in 0..l {
189        let row = &mut coef[p * taps..(p + 1) * taps];
190        let fraction = p as f64 / l as f64;
191        for (j, slot) in row.iter_mut().enumerate() {
192            let t = (half - 1.0) - j as f64 + fraction;
193            let r = t / half;
194            let window = if r.abs() >= 1.0 {
195                0.0
196            } else {
197                bessel_i0(beta * (1.0 - r * r).sqrt()) / i0_beta
198            };
199            *slot = 2.0 * cutoff * sinc(2.0 * cutoff * t) * window;
200        }
201        let sum: f64 = row.iter().sum();
202        for slot in row.iter_mut() {
203            *slot /= sum;
204        }
205    }
206    Ok((info, coef))
207}
208
209/// A dot product with eight independent accumulators; `a` and `b` have the same length, a multiple of 8.
210#[inline]
211fn dot(a: &[f64], b: &[f64]) -> f64 {
212    debug_assert_eq!(a.len(), b.len());
213    debug_assert_eq!(a.len() % 8, 0);
214    let mut acc = [0.0f64; 8];
215    for (x, y) in a.chunks_exact(8).zip(b.chunks_exact(8)) {
216        for i in 0..8 {
217            acc[i] += x[i] * y[i];
218        }
219    }
220    ((acc[0] + acc[4]) + (acc[1] + acc[5])) + ((acc[2] + acc[6]) + (acc[3] + acc[7]))
221}
222
223/// A streaming rational resampler for any number of channels that advance together.
224///
225/// Planar buffers (one `Vec<f64>` per channel) are used so the caller can reuse them: nothing in
226/// [`Resampler::process`] allocates, provided the input block has at most `max_block` frames and the
227/// output buffers are long enough ([`Resampler::output_len_for`]).
228pub struct Resampler {
229    info: FilterInfo,
230    coef: Box<[f64]>,
231    half: usize,
232    max_block: usize,
233    history: Vec<Vec<f64>>,
234    /// Absolute index of `history[c][0]` (negative at the start: the leading zeros).
235    base: i64,
236    /// Absolute index of the input sample at or left of the next output's position.
237    k: i64,
238    /// Phase of the next output, `0..L`.
239    p: usize,
240    in_total: u64,
241    out_total: u64,
242}
243
244impl Resampler {
245    /// A converter from `from_hz` to `to_hz` for `channels` channels, taking at most `max_block`
246    /// frames per call.
247    pub fn new(
248        from_hz: u32,
249        to_hz: u32,
250        channels: usize,
251        quality: Quality,
252        max_block: usize,
253    ) -> Result<Self, ConvertError> {
254        if from_hz == 0 || to_hz == 0 || channels == 0 || max_block == 0 {
255            return Err(ConvertError::InvalidArgument(
256                "rates, channels and block size must be positive".into(),
257            ));
258        }
259        if from_hz == to_hz {
260            return Err(ConvertError::InvalidArgument(
261                "the rates are equal: there is nothing to resample".into(),
262            ));
263        }
264        let (info, coef) = design(from_hz, to_hz, quality)?;
265        let half = info.taps / 2;
266        let mut resampler = Self {
267            info,
268            coef: coef.into_boxed_slice(),
269            half,
270            max_block,
271            history: (0..channels)
272                .map(|_| Vec::with_capacity(info.taps + max_block))
273                .collect(),
274            base: 0,
275            k: 0,
276            p: 0,
277            in_total: 0,
278            out_total: 0,
279        };
280        resampler.reset();
281        Ok(resampler)
282    }
283
284    pub fn info(&self) -> &FilterInfo {
285        &self.info
286    }
287
288    pub fn channels(&self) -> usize {
289        self.history.len()
290    }
291
292    /// Input frames the converter holds back: the algorithmic latency. Output sample `n` is aligned
293    /// with input time `n * M / L` and is produced once the input has reached `delay_frames()` frames past it.
294    pub fn delay_frames(&self) -> usize {
295        self.half
296    }
297
298    /// Zero frames to feed after the last input to flush the tail out.
299    pub fn pad_frames(&self) -> usize {
300        self.half
301    }
302
303    /// Input frames fed since the start or the last reset.
304    pub fn frames_in(&self) -> u64 {
305        self.in_total
306    }
307
308    /// Output frames produced since the start or the last reset.
309    pub fn frames_out(&self) -> u64 {
310        self.out_total
311    }
312
313    /// Forgets the signal: the next input is the start of a new stream.
314    pub fn reset(&mut self) {
315        let lead = self.half - 1;
316        for history in &mut self.history {
317            history.clear();
318            history.resize(lead, 0.0);
319        }
320        self.base = -(lead as i64);
321        self.k = 0;
322        self.p = 0;
323        self.in_total = 0;
324        self.out_total = 0;
325    }
326
327    /// Output frames produced in all once `input_total` input frames have been fed.
328    fn outputs_after(&self, input_total: u64) -> u64 {
329        let usable = input_total.saturating_sub(self.half as u64);
330        let numerator = u128::from(usable) * self.info.l as u128;
331        numerator.div_ceil(self.info.m as u128) as u64
332    }
333
334    /// How many output frames feeding `input_frames` more input produces, exactly.
335    pub fn output_len_for(&self, input_frames: usize) -> usize {
336        (self.outputs_after(self.in_total + input_frames as u64) - self.out_total) as usize
337    }
338
339    /// The most input frames that can be fed so that no more than `output_frames` come out.
340    pub fn max_input_for_output(&self, output_frames: usize) -> usize {
341        let allowed_total = u128::from(self.out_total) + output_frames as u128;
342        let usable = allowed_total * self.info.m as u128 / self.info.l as u128;
343        let input_total = usable + self.half as u128;
344        input_total
345            .saturating_sub(u128::from(self.in_total))
346            .min(usize::MAX as u128) as usize
347    }
348
349    /// Feeds `n` frames (`input[c][..n]` for each channel) and writes the output frames to the
350    /// front of `output[c]`; returns how many ([`Resampler::output_len_for`]). `n` must be at most
351    /// `max_block` and every `output[c]` at least that long.
352    pub fn process(&mut self, input: &[Vec<f64>], n: usize, output: &mut [Vec<f64>]) -> usize {
353        assert_eq!(
354            input.len(),
355            self.history.len(),
356            "one input buffer per channel"
357        );
358        assert_eq!(
359            output.len(),
360            self.history.len(),
361            "one output buffer per channel"
362        );
363        assert!(
364            n <= self.max_block,
365            "a block of {n} frames exceeds the maximum of {}",
366            self.max_block
367        );
368        let taps = self.info.taps;
369        let (l, m) = (self.info.l, self.info.m);
370        let lead = self.half as i64 - 1;
371        let wanted = self.output_len_for(n);
372
373        // Keep already-consumed history in place until the fixed allocation
374        // needs room. Compacting once per block avoids copying the long FIR
375        // window for every small producer call.
376        if self.history[0].len() + n > taps + self.max_block {
377            let discard = ((self.k - lead - self.base).max(0) as usize).min(self.history[0].len());
378            for history in &mut self.history {
379                history.copy_within(discard.., 0);
380                history.truncate(history.len() - discard);
381            }
382            self.base += discard as i64;
383        }
384        let mut next_k = self.k;
385        let mut next_p = self.p;
386        for (channel, history) in self.history.iter_mut().enumerate() {
387            history.extend_from_slice(&input[channel][..n]);
388            let out = &mut output[channel];
389            assert!(
390                out.len() >= wanted,
391                "the output buffer holds {} frames, {wanted} are needed",
392                out.len()
393            );
394            let (mut k, mut p) = (self.k, self.p);
395            let mut count = 0usize;
396            loop {
397                let start = (k - lead - self.base) as usize;
398                if start + taps > history.len() {
399                    break;
400                }
401                out[count] = dot(
402                    &history[start..start + taps],
403                    &self.coef[p * taps..(p + 1) * taps],
404                );
405                count += 1;
406                p += m;
407                k += (p / l) as i64;
408                p %= l;
409            }
410            debug_assert_eq!(count, wanted);
411            next_k = k;
412            next_p = p;
413        }
414        self.k = next_k;
415        self.p = next_p;
416        self.in_total += n as u64;
417        self.out_total += wanted as u64;
418        wanted
419    }
420}
421
422#[cfg(test)]
423pub(crate) mod tests {
424    use super::*;
425    use std::f64::consts::PI;
426
427    /// Sine of `hz` at amplitude `amplitude` sampled at `rate`, `len` frames from `start`.
428    pub fn tone(rate: f64, hz: f64, amplitude: f64, start: usize, len: usize) -> Vec<f64> {
429        (start..start + len)
430            .map(|n| amplitude * (2.0 * PI * hz * n as f64 / rate).sin())
431            .collect()
432    }
433
434    /// Runs one channel through a resampler in blocks of `block`, returning everything it produced.
435    pub fn run(resampler: &mut Resampler, input: &[f64], block: usize) -> Vec<f64> {
436        let mut result = Vec::new();
437        let mut out = vec![Vec::new()];
438        for chunk in input.chunks(block) {
439            let wanted = resampler.output_len_for(chunk.len());
440            out[0].resize(wanted, 0.0);
441            let produced = resampler.process(&[chunk.to_vec()], chunk.len(), &mut out);
442            result.extend_from_slice(&out[0][..produced]);
443        }
444        result
445    }
446
447    /// Feeds the tail of zeros and returns what comes out.
448    pub fn finish(resampler: &mut Resampler, block: usize) -> Vec<f64> {
449        run(resampler, &vec![0.0; resampler.pad_frames()], block)
450    }
451
452    fn make(from: u32, to: u32, quality: Quality) -> Resampler {
453        Resampler::new(from, to, 1, quality, 4096).unwrap()
454    }
455
456    #[test]
457    fn the_polyphase_ratio_is_the_reduced_fraction() {
458        for (from, to, l, m) in [
459            (44_100, 48_000, 160, 147),
460            (48_000, 44_100, 147, 160),
461            (44_100, 88_200, 2, 1),
462            (96_000, 44_100, 147, 320),
463            (768_000, 44_100, 147, 2560),
464            (44_100, 768_000, 2560, 147),
465            (705_600, 48_000, 10, 147),
466        ] {
467            let resampler = make(from, to, Quality::Fast);
468            assert_eq!(
469                (resampler.info().l, resampler.info().m),
470                (l, m),
471                "{from} -> {to}"
472            );
473        }
474    }
475
476    #[test]
477    fn equal_rates_and_nonsense_are_refused() {
478        assert!(Resampler::new(48_000, 48_000, 2, Quality::High, 64).is_err());
479        assert!(Resampler::new(0, 48_000, 2, Quality::High, 64).is_err());
480        assert!(Resampler::new(48_000, 44_100, 0, Quality::High, 64).is_err());
481    }
482
483    #[test]
484    fn a_ratio_that_needs_an_unreasonable_filter_is_unsupported() {
485        // 44100 Hz to 47993 Hz does not reduce: 47993 phases of about 160 taps.
486        let error = Resampler::new(44_100, 47_993, 2, Quality::High, 64)
487            .err()
488            .unwrap();
489        assert_eq!(error.code(), "unsupported");
490    }
491
492    #[test]
493    fn every_standard_ratio_builds_within_the_limits() {
494        let rates = [
495            44_100u32, 88_200, 176_400, 352_800, 705_600, 48_000, 96_000, 192_000, 384_000, 768_000,
496        ];
497        for &from in &rates {
498            for &to in &rates {
499                if from == to {
500                    continue;
501                }
502                for quality in [Quality::High, Quality::Fast] {
503                    let resampler = Resampler::new(from, to, 1, quality, 64)
504                        .unwrap_or_else(|error| panic!("{from} -> {to} {quality:?}: {error}"));
505                    let info = resampler.info();
506                    assert!(info.taps <= MAX_TAPS);
507                    assert!(info.taps * info.l <= MAX_COEFFICIENTS);
508                    assert_eq!(info.taps % 8, 0);
509                }
510            }
511        }
512    }
513
514    #[test]
515    fn the_gain_at_dc_is_exactly_one_in_every_phase() {
516        for (from, to) in [
517            (44_100, 48_000),
518            (48_000, 44_100),
519            (96_000, 44_100),
520            (44_100, 192_000),
521        ] {
522            let mut resampler = make(from, to, Quality::High);
523            let input = vec![0.3; 20_000];
524            let mut output = run(&mut resampler, &input, 777);
525            output.extend(finish(&mut resampler, 777));
526            // The first outputs see the zeros before the signal; after the filter's length the gain is DC.
527            let info = *resampler.info();
528            let margin = info.taps * info.l / info.m + 8;
529            let settled = &output[margin..output.len() - margin];
530            let worst = settled.iter().map(|y| (y - 0.3).abs()).fold(0.0, f64::max);
531            assert!(worst < 1e-13, "{from} -> {to}: DC gain off by {worst}");
532        }
533    }
534
535    #[test]
536    fn the_output_length_is_ceil_of_the_input_length_times_l_over_m() {
537        for (from, to, frames) in [
538            (44_100u32, 48_000u32, 10_000usize),
539            (48_000, 44_100, 9_999),
540            (96_000, 44_100, 12_345),
541            (44_100, 88_200, 777),
542        ] {
543            let mut resampler = make(from, to, Quality::Fast);
544            let mut produced = run(&mut resampler, &vec![0.1; frames], 513).len();
545            produced += finish(&mut resampler, 513).len();
546            let info = *resampler.info();
547            let expected = (frames * info.l).div_ceil(info.m);
548            assert_eq!(produced, expected, "{from} -> {to}");
549            assert_eq!(resampler.frames_out(), expected as u64);
550        }
551    }
552
553    #[test]
554    fn output_len_for_and_max_input_for_output_are_exact_and_agree() {
555        let mut resampler = make(48_000, 44_100, Quality::Fast);
556        let mut fed = 0usize;
557        let mut made = 0usize;
558        for step in [1usize, 7, 160, 3, 1000, 2, 4095] {
559            let predicted = resampler.output_len_for(step);
560            let produced = run(&mut resampler, &vec![0.0; step], 4096).len();
561            assert_eq!(predicted, produced);
562            fed += step;
563            made += produced;
564            // Everything up to the largest allowed feed produces no more than asked for.
565            for cap in [0usize, 1, 5, 100] {
566                let allowed = resampler.max_input_for_output(cap);
567                assert!(resampler.output_len_for(allowed) <= cap, "cap {cap}");
568                assert!(resampler.output_len_for(allowed + 1) > cap, "cap {cap}");
569            }
570        }
571        assert_eq!(resampler.frames_in(), fed as u64);
572        assert_eq!(resampler.frames_out(), made as u64);
573    }
574
575    #[test]
576    fn chunking_does_not_change_a_single_bit() {
577        let input = tone(44_100.0, 1_234.5, 0.7, 0, 30_000);
578        let mut reference = make(44_100, 48_000, Quality::High);
579        let mut expected = run(&mut reference, &input, 4096);
580        expected.extend(finish(&mut reference, 4096));
581        for block in [1usize, 3, 100, 147, 1000, 4096] {
582            let mut resampler = make(44_100, 48_000, Quality::High);
583            let mut got = run(&mut resampler, &input, block);
584            got.extend(finish(&mut resampler, block));
585            assert_eq!(got.len(), expected.len(), "block {block}");
586            assert!(
587                got.iter()
588                    .zip(&expected)
589                    .all(|(a, b)| a.to_bits() == b.to_bits()),
590                "block {block}"
591            );
592        }
593    }
594
595    #[test]
596    fn a_reset_forgets_the_past() {
597        let input = tone(48_000.0, 997.0, 0.5, 0, 9_000);
598        let mut resampler = make(48_000, 96_000, Quality::Fast);
599        let first = run(&mut resampler, &input, 1000);
600        run(
601            &mut resampler,
602            &tone(48_000.0, 5_000.0, 0.9, 0, 3_000),
603            1000,
604        );
605        resampler.reset();
606        assert_eq!(resampler.frames_in(), 0);
607        let again = run(&mut resampler, &input, 1000);
608        assert_eq!(first.len(), again.len());
609        assert!(first
610            .iter()
611            .zip(&again)
612            .all(|(a, b)| a.to_bits() == b.to_bits()));
613    }
614
615    #[test]
616    fn an_impulse_comes_back_where_it_went_in() {
617        // The filter is zero-phase: an impulse at input n0 peaks at output n0 * L / M.
618        for (from, to, n0) in [
619            (48_000u32, 96_000u32, 500usize),
620            (96_000, 48_000, 800),
621            (44_100, 48_000, 640),
622        ] {
623            let mut resampler = make(from, to, Quality::High);
624            let mut input = vec![0.0; 4_000];
625            input[n0] = 1.0;
626            let mut output = run(&mut resampler, &input, 512);
627            output.extend(finish(&mut resampler, 512));
628            let (peak, _) = output
629                .iter()
630                .enumerate()
631                .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
632                .unwrap();
633            let expected = n0 as f64 * f64::from(to) / f64::from(from);
634            assert!(
635                (peak as f64 - expected).abs() <= 1.0,
636                "{from} -> {to}: peak at {peak}, expected {expected}"
637            );
638            // When the impulse lands on an output sample the response is symmetric around it.
639            if (expected - expected.round()).abs() < 1e-9 {
640                let around = |d: usize| (output[peak - d] - output[peak + d]).abs();
641                assert!(around(1) < 1e-9 && around(5) < 1e-9, "{from} -> {to}");
642            }
643        }
644    }
645
646    #[test]
647    fn channels_are_independent_and_advance_together() {
648        let left = tone(44_100.0, 440.0, 0.5, 0, 8_000);
649        let right = tone(44_100.0, 3_000.0, 0.25, 0, 8_000);
650        let mut stereo = Resampler::new(44_100, 48_000, 2, Quality::Fast, 1_000).unwrap();
651        let mut mono_left = Resampler::new(44_100, 48_000, 1, Quality::Fast, 1_000).unwrap();
652        let mut mono_right = Resampler::new(44_100, 48_000, 1, Quality::Fast, 1_000).unwrap();
653        let mut out = vec![Vec::new(), Vec::new()];
654        let mut got_left = Vec::new();
655        let mut got_right = Vec::new();
656        for (l, r) in left.chunks(1_000).zip(right.chunks(1_000)) {
657            let wanted = stereo.output_len_for(l.len());
658            out[0].resize(wanted, 0.0);
659            out[1].resize(wanted, 0.0);
660            let produced = stereo.process(&[l.to_vec(), r.to_vec()], l.len(), &mut out);
661            got_left.extend_from_slice(&out[0][..produced]);
662            got_right.extend_from_slice(&out[1][..produced]);
663        }
664        let want_left = run(&mut mono_left, &left, 1_000);
665        let want_right = run(&mut mono_right, &right, 1_000);
666        assert!(got_left
667            .iter()
668            .zip(&want_left)
669            .all(|(a, b)| a.to_bits() == b.to_bits()));
670        assert!(got_right
671            .iter()
672            .zip(&want_right)
673            .all(|(a, b)| a.to_bits() == b.to_bits()));
674    }
675}