weirdnet-dsp 0.3.0

Weirdnet DSP building blocks: RBJ biquad filters, level helpers (dB, peak, RMS) and fades. Pure functions over slices, no I/O, no allocation per block.
Documentation
//! Streaming sample-rate conversion with a windowed-sinc kernel, and a fine ratio trim for following another device's clock.
//!
//! [`Resampler::process`] takes interleaved input and writes interleaved output, both into caller slices: nothing allocates after
//! [`Resampler::new`]. Output is the same whatever sizes the input arrives in. At a ratio of exactly one the output is the input,
//! sample for sample. The kernel is 16 zero crossings each side under a Blackman-Harris window, with its cutoff at the lower of
//! the two rates' Nyquist frequencies (a little below it when going down, to keep images out).
//!
//! ```
//! use weirdnet_dsp::resample::Resampler;
//!
//! let mut r = Resampler::new(44_100, 48_000, 1)?;
//! let input = vec![0.5f32; 4410];
//! let mut out = vec![0.0f32; 6000];
//! let (used, written) = r.process(&input, &mut out);
//! assert_eq!(used, 4410);
//! assert!(written > 4700 && written <= 4800);
//! # Ok::<(), weirdnet_dsp::DspError>(())
//! ```

use crate::DspError;

/// Zero crossings of the kernel on each side, at the cutoff (the kernel is wider in input frames when going down).
const TAPS: usize = 16;
/// Kernel table entries per input frame of distance (linear interpolation between them).
const PHASES: usize = 512;
/// Room for newly arrived input, in frames, besides the kernel's lookahead.
const ROOM: usize = 2048;
/// The trim can move the ratio by at most this much either way (1 %).
pub const MAX_TRIM: f64 = 0.01;

/// A streaming resampler for interleaved audio.
pub struct Resampler {
    channels: usize,
    ratio: f64,
    trim: f64,
    step: f64,
    /// The next output's position in the history: whole frames and a fraction kept apart, so moving the history never rounds it.
    at: usize,
    frac: f64,
    /// The kernel's half width in input frames.
    half: usize,
    filled: usize,
    capacity: usize,
    hist: Vec<f32>,
    table: Vec<f32>,
    exact: bool,
}

impl Resampler {
    /// A resampler from `from` Hz to `to` Hz for `channels` interleaved channels.
    pub fn new(from: u32, to: u32, channels: u16) -> Result<Resampler, DspError> {
        if from == 0 || to == 0 {
            return Err(DspError::InvalidSampleRate);
        }
        if channels == 0 {
            return Err(DspError::NoChannels);
        }
        let ratio = f64::from(to) / f64::from(from);
        let cutoff = if ratio < 1.0 { ratio * 0.97 } else { 1.0 };
        let half = (TAPS as f64 / cutoff).ceil() as usize;
        let table = (0..=half * PHASES + 1)
            .map(|i| {
                let t = i as f64 / PHASES as f64;
                if t >= half as f64 {
                    return 0.0;
                }
                let x = std::f64::consts::PI * cutoff * t;
                let sinc = if x == 0.0 { 1.0 } else { x.sin() / x };
                let u = std::f64::consts::PI * t / half as f64;
                let w = 0.35875 + 0.48829 * u.cos() + 0.14128 * (2.0 * u).cos() + 0.01168 * (3.0 * u).cos();
                (cutoff * sinc * w) as f32
            })
            .collect();
        let ch = usize::from(channels);
        let capacity = 2 * half + ROOM;
        let mut r = Resampler {
            channels: ch,
            ratio,
            trim: 1.0,
            step: 0.0,
            at: half,
            frac: 0.0,
            half,
            filled: half,
            capacity,
            hist: vec![0.0; capacity * ch],
            table,
            exact: false,
        };
        r.update();
        Ok(r)
    }

    fn update(&mut self) {
        self.step = 1.0 / (self.ratio * self.trim);
        self.exact = self.step == 1.0;
    }

    /// Output frames per input frame, trim included.
    pub fn ratio(&self) -> f64 {
        self.ratio * self.trim
    }

    /// Trims the ratio by a factor (1.0 is none) to follow a clock that runs a little fast or slow, within ±[`MAX_TRIM`].
    pub fn set_trim(&mut self, trim: f64) {
        self.trim = trim.clamp(1.0 - MAX_TRIM, 1.0 + MAX_TRIM);
        self.update();
    }

    /// The trim in use.
    pub fn trim(&self) -> f64 {
        self.trim
    }

    /// Input frames held inside, not yet turned into output (its delay, in input frames, besides the kernel's half width).
    pub fn pending(&self) -> f64 {
        self.filled as f64 - self.at as f64 - self.frac
    }

    /// Converts as much of `input` as fits into `output` and returns (input frames used, output frames written). Call again with
    /// the rest of the input or more room for output. Output waits for the kernel's lookahead (16 frames, more when going down).
    pub fn process(&mut self, input: &[f32], output: &mut [f32]) -> (usize, usize) {
        let ch = self.channels;
        let (in_frames, out_frames) = (input.len() / ch, output.len() / ch);
        let (mut used, mut written) = (0, 0);
        loop {
            while written < out_frames && self.at + self.half < self.filled {
                self.frame(&mut output[written * ch..(written + 1) * ch]);
                self.frac += self.step;
                let whole = self.frac.floor();
                self.at += whole as usize;
                self.frac -= whole;
                written += 1;
            }
            let base = self.at.saturating_sub(self.half - 1).min(self.filled);
            if base > 0 {
                self.hist.copy_within(base * ch..self.filled * ch, 0);
                self.filled -= base;
                self.at -= base;
            }
            if written == out_frames {
                break;
            }
            let take = (in_frames - used).min(self.capacity - self.filled);
            if take == 0 {
                break;
            }
            self.hist[self.filled * ch..(self.filled + take) * ch].copy_from_slice(&input[used * ch..(used + take) * ch]);
            self.filled += take;
            used += take;
        }
        (used, written)
    }

    fn frame(&self, out: &mut [f32]) {
        let ch = self.channels;
        let (i, frac) = (self.at, self.frac);
        if self.exact && frac == 0.0 {
            out.copy_from_slice(&self.hist[i * ch..(i + 1) * ch]);
            return;
        }
        out.fill(0.0);
        let mut total = 0.0f32;
        for k in (i + 1 - self.half)..=(i + self.half) {
            let t = (k as f64 - i as f64 - frac).abs() * PHASES as f64;
            let j = t as usize;
            let f = (t - j as f64) as f32;
            let w = self.table[j] + (self.table[j + 1] - self.table[j]) * f;
            total += w;
            let x = &self.hist[k * ch..(k + 1) * ch];
            for c in 0..ch {
                out[c] += w * x[c];
            }
        }
        // the windowed kernel's weights sum to almost one; dividing keeps a constant exactly constant
        if total > 1e-6 {
            let g = 1.0 / total;
            for v in out.iter_mut() {
                *v *= g;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn run(r: &mut Resampler, input: &[f32], chunk: usize) -> Vec<f32> {
        let ch = r.channels;
        let mut out = Vec::new();
        let mut buf = vec![0.0f32; 333 * ch];
        for piece in input.chunks(chunk * ch) {
            let mut at = 0;
            while at < piece.len() {
                let (used, written) = r.process(&piece[at..], &mut buf);
                out.extend_from_slice(&buf[..written * ch]);
                at += used * ch;
                if used == 0 && written == 0 {
                    break;
                }
            }
        }
        loop {
            let (_, written) = r.process(&[], &mut buf);
            if written == 0 {
                break;
            }
            out.extend_from_slice(&buf[..written * ch]);
        }
        out
    }

    fn sine(rate: u32, hz: f64, frames: usize) -> Vec<f32> {
        (0..frames).map(|i| (2.0 * std::f64::consts::PI * hz * i as f64 / f64::from(rate)).sin() as f32).collect()
    }

    #[test]
    fn at_one_to_one_the_output_is_the_input() {
        let input: Vec<f32> = (0..4000).map(|i| ((i * 7919) % 1000) as f32 / 1000.0 - 0.5).collect();
        let mut r = Resampler::new(48_000, 48_000, 2).unwrap();
        let out = run(&mut r, &input, 100);
        assert_eq!(out.len(), input.len() - 2 * TAPS, "all but the last 16 frames (stereo), held for lookahead");
        assert_eq!(&out[..], &input[..out.len()]);
    }

    #[test]
    fn the_output_does_not_depend_on_how_the_input_is_cut() {
        let input = sine(44_100, 997.0, 20_000);
        let a = run(&mut Resampler::new(44_100, 48_000, 1).unwrap(), &input, 64);
        let b = run(&mut Resampler::new(44_100, 48_000, 1).unwrap(), &input, 1500);
        let c = run(&mut Resampler::new(44_100, 48_000, 1).unwrap(), &input, 7);
        assert_eq!(a, b);
        assert_eq!(a, c);
    }

    #[test]
    fn a_tone_keeps_its_pitch_and_level_and_the_count_follows_the_ratio() {
        for (from, to) in [(44_100, 48_000), (48_000, 44_100), (48_000, 96_000), (96_000, 48_000)] {
            let input = sine(from, 1000.0, from as usize);
            let out = run(&mut Resampler::new(from, to, 1).unwrap(), &input, 512);
            let expected = (input.len() as f64 * f64::from(to) / f64::from(from)) as usize;
            assert!(out.len().abs_diff(expected) <= TAPS * 2 + 2, "{from}->{to}: {} frames, expected about {expected}", out.len());
            // compare with the ideal tone at the output rate, past the start
            let ideal = sine(to, 1000.0, out.len());
            let err = out[200..out.len() - 200].iter().zip(&ideal[200..]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
            assert!(err < 2e-3, "{from}->{to}: max error {err}");
        }
    }

    #[test]
    fn going_down_keeps_tones_above_the_new_nyquist_out() {
        let input = sine(96_000, 30_000.0, 48_000);
        let out = run(&mut Resampler::new(96_000, 48_000, 1).unwrap(), &input, 512);
        let peak = out[100..out.len() - 100].iter().fold(0.0f32, |m, x| m.max(x.abs()));
        assert!(peak < 0.01, "30 kHz leaks through at {peak} (below -40 dB wanted)");
    }

    #[test]
    fn the_trim_changes_how_many_frames_come_out() {
        let input = vec![0.25f32; 100_000];
        let n0 = run(&mut Resampler::new(48_000, 48_000, 1).unwrap(), &input, 480).len();
        let mut r = Resampler::new(48_000, 48_000, 1).unwrap();
        r.set_trim(1.0005);
        let out = run(&mut r, &input, 480);
        assert!((out.len() as i64 - n0 as i64 - 50).abs() <= 2, "{} vs {n0}", out.len());
        assert!(out[100..].iter().all(|x| (x - 0.25).abs() < 1e-4), "a constant stays constant");
        r.set_trim(2.0);
        assert_eq!(r.trim(), 1.0 + MAX_TRIM);
        assert!(Resampler::new(0, 48_000, 1).is_err());
    }
}