forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

stretch.rs607 lines, 26.6 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
19use crate::project::SpeedRamp;
20
21/// Analysis window, in frames: long enough that a window holds several
22/// periods of anything a person calls a pitch (at 48 kHz, 1024 frames is
23/// 21 ms -- four periods of a 187 Hz tone), short enough that a placement
24/// mistake cannot smear a consonant.
25const N: usize = 1024;
26/// Synthesis hop, in frames: half the window, which is what makes the Hann
27/// windows of consecutive frames sum to one everywhere -- the overlap-add
28/// neither adds gain nor leaves a seam.
29const HS: usize = N / 2;
30/// How far either side of the nominal position a window may be placed to find
31/// the best continuation: half a window again, which is the classic WSOLA
32/// compromise between finding the good overlap and keeping the search cheap
33/// (it is O(N·SEARCH) per frame, and this keeps it under a million adds).
34const SEARCH: usize = N / 2;
35/// How far past a window's own span a transient may sit and still be pulled in to
36/// the ramp's mapping ([`TimeStretch::locked`]).
37const LOCK_REACH: usize = N / 4;
38/// Frames either side of a transient's peak left out of "the rest of the window".
39const LOCK_SKIP: usize = 128;
40/// How many times the peak's power the rest of the window's mean power must stay
41/// under for the peak to be a transient: amplitude 8 over the surroundings.
42const LOCK_CREST: f32 = 64.;
43
44/// One speeded segment's time-stretch: interleaved f32 in, interleaved f32
45/// out, at the timeline's own sample rate and channel count, paced to the
46/// frames the timeline promised the segment (`owed` -- the A/V sync
47/// invariant, which the device and an export both read).
48///
49/// WSOLA in one breath: windows of [`N`] frames are overlap-added at
50/// [`HS`]-frame hops, read from the input at [`Ha`] = `HS · speed`-frame hops.
51/// Each window after the first is shifted within ±[`SEARCH`] of its nominal
52/// read position to the offset whose first `HS` frames best match the
53/// *natural continuation* of the window before it -- the input that followed
54/// that window's own read position -- measured by normalized cross-correlation
55/// on the first channel, and the one offset is applied to every channel so a
56/// stereo pair stays coherent. The output is the input at the timeline's rate
57/// with its pitch kept: `speed` frames of source per frame of output, to the
58/// frame.
59///
60/// The contract with the emit path is [`Resample`](crate::audio)'s own:
61/// [`process`](Self::process) rewrites a decoded buffer as whatever output
62/// frames are ready (an empty one is fine -- the first window only completes
63/// once `N + SEARCH` frames are buffered, and a caller's buffers are packet
64/// sized), and [`flush`](Self::flush) pays whatever the input's end left
65/// owed, in silence, so a segment lands on its promise exactly.
66pub(crate) struct TimeStretch {
67 /// Analysis hop: how far the read position advances per synthesized
68 /// window. `HS · speed`, rounded once here so it never rounds again --
69 /// the speed itself is spent on this number and nowhere else.
70 ha: usize,
71 channels: usize,
72 /// Output frames the timeline was promised and has not been paid. Paced
73 /// to exactly, by truncation and by silence, for [`Resample`]'s reason:
74 /// the picture's clip boundaries are exact, and this keeps the sound's
75 /// exact with them.
76 owed: u64,
77 hann: Vec<f32>,
78 /// Input not yet consumed, interleaved. `base` is the frame index of its
79 /// first frame within the segment's whole stream, so the analysis
80 /// positions below stay absolute -- and survive the buffer compaction
81 /// that keeps this from growing without bound.
82 input: Vec<f32>,
83 base: usize,
84 /// The nominal read position of the next window, in stream frames. Starts
85 /// at 0 and advances by `ha`.
86 anext: usize,
87 /// The read position the last window actually used, for the natural
88 /// continuation the next one is matched against. `None` until one window
89 /// has been placed -- the first has nothing to match and takes its
90 /// nominal position as-is.
91 prev: Option<usize>,
92 /// The overlap-add accumulator: the tail of the last window that the next
93 /// one completes, interleaved, always `N - HS` frames.
94 overlap: Vec<f32>,
95 /// Whether any window has been synthesized -- a segment whose whole
96 /// source is shorter than a window never primes, and is passed through
97 /// as the decoder read it, padded to its promise in silence: the honest
98 /// degenerate, rather than a stretched half-window of nothing.
99 started: bool,
100 /// A speed ramp to follow, with the samples one timeline frame is: the read
101 /// position of every window then comes off the ramp's integral instead of a
102 /// fixed hop. `None` is a constant `speed`.
103 ramp: Option<(SpeedRamp, f64)>,
104 /// Windows placed so far -- the output position of the next one is `window * HS`.
105 window: usize,
106}
107
108impl TimeStretch {
109 /// `speed` is source frames per output frame, as [`crate::project::Stretch`]
110 /// states it; `owed` is the segment's whole promise in output frames, the
111 /// same number [`crate::audio::Resample`] paces to when it works alone.
112 ///
113 /// `ramp` makes the read position follow a speed ramp ([`SpeedRamp`], and the
114 /// samples per timeline frame): `speed` is then only the mean, kept for the
115 /// hop that is unused. The pitch holds as at a constant speed, because only the
116 /// windows' read positions move -- each is still copied whole.
117 pub(crate) fn new(
118 speed: f64,
119 owed: u64,
120 channels: usize,
121 ramp: Option<(SpeedRamp, f64)>,
122 ) -> Self {
123 // The classic Hann, in the half-open form the overlap-add wants: 0 at
124 // either end, so a window never snaps the seam it is pasting over.
125 let hann = (0..N)
126 .map(|i| {
127 (std::f64::consts::PI * i as f64 / N as f64).sin().powi(2) as f32
128 })
129 .collect();
130 let mut t = Self {
131 ha: (HS as f64 * speed).round().max(1.) as usize,
132 channels,
133 owed,
134 hann,
135 input: Vec::new(),
136 base: 0,
137 anext: 0,
138 prev: None,
139 overlap: vec![0.; (N - HS) * channels],
140 started: false,
141 ramp,
142 window: 0,
143 };
144 t.anext = t.nominal();
145 t
146 }
147
148 /// The nominal read position of the window about to be placed. A constant
149 /// speed advances by `ha` from 0; a ramp reads each window where the ramp has
150 /// carried the source by the middle of its output span, less half a window --
151 /// so the sound at an output instant is the source the ramp names for it, not
152 /// a window late.
153 fn nominal(&self) -> usize {
154 match &self.ramp {
155 None => self.window * self.ha,
156 Some((ramp, spf)) => {
157 let mid = (self.window * HS + N / 2) as f64 / spf;
158 (ramp.source_frames(mid) * spf - (N / 2) as f64).round().max(0.0) as usize
159 }
160 }
161 }
162
163 /// Where to read the window about to be placed so that a sharp transient in
164 /// reach lands on the ramp's mapping, when there is one; `None` for the usual
165 /// search (and always at a constant speed).
166 ///
167 /// A window copies its input at real time, so a click inside it lands off the
168 /// mapping by its distance from the window's centre times how far the ramp's
169 /// rate is from 1 -- milliseconds at 2x -- and two overlapping windows that
170 /// both hold it would put it down twice, at two such offsets. A transient has
171 /// no pitch to keep in phase, so every window that holds one is read so that
172 /// its loudest sample lands exactly where the ramp says it plays: the copies
173 /// then coincide, and the click is neither late nor doubled. "A transient" is a
174 /// peak that stands [`LOCK_CREST`] times over the rest of the window in power.
175 fn locked(&self) -> Option<usize> {
176 let (ramp, spf) = self.ramp.as_ref()?;
177 let at = |i: usize| -> f32 {
178 if self.has(i) && i >= self.base {
179 self.input[(i - self.base) * self.channels].abs()
180 } else {
181 0.
182 }
183 };
184 let lo = self.anext.saturating_sub(LOCK_REACH);
185 let hi = self.anext + N + LOCK_REACH;
186 let (mut m, mut peak) = (lo, 0f32);
187 for i in lo..hi {
188 if at(i) > peak {
189 (m, peak) = (i, at(i));
190 }
191 }
192 if peak < 0.05 {
193 return None;
194 }
195 let rest: f32 = (self.anext..self.anext + N)
196 .filter(|i| i.abs_diff(m) > LOCK_SKIP)
197 .map(|i| at(i).powi(2))
198 .sum::<f32>()
199 / N as f32;
200 if peak * peak < LOCK_CREST * rest {
201 return None;
202 }
203 let there = (ramp.timeline_frames(m as f64 / spf) * spf).round() as i64;
204 let u = there - (self.window * HS) as i64;
205 if !(16..N as i64 - 16).contains(&u) {
206 return None;
207 }
208 let read = m as i64 - u;
209 let shift = (read - self.anext as i64).unsigned_abs() as usize;
210 (read >= self.base as i64 && shift <= N / 2).then_some(read as usize)
211 }
212
213 /// Moves to the next window.
214 fn advance(&mut self) {
215 self.window += 1;
216 self.anext = self.nominal();
217 }
218
219 /// Frames of input the stretcher holds, stream-indexed -- every question
220 /// below is asked in stream frames and answered against this.
221 fn has(&self, frame: usize) -> bool {
222 frame < self.base + self.input.len() / self.channels
223 }
224
225 /// The first channel's frames `[at, at + HS)` as the correlation target,
226 /// zero-padded past the input's end -- the flush path reads past what was
227 /// decoded, and a target of zeros simply stops favouring any offset.
228 fn natural(&self, at: usize) -> Vec<f32> {
229 (0..HS)
230 .map(|i| {
231 if self.has(at + i) {
232 self.input[((at + i - self.base) * self.channels)..][0]
233 } else {
234 0.
235 }
236 })
237 .collect()
238 }
239
240 /// Normalized cross-correlation of the first channel at `[at, at + HS)`
241 /// against `target`: 1 for a perfect match, 0 for nothing in common,
242 /// amplitude-free so a loud passage does not win on loudness alone.
243 fn match_at(&self, at: usize, target: &[f32]) -> f32 {
244 let (mut dot, mut ea, mut eb) = (0f32, 0f32, 0f32);
245 for (i, &b) in target[..HS].iter().enumerate() {
246 let a = if self.has(at + i) {
247 self.input[((at + i - self.base) * self.channels)..][0]
248 } else {
249 0.
250 };
251 dot += a * b;
252 ea += a * a;
253 eb += b * b;
254 }
255 dot / (ea.sqrt() * eb.sqrt() + 1e-9)
256 }
257
258 /// Overlap-adds one window read at `at` and hands back the `HS` output
259 /// frames it completes: the accumulator's head, released, with the
260 /// window's contribution added to what the last one left behind. The
261 /// Hann hops at half its width, so the two contributions over any
262 /// completed frame sum to one and the windowing leaves no trace of
263 /// itself.
264 fn place(&mut self, at: usize) -> Vec<f32> {
265 let mut out = std::mem::take(&mut self.overlap);
266 out.resize(N * self.channels, 0.);
267 for i in 0..N {
268 let w = self.hann[i];
269 let src = if self.has(at + i) {
270 &self.input[((at + i - self.base) * self.channels)..][..self.channels]
271 } else {
272 &[0., 0.][..self.channels.min(2)]
273 };
274 for c in 0..self.channels {
275 out[i * self.channels + c] += src.get(c).copied().unwrap_or(0.) * w;
276 }
277 }
278 let done = out[..HS * self.channels].to_vec();
279 self.overlap = out[HS * self.channels..].to_vec();
280 self.overlap
281 .resize((N - HS) * self.channels, 0.);
282 done
283 }
284
285 /// Whether another window can be placed: its whole search range and its
286 /// whole window must be buffered, and so must the natural continuation
287 /// the *next* window is matched against -- one look-ahead window of
288 /// latency, which is what the caller's empty emits ride out.
289 fn ready(&self) -> bool {
290 let have = self.base + self.input.len() / self.channels;
291 self.anext + SEARCH + N + HS <= have
292 }
293
294 /// Rewrites `buf` as the output frames this stretch has ready for it --
295 /// possibly none (see the struct doc). Consumes the input, compacts what
296 /// is left, and never returns more than the segment is owed.
297 pub(crate) fn process(&mut self, buf: &mut Vec<f32>, channels: usize) {
298 debug_assert_eq!(channels, self.channels, "the layout is fixed at open");
299 self.input.append(buf);
300 let mut out: Vec<f32> = Vec::new();
301 while self.owed > 0 && self.ready() {
302 let reach = SEARCH;
303 let want = self
304 .anext
305 .saturating_sub(reach)
306 .max(self.prev.map_or(0, |p| p + HS - SEARCH));
307 // The best continuation in the search range: every offset is
308 let at = match (self.locked(), self.prev) {
309 (Some(at), _) => at,
310 (None, None) => self.anext,
311 (None, Some(p)) => {
312 let target = self.natural(p + HS);
313 // A silent continuation says nothing about where the next
314 // window belongs: every offset matches it equally (which
315 // is to say not at all), and the search would pick one on
316 // rounding noise. The nominal position is the honest
317 // answer there -- silence continued is silence, and the
318 // burst that follows starts where the timeline says.
319 let loud = target.iter().fold(0f32, |m, x| m + x * x);
320 if loud < 1e-4 {
321 self.anext
322 } else {
323 // Scored once each and argmax'd after: a comparator
324 // that re-measured both sides of every comparison is
325 // a search squared, and this search already is the
326 // module's cost.
327 (want..=self.anext + reach)
328 .map(|at| (self.match_at(at, &target), at))
329 .max_by(|(a, _), (b, _)| a.total_cmp(b))
330 .map_or(self.anext, |(_, at)| at)
331 }
332 }
333 };
334 // Never past the promise: the last window a segment can pay for
335 // may be a partial one, and the frames it still owes -- not the
336 // hop a full window would have completed -- are what leaves here.
337 let frames = self.place(at);
338 let pays = frames.len().min(self.owed as usize * self.channels);
339 out.extend_from_slice(&frames[..pays]);
340 self.owed -= (pays / self.channels) as u64;
341 self.prev = Some(at);
342 self.advance();
343 self.started = true;
344 }
345 // Consumed input is everything before the next window's search range
346 // and before the continuation it is matched against -- either may be
347 // the earlier one.
348 let keep = self
349 .anext
350 .saturating_sub(SEARCH)
351 .min(self.prev.map_or(usize::MAX, |p| p + HS));
352 let drop = (keep.saturating_sub(self.base)).min(self.input.len() / self.channels);
353 self.input.drain(..drop * self.channels);
354 self.base += drop;
355 *buf = out;
356 }
357
358 /// The end of the segment: whatever windows the buffered input still
359 /// completes are placed at their nominal positions -- no search, because
360 /// the offsets the search would pick from are half padding -- and what
361 /// the promise still lacks is paid in silence. Pads or truncates to
362 /// `owed` exactly, for the reason every flush in this path does: the
363 /// device's seconds are the timeline's seconds, and a segment that lands
364 /// one frame long is a segment every later segment is one frame late
365 /// against. `false` means the consumer went away.
366 pub(crate) fn flush(
367 &mut self,
368 channels: usize,
369 timeline: &mut u64,
370 tx: &std::sync::mpsc::SyncSender<crate::audio::AudioChunk>,
371 ) -> bool {
372 let mut send = |frames: Vec<f32>| -> bool {
373 if frames.is_empty() {
374 return true;
375 }
376 let chunk = crate::audio::AudioChunk {
377 start_sample: *timeline,
378 samples: frames,
379 };
380 *timeline += (chunk.samples.len() / channels) as u64;
381 tx.send(chunk).is_ok()
382 };
383 // A segment too short to ever prime: the decoder's own frames, as
384 // they came -- the honest degenerate -- and the padding below pays
385 // the rest of the promise.
386 if !self.started && self.input.len() / self.channels < N + SEARCH {
387 let mut rest = std::mem::take(&mut self.input);
388 let owed = (self.owed as usize).min(usize::MAX / channels) * channels;
389 if rest.len() > owed {
390 rest.truncate(owed);
391 }
392 self.owed -= (rest.len() / channels) as u64;
393 if !send(rest) {
394 return false;
395 }
396 } else {
397 // The windows the buffer still completes, placed nominally; the
398 // zero-padding in `place` finishes the last of them.
399 while self.owed > 0 && self.anext < self.base + self.input.len() / self.channels + N {
400 let at = self.locked().unwrap_or(self.anext);
401 let frames = self.place(at);
402 self.advance();
403 let pays = (self.owed as usize).min(frames.len() / channels) * channels;
404 self.owed -= (pays / channels) as u64;
405 if !send(frames[..pays].to_vec()) {
406 return false;
407 }
408 }
409 }
410 // The promise, in silence, to the frame.
411 while self.owed > 0 {
412 let frames = (self.owed as usize).min(crate::audio::SAMPLES_PER_PACKET as usize);
413 if !send(vec![0.; frames * channels]) {
414 return false;
415 }
416 self.owed -= frames as u64;
417 }
418 true
419 }
420}
421
422#[cfg(test)]
423mod tests {
424 use super::*;
425
426 /// Runs a stretcher over a whole signal the way the emit path does: one
427 /// packet-shaped buffer at a time, whatever comes out collected, then the
428 fn stretched(speed: f64, owed: u64, samples: &[f32]) -> Vec<f32> {
429 let mut s = TimeStretch::new(speed, owed, 1, None);
430 let mut out = Vec::new();
431 for chunk in samples.chunks(1024) {
432 let mut buf = chunk.to_vec();
433 s.process(&mut buf, 1);
434 out.extend_from_slice(&buf);
435 }
436 let before = out.len();
437 // Drained on its own thread, the way the device drains the worker in
438 // the real path: the channel is four chunks deep, and a flush that
439 // owes more silence than that would block on a receiver nobody is
440 // reading yet.
441 let (tx, rx) = std::sync::mpsc::sync_channel(4);
442 let drained = std::thread::spawn(move || {
443 rx.into_iter()
444 .map(|c: crate::audio::AudioChunk| (c.start_sample, c.samples))
445 .collect::<Vec<_>>()
446 });
447 let mut timeline = 0;
448 s.flush(1, &mut timeline, &tx);
449 drop(tx);
450 let mut paid = 0;
451 for (_, frames) in drained.join().unwrap() {
452 paid += frames.len();
453 out.extend_from_slice(&frames);
454 }
455 assert_eq!(
456 before + paid,
457 owed as usize,
458 "the promise is paid to the frame"
459 );
460 // The promise is what the two halves paid together: the flush's own
461 // count is only its tail, and a segment that primed early paid most
462 // of its way on the process path.
463 assert_eq!(
464 before + timeline as usize,
465 owed as usize,
466 "the promise is paid to the frame"
467 );
468 out
469 }
470
471 /// The amplitude of `hz` inside `samples`, by Goertzel at 48 kHz: the
472 /// dominant-frequency meter these tests assert pitch with, rather than
473 /// trusting that a stretch *sounds* unchanged.
474 fn amplitude(samples: &[f32], hz: f64) -> f64 {
475 let n = samples.len() as f64;
476 let w = 2. * std::f64::consts::PI * hz / 48_000.;
477 let coeff = 2. * w.cos();
478 let (mut s1, mut s2) = (0., 0.);
479 for &x in samples {
480 let s0 = f64::from(x) + coeff * s1 - s2;
481 s2 = s1;
482 s1 = s0;
483 }
484 2. * (s1 * s1 + s2 * s2 - coeff * s1 * s2).sqrt() / n
485 }
486
487 /// Two seconds of a 440 Hz sine at 48 kHz, one channel: the plain,
488 /// pitch-carrying signal every assertion below stretches.
489 fn sine(hz: f64, secs: f64) -> Vec<f32> {
490 (0..(secs * 48_000.) as usize)
491 .map(|i| (2. * std::f64::consts::PI * hz * i as f64 / 48_000.).sin() as f32)
492 .collect()
493 }
494
495
496 #[test]
497 fn a_2x_stretch_halves_the_time_and_keeps_the_pitch() {
498 let input = sine(440., 2.);
499 let out = stretched(2.0, 48_000, &input);
500 // The promise is the timeline's: one second out for two in.
501 assert_eq!(out.len(), 48_000, "owed exactly");
502 // Pitch, measured: 440 Hz is the loudest thing in the output by far,
503 // and the octave the tape effect would have put there (880) is not.
504 let keep = amplitude(&out, 440.);
505 let octave = amplitude(&out, 880.);
506 assert!(keep > 0.4, "440 Hz survives at {keep}");
507 assert!(octave < keep / 4., "the tape-effect octave is gone: {octave} vs {keep}");
508 }
509
510 #[test]
511 fn a_half_speed_stretch_doubles_the_time_and_keeps_the_pitch() {
512 let input = sine(440., 1.);
513 let out = stretched(0.5, 96_000, &input);
514 assert_eq!(out.len(), 96_000, "owed exactly");
515 let keep = amplitude(&out, 440.);
516 let sub = amplitude(&out, 220.);
517 assert!(keep > 0.4, "440 Hz survives at {keep}");
518 assert!(sub < keep / 4., "the tape-effect sub-octave is gone: {sub} vs {keep}");
519 }
520
521 #[test]
522 fn a_stereo_pair_keeps_its_channels_in_step() {
523 // Left is the 440 Hz sine, right the same one panned down: a stereo
524 // pair whose channels differ only in level, which is what a real
525 // image is made of. The stretch's one search offset for both
526 // channels is what keeps the pair from smearing, and the two halves
527 // staying in step -- the cross-correlation of right against left
528 // peaking at lag zero, both still the tone they went in as -- is what
529 // says it did.
530 let left = sine(440., 2.);
531 let right: Vec<f32> = left.iter().map(|&x| x * 0.7).collect();
532 let input: Vec<f32> = left
533 .iter()
534 .zip(&right)
535 .flat_map(|(&l, &r)| [l, r])
536 .collect();
537 let mut s = TimeStretch::new(2.0, 48_000, 2, None);
538 let mut out = Vec::new();
539 for chunk in input.chunks(2048) {
540 let mut buf = chunk.to_vec();
541 s.process(&mut buf, 2);
542 out.extend_from_slice(&buf);
543 }
544 let (tx, rx) = std::sync::mpsc::sync_channel(4);
545 let drained = std::thread::spawn(move || {
546 rx.into_iter()
547 .flat_map(|c: crate::audio::AudioChunk| c.samples)
548 .collect::<Vec<_>>()
549 });
550 let mut timeline = 0;
551 s.flush(2, &mut timeline, &tx);
552 drop(tx);
553 out.extend(drained.join().unwrap());
554 assert_eq!(out.len(), 96_000);
555 let l: Vec<f32> = out.chunks(2).map(|f| f[0]).collect();
556 let r: Vec<f32> = out.chunks(2).map(|f| f[1]).collect();
557 assert!(amplitude(&l, 440.) > 0.4, "left keeps its tone");
558 assert!(amplitude(&r, 440.) > 0.25, "right keeps the same one, panned");
559 // In step: the correlation of right against left is greatest at lag
560 // zero -- a channel smeared to its own timings peaks somewhere else.
561 let at = |lag: i32| -> f32 {
562 let n = l.len() as i32;
563 let (mut dot, mut ea, mut eb) = (0f32, 0f32, 0f32);
564 for i in 0..n {
565 let j = i + lag;
566 if j < 0 || j >= n {
567 continue;
568 }
569 dot += l[i as usize] * r[j as usize];
570 ea += l[i as usize] * l[i as usize];
571 eb += r[j as usize] * r[j as usize];
572 }
573 dot / (ea.sqrt() * eb.sqrt() + 1e-9)
574 };
575 let zero = at(0);
576 let worst = (-256..=256)
577 .filter(|&lag| lag != 0)
578 .map(at)
579 .fold(0f32, f32::max);
580 assert!(
581 zero > worst,
582 "the pair is in step: lag 0 at {zero}, best other {worst}"
583 );
584 }
585
586 #[test]
587 fn a_segment_shorter_than_a_window_passes_through_honestly() {
588 // 600 frames is under the prime (N + SEARCH): no window ever
589 // completes, and the decoder's own frames come out padded to the
590 // promise in silence -- degenerate, and exactly what it owes.
591 let input = sine(440., 600. / 48_000.);
592 let out = stretched(2.0, 400, &input);
593 assert_eq!(out.len(), 400);
594 assert_eq!(out[..400], input[..400], "the frames as they were");
595 }
596
597 #[test]
598 fn the_promise_is_padded_when_the_source_runs_short() {
599 // A window's worth of input for two seconds of promise: whatever the
600 // stretch makes of it, the rest is silence, to the frame.
601 let input = sine(440., 0.02);
602 let out = stretched(2.0, 96_000, &input);
603 assert_eq!(out.len(), 96_000, "owed exactly");
604 let tail = &out[48_000..];
605 assert!(tail.iter().all(|&x| x == 0.), "the shortfall is silence");
606 }
607}