use crate::DspError;
use signalsmith_stretch::Stretch;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StretchQuality {
Fast,
#[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(())
}
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;
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)
}
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; 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()
}
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");
}
}