Skip to main content

weirdnet_audio_plugin/builtin/
pitch.rs

1use crate::{ParamSpec, ParamValues, Plugin, PluginError};
2use weirdnet_media::waveform::Waveform;
3
4/// `weirdnet.pitch`: moves the pitch of a sound.
5///
6/// | Parameter | Range | Default |
7/// | --- | --- | --- |
8/// | `semitones` | -24 to +24 | 0 |
9/// | `cents` | -100 to +100 | 0 |
10/// | `preserve_length` | on or off | on |
11/// | `quality` | `fast` or `good` (with `preserve_length` only) | `good` |
12///
13/// The shift is `semitones + cents / 100` semitones, a frequency ratio of `2^(shift / 12)`.
14///
15/// * With **`preserve_length`** on the sound keeps its length and only the pitch moves (Signalsmith Stretch through `weirdnet-dsp`, so
16///   large shifts of a bass drum smear, and attacks soften a little). This needs the crate feature `stretch`, on by default; without it
17///   this mode is an error.
18/// * With it off the sound is resampled (cubic interpolation), like a tape speed change: the length changes by `1 / ratio`, and no
19///   artefacts beyond the interpolation. It works without the `stretch` feature.
20///
21/// A shift of zero returns the input's samples unchanged (shared, not copied).
22pub struct Pitch;
23
24fn specs() -> &'static [ParamSpec] {
25    use std::sync::OnceLock;
26    static SPECS: OnceLock<Vec<ParamSpec>> = OnceLock::new();
27    SPECS.get_or_init(|| {
28        vec![
29            ParamSpec::float("semitones", -24.0, 24.0, 0.0, "st"),
30            ParamSpec::float("cents", -100.0, 100.0, 0.0, "ct"),
31            ParamSpec::boolean("preserve_length", true),
32            ParamSpec::choice("quality", &["fast", "good"], "good"),
33        ]
34    })
35}
36
37impl Plugin for Pitch {
38    fn id(&self) -> &'static str {
39        "weirdnet.pitch"
40    }
41
42    fn params(&self) -> &[ParamSpec] {
43        specs()
44    }
45
46    fn process(&self, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError> {
47        let shift = values.float("semitones") + values.float("cents") / 100.0;
48        if shift == 0.0 || input.frames() == 0 {
49            return Ok(input.clone());
50        }
51        let out = if values.bool("preserve_length") {
52            shift_keeping_length(input, shift, values.choice("quality") == "fast")?
53        } else {
54            resample(input, 2f64.powf(shift / 12.0))
55        };
56        Ok(Waveform::new(input.sample_rate(), input.channels(), out)?)
57    }
58}
59
60#[cfg(feature = "stretch")]
61fn shift_keeping_length(input: &Waveform, shift: f64, fast: bool) -> Result<Vec<f32>, PluginError> {
62    use weirdnet_dsp::stretch::{StretchQuality, pitch_shift};
63    let quality = if fast { StretchQuality::Fast } else { StretchQuality::Good };
64    pitch_shift(input.samples(), input.channels(), input.sample_rate(), shift, quality).map_err(|e| PluginError::Internal(e.to_string()))
65}
66
67#[cfg(not(feature = "stretch"))]
68fn shift_keeping_length(_: &Waveform, _: f64, _: bool) -> Result<Vec<f32>, PluginError> {
69    Err(PluginError::Internal(
70        "this build has no pitch shift that keeps the length (the crate feature `stretch` is off); turn preserve_length off".into(),
71    ))
72}
73
74/// Plays the samples `ratio` times as fast, with cubic (Catmull-Rom) interpolation between them, per channel. The first and last samples
75/// are repeated at the edges.
76fn resample(input: &Waveform, ratio: f64) -> Vec<f32> {
77    let ch = usize::from(input.channels());
78    let src = input.samples();
79    let frames = input.frames();
80    let out_frames = ((frames as f64) / ratio).round().max(1.0) as usize;
81    let at = |frame: isize, c: usize| -> f32 { src[(frame.clamp(0, frames as isize - 1) as usize) * ch + c] };
82    let mut out = Vec::with_capacity(out_frames * ch);
83    for i in 0..out_frames {
84        let pos = i as f64 * ratio;
85        let base = pos.floor() as isize;
86        let t = (pos - base as f64) as f32;
87        for c in 0..ch {
88            let (p0, p1, p2, p3) = (at(base - 1, c), at(base, c), at(base + 1, c), at(base + 2, c));
89            let a = -0.5 * p0 + 1.5 * p1 - 1.5 * p2 + 0.5 * p3;
90            let b = p0 - 2.5 * p1 + 2.0 * p2 - 0.5 * p3;
91            let cc = -0.5 * p0 + 0.5 * p2;
92            out.push(((a * t + b) * t + cc) * t + p1);
93        }
94    }
95    out
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::Registry;
102
103    const RATE: u32 = 48_000;
104
105    fn run(input: &Waveform, v: ParamValues) -> Result<Waveform, PluginError> {
106        Registry::with_builtins().process("weirdnet.pitch", input, &v)
107    }
108
109    fn hz(w: &Waveform) -> f64 {
110        let x = w.samples();
111        let mid = &x[x.len() / 4..x.len() * 3 / 4];
112        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
113    }
114
115    #[test]
116    fn zero_shift_returns_the_same_samples() {
117        let w = Waveform::tone(RATE, 440.0, 4_800, 0.5).unwrap();
118        let out = run(&w, ParamValues::new()).unwrap();
119        assert!(std::ptr::eq(out.samples().as_ptr(), w.samples().as_ptr()) || out == w);
120        assert_eq!(run(&w, ParamValues::new().with_bool("preserve_length", false)).unwrap(), w);
121    }
122
123    #[test]
124    fn resampling_changes_length_and_pitch_together_by_the_ratio() {
125        let w = Waveform::tone(RATE, 440.0, 24_000, 0.5).unwrap();
126        for (st, cents) in [(12.0, 0.0), (-12.0, 0.0), (7.0, 0.0), (0.0, 50.0), (-3.0, -25.0)] {
127            let shift = st + cents / 100.0;
128            let ratio = 2f64.powf(shift / 12.0);
129            let out = run(&w, ParamValues::new().with_float("semitones", st).with_float("cents", cents).with_bool("preserve_length", false)).unwrap();
130            assert_eq!(out.frames(), (24_000.0 / ratio).round() as usize, "{shift} st");
131            let f = hz(&out);
132            assert!((f / (440.0 * ratio) - 1.0).abs() < 0.01, "{shift} st: {f} Hz, wanted {}", 440.0 * ratio);
133        }
134    }
135
136    #[test]
137    fn resampling_stereo_keeps_the_channels_apart() {
138        let mut s = Vec::new();
139        for i in 0..4_800 {
140            s.extend([(i as f32 * 0.01).sin() * 0.5, 0.0]);
141        }
142        let w = Waveform::new(RATE, 2, s).unwrap();
143        let out = run(&w, ParamValues::new().with_float("semitones", 5.0).with_bool("preserve_length", false)).unwrap();
144        assert!(out.samples().iter().skip(1).step_by(2).all(|x| *x == 0.0));
145        assert!(out.samples().iter().step_by(2).any(|x| x.abs() > 0.1));
146    }
147
148    #[cfg(feature = "stretch")]
149    #[test]
150    fn preserving_the_length_moves_only_the_pitch() {
151        let w = Waveform::tone(RATE, 440.0, 24_000, 0.5).unwrap();
152        for (st, cents) in [(12.0, 0.0), (-12.0, 0.0), (5.0, 0.0), (0.0, 100.0)] {
153            let shift = st + cents / 100.0;
154            let out = run(&w, ParamValues::new().with_float("semitones", st).with_float("cents", cents)).unwrap();
155            assert_eq!(out.frames(), w.frames());
156            let want = 440.0 * 2f64.powf(shift / 12.0);
157            assert!((hz(&out) / want - 1.0).abs() < 0.03, "{shift} st: {} Hz, wanted {want}", hz(&out));
158        }
159    }
160
161    #[cfg(feature = "stretch")]
162    #[test]
163    fn a_short_sound_survives_a_shift() {
164        let w = Waveform::tone(RATE, 440.0, 1_200, 0.5).unwrap();
165        let out = run(&w, ParamValues::new().with_float("semitones", 3.0)).unwrap();
166        assert_eq!(out.frames(), 1_200);
167        assert!(out.samples().iter().fold(0.0f32, |m, s| m.max(s.abs())) > 0.2);
168    }
169
170    #[test]
171    fn limits_and_empty_input() {
172        let w = Waveform::tone(RATE, 440.0, 480, 0.5).unwrap();
173        assert!(matches!(run(&w, ParamValues::new().with_float("semitones", 25.0)), Err(PluginError::InvalidParam { .. })));
174        assert!(matches!(run(&w, ParamValues::new().with_float("cents", -101.0)), Err(PluginError::InvalidParam { .. })));
175        assert!(run(&w, ParamValues::new().with_float("semitones", -24.0).with_float("cents", -100.0).with_bool("preserve_length", false)).is_ok());
176        let empty = Waveform::silence(RATE, 1, 0).unwrap();
177        assert_eq!(run(&empty, ParamValues::new().with_float("semitones", 3.0)).unwrap().frames(), 0);
178    }
179
180    #[cfg(not(feature = "stretch"))]
181    #[test]
182    fn without_the_feature_keeping_the_length_is_an_error() {
183        let w = Waveform::tone(RATE, 440.0, 480, 0.5).unwrap();
184        assert!(matches!(run(&w, ParamValues::new().with_float("semitones", 3.0)), Err(PluginError::Internal(_))));
185    }
186}