weirdnet-dsp 0.2.1

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
//! Time stretch and pitch shift, over the [Signalsmith Stretch](https://github.com/Signalsmith-Audio/signalsmith-stretch) library.
//! Behind the `stretch` feature, because it builds C++ (with bindgen: clang and libclang must be installed).
//!
//! Both functions work on a whole interleaved buffer at once and allocate their output, so they belong on a worker thread, never in an
//! audio callback.
//!
//! ```
//! use weirdnet_dsp::stretch::{StretchQuality, time_stretch};
//!
//! let input = vec![0.0f32; 4_800]; // 0.1 s of mono silence at 48 kHz
//! let slower = time_stretch(&input, 1, 48_000, 6_000, StretchQuality::Good)?; // 1.25 times as long
//! assert_eq!(slower.len(), 6_000);
//! # Ok::<(), weirdnet_dsp::DspError>(())
//! ```

use crate::DspError;
use signalsmith_stretch::Stretch;

/// How much work the stretch does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StretchQuality {
    /// The library's cheaper preset: about 30 % faster, with softer attacks on strong stretches.
    Fast,
    /// The library's default preset.
    #[default]
    Good,
}

fn engine(channels: u16, sample_rate: u32, quality: StretchQuality) -> Result<Stretch, DspError> {
    if sample_rate == 0 {
        return Err(DspError::InvalidSampleRate);
    }
    if channels == 0 {
        return Err(DspError::NotFinite("the channel count (it is zero, so it is not a count)"));
    }
    Ok(match quality {
        StretchQuality::Fast => Stretch::preset_cheaper(u32::from(channels), sample_rate),
        StretchQuality::Good => Stretch::preset_default(u32::from(channels), sample_rate),
    })
}

fn check(input: &[f32], channels: u16) -> Result<(), DspError> {
    if !input.len().is_multiple_of(usize::from(channels.max(1))) {
        return Err(DspError::NotFinite("the sample count (it is not a whole number of frames)"));
    }
    if input.iter().any(|s| !s.is_finite()) {
        return Err(DspError::NotFinite("a sample"));
    }
    Ok(())
}

/// Changes the length of interleaved `input` to exactly `out_frames` frames, keeping the pitch. More frames out than in slows the sound
/// down. Empty input or zero output frames give an empty result.
pub fn time_stretch(input: &[f32], channels: u16, sample_rate: u32, out_frames: usize, quality: StretchQuality) -> Result<Vec<f32>, DspError> {
    let mut s = engine(channels, sample_rate, quality)?;
    check(input, channels)?;
    if input.is_empty() || out_frames == 0 {
        return Ok(Vec::new());
    }
    let ch = usize::from(channels);
    let in_frames = input.len() / ch;
    // The library gives silence for input shorter than about its latency, so a short sound is padded with silence to twice the latency, and
    // the output is cut back to the length asked for (the padding stretches to silence at the end).
    let min_frames = s.input_latency() * 2;
    if in_frames < min_frames {
        let mut padded = input.to_vec();
        padded.resize(min_frames * ch, 0.0);
        let total = (out_frames as f64 * min_frames as f64 / in_frames as f64).ceil() as usize;
        let mut out = vec![0.0f32; total * ch];
        s.exact(&padded, &mut out);
        out.truncate(out_frames * ch);
        return Ok(out);
    }
    let mut out = vec![0.0f32; out_frames * ch];
    s.exact(input, &mut out);
    Ok(out)
}

/// Moves the pitch of interleaved `input` by `semitones` (and any cents as a fraction), keeping its length.
pub fn pitch_shift(input: &[f32], channels: u16, sample_rate: u32, semitones: f64, quality: StretchQuality) -> Result<Vec<f32>, DspError> {
    let mut s = engine(channels, sample_rate, quality)?;
    check(input, channels)?;
    if !semitones.is_finite() {
        return Err(DspError::NotFinite("the pitch shift"));
    }
    if input.is_empty() {
        return Ok(Vec::new());
    }
    s.set_transpose_factor_semitones(semitones as f32, None);
    let ch = usize::from(channels);
    let min_frames = s.input_latency() * 2; // as in `time_stretch`: a short sound is padded, then cut back
    let mut padded = input.to_vec();
    padded.resize(padded.len().max(min_frames * ch), 0.0);
    let mut out = vec![0.0f32; padded.len()];
    s.exact(&padded, &mut out);
    out.truncate(input.len());
    Ok(out)
}

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

    const RATE: u32 = 48_000;

    fn tone(hz: f64, frames: usize) -> Vec<f32> {
        (0..frames).map(|i| (0.5 * (std::f64::consts::TAU * hz * i as f64 / f64::from(RATE)).sin()) as f32).collect()
    }

    /// Frequency by counting rising zero crossings over the middle of the buffer (a pure tone only).
    fn hz(x: &[f32]) -> f64 {
        let (a, b) = (x.len() / 4, x.len() * 3 / 4);
        let mid = &x[a..b];
        let crossings = mid.windows(2).filter(|w| w[0] <= 0.0 && w[1] > 0.0).count();
        crossings as f64 * f64::from(RATE) / mid.len() as f64
    }

    #[test]
    fn stretch_has_the_exact_length_and_keeps_the_pitch() {
        let input = tone(440.0, 24_000);
        for out_frames in [12_000, 24_000, 30_000, 48_000] {
            let out = time_stretch(&input, 1, RATE, out_frames, StretchQuality::Good).unwrap();
            assert_eq!(out.len(), out_frames);
            let f = hz(&out);
            assert!((f - 440.0).abs() < 8.0, "{out_frames} frames: {f} Hz");
        }
    }

    #[test]
    fn stereo_channels_stay_apart() {
        let left = tone(440.0, 12_000);
        let mut input = Vec::new();
        for s in &left {
            input.extend([*s, 0.0]);
        }
        let out = time_stretch(&input, 2, RATE, 18_000, StretchQuality::Fast).unwrap();
        assert_eq!(out.len(), 36_000);
        let right_peak = out.iter().skip(1).step_by(2).fold(0.0f32, |m, s| m.max(s.abs()));
        let left_peak = out.iter().step_by(2).fold(0.0f32, |m, s| m.max(s.abs()));
        assert!(right_peak < 1e-3 && left_peak > 0.2, "left {left_peak}, right {right_peak}");
    }

    #[test]
    fn pitch_shift_keeps_the_length_and_moves_the_pitch() {
        let input = tone(440.0, 24_000);
        let up = pitch_shift(&input, 1, RATE, 12.0, StretchQuality::Good).unwrap();
        assert_eq!(up.len(), input.len());
        assert!((hz(&up) - 880.0).abs() < 16.0, "{}", hz(&up));
        let same = pitch_shift(&input, 1, RATE, 0.0, StretchQuality::Good).unwrap();
        assert!((hz(&same) - 440.0).abs() < 8.0);
    }

    #[test]
    fn short_sounds_are_not_lost() {
        for frames in [100usize, 480, 1_200, 2_400, 4_800] {
            let input = tone(440.0, frames);
            let out = time_stretch(&input, 1, RATE, frames * 5 / 4, StretchQuality::Good).unwrap();
            assert_eq!(out.len(), frames * 5 / 4);
            let (e_in, e_out): (f32, f32) = (input.iter().map(|s| s * s).sum(), out.iter().map(|s| s * s).sum());
            let ratio = e_out / e_in;
            assert!((0.8..1.6).contains(&ratio), "{frames} frames: energy ratio {ratio} (ideal 1.25)");
        }
    }

    #[test]
    fn a_short_sound_can_be_pitch_shifted() {
        let input = tone(440.0, 1_200);
        let out = pitch_shift(&input, 1, RATE, 5.0, StretchQuality::Good).unwrap();
        assert_eq!(out.len(), input.len());
        assert!(out.iter().fold(0.0f32, |m, s| m.max(s.abs())) > 0.2, "not silent");
    }

    #[test]
    fn tiny_empty_and_bad_input_are_handled() {
        assert!(time_stretch(&[], 1, RATE, 100, StretchQuality::Good).unwrap().is_empty());
        assert!(time_stretch(&[0.1; 10], 1, RATE, 0, StretchQuality::Good).unwrap().is_empty());
        let tiny = time_stretch(&[0.1; 10], 1, RATE, 25, StretchQuality::Good).unwrap();
        assert_eq!(tiny.len(), 25);
        assert!(tiny.iter().all(|s| s.is_finite()));
        assert_eq!(time_stretch(&[0.0; 4], 1, 0, 4, StretchQuality::Good), Err(DspError::InvalidSampleRate));
        assert!(time_stretch(&[0.0; 3], 2, RATE, 4, StretchQuality::Good).is_err(), "not whole frames");
        assert!(time_stretch(&[f32::NAN; 4], 1, RATE, 4, StretchQuality::Good).is_err());
        assert!(pitch_shift(&[0.0; 4], 1, RATE, f64::NAN, StretchQuality::Good).is_err());
    }

    #[test]
    fn the_same_input_gives_the_same_output() {
        let input = tone(330.0, 20_000);
        let a = time_stretch(&input, 1, RATE, 25_000, StretchQuality::Good).unwrap();
        let b = time_stretch(&input, 1, RATE, 25_000, StretchQuality::Good).unwrap();
        assert_eq!(a, b, "a cache key can rely on this");
    }
}