weirdnet-audio-plugin 0.3.0

Audio plugins for Weirdnet: the Plugin trait, typed parameters, a registry, chain processing with a content-hash cache key, and the built-ins gain, levels and frequencies.
Documentation
use crate::{ParamSpec, ParamValues, Plugin, PluginError};
use weirdnet_media::waveform::Waveform;

/// `weirdnet.pitch`: moves the pitch of a sound.
///
/// | Parameter | Range | Default |
/// | --- | --- | --- |
/// | `semitones` | -24 to +24 | 0 |
/// | `cents` | -100 to +100 | 0 |
/// | `preserve_length` | on or off | on |
/// | `quality` | `fast` or `good` (with `preserve_length` only) | `good` |
///
/// The shift is `semitones + cents / 100` semitones, a frequency ratio of `2^(shift / 12)`.
///
/// * With **`preserve_length`** on the sound keeps its length and only the pitch moves (Signalsmith Stretch through `weirdnet-dsp`, so
///   large shifts of a bass drum smear, and attacks soften a little). This needs the crate feature `stretch`, on by default; without it
///   this mode is an error.
/// * With it off the sound is resampled (cubic interpolation), like a tape speed change: the length changes by `1 / ratio`, and no
///   artefacts beyond the interpolation. It works without the `stretch` feature.
///
/// A shift of zero returns the input's samples unchanged (shared, not copied).
pub struct Pitch;

fn specs() -> &'static [ParamSpec] {
    use std::sync::OnceLock;
    static SPECS: OnceLock<Vec<ParamSpec>> = OnceLock::new();
    SPECS.get_or_init(|| {
        vec![
            ParamSpec::float("semitones", -24.0, 24.0, 0.0, "st"),
            ParamSpec::float("cents", -100.0, 100.0, 0.0, "ct"),
            ParamSpec::boolean("preserve_length", true),
            ParamSpec::choice("quality", &["fast", "good"], "good"),
        ]
    })
}

impl Plugin for Pitch {
    fn id(&self) -> &'static str {
        "weirdnet.pitch"
    }

    fn params(&self) -> &[ParamSpec] {
        specs()
    }

    fn process(&self, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError> {
        let shift = values.float("semitones") + values.float("cents") / 100.0;
        if shift == 0.0 || input.frames() == 0 {
            return Ok(input.clone());
        }
        let out = if values.bool("preserve_length") {
            shift_keeping_length(input, shift, values.choice("quality") == "fast")?
        } else {
            resample(input, 2f64.powf(shift / 12.0))
        };
        Ok(Waveform::new(input.sample_rate(), input.channels(), out)?)
    }
}

#[cfg(feature = "stretch")]
fn shift_keeping_length(input: &Waveform, shift: f64, fast: bool) -> Result<Vec<f32>, PluginError> {
    use weirdnet_dsp::stretch::{StretchQuality, pitch_shift};
    let quality = if fast { StretchQuality::Fast } else { StretchQuality::Good };
    pitch_shift(input.samples(), input.channels(), input.sample_rate(), shift, quality).map_err(|e| PluginError::Internal(e.to_string()))
}

#[cfg(not(feature = "stretch"))]
fn shift_keeping_length(_: &Waveform, _: f64, _: bool) -> Result<Vec<f32>, PluginError> {
    Err(PluginError::Internal(
        "this build has no pitch shift that keeps the length (the crate feature `stretch` is off); turn preserve_length off".into(),
    ))
}

/// Plays the samples `ratio` times as fast, with cubic (Catmull-Rom) interpolation between them, per channel. The first and last samples
/// are repeated at the edges.
fn resample(input: &Waveform, ratio: f64) -> Vec<f32> {
    let ch = usize::from(input.channels());
    let src = input.samples();
    let frames = input.frames();
    let out_frames = ((frames as f64) / ratio).round().max(1.0) as usize;
    let at = |frame: isize, c: usize| -> f32 { src[(frame.clamp(0, frames as isize - 1) as usize) * ch + c] };
    let mut out = Vec::with_capacity(out_frames * ch);
    for i in 0..out_frames {
        let pos = i as f64 * ratio;
        let base = pos.floor() as isize;
        let t = (pos - base as f64) as f32;
        for c in 0..ch {
            let (p0, p1, p2, p3) = (at(base - 1, c), at(base, c), at(base + 1, c), at(base + 2, c));
            let a = -0.5 * p0 + 1.5 * p1 - 1.5 * p2 + 0.5 * p3;
            let b = p0 - 2.5 * p1 + 2.0 * p2 - 0.5 * p3;
            let cc = -0.5 * p0 + 0.5 * p2;
            out.push(((a * t + b) * t + cc) * t + p1);
        }
    }
    out
}

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

    const RATE: u32 = 48_000;

    fn run(input: &Waveform, v: ParamValues) -> Result<Waveform, PluginError> {
        Registry::with_builtins().process("weirdnet.pitch", input, &v)
    }

    fn hz(w: &Waveform) -> f64 {
        let x = w.samples();
        let mid = &x[x.len() / 4..x.len() * 3 / 4];
        mid.windows(2).filter(|p| p[0] <= 0.0 && p[1] > 0.0).count() as f64 * f64::from(w.sample_rate()) / mid.len() as f64
    }

    #[test]
    fn zero_shift_returns_the_same_samples() {
        let w = Waveform::tone(RATE, 440.0, 4_800, 0.5).unwrap();
        let out = run(&w, ParamValues::new()).unwrap();
        assert!(std::ptr::eq(out.samples().as_ptr(), w.samples().as_ptr()) || out == w);
        assert_eq!(run(&w, ParamValues::new().with_bool("preserve_length", false)).unwrap(), w);
    }

    #[test]
    fn resampling_changes_length_and_pitch_together_by_the_ratio() {
        let w = Waveform::tone(RATE, 440.0, 24_000, 0.5).unwrap();
        for (st, cents) in [(12.0, 0.0), (-12.0, 0.0), (7.0, 0.0), (0.0, 50.0), (-3.0, -25.0)] {
            let shift = st + cents / 100.0;
            let ratio = 2f64.powf(shift / 12.0);
            let out = run(&w, ParamValues::new().with_float("semitones", st).with_float("cents", cents).with_bool("preserve_length", false)).unwrap();
            assert_eq!(out.frames(), (24_000.0 / ratio).round() as usize, "{shift} st");
            let f = hz(&out);
            assert!((f / (440.0 * ratio) - 1.0).abs() < 0.01, "{shift} st: {f} Hz, wanted {}", 440.0 * ratio);
        }
    }

    #[test]
    fn resampling_stereo_keeps_the_channels_apart() {
        let mut s = Vec::new();
        for i in 0..4_800 {
            s.extend([(i as f32 * 0.01).sin() * 0.5, 0.0]);
        }
        let w = Waveform::new(RATE, 2, s).unwrap();
        let out = run(&w, ParamValues::new().with_float("semitones", 5.0).with_bool("preserve_length", false)).unwrap();
        assert!(out.samples().iter().skip(1).step_by(2).all(|x| *x == 0.0));
        assert!(out.samples().iter().step_by(2).any(|x| x.abs() > 0.1));
    }

    #[cfg(feature = "stretch")]
    #[test]
    fn preserving_the_length_moves_only_the_pitch() {
        let w = Waveform::tone(RATE, 440.0, 24_000, 0.5).unwrap();
        for (st, cents) in [(12.0, 0.0), (-12.0, 0.0), (5.0, 0.0), (0.0, 100.0)] {
            let shift = st + cents / 100.0;
            let out = run(&w, ParamValues::new().with_float("semitones", st).with_float("cents", cents)).unwrap();
            assert_eq!(out.frames(), w.frames());
            let want = 440.0 * 2f64.powf(shift / 12.0);
            assert!((hz(&out) / want - 1.0).abs() < 0.03, "{shift} st: {} Hz, wanted {want}", hz(&out));
        }
    }

    #[cfg(feature = "stretch")]
    #[test]
    fn a_short_sound_survives_a_shift() {
        let w = Waveform::tone(RATE, 440.0, 1_200, 0.5).unwrap();
        let out = run(&w, ParamValues::new().with_float("semitones", 3.0)).unwrap();
        assert_eq!(out.frames(), 1_200);
        assert!(out.samples().iter().fold(0.0f32, |m, s| m.max(s.abs())) > 0.2);
    }

    #[test]
    fn limits_and_empty_input() {
        let w = Waveform::tone(RATE, 440.0, 480, 0.5).unwrap();
        assert!(matches!(run(&w, ParamValues::new().with_float("semitones", 25.0)), Err(PluginError::InvalidParam { .. })));
        assert!(matches!(run(&w, ParamValues::new().with_float("cents", -101.0)), Err(PluginError::InvalidParam { .. })));
        assert!(run(&w, ParamValues::new().with_float("semitones", -24.0).with_float("cents", -100.0).with_bool("preserve_length", false)).is_ok());
        let empty = Waveform::silence(RATE, 1, 0).unwrap();
        assert_eq!(run(&empty, ParamValues::new().with_float("semitones", 3.0)).unwrap().frames(), 0);
    }

    #[cfg(not(feature = "stretch"))]
    #[test]
    fn without_the_feature_keeping_the_length_is_an_error() {
        let w = Waveform::tone(RATE, 440.0, 480, 0.5).unwrap();
        assert!(matches!(run(&w, ParamValues::new().with_float("semitones", 3.0)), Err(PluginError::Internal(_))));
    }
}