forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

stretch.rs502 lines, 22.3 KiBHistoryRawDownload
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.
23const 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.
27const 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).
32const 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.
56pub(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
92impl 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)]
318mod 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}