SPB Git

Repository Public

resample.rs 5.4 KB 149 lines rust

1//! ORIX Sonata2//! File: crates/sonata-dsp/src/analysis/resample.rs3//! Description: Offline sample-rate conversion by Kaiser-windowed sinc interpolation4//! (arbitrary ratios, anti-aliased when downsampling). Not for the audio thread.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89/// Zero crossings on each side of the kernel centre.10const HALF_ZEROS: usize = 32;11/// Table resolution per zero crossing.12const TABLE_RES: usize = 512;13/// Kaiser beta: about -100 dB stop band.14const BETA: f64 = 10.0;15/// Pass band edge as a fraction of the lower Nyquist frequency.16const ROLLOFF: f64 = 0.945;1718fn bessel_i0(x: f64) -> f64 {19    let (mut sum, mut term, mut k) = (1.0, 1.0, 1.0);20    while term > 1e-17 * sum {21        term *= (x / (2.0 * k)) * (x / (2.0 * k));22        sum += term;23        k += 1.0;24    }25    sum26}2728/// A reusable converter between two rates.29pub struct Resampler {30    from: u32,31    to: u32,32    /// Windowed sinc sampled on [0, HALF_ZEROS] with TABLE_RES points per unit, plus a guard.33    table: Vec<f32>,34    scale: f64,35}3637impl Resampler {38    pub fn new(from: u32, to: u32) -> Resampler {39        let (from, to) = (from.max(1), to.max(1));40        let scale = (to as f64 / from as f64).min(1.0) * ROLLOFF;41        let n = HALF_ZEROS * TABLE_RES;42        let i0b = bessel_i0(BETA);43        let table = (0..=n + 1)44            .map(|i| {45                let x = i as f64 / TABLE_RES as f64;46                if x >= HALF_ZEROS as f64 {47                    return 0.0;48                }49                let sinc = if x == 0.0 { 1.0 } else { (std::f64::consts::PI * x).sin() / (std::f64::consts::PI * x) };50                let w = bessel_i0(BETA * (1.0 - (x / HALF_ZEROS as f64).powi(2)).max(0.0).sqrt()) / i0b;51                (sinc * w) as f3252            })53            .collect();54        Resampler { from, to, table, scale }55    }5657    /// Number of output samples produced for `n` input samples.58    pub fn output_len(&self, n: usize) -> usize {59        ((n as u128 * self.to as u128).div_ceil(self.from as u128)) as usize60    }6162    #[inline]63    fn kernel(&self, d: f64) -> f32 {64        let x = d.abs() * self.scale * TABLE_RES as f64;65        let i = x as usize;66        if i >= self.table.len() - 1 {67            return 0.0;68        }69        let f = (x - i as f64) as f32;70        self.table[i] + (self.table[i + 1] - self.table[i]) * f71    }7273    /// Converts a whole signal. Samples outside the input are treated as zero; output sample `j`74    /// is the band-limited signal evaluated at input time `j * from / to` (no added delay).75    pub fn process(&self, input: &[f32]) -> Vec<f32> {76        if self.from == self.to {77            return input.to_vec();78        }79        let out_len = self.output_len(input.len());80        let step = self.from as f64 / self.to as f64;81        let reach = (HALF_ZEROS as f64 / self.scale).ceil() as isize;82        let gain = self.scale as f32;83        let mut out = Vec::with_capacity(out_len);84        for j in 0..out_len {85            let t = j as f64 * step;86            let centre = t.floor() as isize;87            let lo = (centre - reach + 1).max(0);88            let hi = (centre + reach).min(input.len() as isize - 1);89            let mut acc = 0.0f32;90            let mut k = lo;91            while k <= hi {92                acc += input[k as usize] * self.kernel(t - k as f64);93                k += 1;94            }95            out.push(acc * gain);96        }97        out98    }99}100101/// Converts `input` from `from` Hz to `to` Hz.102pub fn resample(input: &[f32], from: u32, to: u32) -> Vec<f32> {103    Resampler::new(from, to).process(input)104}105106#[cfg(test)]107mod tests {108    use super::*;109110    fn sine(freq: f64, rate: u32, n: usize) -> Vec<f32> {111        (0..n).map(|i| (2.0 * std::f64::consts::PI * freq * i as f64 / rate as f64).sin() as f32).collect()112    }113114    fn rms_error(a: &[f32], b: &[f32], skip: usize) -> f64 {115        let n = a.len().min(b.len()) - skip;116        (a[skip..n].iter().zip(&b[skip..n]).map(|(x, y)| ((x - y) as f64).powi(2)).sum::<f64>() / (n - skip) as f64).sqrt()117    }118119    #[test]120    fn sine_survives_common_ratios() {121        // Tolerance: RMS error below -80 dB relative to a full-scale sine, away from the edges.122        for (from, to) in [(44_100, 48_000), (48_000, 44_100), (48_000, 96_000), (96_000, 48_000), (44_100, 192_000), (192_000, 44_100)] {123            let x = sine(1000.0, from, from as usize / 2);124            let y = resample(&x, from, to);125            let want = sine(1000.0, to, y.len());126            assert!((y.len() as i64 - to as i64 / 2).abs() <= 1);127            let err = rms_error(&y, &want, 2000);128            assert!(err < 1e-4 * std::f64::consts::FRAC_1_SQRT_2, "{from}->{to}: rms error {err}");129        }130    }131132    #[test]133    fn downsampling_rejects_content_above_the_new_nyquist() {134        // 30 kHz at 96 kHz would alias to 18 kHz at 48 kHz; it must be attenuated by more than 90 dB.135        let x = sine(30_000.0, 96_000, 48_000);136        let y = resample(&x, 96_000, 48_000);137        let peak = y[2000..y.len() - 2000].iter().fold(0.0f32, |a, b| a.max(b.abs()));138        assert!(peak < 10f32.powf(-90.0 / 20.0), "alias peak {peak}");139    }140141    #[test]142    fn identity_and_lengths() {143        let x = sine(440.0, 48_000, 1000);144        assert_eq!(resample(&x, 48_000, 48_000), x);145        assert_eq!(Resampler::new(44_100, 48_000).output_len(44_100), 48_000);146        assert!(resample(&[], 44_100, 48_000).is_empty());147    }148}149
Files main
Menu

Theme