forge
Explore
Log in

Don't you dare go Hollow

A speeded clip keeps its pitch

Browse files at this commit

475f10cf2bc7d99ab4c3d408f8c9b0cfae102957Ahmet Kaan GümüşParent: 1077f5f
  • feat
    • a speeded clip keeps its pitch
Show full message
✨ feat(engine): a speeded clip keeps its pitch

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.rsmodified+105 -39
@@ -53,6 +53,7 @@ use symphonia_core::units;
53 use symphonia_core::units::{Time, TimeBase};53 use symphonia_core::units::{Time, TimeBase};
54 54
55 use crate::eq::{EqParams, EqState};55 use crate::eq::{EqParams, EqState};
56+use crate::stretch::TimeStretch;
56 use crate::limiter::{Limiter, LimiterState};57 use crate::limiter::{Limiter, LimiterState};
57 58
58 /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.59 /// 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";
85 const PRE_ROLL: u32 = 2;86 const PRE_ROLL: u32 = 2;
86 87
87 /// Frames per channel one AAC-LC packet carries. Fixed by the codec.88 /// Frames per channel one AAC-LC packet carries. Fixed by the codec.
88-const SAMPLES_PER_PACKET: u32 = 1024;89+pub(crate) const SAMPLES_PER_PACKET: u32 = 1024;
89 90
90 /// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the91 /// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the
91 /// 256-sample overlap-add the target frame is reconstructed with.92 /// 256-sample overlap-add the target frame is reconstructed with.
@@ -493,16 +494,23 @@ impl AudioSession {
493 })494 })
494 .collect();495 .collect();
495 496
496- // One resampler per segment that needs one, built where the sample rate497+ // One rate chain per segment that needs one, built where the sample
497- // is known: what the timeline owes it is seconds there and frames here.498+ // rate is known: what the timeline owes it is seconds there and frames
499+ // here.
498 //500 //
499- // Two things ask for one and they compose into a single step: the clip's501+ // Two things ask for one, and they are NOT the same thing: a source
500- // own speed, and a source written at a rate other than the timeline's --502+ // written at a rate other than the timeline's is a *rate conversion*
501- // the ratio of the two rates is exactly a speed, and reading the samples503+ // -- reading the samples at the ratio of the two rates is what keeps
502- // at it is what keeps a 48 kHz file's pitch on a 44.1 kHz timeline. A504+ // a 48 kHz file's pitch on a 44.1 kHz timeline, and is the resampler's
503- // segment with neither has no resampler at all and reaches the mixer505+ // whole duty now. A clip whose own [`Speed`] is not real time is a
504- // with the decoder's own samples, byte for byte, as it always did.506+ // *time* change: the resample hands the stretch a pitch-true stream
505- let speeds: Vec<Option<Resample>> = segments507+ // and the stretch hands the timeline the clip's compressed or
508+ // stretched seconds with every period of the signal kept (the tape
509+ // effect this used to be -- one resample at the speed -- moved the
510+ // pitch with the rate). A segment with neither has no chain at all
511+ // and reaches the mixer with the decoder's own samples, byte for
512+ // byte, as it always did.
513+ let speeds: Vec<Option<Rate>> = segments
506 .iter()514 .iter()
507 .zip(segs)515 .zip(segs)
508 .enumerate()516 .enumerate()
@@ -516,6 +524,7 @@ impl AudioSession {
516 if stretch.is_none() && rate == meta.sample_rate {524 if stretch.is_none() && rate == meta.sample_rate {
517 return None;525 return None;
518 }526 }
527+ let channels = usize::from(meta.channels);
519 // A speeded clip states the timeline it owes; a plain one owes528 // A speeded clip states the timeline it owes; a plain one owes
520 // the window it was placed for, and an open-ended window owes529 // the window it was placed for, and an open-ended window owes
521 // whatever its source has ([`Resample::UNBOUNDED`]).530 // whatever its source has ([`Resample::UNBOUNDED`]).
@@ -527,7 +536,22 @@ impl AudioSession {
527 frames if frames > 0.0 => Resample::UNBOUNDED,536 frames if frames > 0.0 => Resample::UNBOUNDED,
528 _ => 0,537 _ => 0,
529 };538 };
530- Some(Resample::new(stretch.map_or(1.0, |s| s.step) * ratio, owed))539+ Some(match stretch {
540+ // A rate conversion alone: the resampler owns the
541+ // segment's promise, as it always has.
542+ None => Rate {
543+ resample: Resample::new(ratio, owed),
544+ stretch: None,
545+ },
546+ // A speeded clip: the resample is only the rate
547+ // conversion -- unbounded, because the ratio is all it
548+ // is asked for -- and the stretch lands the timeline's
549+ // frames exactly.
550+ Some(s) => Rate {
551+ resample: Resample::new(ratio, Resample::UNBOUNDED),
552+ stretch: Some(TimeStretch::new(s.step, owed, channels)),
553+ },
554+ })
531 })555 })
532 .collect();556 .collect();
533 557
@@ -2585,36 +2609,39 @@ impl Segment {
2585 }2609 }
2586 }2610 }
2587 2611
2588-/// One speeded segment's resampler: the tape effect, done by reading the2612+/// One segment's rate conversion: the decoded samples read at the ratio of
2589-/// decoded samples at a rate other than the one they were written at, so the2613+/// the source's own sample rate to the timeline's, which is a pure rate
2590-/// pitch moves with the speed. Linear interpolation between the two frames a2614+/// conversion -- the pitch is preserved because the frames are read at the
2591-/// fractional position falls between -- one multiply-add per channel, which is2615+/// ratio of the rates rather than dropped, and 48 kHz onto a 44.1 kHz
2592-/// nothing beside the decode that produced them, and enough that a 2x clip is2616+/// timeline is one resampler, not two. Linear interpolation between the two
2593-/// not the aliasing mess plain sample-dropping would give.2617+/// frames a fractional position falls between -- one multiply-add per
2618+/// channel, which is nothing beside the decode that produced them, and for a
2619+/// 48:44.1 ratio its worst-case image lands ~40 dB down; the alternative is
2620+/// a windowed-sinc kernel and a new state machine for a conversion that is
2621+/// not the audible risk in this path.
2594 ///2622 ///
2595 /// It lives across the whole segment: `pos` carries the fraction over a packet2623 /// It lives across the whole segment: `pos` carries the fraction over a packet
2596 /// boundary and `tail` keeps the frame before the buffer, so the interpolation2624 /// boundary and `tail` keeps the frame before the buffer, so the interpolation
2597 /// at the seam is the same one it would have been inside a buffer. A segment2625 /// at the seam is the same one it would have been inside a buffer. A segment
2598-/// starts one clean and drops it at the end, which is what makes a seek a reset2626+/// starts one clean and drops it at the end, which is what makes a seek a
2599-/// for free -- exactly as the equalizer's state does.2627+/// reset for free -- exactly as the equalizer's state does.
2600 ///2628 ///
2601-/// It is also what makes a file written at another sample rate playable at all:2629+/// Time is no longer this struct's business: a clip whose own
2602-/// the step is the clip's speed *times* the source rate over the timeline's, so2630+/// [`Speed`](crate::project::Speed) is not real time is re-timed by the
2603-/// 48 kHz read onto a 44.1 kHz timeline is one resampler, not two, and the pitch2631+/// [`TimeStretch`] behind it in its [`Rate`] chain, which compresses or
2604-/// is preserved because the frames are read at the ratio of the rates rather2632+/// stretches the timeline while keeping every period of the signal its own
2605-/// than dropped. Linear interpolation is what a speed change already uses here2633+/// length -- this hands it a pitch-true stream at the timeline's rate and
2606-/// -- for a 48:44.1 ratio its worst-case image lands ~40 dB down and the2634+/// that is the whole of the hand-off.
2607-/// alternative is a windowed-sinc kernel and a new state machine for a
2608-/// conversion that is not the audible risk in this path.
2609 ///2635 ///
2610 /// `owed` is what the timeline gives the segment, in frames per channel:2636 /// `owed` is what the timeline gives the segment, in frames per channel:
2611 /// resampling resolves to whole samples and a clip's own window resolves to2637 /// resampling resolves to whole samples and a clip's own window resolves to
2612 /// whole *source* frames, so the two miss each other by a sample or two per2638 /// whole *source* frames, so the two miss each other by a sample or two per
2613 /// clip. Truncating and padding to what is owed keeps that from accumulating2639 /// clip. Truncating and padding to what is owed keeps that from accumulating
2614-/// into audible drift over a timeline of speeded cuts -- the picture's clip2640+/// into audible drift over a timeline of rate-mismatched cuts -- the picture's
2615-/// boundaries are exact by construction, and this makes the sound's exact too.2641+/// clip boundaries are exact by construction, and this makes the sound's
2642+/// exact too.
2616 struct Resample {2643 struct Resample {
2617- /// Source frames per output frame: the speed itself.2644+ /// Source frames per output frame: the ratio of the two sample rates.
2618 step: f64,2645 step: f64,
2619 /// Where the next output frame reads, relative to the current buffer's2646 /// Where the next output frame reads, relative to the current buffer's
2620 /// first frame. Negative means it reads across the seam, into `tail`.2647 /// first frame. Negative means it reads across the seam, into `tail`.
@@ -2704,6 +2731,44 @@ impl Resample {
2704 }2731 }
2705 }2732 }
2706 2733
2734+/// One speeded-or-converted segment's whole rate chain: the resample that
2735+/// turns the source's own rate into the timeline's, and -- only for a clip
2736+/// whose [`Speed`](crate::project::Speed) is not real time -- the stretch
2737+/// that changes its *time* without touching its pitch, after the resample
2738+/// and before the equalizer sees a sample (the filter's bands are set in the
2739+/// frequency a listener hears, and after a stretch that is still the
2740+/// frequency the file was written at).
2741+///
2742+/// Which half owns the segment's promise depends on which halves there are:
2743+/// a rate conversion alone is paced by the resample, as it always was, and a
2744+/// speeded clip's resample runs unbounded (the ratio is all it is asked for)
2745+/// while the stretch lands the timeline's frames exactly.
2746+struct Rate {
2747+ resample: Resample,
2748+ stretch: Option<TimeStretch>,
2749+}
2750+
2751+impl Rate {
2752+ fn process(&mut self, buf: &mut Vec<f32>, channels: usize) {
2753+ self.resample.process(buf, channels);
2754+ if let Some(stretch) = self.stretch.as_mut() {
2755+ stretch.process(buf, channels);
2756+ }
2757+ }
2758+
2759+ fn flush(
2760+ &mut self,
2761+ channels: usize,
2762+ timeline: &mut u64,
2763+ tx: &SyncSender<AudioChunk>,
2764+ ) -> bool {
2765+ match self.stretch.as_mut() {
2766+ Some(stretch) => stretch.flush(channels, timeline, tx),
2767+ None => self.resample.flush(channels, timeline, tx),
2768+ }
2769+ }
2770+}
2771+
2707 struct Worker {2772 struct Worker {
2708 /// Indexed by [`Segment::source`]; only the sources some segment names are2773 /// Indexed by [`Segment::source`]; only the sources some segment names are
2709 /// `Some`, the rest were never opened.2774 /// `Some`, the rest were never opened.
@@ -2715,10 +2780,11 @@ struct Worker {
2715 /// Beside the segments rather than inside them so the emit path can hold the2780 /// Beside the segments rather than inside them so the emit path can hold the
2716 /// window rules and the filter memory at once without splitting a borrow.2781 /// window rules and the filter memory at once without splitting a borrow.
2717 eqs: Vec<Option<EqState>>,2782 eqs: Vec<Option<EqState>>,
2718- /// One per entry of `segments` again: the rate that segment is read at, or2783+ /// One per entry of `segments` again: that segment's rate chain, or
2719- /// `None` for one at real time -- which is every segment of a project nobody2784+ /// `None` for one at real time on the timeline's own rate -- which is
2720- /// has speeded, and the path that emits the decoder's own samples untouched.2785+ /// every segment of a project nobody has speeded or rate-mismatched, and
2721- speeds: Vec<Option<Resample>>,2786+ /// the path that emits the decoder's own samples untouched.
2787+ speeds: Vec<Option<Rate>>,
2722 /// `start_sample` of the first chunk.2788 /// `start_sample` of the first chunk.
2723 timeline: u64,2789 timeline: u64,
2724 tx: SyncSender<AudioChunk>,2790 tx: SyncSender<AudioChunk>,
@@ -2981,7 +3047,7 @@ fn run(mut w: Worker) {
2981 /// [`Resample::flush`]). Nothing at all at real time, where a segment owes the3047 /// [`Resample::flush`]). Nothing at all at real time, where a segment owes the
2982 /// timeline only the samples it decoded.3048 /// timeline only the samples it decoded.
2983 fn settle(3049 fn settle(
2984- speed: &mut Option<Resample>,3050+ speed: &mut Option<Rate>,
2985 channels: usize,3051 channels: usize,
2986 timeline: &mut u64,3052 timeline: &mut u64,
2987 tx: &SyncSender<AudioChunk>,3053 tx: &SyncSender<AudioChunk>,
@@ -3013,7 +3079,7 @@ fn emit(
3013 channels: usize,3079 channels: usize,
3014 seg: &Segment,3080 seg: &Segment,
3015 eq: Option<&mut EqState>,3081 eq: Option<&mut EqState>,
3016- speed: Option<&mut Resample>,3082+ speed: Option<&mut Rate>,
3017 pos: u64,3083 pos: u64,
3018 next: u64,3084 next: u64,
3019 timeline: &mut u64,3085 timeline: &mut u64,
@@ -3062,7 +3128,7 @@ fn run_ac3(
3062 track: &mut Ac3Track,3128 track: &mut Ac3Track,
3063 seg: &Segment,3129 seg: &Segment,
3064 mut eq: Option<&mut EqState>,3130 mut eq: Option<&mut EqState>,
3065- speed: &mut Option<Resample>,3131+ speed: &mut Option<Rate>,
3066 channels: usize,3132 channels: usize,
3067 timeline: &mut u64,3133 timeline: &mut u64,
3068 tx: &SyncSender<AudioChunk>,3134 tx: &SyncSender<AudioChunk>,
@@ -3125,7 +3191,7 @@ fn run_mkv_ac3(
3125 track: &mut MkvAc3Track,3191 track: &mut MkvAc3Track,
3126 seg: &Segment,3192 seg: &Segment,
3127 mut eq: Option<&mut EqState>,3193 mut eq: Option<&mut EqState>,
3128- speed: &mut Option<Resample>,3194+ speed: &mut Option<Rate>,
3129 channels: usize,3195 channels: usize,
3130 timeline: &mut u64,3196 timeline: &mut u64,
3131 tx: &SyncSender<AudioChunk>,3197 tx: &SyncSender<AudioChunk>,
@@ -3192,7 +3258,7 @@ fn run_sym(
3192 track: &mut SymTrack,3258 track: &mut SymTrack,
3193 seg: &Segment,3259 seg: &Segment,
3194 mut eq: Option<&mut EqState>,3260 mut eq: Option<&mut EqState>,
3195- speed: &mut Option<Resample>,3261+ speed: &mut Option<Rate>,
3196 channels: usize,3262 channels: usize,
3197 timeline: &mut u64,3263 timeline: &mut u64,
3198 tx: &SyncSender<AudioChunk>,3264 tx: &SyncSender<AudioChunk>,
crates/engine/src/lib.rsmodified+1 -0
@@ -24,6 +24,7 @@ pub mod scale;
24 pub mod scratch;24 pub mod scratch;
25 pub mod silence;25 pub mod silence;
26 pub mod subtitle;26 pub mod subtitle;
27+pub(crate) mod stretch;
27 pub mod tonemap;28 pub mod tonemap;
28 pub mod waveform;29 pub mod waveform;
29 30
crates/engine/src/project.rsmodified+5 -3
@@ -97,9 +97,11 @@ pub const MAX_GAIN_DB: f32 = 12.0;
97 /// number that was set. A thousandth is finer than any card can drag and coarser97 /// number that was set. A thousandth is finer than any card can drag and coarser
98 /// than any rounding anyone can hear.98 /// than any rounding anyone can hear.
99 ///99 ///
100-/// The rate alone: a speeded clip is resampled, so its pitch moves with it (the100+/// The rate alone: the audio path time-stretches a speeded clip
101-/// tape effect). Nothing here preserves pitch and nothing here plays backwards101+/// (`crate::stretch`), so its pitch stays where it was recorded while its
102-/// -- [`Speed::MIN`] is a quarter speed, [`Speed::MAX`] four times.102+/// seconds compress or stretch -- the tape effect this used to be is gone.
103+/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed,
104+/// [`Speed::MAX`] four times.
103 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]105 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
104 pub struct Speed(u16);106 pub struct Speed(u16);
105 107
crates/engine/src/stretch.rsadded+502 -0
@@ -0,0 +1,502 @@
1+//! Time-stretching that keeps the pitch: WSOLA, hand-rolled.
2+//!
3+//! A speeded clip used to be resampled -- the tape effect, its pitch moving
4+//! with its rate. The rate conversion (a source written at another sample
5+//! rate than the timeline's) is still a resample and still is, because
6+//! reading frames at the ratio of two rates is pitch-true by construction.
7+//! What [`crate::project::Speed`] asks for is *time* alone, and that is this
8+//! module's: the waveform is cut into overlapping windows and re-assembled at
9+//! a different hop, each window placed where it best continues the one before
10+//! it (Waveform Similarity Overlap-add, Verhelst & Roelands 1993), so the
11+//! timeline compresses or stretches while every period of the underlying
12+//! signal keeps its own length -- the words, the notes and the beeps stay at
13+//! the frequency they were recorded at.
14+//!
15+//! The one consumer is [`crate::audio`]'s emit path, after the rate
16+//! conversion and before the equalizer, exactly where the resample used to
17+//! sit; see [`TimeStretch`] for the buffering contract it keeps there.
18+
19+/// Analysis window, in frames: long enough that a window holds several
20+/// periods of anything a person calls a pitch (at 48 kHz, 1024 frames is
21+/// 21 ms -- four periods of a 187 Hz tone), short enough that a placement
22+/// mistake cannot smear a consonant.
23+const N: usize = 1024;
24+/// Synthesis hop, in frames: half the window, which is what makes the Hann
25+/// windows of consecutive frames sum to one everywhere -- the overlap-add
26+/// neither adds gain nor leaves a seam.
27+const HS: usize = N / 2;
28+/// How far either side of the nominal position a window may be placed to find
29+/// the best continuation: half a window again, which is the classic WSOLA
30+/// compromise between finding the good overlap and keeping the search cheap
31+/// (it is O(N·SEARCH) per frame, and this keeps it under a million adds).
32+const SEARCH: usize = N / 2;
33+
34+/// One speeded segment's time-stretch: interleaved f32 in, interleaved f32
35+/// out, at the timeline's own sample rate and channel count, paced to the
36+/// frames the timeline promised the segment (`owed` -- the A/V sync
37+/// invariant, which the device and an export both read).
38+///
39+/// WSOLA in one breath: windows of [`N`] frames are overlap-added at
40+/// [`HS`]-frame hops, read from the input at [`Ha`] = `HS · speed`-frame hops.
41+/// Each window after the first is shifted within ±[`SEARCH`] of its nominal
42+/// read position to the offset whose first `HS` frames best match the
43+/// *natural continuation* of the window before it -- the input that followed
44+/// that window's own read position -- measured by normalized cross-correlation
45+/// on the first channel, and the one offset is applied to every channel so a
46+/// stereo pair stays coherent. The output is the input at the timeline's rate
47+/// with its pitch kept: `speed` frames of source per frame of output, to the
48+/// frame.
49+///
50+/// The contract with the emit path is [`Resample`](crate::audio)'s own:
51+/// [`process`](Self::process) rewrites a decoded buffer as whatever output
52+/// frames are ready (an empty one is fine -- the first window only completes
53+/// once `N + SEARCH` frames are buffered, and a caller's buffers are packet
54+/// sized), and [`flush`](Self::flush) pays whatever the input's end left
55+/// owed, in silence, so a segment lands on its promise exactly.
56+pub(crate) struct TimeStretch {
57+ /// Analysis hop: how far the read position advances per synthesized
58+ /// window. `HS · speed`, rounded once here so it never rounds again --
59+ /// the speed itself is spent on this number and nowhere else.
60+ ha: usize,
61+ channels: usize,
62+ /// Output frames the timeline was promised and has not been paid. Paced
63+ /// to exactly, by truncation and by silence, for [`Resample`]'s reason:
64+ /// the picture's clip boundaries are exact, and this keeps the sound's
65+ /// exact with them.
66+ owed: u64,
67+ hann: Vec<f32>,
68+ /// Input not yet consumed, interleaved. `base` is the frame index of its
69+ /// first frame within the segment's whole stream, so the analysis
70+ /// positions below stay absolute -- and survive the buffer compaction
71+ /// that keeps this from growing without bound.
72+ input: Vec<f32>,
73+ base: usize,
74+ /// The nominal read position of the next window, in stream frames. Starts
75+ /// at 0 and advances by `ha`.
76+ anext: usize,
77+ /// The read position the last window actually used, for the natural
78+ /// continuation the next one is matched against. `None` until one window
79+ /// has been placed -- the first has nothing to match and takes its
80+ /// nominal position as-is.
81+ prev: Option<usize>,
82+ /// The overlap-add accumulator: the tail of the last window that the next
83+ /// one completes, interleaved, always `N - HS` frames.
84+ overlap: Vec<f32>,
85+ /// Whether any window has been synthesized -- a segment whose whole
86+ /// source is shorter than a window never primes, and is passed through
87+ /// as the decoder read it, padded to its promise in silence: the honest
88+ /// degenerate, rather than a stretched half-window of nothing.
89+ started: bool,
90+}
91+
92+impl TimeStretch {
93+ /// `speed` is source frames per output frame, as [`crate::project::Stretch`]
94+ /// states it; `owed` is the segment's whole promise in output frames, the
95+ /// same number [`crate::audio::Resample`] paces to when it works alone.
96+ pub(crate) fn new(speed: f64, owed: u64, channels: usize) -> Self {
97+ // The classic Hann, in the half-open form the overlap-add wants: 0 at
98+ // either end, so a window never snaps the seam it is pasting over.
99+ let hann = (0..N)
100+ .map(|i| {
101+ (std::f64::consts::PI * i as f64 / N as f64).sin().powi(2) as f32
102+ })
103+ .collect();
104+ Self {
105+ ha: (HS as f64 * speed).round().max(1.) as usize,
106+ channels,
107+ owed,
108+ hann,
109+ input: Vec::new(),
110+ base: 0,
111+ anext: 0,
112+ prev: None,
113+ overlap: vec![0.; (N - HS) * channels],
114+ started: false,
115+ }
116+ }
117+
118+ /// Frames of input the stretcher holds, stream-indexed -- every question
119+ /// below is asked in stream frames and answered against this.
120+ fn has(&self, frame: usize) -> bool {
121+ frame < self.base + self.input.len() / self.channels
122+ }
123+
124+ /// The first channel's frames `[at, at + HS)` as the correlation target,
125+ /// zero-padded past the input's end -- the flush path reads past what was
126+ /// decoded, and a target of zeros simply stops favouring any offset.
127+ fn natural(&self, at: usize) -> Vec<f32> {
128+ (0..HS)
129+ .map(|i| {
130+ self.has(at + i)
131+ .then(|| {
132+ self.input[((at + i - self.base) * self.channels)..][0]
133+ })
134+ .unwrap_or(0.)
135+ })
136+ .collect()
137+ }
138+
139+ /// Normalized cross-correlation of the first channel at `[at, at + HS)`
140+ /// against `target`: 1 for a perfect match, 0 for nothing in common,
141+ /// amplitude-free so a loud passage does not win on loudness alone.
142+ fn match_at(&self, at: usize, target: &[f32]) -> f32 {
143+ let (mut dot, mut ea, mut eb) = (0f32, 0f32, 0f32);
144+ for i in 0..HS {
145+ let a = self.has(at + i)
146+ .then(|| self.input[((at + i - self.base) * self.channels)..][0])
147+ .unwrap_or(0.);
148+ let b = target[i];
149+ dot += a * b;
150+ ea += a * a;
151+ eb += b * b;
152+ }
153+ dot / (ea.sqrt() * eb.sqrt() + 1e-9)
154+ }
155+
156+ /// Overlap-adds one window read at `at` and hands back the `HS` output
157+ /// frames it completes: the accumulator's head, released, with the
158+ /// window's contribution added to what the last one left behind. The
159+ /// Hann hops at half its width, so the two contributions over any
160+ /// completed frame sum to one and the windowing leaves no trace of
161+ /// itself.
162+ fn place(&mut self, at: usize) -> Vec<f32> {
163+ let mut out = std::mem::take(&mut self.overlap);
164+ out.resize(N * self.channels, 0.);
165+ for i in 0..N {
166+ let w = self.hann[i];
167+ let src = if self.has(at + i) {
168+ &self.input[((at + i - self.base) * self.channels)..][..self.channels]
169+ } else {
170+ &[0., 0.][..self.channels.min(2)]
171+ };
172+ for c in 0..self.channels {
173+ out[i * self.channels + c] += src.get(c).copied().unwrap_or(0.) * w;
174+ }
175+ }
176+ let done = out[..HS * self.channels].to_vec();
177+ self.overlap = out[HS * self.channels..].to_vec();
178+ self.overlap
179+ .resize((N - HS) * self.channels, 0.);
180+ done
181+ }
182+
183+ /// Whether another window can be placed: its whole search range and its
184+ /// whole window must be buffered, and so must the natural continuation
185+ /// the *next* window is matched against -- one look-ahead window of
186+ /// latency, which is what the caller's empty emits ride out.
187+ fn ready(&self) -> bool {
188+ let have = self.base + self.input.len() / self.channels;
189+ self.anext + SEARCH + N + HS <= have
190+ }
191+
192+ /// Rewrites `buf` as the output frames this stretch has ready for it --
193+ /// possibly none (see the struct doc). Consumes the input, compacts what
194+ /// is left, and never returns more than the segment is owed.
195+ pub(crate) fn process(&mut self, buf: &mut Vec<f32>, channels: usize) {
196+ debug_assert_eq!(channels, self.channels, "the layout is fixed at open");
197+ self.input.append(buf);
198+ let mut out: Vec<f32> = Vec::new();
199+ while self.owed > 0 && self.ready() {
200+ let want = self
201+ .anext
202+ .saturating_sub(SEARCH)
203+ .max(self.prev.map_or(0, |p| p + HS - SEARCH));
204+ // The best continuation in the search range: every offset is
205+ let at = match self.prev {
206+ None => self.anext,
207+ Some(p) => {
208+ let target = self.natural(p + HS);
209+ // A silent continuation says nothing about where the next
210+ // window belongs: every offset matches it equally (which
211+ // is to say not at all), and the search would pick one on
212+ // rounding noise. The nominal position is the honest
213+ // answer there -- silence continued is silence, and the
214+ // burst that follows starts where the timeline says.
215+ let loud = target.iter().fold(0f32, |m, x| m + x * x);
216+ if loud < 1e-4 {
217+ self.anext
218+ } else {
219+ // Scored once each and argmax'd after: a comparator
220+ // that re-measured both sides of every comparison is
221+ // a search squared, and this search already is the
222+ // module's cost.
223+ (want..=self.anext + SEARCH)
224+ .map(|at| (self.match_at(at, &target), at))
225+ .max_by(|(a, _), (b, _)| a.total_cmp(b))
226+ .map_or(self.anext, |(_, at)| at)
227+ }
228+ }
229+ };
230+ // Never past the promise: the last window a segment can pay for
231+ // may be a partial one, and the frames it still owes -- not the
232+ // hop a full window would have completed -- are what leaves here.
233+ let frames = self.place(at);
234+ let pays = frames.len().min(self.owed as usize * self.channels);
235+ out.extend_from_slice(&frames[..pays]);
236+ self.owed -= (pays / self.channels) as u64;
237+ self.prev = Some(at);
238+ self.anext += self.ha;
239+ self.started = true;
240+ }
241+ // Consumed input is everything before the next window's search range
242+ // and before the continuation it is matched against -- either may be
243+ // the earlier one.
244+ let keep = self
245+ .anext
246+ .saturating_sub(SEARCH)
247+ .min(self.prev.map_or(usize::MAX, |p| p + HS));
248+ let drop = (keep.saturating_sub(self.base)).min(self.input.len() / self.channels);
249+ self.input.drain(..drop * self.channels);
250+ self.base += drop;
251+ *buf = out;
252+ }
253+
254+ /// The end of the segment: whatever windows the buffered input still
255+ /// completes are placed at their nominal positions -- no search, because
256+ /// the offsets the search would pick from are half padding -- and what
257+ /// the promise still lacks is paid in silence. Pads or truncates to
258+ /// `owed` exactly, for the reason every flush in this path does: the
259+ /// device's seconds are the timeline's seconds, and a segment that lands
260+ /// one frame long is a segment every later segment is one frame late
261+ /// against. `false` means the consumer went away.
262+ pub(crate) fn flush(
263+ &mut self,
264+ channels: usize,
265+ timeline: &mut u64,
266+ tx: &std::sync::mpsc::SyncSender<crate::audio::AudioChunk>,
267+ ) -> bool {
268+ let mut send = |frames: Vec<f32>| -> bool {
269+ if frames.is_empty() {
270+ return true;
271+ }
272+ let chunk = crate::audio::AudioChunk {
273+ start_sample: *timeline,
274+ samples: frames,
275+ };
276+ *timeline += (chunk.samples.len() / channels) as u64;
277+ tx.send(chunk).is_ok()
278+ };
279+ // A segment too short to ever prime: the decoder's own frames, as
280+ // they came -- the honest degenerate -- and the padding below pays
281+ // the rest of the promise.
282+ if !self.started && self.input.len() / self.channels < N + SEARCH {
283+ let mut rest = std::mem::take(&mut self.input);
284+ let owed = (self.owed as usize).min(usize::MAX / channels) * channels;
285+ if rest.len() > owed {
286+ rest.truncate(owed);
287+ }
288+ self.owed -= (rest.len() / channels) as u64;
289+ if !send(rest) {
290+ return false;
291+ }
292+ } else {
293+ // The windows the buffer still completes, placed nominally; the
294+ // zero-padding in `place` finishes the last of them.
295+ while self.owed > 0 && self.anext < self.base + self.input.len() / self.channels + N {
296+ let frames = self.place(self.anext);
297+ self.anext += self.ha;
298+ let pays = (self.owed as usize).min(frames.len() / channels) * channels;
299+ self.owed -= (pays / channels) as u64;
300+ if !send(frames[..pays].to_vec()) {
301+ return false;
302+ }
303+ }
304+ }
305+ // The promise, in silence, to the frame.
306+ while self.owed > 0 {
307+ let frames = (self.owed as usize).min(crate::audio::SAMPLES_PER_PACKET as usize);
308+ if !send(vec![0.; frames * channels]) {
309+ return false;
310+ }
311+ self.owed -= frames as u64;
312+ }
313+ true
314+ }
315+}
316+
317+#[cfg(test)]
318+mod tests {
319+ use super::*;
320+
321+ /// Runs a stretcher over a whole signal the way the emit path does: one
322+ /// packet-shaped buffer at a time, whatever comes out collected, then the
323+ fn stretched(speed: f64, owed: u64, samples: &[f32]) -> Vec<f32> {
324+ let mut s = TimeStretch::new(speed, owed, 1);
325+ let mut out = Vec::new();
326+ for chunk in samples.chunks(1024) {
327+ let mut buf = chunk.to_vec();
328+ s.process(&mut buf, 1);
329+ out.extend_from_slice(&buf);
330+ }
331+ let before = out.len();
332+ // Drained on its own thread, the way the device drains the worker in
333+ // the real path: the channel is four chunks deep, and a flush that
334+ // owes more silence than that would block on a receiver nobody is
335+ // reading yet.
336+ let (tx, rx) = std::sync::mpsc::sync_channel(4);
337+ let drained = std::thread::spawn(move || {
338+ rx.into_iter()
339+ .map(|c: crate::audio::AudioChunk| (c.start_sample, c.samples))
340+ .collect::<Vec<_>>()
341+ });
342+ let mut timeline = 0;
343+ s.flush(1, &mut timeline, &tx);
344+ drop(tx);
345+ let mut paid = 0;
346+ for (_, frames) in drained.join().unwrap() {
347+ paid += frames.len();
348+ out.extend_from_slice(&frames);
349+ }
350+ assert_eq!(
351+ before + paid,
352+ owed as usize,
353+ "the promise is paid to the frame"
354+ );
355+ // The promise is what the two halves paid together: the flush's own
356+ // count is only its tail, and a segment that primed early paid most
357+ // of its way on the process path.
358+ assert_eq!(
359+ before + timeline as usize,
360+ owed as usize,
361+ "the promise is paid to the frame"
362+ );
363+ out
364+ }
365+
366+ /// The amplitude of `hz` inside `samples`, by Goertzel at 48 kHz: the
367+ /// dominant-frequency meter these tests assert pitch with, rather than
368+ /// trusting that a stretch *sounds* unchanged.
369+ fn amplitude(samples: &[f32], hz: f64) -> f64 {
370+ let n = samples.len() as f64;
371+ let w = 2. * std::f64::consts::PI * hz / 48_000.;
372+ let coeff = 2. * w.cos();
373+ let (mut s1, mut s2) = (0., 0.);
374+ for &x in samples {
375+ let s0 = f64::from(x) + coeff * s1 - s2;
376+ s2 = s1;
377+ s1 = s0;
378+ }
379+ 2. * (s1 * s1 + s2 * s2 - coeff * s1 * s2).sqrt() / n
380+ }
381+
382+ /// Two seconds of a 440 Hz sine at 48 kHz, one channel: the plain,
383+ /// pitch-carrying signal every assertion below stretches.
384+ fn sine(hz: f64, secs: f64) -> Vec<f32> {
385+ (0..(secs * 48_000.) as usize)
386+ .map(|i| (2. * std::f64::consts::PI * hz * i as f64 / 48_000.).sin() as f32)
387+ .collect()
388+ }
389+
390+
391+ #[test]
392+ fn a_2x_stretch_halves_the_time_and_keeps_the_pitch() {
393+ let input = sine(440., 2.);
394+ let out = stretched(2.0, 48_000, &input);
395+ // The promise is the timeline's: one second out for two in.
396+ assert_eq!(out.len(), 48_000, "owed exactly");
397+ // Pitch, measured: 440 Hz is the loudest thing in the output by far,
398+ // and the octave the tape effect would have put there (880) is not.
399+ let keep = amplitude(&out, 440.);
400+ let octave = amplitude(&out, 880.);
401+ assert!(keep > 0.4, "440 Hz survives at {keep}");
402+ assert!(octave < keep / 4., "the tape-effect octave is gone: {octave} vs {keep}");
403+ }
404+
405+ #[test]
406+ fn a_half_speed_stretch_doubles_the_time_and_keeps_the_pitch() {
407+ let input = sine(440., 1.);
408+ let out = stretched(0.5, 96_000, &input);
409+ assert_eq!(out.len(), 96_000, "owed exactly");
410+ let keep = amplitude(&out, 440.);
411+ let sub = amplitude(&out, 220.);
412+ assert!(keep > 0.4, "440 Hz survives at {keep}");
413+ assert!(sub < keep / 4., "the tape-effect sub-octave is gone: {sub} vs {keep}");
414+ }
415+
416+ #[test]
417+ fn a_stereo_pair_keeps_its_channels_in_step() {
418+ // Left is the 440 Hz sine, right the same one panned down: a stereo
419+ // pair whose channels differ only in level, which is what a real
420+ // image is made of. The stretch's one search offset for both
421+ // channels is what keeps the pair from smearing, and the two halves
422+ // staying in step -- the cross-correlation of right against left
423+ // peaking at lag zero, both still the tone they went in as -- is what
424+ // says it did.
425+ let left = sine(440., 2.);
426+ let right: Vec<f32> = left.iter().map(|&x| x * 0.7).collect();
427+ let input: Vec<f32> = left
428+ .iter()
429+ .zip(&right)
430+ .flat_map(|(&l, &r)| [l, r])
431+ .collect();
432+ let mut s = TimeStretch::new(2.0, 48_000, 2);
433+ let mut out = Vec::new();
434+ for chunk in input.chunks(2048) {
435+ let mut buf = chunk.to_vec();
436+ s.process(&mut buf, 2);
437+ out.extend_from_slice(&buf);
438+ }
439+ let (tx, rx) = std::sync::mpsc::sync_channel(4);
440+ let drained = std::thread::spawn(move || {
441+ rx.into_iter()
442+ .flat_map(|c: crate::audio::AudioChunk| c.samples)
443+ .collect::<Vec<_>>()
444+ });
445+ let mut timeline = 0;
446+ s.flush(2, &mut timeline, &tx);
447+ drop(tx);
448+ out.extend(drained.join().unwrap());
449+ assert_eq!(out.len(), 96_000);
450+ let l: Vec<f32> = out.chunks(2).map(|f| f[0]).collect();
451+ let r: Vec<f32> = out.chunks(2).map(|f| f[1]).collect();
452+ assert!(amplitude(&l, 440.) > 0.4, "left keeps its tone");
453+ assert!(amplitude(&r, 440.) > 0.25, "right keeps the same one, panned");
454+ // In step: the correlation of right against left is greatest at lag
455+ // zero -- a channel smeared to its own timings peaks somewhere else.
456+ let at = |lag: i32| -> f32 {
457+ let n = l.len() as i32;
458+ let (mut dot, mut ea, mut eb) = (0f32, 0f32, 0f32);
459+ for i in 0..n {
460+ let j = i + lag;
461+ if j < 0 || j >= n {
462+ continue;
463+ }
464+ dot += l[i as usize] * r[j as usize];
465+ ea += l[i as usize] * l[i as usize];
466+ eb += r[j as usize] * r[j as usize];
467+ }
468+ dot / (ea.sqrt() * eb.sqrt() + 1e-9)
469+ };
470+ let zero = at(0);
471+ let worst = (-256..=256)
472+ .filter(|&lag| lag != 0)
473+ .map(at)
474+ .fold(0f32, f32::max);
475+ assert!(
476+ zero > worst,
477+ "the pair is in step: lag 0 at {zero}, best other {worst}"
478+ );
479+ }
480+
481+ #[test]
482+ fn a_segment_shorter_than_a_window_passes_through_honestly() {
483+ // 600 frames is under the prime (N + SEARCH): no window ever
484+ // completes, and the decoder's own frames come out padded to the
485+ // promise in silence -- degenerate, and exactly what it owes.
486+ let input = sine(440., 600. / 48_000.);
487+ let out = stretched(2.0, 400, &input);
488+ assert_eq!(out.len(), 400);
489+ assert_eq!(out[..600.min(400)], input[..600.min(400)], "the frames as they were");
490+ }
491+
492+ #[test]
493+ fn the_promise_is_padded_when_the_source_runs_short() {
494+ // A window's worth of input for two seconds of promise: whatever the
495+ // stretch makes of it, the rest is silence, to the frame.
496+ let input = sine(440., 0.02);
497+ let out = stretched(2.0, 96_000, &input);
498+ assert_eq!(out.len(), 96_000, "owed exactly");
499+ let tail = &out[48_000..];
500+ assert!(tail.iter().all(|&x| x == 0.), "the shortfall is silence");
501+ }
502+}
crates/engine/tests/speed.rsmodified+120 -0
@@ -331,6 +331,126 @@ fn an_mp4_export_resamples_a_speeded_sound_clip() {
331 std::fs::remove_file(&out).ok();331 std::fs::remove_file(&out).ok();
332 }332 }
333 333
334+/// The amplitude of `hz` inside `samples`, by Goertzel at the fixture's rate
335+/// over a fixed window: the pitch meter the pitch tests assert with, rather
336+/// than trusting that a re-timed beep *sounds* unchanged.
337+fn tone(samples: &[f32], hz: f64) -> f64 {
338+ let n = samples.len() as f64;
339+ let w = 2. * std::f64::consts::PI * hz / f64::from(RATE);
340+ let coeff = 2. * w.cos();
341+ let (mut s1, mut s2) = (0., 0.);
342+ for &x in samples {
343+ let s0 = f64::from(x) + coeff * s1 - s2;
344+ s2 = s1;
345+ s1 = s0;
346+ }
347+ 2. * (s1 * s1 + s2 * s2 - coeff * s1 * s2).sqrt() / n
348+}
349+
350+/// The beep's own frequency in the played samples, to the nearest strong
351+/// Goertzel bin: the fixture's beep is 1 kHz, and this walks a coarse ladder
352+/// of bins around it so the measurement is of *where the energy sits*, not of
353+/// one bin that could be low for its own reasons.
354+fn beep_hz(samples: &[f32], at: f64) -> f64 {
355+ // One channel, before anything else: the stream is interleaved stereo,
356+ // and a Goertzel fed a 1 kHz tone woven with its own copy reads a
357+ // carrier, not the tone.
358+ let mono: Vec<f32> = samples.chunks(2).map(|f| f[0]).collect();
359+ let samples = &mono[..];
360+ // The beep is a tenth of a second at real time and shrinks with the rate,
361+ // so the window is centred on the loudest sample at or after its start
362+ // and is a fifth of a second wide: the beep whole, the silence around it
363+ // mostly out, at every rate the engine can hold.
364+ let stereo = f64::from(RATE);
365+ let from = (at * stereo) as usize;
366+ let peak = samples[from..]
367+ .iter()
368+ .enumerate()
369+ .max_by(|(_, a), (_, b)| a.abs().total_cmp(&b.abs()))
370+ .map(|(i, _)| from + i)
371+ .expect("a sample after the beep starts");
372+ let half = (stereo * 0.1) as usize;
373+ let window = &samples[peak.saturating_sub(half)..(peak + half).min(samples.len())];
374+ (700..=1400)
375+ .step_by(25)
376+ .map(|hz| (tone(window, f64::from(hz)), hz))
377+ .max_by(|(a, _), (b, _)| a.total_cmp(b))
378+ .expect("a window to measure")
379+ .1 as f64
380+}
381+
382+/// The pitch itself: a 2x clip plays its beep at 1 kHz, not the octave. The
383+/// tape effect -- one resample at the speed -- put it there (this ladder's
384+/// peak reads 1350 Hz on this fixture before the stretch landed, the octave
385+/// smeared by how short the re-timed beep is); the time-stretch behind the
386+/// rate conversion keeps every period of the signal its own length, beep
387+/// included.
388+#[test]
389+fn a_2x_clip_keeps_the_beeps_pitch() {
390+ let (mut project, _) = sync_project();
391+ project
392+ .set_speed(Lane::V1, 0, Speed::from_permille(2000))
393+ .expect("room for it");
394+ let played = play(&project);
395+ let at = beep_at(&played);
396+ let hz = beep_hz(&played, at);
397+ assert!(
398+ (hz - 1000.).abs() <= 1000. * 0.02,
399+ "the beep measures {hz} Hz: the tape effect would put it near 2000"
400+ );
401+}
402+
403+/// The symmetric half: a clip at half speed plays its beep at 1 kHz too, not
404+/// the sub-octave the tape effect would leave there.
405+#[test]
406+fn a_half_speed_clip_keeps_the_beeps_pitch() {
407+ let (mut project, _) = sync_project();
408+ project
409+ .set_speed(Lane::V1, 0, Speed::from_permille(500))
410+ .expect("room for it");
411+ let played = play(&project);
412+ let at = beep_at(&played);
413+ let hz = beep_hz(&played, at);
414+ assert!(
415+ (hz - 1000.).abs() <= 1000. * 0.02,
416+ "the beep measures {hz} Hz: the tape effect would put it near 500"
417+ );
418+}
419+
420+/// The export's own path, measured the same way: a 2x WAV carries the beep at
421+/// 1 kHz, so what a file plays is what the preview played -- the stretch sits
422+/// at the one choke point both of them go through.
423+#[test]
424+fn a_wav_export_of_a_2x_clip_keeps_the_beeps_pitch() {
425+ let (mut project, meta) = sync_project();
426+ project
427+ .set_speed(Lane::V1, 0, Speed::from_permille(2000))
428+ .expect("room for it");
429+ let out = out_path("pitch", "wav");
430+ let handle = engine::export::start(
431+ project,
432+ meta,
433+ &out,
434+ &ExportSettings {
435+ format: Format::Wav,
436+ ..Default::default()
437+ },
438+ );
439+ wait(&handle, Duration::from_secs(120)).expect("wav export");
440+ let mut reader = hound::WavReader::open(&out).expect("read the export back");
441+ let samples: Vec<f32> = reader
442+ .samples::<i16>()
443+ .map(|s| f32::from(s.expect("a sample")) / f32::from(i16::MAX))
444+ .collect();
445+ let at = beep_at(&samples);
446+ let hz = beep_hz(&samples, at);
447+ assert!(
448+ (hz - 1000.).abs() <= 1000. * 0.02,
449+ "the beep in the file measures {hz} Hz, not the 1 kHz it was recorded at"
450+ );
451+ std::fs::remove_file(&out).ok();
452+}
453+
334 /// The half that honours, and the shape that catches a walk that only works at454 /// The half that honours, and the shape that catches a walk that only works at
335 /// one rate: **2x then 1x on the same lane**. Each span picks its own source455 /// one rate: **2x then 1x on the same lane**. Each span picks its own source
336 /// frames, so the mark inside the fast clip lands at half its source offset and456 /// frames, so the mark inside the fast clip lands at half its source offset and