//! Speed without pitch: WSOLA (waveform-similarity overlap-add). Hann-windowed frames are overlap-added at a fixed //! output hop; each next frame is taken from near its nominal input position (input advances `speed` times the //! output hop), shifted by up to ±12 ms to where it best continues the frame before. Streaming: push input blocks, //! pull output; the speed can change between blocks. /// Frame length, overlap and search window, in seconds. const FRAME: f64 = 0.040; const SEARCH: f64 = 0.012; pub const MIN_SPEED: f64 = 0.5; pub const MAX_SPEED: f64 = 3.0; pub struct Stretcher { channels: usize, n: usize, hop: usize, search: usize, speed: f64, window: Vec, /// Interleaved input not yet consumed; `base` is the absolute frame index of its first frame. input: Vec, base: usize, /// Nominal analysis position of the next frame (absolute, in frames), and the start chosen for the last one. pos: f64, last: Option, /// Overlap-add accumulator: `n` frames, interleaved. acc: Vec, out: Vec, flushed: bool, } impl Stretcher { pub fn new(rate: u32, channels: u16) -> Stretcher { let channels = channels.max(1) as usize; let n = ((rate as f64 * FRAME) as usize).max(64) & !1; let window = (0..n).map(|i| (0.5 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / n as f64).cos()) as f32).collect(); Stretcher { channels, n, hop: n / 2, search: (rate as f64 * SEARCH) as usize, speed: 1.0, window, input: Vec::new(), base: 0, pos: 0.0, last: None, acc: vec![0.0; n * channels], out: Vec::new(), flushed: false, } } pub fn speed(&self) -> f64 { self.speed } /// 0.5–3×; outside values are clamped, NaN keeps the current speed. pub fn set_speed(&mut self, speed: f64) { if speed.is_finite() { self.speed = speed.clamp(MIN_SPEED, MAX_SPEED); } } fn frames_in(&self) -> usize { self.input.len() / self.channels } /// Mono sample at an absolute input frame (0 outside what is buffered). fn mono(&self, abs: usize) -> f32 { if abs < self.base { return 0.0; } let i = abs - self.base; if i >= self.frames_in() { return 0.0; } let row = &self.input[i * self.channels..(i + 1) * self.channels]; row.iter().sum::() / self.channels as f32 } /// Adds interleaved samples. pub fn push(&mut self, samples: &[f32]) { self.input.extend_from_slice(samples); self.run(false); } /// No more input: everything buffered comes out. pub fn finish(&mut self) { if !self.flushed { self.flushed = true; self.run(true); // The tail of the accumulator is the last frame's second half. self.out.extend_from_slice(&self.acc[..self.hop * self.channels]); self.acc.iter_mut().for_each(|x| *x = 0.0); } } /// Takes what is ready. pub fn pull(&mut self) -> Vec { std::mem::take(&mut self.out) } fn run(&mut self, last: bool) { let (n, hop, s, ch) = (self.n, self.hop, self.search, self.channels); loop { let nominal = self.pos.round() as usize; let end_needed = nominal + s + n; let have = self.base + self.frames_in(); if have < end_needed && !(last && nominal < have) { break; } // Best start near the nominal one: the frame that best continues the last frame's natural sequel. let start = match self.last { None => nominal, Some(prev) => { let lo = nominal.saturating_sub(s).max(self.base); let hi = (nominal + s).min(have.saturating_sub(n).max(lo)); let target = prev + hop; let mut best = (f32::MIN, nominal.clamp(lo, hi)); let step = 2; let overlap = hop; let mut d = lo; while d <= hi { let mut c = 0.0f32; let mut k = 0; while k < overlap { c += self.mono(target + k) * self.mono(d + k); k += 4; } if c > best.0 { best = (c, d); } d += step; } best.1 } }; for i in 0..n { let w = self.window[i]; let abs = start + i; for c in 0..ch { let v = if abs >= self.base && abs - self.base < self.frames_in() { self.input[(abs - self.base) * ch + c] } else { 0.0 }; self.acc[i * ch + c] += v * w; } } // The first hop of the accumulator is complete: emit it and shift. self.out.extend_from_slice(&self.acc[..hop * ch]); self.acc.copy_within(hop * ch.., 0); let len = self.acc.len(); self.acc[len - hop * ch..].iter_mut().for_each(|x| *x = 0.0); self.last = Some(start); self.pos += hop as f64 * self.speed; // Drop input nothing will read again. let keep_from = (self.pos as usize).saturating_sub(s).min(start + hop).min(self.base + self.frames_in()); if keep_from > self.base { let drop = keep_from - self.base; self.input.drain(..drop * ch); self.base = keep_from; } if last && self.pos as usize >= have { break; } } } } /// The whole of `samples` at `speed` (tests and short clips). pub fn stretch(samples: &[f32], rate: u32, channels: u16, speed: f64) -> Vec { let mut s = Stretcher::new(rate, channels); s.set_speed(speed); for block in samples.chunks(4096 * channels.max(1) as usize) { s.push(block); } s.finish(); s.pull() }