From 475f10cf2bc7d99ab4c3d408f8c9b0cfae102957 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 16 Aug 2026 02:01:34 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20a=20speeded=20clip?= =?UTF-8?q?=20keeps=20its=20pitch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tape effect is gone: a speeded clip's audio was resampled at its speed, so its pitch moved with its rate. The resample is now only what it always should have been -- the rate conversion, reading a source written at another sample rate at the ratio of the two rates, pitch- true by construction -- and the time the Speed asks for is taken by a WSOLA stretch behind it: windows overlap-added at a different hop, each placed where it best continues the one before it, so the timeline compresses or stretches while every period of the signal keeps its own length. The beep stays a 1 kHz beep at 2x, the words stay spoken. Hand-rolled, no new dependencies: N=1024 Hann windows, 512-frame synthesis hop, ±512 search on the first channel by normalized cross- correlation against the natural continuation, one offset for every channel so a stereo pair stays coherent. A silent continuation is placed nominally -- nothing to match -- and a segment too short to prime a window passes through as the decoder read it. Both halves of the chain pace the timeline's promise to the frame, which is the A/V sync invariant the speed suite pins. Measured, not felt: the stretch's own tests put a 440 Hz sine through 2x and 0.5x and read 440 back by Goertzel with the octave gone; the sync fixture's 1 kHz beep plays at 1 kHz at 2x and 0.5x through the real open path (the tape effect's ladder peak read 1350 Hz there), and a 2x WAV export carries the same 1 kHz back out. --- crates/engine/src/audio.rs | 144 +++++++--- crates/engine/src/lib.rs | 1 + crates/engine/src/project.rs | 8 +- crates/engine/src/stretch.rs | 502 +++++++++++++++++++++++++++++++++++ crates/engine/tests/speed.rs | 120 +++++++++ 5 files changed, 733 insertions(+), 42 deletions(-) create mode 100644 crates/engine/src/stretch.rs diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 7b95ac8..c789bc1 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -53,6 +53,7 @@ use symphonia_core::units; use symphonia_core::units::{Time, TimeBase}; use crate::eq::{EqParams, EqState}; +use crate::stretch::TimeStretch; use crate::limiter::{Limiter, LimiterState}; /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list. @@ -85,7 +86,7 @@ const MP4_DECODED: &str = "AAC-LC and AC-3/E-AC-3"; const PRE_ROLL: u32 = 2; /// Frames per channel one AAC-LC packet carries. Fixed by the codec. -const SAMPLES_PER_PACKET: u32 = 1024; +pub(crate) const SAMPLES_PER_PACKET: u32 = 1024; /// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the /// 256-sample overlap-add the target frame is reconstructed with. @@ -493,16 +494,23 @@ impl AudioSession { }) .collect(); - // One resampler per segment that needs one, built where the sample rate - // is known: what the timeline owes it is seconds there and frames here. + // One rate chain per segment that needs one, built where the sample + // rate is known: what the timeline owes it is seconds there and frames + // here. // - // Two things ask for one and they compose into a single step: the clip's - // own speed, and a source written at a rate other than the timeline's -- - // the ratio of the two rates is exactly a speed, and reading the samples - // at it is what keeps a 48 kHz file's pitch on a 44.1 kHz timeline. A - // segment with neither has no resampler at all and reaches the mixer - // with the decoder's own samples, byte for byte, as it always did. - let speeds: Vec> = segments + // Two things ask for one, and they are NOT the same thing: a source + // written at a rate other than the timeline's is a *rate conversion* + // -- reading the samples at the ratio of the two rates is what keeps + // a 48 kHz file's pitch on a 44.1 kHz timeline, and is the resampler's + // whole duty now. A clip whose own [`Speed`] is not real time is a + // *time* change: the resample hands the stretch a pitch-true stream + // and the stretch hands the timeline the clip's compressed or + // stretched seconds with every period of the signal kept (the tape + // effect this used to be -- one resample at the speed -- moved the + // pitch with the rate). A segment with neither has no chain at all + // and reaches the mixer with the decoder's own samples, byte for + // byte, as it always did. + let speeds: Vec> = segments .iter() .zip(segs) .enumerate() @@ -516,6 +524,7 @@ impl AudioSession { if stretch.is_none() && rate == meta.sample_rate { return None; } + let channels = usize::from(meta.channels); // A speeded clip states the timeline it owes; a plain one owes // the window it was placed for, and an open-ended window owes // whatever its source has ([`Resample::UNBOUNDED`]). @@ -527,7 +536,22 @@ impl AudioSession { frames if frames > 0.0 => Resample::UNBOUNDED, _ => 0, }; - Some(Resample::new(stretch.map_or(1.0, |s| s.step) * ratio, owed)) + Some(match stretch { + // A rate conversion alone: the resampler owns the + // segment's promise, as it always has. + None => Rate { + resample: Resample::new(ratio, owed), + stretch: None, + }, + // A speeded clip: the resample is only the rate + // conversion -- unbounded, because the ratio is all it + // is asked for -- and the stretch lands the timeline's + // frames exactly. + Some(s) => Rate { + resample: Resample::new(ratio, Resample::UNBOUNDED), + stretch: Some(TimeStretch::new(s.step, owed, channels)), + }, + }) }) .collect(); @@ -2585,36 +2609,39 @@ impl Segment { } } -/// One speeded segment's resampler: the tape effect, done by reading the -/// decoded samples at a rate other than the one they were written at, so the -/// pitch moves with the speed. Linear interpolation between the two frames a -/// fractional position falls between -- one multiply-add per channel, which is -/// nothing beside the decode that produced them, and enough that a 2x clip is -/// not the aliasing mess plain sample-dropping would give. +/// One segment's rate conversion: the decoded samples read at the ratio of +/// the source's own sample rate to the timeline's, which is a pure rate +/// conversion -- the pitch is preserved because the frames are read at the +/// ratio of the rates rather than dropped, and 48 kHz onto a 44.1 kHz +/// timeline is one resampler, not two. Linear interpolation between the two +/// frames a fractional position falls between -- one multiply-add per +/// channel, which is nothing beside the decode that produced them, and for a +/// 48:44.1 ratio its worst-case image lands ~40 dB down; the alternative is +/// a windowed-sinc kernel and a new state machine for a conversion that is +/// not the audible risk in this path. /// /// It lives across the whole segment: `pos` carries the fraction over a packet /// boundary and `tail` keeps the frame before the buffer, so the interpolation /// at the seam is the same one it would have been inside a buffer. A segment -/// starts one clean and drops it at the end, which is what makes a seek a reset -/// for free -- exactly as the equalizer's state does. +/// starts one clean and drops it at the end, which is what makes a seek a +/// reset for free -- exactly as the equalizer's state does. /// -/// It is also what makes a file written at another sample rate playable at all: -/// the step is the clip's speed *times* the source rate over the timeline's, so -/// 48 kHz read onto a 44.1 kHz timeline is one resampler, not two, and the pitch -/// is preserved because the frames are read at the ratio of the rates rather -/// than dropped. Linear interpolation is what a speed change already uses here -/// -- for a 48:44.1 ratio its worst-case image lands ~40 dB down and the -/// alternative is a windowed-sinc kernel and a new state machine for a -/// conversion that is not the audible risk in this path. +/// Time is no longer this struct's business: a clip whose own +/// [`Speed`](crate::project::Speed) is not real time is re-timed by the +/// [`TimeStretch`] behind it in its [`Rate`] chain, which compresses or +/// stretches the timeline while keeping every period of the signal its own +/// length -- this hands it a pitch-true stream at the timeline's rate and +/// that is the whole of the hand-off. /// /// `owed` is what the timeline gives the segment, in frames per channel: /// resampling resolves to whole samples and a clip's own window resolves to /// whole *source* frames, so the two miss each other by a sample or two per /// clip. Truncating and padding to what is owed keeps that from accumulating -/// into audible drift over a timeline of speeded cuts -- the picture's clip -/// boundaries are exact by construction, and this makes the sound's exact too. +/// into audible drift over a timeline of rate-mismatched cuts -- the picture's +/// clip boundaries are exact by construction, and this makes the sound's +/// exact too. struct Resample { - /// Source frames per output frame: the speed itself. + /// Source frames per output frame: the ratio of the two sample rates. step: f64, /// Where the next output frame reads, relative to the current buffer's /// first frame. Negative means it reads across the seam, into `tail`. @@ -2704,6 +2731,44 @@ impl Resample { } } +/// One speeded-or-converted segment's whole rate chain: the resample that +/// turns the source's own rate into the timeline's, and -- only for a clip +/// whose [`Speed`](crate::project::Speed) is not real time -- the stretch +/// that changes its *time* without touching its pitch, after the resample +/// and before the equalizer sees a sample (the filter's bands are set in the +/// frequency a listener hears, and after a stretch that is still the +/// frequency the file was written at). +/// +/// Which half owns the segment's promise depends on which halves there are: +/// a rate conversion alone is paced by the resample, as it always was, and a +/// speeded clip's resample runs unbounded (the ratio is all it is asked for) +/// while the stretch lands the timeline's frames exactly. +struct Rate { + resample: Resample, + stretch: Option, +} + +impl Rate { + fn process(&mut self, buf: &mut Vec, channels: usize) { + self.resample.process(buf, channels); + if let Some(stretch) = self.stretch.as_mut() { + stretch.process(buf, channels); + } + } + + fn flush( + &mut self, + channels: usize, + timeline: &mut u64, + tx: &SyncSender, + ) -> bool { + match self.stretch.as_mut() { + Some(stretch) => stretch.flush(channels, timeline, tx), + None => self.resample.flush(channels, timeline, tx), + } + } +} + struct Worker { /// Indexed by [`Segment::source`]; only the sources some segment names are /// `Some`, the rest were never opened. @@ -2715,10 +2780,11 @@ struct Worker { /// Beside the segments rather than inside them so the emit path can hold the /// window rules and the filter memory at once without splitting a borrow. eqs: Vec>, - /// One per entry of `segments` again: the rate that segment is read at, or - /// `None` for one at real time -- which is every segment of a project nobody - /// has speeded, and the path that emits the decoder's own samples untouched. - speeds: Vec>, + /// One per entry of `segments` again: that segment's rate chain, or + /// `None` for one at real time on the timeline's own rate -- which is + /// every segment of a project nobody has speeded or rate-mismatched, and + /// the path that emits the decoder's own samples untouched. + speeds: Vec>, /// `start_sample` of the first chunk. timeline: u64, tx: SyncSender, @@ -2981,7 +3047,7 @@ fn run(mut w: Worker) { /// [`Resample::flush`]). Nothing at all at real time, where a segment owes the /// timeline only the samples it decoded. fn settle( - speed: &mut Option, + speed: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -3013,7 +3079,7 @@ fn emit( channels: usize, seg: &Segment, eq: Option<&mut EqState>, - speed: Option<&mut Resample>, + speed: Option<&mut Rate>, pos: u64, next: u64, timeline: &mut u64, @@ -3062,7 +3128,7 @@ fn run_ac3( track: &mut Ac3Track, seg: &Segment, mut eq: Option<&mut EqState>, - speed: &mut Option, + speed: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -3125,7 +3191,7 @@ fn run_mkv_ac3( track: &mut MkvAc3Track, seg: &Segment, mut eq: Option<&mut EqState>, - speed: &mut Option, + speed: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -3192,7 +3258,7 @@ fn run_sym( track: &mut SymTrack, seg: &Segment, mut eq: Option<&mut EqState>, - speed: &mut Option, + speed: &mut Option, channels: usize, timeline: &mut u64, tx: &SyncSender, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index be01647..27913f0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -24,6 +24,7 @@ pub mod scale; pub mod scratch; pub mod silence; pub mod subtitle; +pub(crate) mod stretch; pub mod tonemap; pub mod waveform; diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 4b508af..2bf21d4 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -97,9 +97,11 @@ pub const MAX_GAIN_DB: f32 = 12.0; /// number that was set. A thousandth is finer than any card can drag and coarser /// than any rounding anyone can hear. /// -/// The rate alone: a speeded clip is resampled, so its pitch moves with it (the -/// tape effect). Nothing here preserves pitch and nothing here plays backwards -/// -- [`Speed::MIN`] is a quarter speed, [`Speed::MAX`] four times. +/// The rate alone: the audio path time-stretches a speeded clip +/// (`crate::stretch`), so its pitch stays where it was recorded while its +/// seconds compress or stretch -- the tape effect this used to be is gone. +/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed, +/// [`Speed::MAX`] four times. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub struct Speed(u16); diff --git a/crates/engine/src/stretch.rs b/crates/engine/src/stretch.rs new file mode 100644 index 0000000..37f0a87 --- /dev/null +++ b/crates/engine/src/stretch.rs @@ -0,0 +1,502 @@ +//! Time-stretching that keeps the pitch: WSOLA, hand-rolled. +//! +//! A speeded clip used to be resampled -- the tape effect, its pitch moving +//! with its rate. The rate conversion (a source written at another sample +//! rate than the timeline's) is still a resample and still is, because +//! reading frames at the ratio of two rates is pitch-true by construction. +//! What [`crate::project::Speed`] asks for is *time* alone, and that is this +//! module's: the waveform is cut into overlapping windows and re-assembled at +//! a different hop, each window placed where it best continues the one before +//! it (Waveform Similarity Overlap-add, Verhelst & Roelands 1993), so the +//! timeline compresses or stretches while every period of the underlying +//! signal keeps its own length -- the words, the notes and the beeps stay at +//! the frequency they were recorded at. +//! +//! The one consumer is [`crate::audio`]'s emit path, after the rate +//! conversion and before the equalizer, exactly where the resample used to +//! sit; see [`TimeStretch`] for the buffering contract it keeps there. + +/// Analysis window, in frames: long enough that a window holds several +/// periods of anything a person calls a pitch (at 48 kHz, 1024 frames is +/// 21 ms -- four periods of a 187 Hz tone), short enough that a placement +/// mistake cannot smear a consonant. +const N: usize = 1024; +/// Synthesis hop, in frames: half the window, which is what makes the Hann +/// windows of consecutive frames sum to one everywhere -- the overlap-add +/// neither adds gain nor leaves a seam. +const HS: usize = N / 2; +/// How far either side of the nominal position a window may be placed to find +/// the best continuation: half a window again, which is the classic WSOLA +/// compromise between finding the good overlap and keeping the search cheap +/// (it is O(N·SEARCH) per frame, and this keeps it under a million adds). +const SEARCH: usize = N / 2; + +/// One speeded segment's time-stretch: interleaved f32 in, interleaved f32 +/// out, at the timeline's own sample rate and channel count, paced to the +/// frames the timeline promised the segment (`owed` -- the A/V sync +/// invariant, which the device and an export both read). +/// +/// WSOLA in one breath: windows of [`N`] frames are overlap-added at +/// [`HS`]-frame hops, read from the input at [`Ha`] = `HS · speed`-frame hops. +/// Each window after the first is shifted within ±[`SEARCH`] of its nominal +/// read position to the offset whose first `HS` frames best match the +/// *natural continuation* of the window before it -- the input that followed +/// that window's own read position -- measured by normalized cross-correlation +/// on the first channel, and the one offset is applied to every channel so a +/// stereo pair stays coherent. The output is the input at the timeline's rate +/// with its pitch kept: `speed` frames of source per frame of output, to the +/// frame. +/// +/// The contract with the emit path is [`Resample`](crate::audio)'s own: +/// [`process`](Self::process) rewrites a decoded buffer as whatever output +/// frames are ready (an empty one is fine -- the first window only completes +/// once `N + SEARCH` frames are buffered, and a caller's buffers are packet +/// sized), and [`flush`](Self::flush) pays whatever the input's end left +/// owed, in silence, so a segment lands on its promise exactly. +pub(crate) struct TimeStretch { + /// Analysis hop: how far the read position advances per synthesized + /// window. `HS · speed`, rounded once here so it never rounds again -- + /// the speed itself is spent on this number and nowhere else. + ha: usize, + channels: usize, + /// Output frames the timeline was promised and has not been paid. Paced + /// to exactly, by truncation and by silence, for [`Resample`]'s reason: + /// the picture's clip boundaries are exact, and this keeps the sound's + /// exact with them. + owed: u64, + hann: Vec, + /// Input not yet consumed, interleaved. `base` is the frame index of its + /// first frame within the segment's whole stream, so the analysis + /// positions below stay absolute -- and survive the buffer compaction + /// that keeps this from growing without bound. + input: Vec, + base: usize, + /// The nominal read position of the next window, in stream frames. Starts + /// at 0 and advances by `ha`. + anext: usize, + /// The read position the last window actually used, for the natural + /// continuation the next one is matched against. `None` until one window + /// has been placed -- the first has nothing to match and takes its + /// nominal position as-is. + prev: Option, + /// The overlap-add accumulator: the tail of the last window that the next + /// one completes, interleaved, always `N - HS` frames. + overlap: Vec, + /// Whether any window has been synthesized -- a segment whose whole + /// source is shorter than a window never primes, and is passed through + /// as the decoder read it, padded to its promise in silence: the honest + /// degenerate, rather than a stretched half-window of nothing. + started: bool, +} + +impl TimeStretch { + /// `speed` is source frames per output frame, as [`crate::project::Stretch`] + /// states it; `owed` is the segment's whole promise in output frames, the + /// same number [`crate::audio::Resample`] paces to when it works alone. + pub(crate) fn new(speed: f64, owed: u64, channels: usize) -> Self { + // The classic Hann, in the half-open form the overlap-add wants: 0 at + // either end, so a window never snaps the seam it is pasting over. + let hann = (0..N) + .map(|i| { + (std::f64::consts::PI * i as f64 / N as f64).sin().powi(2) as f32 + }) + .collect(); + Self { + ha: (HS as f64 * speed).round().max(1.) as usize, + channels, + owed, + hann, + input: Vec::new(), + base: 0, + anext: 0, + prev: None, + overlap: vec![0.; (N - HS) * channels], + started: false, + } + } + + /// Frames of input the stretcher holds, stream-indexed -- every question + /// below is asked in stream frames and answered against this. + fn has(&self, frame: usize) -> bool { + frame < self.base + self.input.len() / self.channels + } + + /// The first channel's frames `[at, at + HS)` as the correlation target, + /// zero-padded past the input's end -- the flush path reads past what was + /// decoded, and a target of zeros simply stops favouring any offset. + fn natural(&self, at: usize) -> Vec { + (0..HS) + .map(|i| { + self.has(at + i) + .then(|| { + self.input[((at + i - self.base) * self.channels)..][0] + }) + .unwrap_or(0.) + }) + .collect() + } + + /// Normalized cross-correlation of the first channel at `[at, at + HS)` + /// against `target`: 1 for a perfect match, 0 for nothing in common, + /// amplitude-free so a loud passage does not win on loudness alone. + fn match_at(&self, at: usize, target: &[f32]) -> f32 { + let (mut dot, mut ea, mut eb) = (0f32, 0f32, 0f32); + for i in 0..HS { + let a = self.has(at + i) + .then(|| self.input[((at + i - self.base) * self.channels)..][0]) + .unwrap_or(0.); + let b = target[i]; + dot += a * b; + ea += a * a; + eb += b * b; + } + dot / (ea.sqrt() * eb.sqrt() + 1e-9) + } + + /// Overlap-adds one window read at `at` and hands back the `HS` output + /// frames it completes: the accumulator's head, released, with the + /// window's contribution added to what the last one left behind. The + /// Hann hops at half its width, so the two contributions over any + /// completed frame sum to one and the windowing leaves no trace of + /// itself. + fn place(&mut self, at: usize) -> Vec { + let mut out = std::mem::take(&mut self.overlap); + out.resize(N * self.channels, 0.); + for i in 0..N { + let w = self.hann[i]; + let src = if self.has(at + i) { + &self.input[((at + i - self.base) * self.channels)..][..self.channels] + } else { + &[0., 0.][..self.channels.min(2)] + }; + for c in 0..self.channels { + out[i * self.channels + c] += src.get(c).copied().unwrap_or(0.) * w; + } + } + let done = out[..HS * self.channels].to_vec(); + self.overlap = out[HS * self.channels..].to_vec(); + self.overlap + .resize((N - HS) * self.channels, 0.); + done + } + + /// Whether another window can be placed: its whole search range and its + /// whole window must be buffered, and so must the natural continuation + /// the *next* window is matched against -- one look-ahead window of + /// latency, which is what the caller's empty emits ride out. + fn ready(&self) -> bool { + let have = self.base + self.input.len() / self.channels; + self.anext + SEARCH + N + HS <= have + } + + /// Rewrites `buf` as the output frames this stretch has ready for it -- + /// possibly none (see the struct doc). Consumes the input, compacts what + /// is left, and never returns more than the segment is owed. + pub(crate) fn process(&mut self, buf: &mut Vec, channels: usize) { + debug_assert_eq!(channels, self.channels, "the layout is fixed at open"); + self.input.append(buf); + let mut out: Vec = Vec::new(); + while self.owed > 0 && self.ready() { + let want = self + .anext + .saturating_sub(SEARCH) + .max(self.prev.map_or(0, |p| p + HS - SEARCH)); + // The best continuation in the search range: every offset is + let at = match self.prev { + None => self.anext, + Some(p) => { + let target = self.natural(p + HS); + // A silent continuation says nothing about where the next + // window belongs: every offset matches it equally (which + // is to say not at all), and the search would pick one on + // rounding noise. The nominal position is the honest + // answer there -- silence continued is silence, and the + // burst that follows starts where the timeline says. + let loud = target.iter().fold(0f32, |m, x| m + x * x); + if loud < 1e-4 { + self.anext + } else { + // Scored once each and argmax'd after: a comparator + // that re-measured both sides of every comparison is + // a search squared, and this search already is the + // module's cost. + (want..=self.anext + SEARCH) + .map(|at| (self.match_at(at, &target), at)) + .max_by(|(a, _), (b, _)| a.total_cmp(b)) + .map_or(self.anext, |(_, at)| at) + } + } + }; + // Never past the promise: the last window a segment can pay for + // may be a partial one, and the frames it still owes -- not the + // hop a full window would have completed -- are what leaves here. + let frames = self.place(at); + let pays = frames.len().min(self.owed as usize * self.channels); + out.extend_from_slice(&frames[..pays]); + self.owed -= (pays / self.channels) as u64; + self.prev = Some(at); + self.anext += self.ha; + self.started = true; + } + // Consumed input is everything before the next window's search range + // and before the continuation it is matched against -- either may be + // the earlier one. + let keep = self + .anext + .saturating_sub(SEARCH) + .min(self.prev.map_or(usize::MAX, |p| p + HS)); + let drop = (keep.saturating_sub(self.base)).min(self.input.len() / self.channels); + self.input.drain(..drop * self.channels); + self.base += drop; + *buf = out; + } + + /// The end of the segment: whatever windows the buffered input still + /// completes are placed at their nominal positions -- no search, because + /// the offsets the search would pick from are half padding -- and what + /// the promise still lacks is paid in silence. Pads or truncates to + /// `owed` exactly, for the reason every flush in this path does: the + /// device's seconds are the timeline's seconds, and a segment that lands + /// one frame long is a segment every later segment is one frame late + /// against. `false` means the consumer went away. + pub(crate) fn flush( + &mut self, + channels: usize, + timeline: &mut u64, + tx: &std::sync::mpsc::SyncSender, + ) -> bool { + let mut send = |frames: Vec| -> bool { + if frames.is_empty() { + return true; + } + let chunk = crate::audio::AudioChunk { + start_sample: *timeline, + samples: frames, + }; + *timeline += (chunk.samples.len() / channels) as u64; + tx.send(chunk).is_ok() + }; + // A segment too short to ever prime: the decoder's own frames, as + // they came -- the honest degenerate -- and the padding below pays + // the rest of the promise. + if !self.started && self.input.len() / self.channels < N + SEARCH { + let mut rest = std::mem::take(&mut self.input); + let owed = (self.owed as usize).min(usize::MAX / channels) * channels; + if rest.len() > owed { + rest.truncate(owed); + } + self.owed -= (rest.len() / channels) as u64; + if !send(rest) { + return false; + } + } else { + // The windows the buffer still completes, placed nominally; the + // zero-padding in `place` finishes the last of them. + while self.owed > 0 && self.anext < self.base + self.input.len() / self.channels + N { + let frames = self.place(self.anext); + self.anext += self.ha; + let pays = (self.owed as usize).min(frames.len() / channels) * channels; + self.owed -= (pays / channels) as u64; + if !send(frames[..pays].to_vec()) { + return false; + } + } + } + // The promise, in silence, to the frame. + while self.owed > 0 { + let frames = (self.owed as usize).min(crate::audio::SAMPLES_PER_PACKET as usize); + if !send(vec![0.; frames * channels]) { + return false; + } + self.owed -= frames as u64; + } + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Runs a stretcher over a whole signal the way the emit path does: one + /// packet-shaped buffer at a time, whatever comes out collected, then the + fn stretched(speed: f64, owed: u64, samples: &[f32]) -> Vec { + let mut s = TimeStretch::new(speed, owed, 1); + let mut out = Vec::new(); + for chunk in samples.chunks(1024) { + let mut buf = chunk.to_vec(); + s.process(&mut buf, 1); + out.extend_from_slice(&buf); + } + let before = out.len(); + // Drained on its own thread, the way the device drains the worker in + // the real path: the channel is four chunks deep, and a flush that + // owes more silence than that would block on a receiver nobody is + // reading yet. + let (tx, rx) = std::sync::mpsc::sync_channel(4); + let drained = std::thread::spawn(move || { + rx.into_iter() + .map(|c: crate::audio::AudioChunk| (c.start_sample, c.samples)) + .collect::>() + }); + let mut timeline = 0; + s.flush(1, &mut timeline, &tx); + drop(tx); + let mut paid = 0; + for (_, frames) in drained.join().unwrap() { + paid += frames.len(); + out.extend_from_slice(&frames); + } + assert_eq!( + before + paid, + owed as usize, + "the promise is paid to the frame" + ); + // The promise is what the two halves paid together: the flush's own + // count is only its tail, and a segment that primed early paid most + // of its way on the process path. + assert_eq!( + before + timeline as usize, + owed as usize, + "the promise is paid to the frame" + ); + out + } + + /// The amplitude of `hz` inside `samples`, by Goertzel at 48 kHz: the + /// dominant-frequency meter these tests assert pitch with, rather than + /// trusting that a stretch *sounds* unchanged. + fn amplitude(samples: &[f32], hz: f64) -> f64 { + let n = samples.len() as f64; + let w = 2. * std::f64::consts::PI * hz / 48_000.; + let coeff = 2. * w.cos(); + let (mut s1, mut s2) = (0., 0.); + for &x in samples { + let s0 = f64::from(x) + coeff * s1 - s2; + s2 = s1; + s1 = s0; + } + 2. * (s1 * s1 + s2 * s2 - coeff * s1 * s2).sqrt() / n + } + + /// Two seconds of a 440 Hz sine at 48 kHz, one channel: the plain, + /// pitch-carrying signal every assertion below stretches. + fn sine(hz: f64, secs: f64) -> Vec { + (0..(secs * 48_000.) as usize) + .map(|i| (2. * std::f64::consts::PI * hz * i as f64 / 48_000.).sin() as f32) + .collect() + } + + + #[test] + fn a_2x_stretch_halves_the_time_and_keeps_the_pitch() { + let input = sine(440., 2.); + let out = stretched(2.0, 48_000, &input); + // The promise is the timeline's: one second out for two in. + assert_eq!(out.len(), 48_000, "owed exactly"); + // Pitch, measured: 440 Hz is the loudest thing in the output by far, + // and the octave the tape effect would have put there (880) is not. + let keep = amplitude(&out, 440.); + let octave = amplitude(&out, 880.); + assert!(keep > 0.4, "440 Hz survives at {keep}"); + assert!(octave < keep / 4., "the tape-effect octave is gone: {octave} vs {keep}"); + } + + #[test] + fn a_half_speed_stretch_doubles_the_time_and_keeps_the_pitch() { + let input = sine(440., 1.); + let out = stretched(0.5, 96_000, &input); + assert_eq!(out.len(), 96_000, "owed exactly"); + let keep = amplitude(&out, 440.); + let sub = amplitude(&out, 220.); + assert!(keep > 0.4, "440 Hz survives at {keep}"); + assert!(sub < keep / 4., "the tape-effect sub-octave is gone: {sub} vs {keep}"); + } + + #[test] + fn a_stereo_pair_keeps_its_channels_in_step() { + // Left is the 440 Hz sine, right the same one panned down: a stereo + // pair whose channels differ only in level, which is what a real + // image is made of. The stretch's one search offset for both + // channels is what keeps the pair from smearing, and the two halves + // staying in step -- the cross-correlation of right against left + // peaking at lag zero, both still the tone they went in as -- is what + // says it did. + let left = sine(440., 2.); + let right: Vec = left.iter().map(|&x| x * 0.7).collect(); + let input: Vec = left + .iter() + .zip(&right) + .flat_map(|(&l, &r)| [l, r]) + .collect(); + let mut s = TimeStretch::new(2.0, 48_000, 2); + let mut out = Vec::new(); + for chunk in input.chunks(2048) { + let mut buf = chunk.to_vec(); + s.process(&mut buf, 2); + out.extend_from_slice(&buf); + } + let (tx, rx) = std::sync::mpsc::sync_channel(4); + let drained = std::thread::spawn(move || { + rx.into_iter() + .flat_map(|c: crate::audio::AudioChunk| c.samples) + .collect::>() + }); + let mut timeline = 0; + s.flush(2, &mut timeline, &tx); + drop(tx); + out.extend(drained.join().unwrap()); + assert_eq!(out.len(), 96_000); + let l: Vec = out.chunks(2).map(|f| f[0]).collect(); + let r: Vec = out.chunks(2).map(|f| f[1]).collect(); + assert!(amplitude(&l, 440.) > 0.4, "left keeps its tone"); + assert!(amplitude(&r, 440.) > 0.25, "right keeps the same one, panned"); + // In step: the correlation of right against left is greatest at lag + // zero -- a channel smeared to its own timings peaks somewhere else. + let at = |lag: i32| -> f32 { + let n = l.len() as i32; + let (mut dot, mut ea, mut eb) = (0f32, 0f32, 0f32); + for i in 0..n { + let j = i + lag; + if j < 0 || j >= n { + continue; + } + dot += l[i as usize] * r[j as usize]; + ea += l[i as usize] * l[i as usize]; + eb += r[j as usize] * r[j as usize]; + } + dot / (ea.sqrt() * eb.sqrt() + 1e-9) + }; + let zero = at(0); + let worst = (-256..=256) + .filter(|&lag| lag != 0) + .map(at) + .fold(0f32, f32::max); + assert!( + zero > worst, + "the pair is in step: lag 0 at {zero}, best other {worst}" + ); + } + + #[test] + fn a_segment_shorter_than_a_window_passes_through_honestly() { + // 600 frames is under the prime (N + SEARCH): no window ever + // completes, and the decoder's own frames come out padded to the + // promise in silence -- degenerate, and exactly what it owes. + let input = sine(440., 600. / 48_000.); + let out = stretched(2.0, 400, &input); + assert_eq!(out.len(), 400); + assert_eq!(out[..600.min(400)], input[..600.min(400)], "the frames as they were"); + } + + #[test] + fn the_promise_is_padded_when_the_source_runs_short() { + // A window's worth of input for two seconds of promise: whatever the + // stretch makes of it, the rest is silence, to the frame. + let input = sine(440., 0.02); + let out = stretched(2.0, 96_000, &input); + assert_eq!(out.len(), 96_000, "owed exactly"); + let tail = &out[48_000..]; + assert!(tail.iter().all(|&x| x == 0.), "the shortfall is silence"); + } +} diff --git a/crates/engine/tests/speed.rs b/crates/engine/tests/speed.rs index cdf564e..af81948 100644 --- a/crates/engine/tests/speed.rs +++ b/crates/engine/tests/speed.rs @@ -331,6 +331,126 @@ fn an_mp4_export_resamples_a_speeded_sound_clip() { std::fs::remove_file(&out).ok(); } +/// The amplitude of `hz` inside `samples`, by Goertzel at the fixture's rate +/// over a fixed window: the pitch meter the pitch tests assert with, rather +/// than trusting that a re-timed beep *sounds* unchanged. +fn tone(samples: &[f32], hz: f64) -> f64 { + let n = samples.len() as f64; + let w = 2. * std::f64::consts::PI * hz / f64::from(RATE); + let coeff = 2. * w.cos(); + let (mut s1, mut s2) = (0., 0.); + for &x in samples { + let s0 = f64::from(x) + coeff * s1 - s2; + s2 = s1; + s1 = s0; + } + 2. * (s1 * s1 + s2 * s2 - coeff * s1 * s2).sqrt() / n +} + +/// The beep's own frequency in the played samples, to the nearest strong +/// Goertzel bin: the fixture's beep is 1 kHz, and this walks a coarse ladder +/// of bins around it so the measurement is of *where the energy sits*, not of +/// one bin that could be low for its own reasons. +fn beep_hz(samples: &[f32], at: f64) -> f64 { + // One channel, before anything else: the stream is interleaved stereo, + // and a Goertzel fed a 1 kHz tone woven with its own copy reads a + // carrier, not the tone. + let mono: Vec = samples.chunks(2).map(|f| f[0]).collect(); + let samples = &mono[..]; + // The beep is a tenth of a second at real time and shrinks with the rate, + // so the window is centred on the loudest sample at or after its start + // and is a fifth of a second wide: the beep whole, the silence around it + // mostly out, at every rate the engine can hold. + let stereo = f64::from(RATE); + let from = (at * stereo) as usize; + let peak = samples[from..] + .iter() + .enumerate() + .max_by(|(_, a), (_, b)| a.abs().total_cmp(&b.abs())) + .map(|(i, _)| from + i) + .expect("a sample after the beep starts"); + let half = (stereo * 0.1) as usize; + let window = &samples[peak.saturating_sub(half)..(peak + half).min(samples.len())]; + (700..=1400) + .step_by(25) + .map(|hz| (tone(window, f64::from(hz)), hz)) + .max_by(|(a, _), (b, _)| a.total_cmp(b)) + .expect("a window to measure") + .1 as f64 +} + +/// The pitch itself: a 2x clip plays its beep at 1 kHz, not the octave. The +/// tape effect -- one resample at the speed -- put it there (this ladder's +/// peak reads 1350 Hz on this fixture before the stretch landed, the octave +/// smeared by how short the re-timed beep is); the time-stretch behind the +/// rate conversion keeps every period of the signal its own length, beep +/// included. +#[test] +fn a_2x_clip_keeps_the_beeps_pitch() { + let (mut project, _) = sync_project(); + project + .set_speed(Lane::V1, 0, Speed::from_permille(2000)) + .expect("room for it"); + let played = play(&project); + let at = beep_at(&played); + let hz = beep_hz(&played, at); + assert!( + (hz - 1000.).abs() <= 1000. * 0.02, + "the beep measures {hz} Hz: the tape effect would put it near 2000" + ); +} + +/// The symmetric half: a clip at half speed plays its beep at 1 kHz too, not +/// the sub-octave the tape effect would leave there. +#[test] +fn a_half_speed_clip_keeps_the_beeps_pitch() { + let (mut project, _) = sync_project(); + project + .set_speed(Lane::V1, 0, Speed::from_permille(500)) + .expect("room for it"); + let played = play(&project); + let at = beep_at(&played); + let hz = beep_hz(&played, at); + assert!( + (hz - 1000.).abs() <= 1000. * 0.02, + "the beep measures {hz} Hz: the tape effect would put it near 500" + ); +} + +/// The export's own path, measured the same way: a 2x WAV carries the beep at +/// 1 kHz, so what a file plays is what the preview played -- the stretch sits +/// at the one choke point both of them go through. +#[test] +fn a_wav_export_of_a_2x_clip_keeps_the_beeps_pitch() { + let (mut project, meta) = sync_project(); + project + .set_speed(Lane::V1, 0, Speed::from_permille(2000)) + .expect("room for it"); + let out = out_path("pitch", "wav"); + let handle = engine::export::start( + project, + meta, + &out, + &ExportSettings { + format: Format::Wav, + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(120)).expect("wav export"); + let mut reader = hound::WavReader::open(&out).expect("read the export back"); + let samples: Vec = reader + .samples::() + .map(|s| f32::from(s.expect("a sample")) / f32::from(i16::MAX)) + .collect(); + let at = beep_at(&samples); + let hz = beep_hz(&samples, at); + assert!( + (hz - 1000.).abs() <= 1000. * 0.02, + "the beep in the file measures {hz} Hz, not the 1 kHz it was recorded at" + ); + std::fs::remove_file(&out).ok(); +} + /// The half that honours, and the shape that catches a walk that only works at /// one rate: **2x then 1x on the same lane**. Each span picks its own source /// frames, so the mark inside the fast clip lands at half its source offset and