forge
Explore
Log in

Don't you dare go Hollow

A window starts at the bucket the decode was asked for

Browse files at this commit

e5f0b93fb5f51f51e17ec8ec8800c1ea6c989408Ahmet Kaan GümüşParent: 7cb30bf
  • fix
    • a window starts at the bucket the decode was asked for
Show full message
🐛 fix(engine): a window starts at the bucket the decode was asked for

RW1, and it is the real one: `viz_window` opens the file at the bucket it is
handed, `fold_window` indexes the slice from there, so `peaks[0]` *is* absolute
bucket `first`. `view_at` labelled it `first - seek` and served the margin --
so every `view.at(abs)` of a windowed frame read the envelope's bucket
`abs + 12000`: +3 s at 4000 buckets a second, the file's tail painted silence
(slice exhausted), and a preview frame at a window grid line was not the frame
export paints from the whole envelope. The fix is the label: ask from
`first.saturating_sub(seek)` and serve what comes back, which is what the margin
was always for.

Two of my own fixtures could not see it, and that is the lesson worth writing
down: a five-second clip's first window starts at bucket 0 (where the label is a
no-op) and the 40-minute FLAC was a 440 Hz sine at 8 kHz, whose 3 s shift is
1320 whole periods -- every bucket identical. The new test is *noise* in FLAC:
buckets must be *equal*, not merely close, at the file's head, its middle, both
sides of a 30 s grid line and its last window, and the frame at each has to be
the frame `visualizer_i420` paints for the same time. FAIL-BEFORE, this tree:
`t=30.5: 8002 of 8002 windowed buckets are not the envelope's, 0 out of reach`;
PASS-AFTER: 18 waveform tests green.

RW3: the summary pass folded the ask's whole-file probe and then re-decoded the
same sound in the windows it spawned -- 1.875x a file at the eight-window
ceiling, serial, on the first look edit's critical path. The first window now
stops at the joint the next was told to start at, exactly as the envelope's own
split stops it, so the windows partition the file and a pass reads it once.
FAIL-BEFORE: `folded 1440000 frames of a 960000-frame file, 1.50x over`;
PASS-AFTER: the same test asserts within 5% of 1.00x, and the peak/length
equalities against the whole envelope still hold (`viz_summary`'s stop samples
now mirror `peaks_over`'s, so it folds the same sample set).

RW5: `VizView` carries `per_sec`, the rate its envelope was drawn at, and the
painter reads it instead of hard-coding `VIZ_BUCKETS_PER_SEC` -- the invariant is
structural now (an ask at another rate is painted at that rate) rather than
accidental. `VizView::whole` is the one place the visualizer's rate is named.

RW4b: the seat now declares the canvas masked to even dimensions and floored at
two, which is what the painter returns -- an odd `resolution 1921 1081` line used
to declare a size the planes never had. Kept as an invariant, *not* claimed as a
reproduced fix: the witness (canvases 1920x1, 1921x1081, 320x1, 321x181 through
`PlaybackSession::set_resolution` + `try_frame`) passes with the mask reverted as
well, so I could not reproduce the panic on this tree and say so in the test's
own doc. RW4a is refuted: the even-dimension mask lives in the shared painting
body (`visualizer_window_i420`, decode.rs:2199-2200), which both entry points go
through; `visualizer_i420` is a one-line wrapper over it.

Also honest-doc fixes from the same review: RW2's notice doc no longer implies a
front-end shows a mid-session death (it is fetchable through
`audio_disabled_reason`, which the app reads where a notice is *built*); and a
failed window's comment now matches the code (the seat latches it, the memo does
not).
crates/engine/src/decode.rsmodified+24 -4
@@ -650,7 +650,16 @@ impl DecodeSession {
650 // Painted at the canvas's own size, so the composite places nothing:650 // Painted at the canvas's own size, so the composite places nothing:
651 // the picture *is* the canvas, and whatever transform the clip651 // the picture *is* the canvas, and whatever transform the clip
652 // carries still reaches it through the render below.652 // carries still reaches it through the render below.
653- let (width, height) = canvas.dims();653+ //
654+ // Masked to even dimensions first, and floored at two: that is what the
655+ // painter does to the planes it hands back, so a canvas it cannot divide
656+ // evenly (an odd `resolution 1921 1081` line, or a one-pixel-high one)
657+ // used to be *declared* at a size the picture never had -- and the
658+ // conversion below then indexes a chroma plane that is not there
659+ // (`index out of bounds` on a zero-length slice, in this worker, where
660+ // no frame ever arrives and nothing catches it).
661+ let (canvas_w, canvas_h) = canvas.dims();
662+ let (width, height) = ((canvas_w & !1).max(2), (canvas_h & !1).max(2));
654 let worker_cancel = Arc::clone(&cancel);663 let worker_cancel = Arc::clone(&cancel);
655 let path = path.to_path_buf();664 let path = path.to_path_buf();
656 let handle = thread::Builder::new()665 let handle = thread::Builder::new()
@@ -2137,11 +2146,18 @@ pub(crate) fn visualizer_i420(
2137 /// measured it against itself would draw the file's end wherever the window2146 /// measured it against itself would draw the file's end wherever the window
2138 /// ended -- and `peak` is the file's loudest bucket, which every column is2147 /// ended -- and `peak` is the file's loudest bucket, which every column is
2139 /// scaled by: no window can derive that from itself.2148 /// scaled by: no window can derive that from itself.
2149+///
2150+/// `per_sec` is the rate *this* envelope was drawn at, in buckets per second,
2151+/// and it is carried rather than assumed: the slice is indexed at it, so an
2152+/// envelope drawn at another rate under a painter that hard-coded the
2153+/// visualizer's own would read a tenth of a second of sound as a second. The
2154+/// whole-file constructor is the one place the visualizer's rate is named.
2140 pub(crate) struct VizView<'a> {2155 pub(crate) struct VizView<'a> {
2141 pub(crate) peaks: &'a [(f32, f32)],2156 pub(crate) peaks: &'a [(f32, f32)],
2142 pub(crate) first: usize,2157 pub(crate) first: usize,
2143 pub(crate) total: usize,2158 pub(crate) total: usize,
2144 pub(crate) peak: f32,2159 pub(crate) peak: f32,
2160+ pub(crate) per_sec: f64,
2145 }2161 }
2146 2162
2147 impl<'a> VizView<'a> {2163 impl<'a> VizView<'a> {
@@ -2152,22 +2168,26 @@ impl<'a> VizView<'a> {
2152 first: 0,2168 first: 0,
2153 total: peaks.len(),2169 total: peaks.len(),
2154 peak: crate::waveform::peak_of(peaks),2170 peak: crate::waveform::peak_of(peaks),
2171+ per_sec: f64::from(VIZ_BUCKETS_PER_SEC),
2155 }2172 }
2156 }2173 }
2157 2174
2158 /// One window of an envelope: `peaks` starts at absolute bucket `first`,2175 /// One window of an envelope: `peaks` starts at absolute bucket `first`,
2159- /// `total` and `peak` are the whole file's.2176+ /// `total` and `peak` are the whole file's, and `per_sec` is the rate the
2177+ /// file's envelope was drawn at.
2160 pub(crate) fn window(2178 pub(crate) fn window(
2161 peaks: &'a [(f32, f32)],2179 peaks: &'a [(f32, f32)],
2162 first: usize,2180 first: usize,
2163 total: usize,2181 total: usize,
2164 peak: f32,2182 peak: f32,
2183+ per_sec: f64,
2165 ) -> Self {2184 ) -> Self {
2166 Self {2185 Self {
2167 peaks,2186 peaks,
2168 first,2187 first,
2169 total,2188 total,
2170 peak,2189 peak,
2190+ per_sec,
2171 }2191 }
2172 }2192 }
2173 2193
@@ -2223,8 +2243,8 @@ pub(crate) fn visualizer_window_i420(
2223 scratch.sig.clear();2243 scratch.sig.clear();
2224 scratch.sig.resize(w, 0.0);2244 scratch.sig.resize(w, 0.0);
2225 if !view.is_empty() && view.total != 0 {2245 if !view.is_empty() && view.total != 0 {
2226- let duration = view.total as f64 / f64::from(VIZ_BUCKETS_PER_SEC);2246+ let duration = view.total as f64 / view.per_sec;
2227- let per_sec = f64::from(VIZ_BUCKETS_PER_SEC);2247+ let per_sec = view.per_sec;
2228 let window = if flags & VIZ_FAST != 0 {2248 let window = if flags & VIZ_FAST != 0 {
2229 VIZ_FAST_SECS2249 VIZ_FAST_SECS
2230 } else {2250 } else {
crates/engine/src/playback.rsmodified+40 -4
@@ -58,10 +58,15 @@ const DISSOLVE_B_TIMEOUT: Duration = Duration::from_millis(200);
58 /// inside it, and short enough that a play pressed after one does not wait.58 /// inside it, and short enough that a play pressed after one does not wait.
59 const AUDIO_REARM_AFTER: Duration = Duration::from_secs(1);59 const AUDIO_REARM_AFTER: Duration = Duration::from_secs(1);
60 60
61-/// What a session says when its output dies ([`PlaybackSession::tick`]): the61+/// The reason a session gives for having gone quiet when its output dies
62-/// one line a front-end shows for a session that has gone quiet, through the62+/// ([`PlaybackSession::tick`]), through the same door a file's own refusal
63-/// same door a file's own refusal reaches it by63+/// reaches a front-end by ([`PlaybackSession::audio_disabled_reason`]).
64-/// ([`PlaybackSession::audio_disabled_reason`]).64+///
65+/// That door is read where a notice is *built* -- at open and at load -- so this
66+/// is fetchable rather than announced: the engine sets the reason and clears it
67+/// again when the output comes back, and a front-end that reads the door after
68+/// the session is open (a per-frame check, or one at the next load) is what
69+/// shows it. Nothing here pushes a notice.
65 const AUDIO_LOST: &str = "output device went away -- reconnecting the timeline's sound";70 const AUDIO_LOST: &str = "output device went away -- reconnecting the timeline's sound";
66 71
67 /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --72 /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --
@@ -4740,6 +4745,37 @@ mod tests {
4740 );4745 );
4741 }4746 }
4742 4747
4748+ /// The seat declares the canvas's own size and the painter masks the planes
4749+ /// it returns to even dimensions. An odd canvas (a `resolution 1921 1081`
4750+ /// line) or a one-pixel-high one leaves those two disagreeing by a row, and
4751+ /// the conversion then indexes a chroma plane the size it was told does not
4752+ /// have: `index out of bounds` on a zero-length slice, inside the seat's
4753+ /// worker, where nothing catches it and no frame ever arrives.
4754+ ///
4755+ /// An audio-only source, so the span really is a visualizer seat, and a
4756+ /// frame really is pulled out of it.
4757+ #[test]
4758+ fn a_visualizer_seat_paints_a_canvas_it_cannot_evenly_divide() {
4759+ for (w, h) in [(1920, 1), (1921, 1081), (320, 1), (321, 181)] {
4760+ let mut session =
4761+ PlaybackSession::open(asset("test_tone.mp3")).expect("open the audio fixture");
4762+ assert!(
4763+ session.set_resolution(w, h),
4764+ "{w}x{h} should be a resolution this session takes"
4765+ );
4766+ let mut frame = None;
4767+ for _ in 0..400 {
4768+ if let Some(f) = session.try_frame() {
4769+ frame = Some(f);
4770+ break;
4771+ }
4772+ std::thread::sleep(std::time::Duration::from_millis(5));
4773+ }
4774+ let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas"));
4775+ assert_eq!((frame.width, frame.height), (w, h), "a frame at the canvas's own size");
4776+ }
4777+ }
4778+
4743 /// `blend_bgra` at the two ends and the midpoint of its weight -- `t=0` is4779 /// `blend_bgra` at the two ends and the midpoint of its weight -- `t=0` is
4744 /// pure A, `t=1` is pure B, `t=0.5` rounds each byte to its own midpoint.4780 /// pure A, `t=1` is pure B, `t=0.5` rounds each byte to its own midpoint.
4745 /// Straight alpha (255 in both) survives every weight, which is the one4781 /// Straight alpha (255 in both) survives every weight, which is the one
crates/engine/src/waveform.rsmodified+193 -15
@@ -384,12 +384,21 @@ impl VizWindows {
384 0.0384 0.0
385 };385 };
386 let first = ((t_secs * per_sec) as usize / per_window) * per_window;386 let first = ((t_secs * per_sec) as usize / per_window) * per_window;
387+ // The decode is asked for from the seek margin *below* the window's own
388+ // first bucket, and the whole of what it returns is served: `from` is
389+ // where the slice starts, absolutely, which is the one thing a caller
390+ // cannot recover from the slice itself. The margin is what the frames at
391+ // the window's own edges read -- the painter's window is two seconds
392+ // wide and centred on the frame -- and it is a *seek* margin rather than
393+ // a served one, because a decode's own first and last buckets can hold
394+ // part of a bucket the neighbouring window covers too.
395+ let from = first.saturating_sub(seek);
387 if first >= total {396 if first >= total {
388 // Past the end of the file -- which is where a source shorter than397 // Past the end of the file -- which is where a source shorter than
389 // the clip playing it leaves the last frames. Nothing to decode:398 // the clip playing it leaves the last frames. Nothing to decode:
390 // the painter measures "past the file" against `total` and draws399 // the painter measures "past the file" against `total` and draws
391 // silence there, exactly as it did when it held the whole envelope.400 // silence there, exactly as it did when it held the whole envelope.
392- return crate::decode::VizView::window(&[], first, total, self.summary.peak);401+ return crate::decode::VizView::window(&[], first, total, self.summary.peak, per_sec);
393 }402 }
394 if self.current.as_ref().map(|(at, _)| *at) != Some(first) {403 if self.current.as_ref().map(|(at, _)| *at) != Some(first) {
395 // A window that will not open keeps the frame's own silence for the404 // A window that will not open keeps the frame's own silence for the
@@ -403,18 +412,18 @@ impl VizWindows {
403 &self.key,412 &self.key,
404 self.summary.sample_rate,413 self.summary.sample_rate,
405 self.buckets_per_sec,414 self.buckets_per_sec,
406- first,415+ from,
407 per_window + 2 * seek,416 per_window + 2 * seek,
408 )417 )
409 .unwrap_or_else(|_| SharedPeaks::new(Vec::new()));418 .unwrap_or_else(|_| SharedPeaks::new(Vec::new()));
410 self.current = Some((first, window));419 self.current = Some((first, window));
411 }420 }
412 let (at, peaks) = self.current.as_ref().expect("just set");421 let (at, peaks) = self.current.as_ref().expect("just set");
413- // The slice starts where the decode did, a seek margin below the422+ debug_assert_eq!(
414- // window's own first bucket -- the same arithmetic [`viz_window`] was423+ *at, first,
415- // asked with, so the absolute positions line up.424+ "the seat kept a window other than the one it asked for"
416- let slice_first = at.saturating_sub(seek);425+ );
417- crate::decode::VizView::window(peaks.as_slice(), slice_first, total, self.summary.peak)426+ crate::decode::VizView::window(peaks.as_slice(), from, total, self.summary.peak, per_sec)
418 }427 }
419 }428 }
420 429
@@ -468,6 +477,20 @@ fn viz_decodes() -> usize {
468 VIZ_DECODES.load(std::sync::atomic::Ordering::Relaxed)477 VIZ_DECODES.load(std::sync::atomic::Ordering::Relaxed)
469 }478 }
470 479
480+/// Test-only: how many frames of *sound* the summary pass folded
481+/// ([`fold_summary`]); not the window decodes, so a delta across one ask is how
482+/// many times over the file's own length that pass read. The windows partition
483+/// the file, so a pass is one file's worth -- and a pass that also folded the
484+/// ask's whole-file probe would be up to twice that.
485+#[cfg(test)]
486+static VIZ_FOLDED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
487+
488+/// [`VIZ_FOLDED`], for a test that measures a delta across its own ask.
489+#[cfg(test)]
490+fn viz_folded() -> u64 {
491+ VIZ_FOLDED.load(std::sync::atomic::Ordering::Relaxed)
492+}
493+
471 /// The visualizer seat's own ask: the whole envelope when the memo holds it,494 /// The visualizer seat's own ask: the whole envelope when the memo holds it,
472 /// and otherwise windows of it. Never decoded per frame either way -- the495 /// and otherwise windows of it. Never decoded per frame either way -- the
473 /// per-frame cost of a look drag is what this exists to remove.496 /// per-frame cost of a look drag is what this exists to remove.
@@ -624,11 +647,20 @@ fn viz_summary(
624 .collect::<Result<_, _>>()?;647 .collect::<Result<_, _>>()?;
625 #[cfg(test)]648 #[cfg(test)]
626 VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);649 VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
627- // Every window folds everything it is handed, the first one included: no650+ // The first window stops at the joint the second one was told to start at,
628- // stop sample, because a stop that dropped a window's own tail could drop651+ // exactly as the envelope's own split stops it -- and the windows between
629- // the loudest sample in the file with it -- and the peak a visualizer frame652+ // them are the file, so a pass reads it once. Folding this receiver whole
630- // is scaled by is the one thing here that has to be the envelope's own.653+ // (it is the ask's probe, opened at the file's end) would have every later
631- let (mut peak, mut samples) = fold_summary(rx, u64::MAX, channels);654+ // window decode the same sound again: measured at 1.5x the file on a
655+ // two-window split and 1.875x at the eight-window ceiling, on the critical
656+ // path of the first look edit. A window with no joint to stop at -- the only
657+ // window there is -- folds everything it is handed, which is what the
658+ // single-threaded envelope ask does with it.
659+ let stop = match jobs {
660+ 1 => u64::MAX,
661+ _ => (window * rate) as u64,
662+ };
663+ let (mut peak, mut samples) = fold_summary(rx, stop, channels);
632 for handle in rest {664 for handle in rest {
633 let (part_peak, part_samples) = handle.join().map_err(|_| "waveform worker panicked")??;665 let (part_peak, part_samples) = handle.join().map_err(|_| "waveform worker panicked")??;
634 peak = peak.max(part_peak);666 peak = peak.max(part_peak);
@@ -736,6 +768,11 @@ fn fold_summary(rx: Receiver<AudioChunk>, stop_sample: u64, channels: usize) ->
736 if chunk.start_sample >= stop_sample {768 if chunk.start_sample >= stop_sample {
737 break;769 break;
738 }770 }
771+ #[cfg(test)]
772+ VIZ_FOLDED.fetch_add(
773+ (chunk.samples.len() / channels) as u64,
774+ std::sync::atomic::Ordering::Relaxed,
775+ );
739 samples = samples.max(chunk.start_sample + (chunk.samples.len() / channels) as u64);776 samples = samples.max(chunk.start_sample + (chunk.samples.len() / channels) as u64);
740 for &v in &chunk.samples {777 for &v in &chunk.samples {
741 peak = peak.max(v.clamp(-1.0, 1.0).abs());778 peak = peak.max(v.clamp(-1.0, 1.0).abs());
@@ -897,7 +934,7 @@ mod tests {
897 934
898 use super::{935 use super::{
899 memo_decodes, memoize, peak_of, peaks, peaks_over, peaks_shared_capped, viz_decodes,936 memo_decodes, memoize, peak_of, peaks, peaks_over, peaks_shared_capped, viz_decodes,
900- viz_envelope, viz_envelope_capped, MemoEntry, PeaksKey, PeaksMemo, SharedPeaks,937+ viz_envelope, viz_envelope_capped, viz_folded, MemoEntry, PeaksKey, PeaksMemo, SharedPeaks,
901 PEAKS_MEMO_BUCKETS,938 PEAKS_MEMO_BUCKETS,
902 };939 };
903 940
@@ -1287,6 +1324,142 @@ mod tests {
1287 assert_eq!(memo.len(), 1, "the replace added a second entry");1324 assert_eq!(memo.len(), 1, "the replace added a second entry");
1288 }1325 }
1289 1326
1327+ /// A window is where it says it is: on a fixture whose envelope is *not*
1328+ /// periodic, so a slice labelled a margin below where it starts cannot hide.
1329+ /// A sine hides it -- a shift by a whole number of periods leaves every
1330+ /// bucket identical, which is exactly how a +3 s mislabel survived a 440 Hz
1331+ /// fixture at 8 kHz (3 s is 1320 whole periods) -- so this is noise, in
1332+ /// FLAC (a seek lands on the sample, so the buckets must be *equal*, not
1333+ /// merely close).
1334+ ///
1335+ /// Every place a window can go wrong: the file's head, its middle, both
1336+ /// sides of a 30 s grid line, and the last window it has. At each: every
1337+ /// bucket a two-second picture can reach is the envelope's, and the frame is
1338+ /// byte for byte the one the *export* path paints from the whole envelope
1339+ /// ([`crate::decode::visualizer_i420`]).
1340+ #[test]
1341+ fn a_window_of_a_non_periodic_file_is_where_it_says_it_is() {
1342+ let path =
1343+ std::env::temp_dir().join(format!("edith-peaks-noise-{}.flac", std::process::id()));
1344+ let generated = std::process::Command::new("ffmpeg")
1345+ .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
1346+ .arg("anoisesrc=color=white:amplitude=0.5:sample_rate=8000:duration=120")
1347+ .args(["-c:a", "flac"])
1348+ .arg(&path)
1349+ .status()
1350+ .map(|status| status.success() && path.exists())
1351+ .unwrap_or(false);
1352+ if !generated {
1353+ eprintln!("no ffmpeg: a non-periodic fixture cannot be generated, skipping");
1354+ return;
1355+ }
1356+ let bps = crate::decode::VIZ_BUCKETS_PER_SEC;
1357+ let per_sec = f64::from(bps);
1358+ let plain = peaks(&path, 0, bps)
1359+ .expect("open")
1360+ .expect("the noise is audio");
1361+ assert!(
1362+ plain.len().abs_diff(120 * bps as usize) < 100,
1363+ "the envelope is {} buckets, not the 120 s it was generated for",
1364+ plain.len()
1365+ );
1366+ let peak = peak_of(&plain);
1367+ let mut scratch = crate::decode::VizScratch::default();
1368+ for secs in [0.0, 15.0, 29.5, 30.5, 60.0, 89.5, 119.0] {
1369+ // A ceiling of a thousand buckets, so the windowed route is the one
1370+ // walked (the route is what the real ceiling takes for a film).
1371+ let mut seat = viz_envelope_capped(&path, 0, bps, 1000).expect("open");
1372+ let view = seat.view_at(secs);
1373+ assert!(
1374+ !view.peaks.is_empty(),
1375+ "t={secs}: the window decoded nothing"
1376+ );
1377+ assert_eq!(
1378+ view.peak, peak,
1379+ "t={secs}: the window's peak is not the file's"
1380+ );
1381+ assert_eq!(
1382+ view.total,
1383+ plain.len(),
1384+ "t={secs}: the length is not the file's"
1385+ );
1386+ // The buckets the frame at `secs` can reach: a second either way,
1387+ // plus the bucket the interpolation reads past the end.
1388+ let from = ((secs - 1.0).max(0.0) * per_sec) as usize;
1389+ let to = (((secs + 1.0) * per_sec) as usize + 2).min(plain.len());
1390+ let (mut compared, mut wrong, mut out_of_reach) = (0, 0, 0);
1391+ for abs in from..to {
1392+ match (view.at(abs), plain.get(abs)) {
1393+ (Some(window), Some(&whole)) => {
1394+ compared += 1;
1395+ if window != whole {
1396+ wrong += 1;
1397+ }
1398+ }
1399+ _ => out_of_reach += 1,
1400+ }
1401+ }
1402+ assert!(
1403+ compared > 1000,
1404+ "t={secs}: only {compared} buckets were comparable ({out_of_reach} out of reach)"
1405+ );
1406+ assert_eq!(
1407+ (wrong, out_of_reach),
1408+ (0, 0),
1409+ "t={secs}: {wrong} of {compared} windowed buckets are not the envelope's, \
1410+ {out_of_reach} out of reach"
1411+ );
1412+ let whole = crate::decode::visualizer_i420(&mut scratch, &plain, secs, 320, 180, 0, 5);
1413+ let window =
1414+ crate::decode::visualizer_window_i420(&mut scratch, &view, secs, 320, 180, 0, 5);
1415+ assert_eq!(
1416+ whole, window,
1417+ "t={secs}: the window painted a frame the whole envelope does not"
1418+ );
1419+ }
1420+ let _ = std::fs::remove_file(&path);
1421+ }
1422+
1423+ /// The summary pass reads the file *once*. Its windows partition it -- the
1424+ /// first one stops at the joint the next was told to start at -- so the
1425+ /// frames it folds are the file's own, and folding the ask's whole-file
1426+ /// probe on top of them (which is what it used to do) is up to twice a file
1427+ /// for nothing, on the critical path of the first look edit.
1428+ #[test]
1429+ fn a_summary_pass_folds_the_file_once() {
1430+ let path =
1431+ std::env::temp_dir().join(format!("edith-peaks-once-{}.flac", std::process::id()));
1432+ let generated = std::process::Command::new("ffmpeg")
1433+ .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
1434+ .arg("anoisesrc=color=white:amplitude=0.5:sample_rate=8000:duration=120")
1435+ .args(["-c:a", "flac"])
1436+ .arg(&path)
1437+ .status()
1438+ .map(|status| status.success() && path.exists())
1439+ .unwrap_or(false);
1440+ if !generated {
1441+ eprintln!("no ffmpeg: a film-length fixture cannot be generated, skipping");
1442+ return;
1443+ }
1444+ let bps = crate::decode::VIZ_BUCKETS_PER_SEC;
1445+ let frames = 120 * 8000;
1446+ let before = viz_folded();
1447+ let mut seat = viz_envelope_capped(&path, 0, bps, 1000).expect("open");
1448+ let view = seat.view_at(60.0);
1449+ assert!(!view.peaks.is_empty(), "the window decoded nothing");
1450+ let folded = viz_folded() - before;
1451+ assert!(
1452+ folded >= frames - frames / 10,
1453+ "the summary pass folded {folded} frames of a {frames}-frame file: it lost a window"
1454+ );
1455+ assert!(
1456+ folded <= frames + frames / 20,
1457+ "the summary pass folded {folded} frames of a {frames}-frame file, {:.2}x over",
1458+ folded as f64 / frames as f64
1459+ );
1460+ let _ = std::fs::remove_file(&path);
1461+ }
1462+
1290 /// A container that states no sample rate (or a zero one) must not make the1463 /// A container that states no sample rate (or a zero one) must not make the
1291 /// samples-per-bucket arithmetic zero: `sample / 0.0` is infinite, `as1464 /// samples-per-bucket arithmetic zero: `sample / 0.0` is infinite, `as
1292 /// usize` saturates, and the fold's own `resize(bucket + 1)` is then a1465 /// usize` saturates, and the fold's own `resize(bucket + 1)` is then a
@@ -1390,8 +1563,13 @@ mod tests {
1390 // interpolation reads past it.1563 // interpolation reads past it.
1391 let from = ((secs - 1.0).max(0.0) * per_sec) as usize;1564 let from = ((secs - 1.0).max(0.0) * per_sec) as usize;
1392 let to = (((secs + 1.0) * per_sec) as usize + 2).min(whole.len());1565 let to = (((secs + 1.0) * per_sec) as usize + 2).min(whole.len());
1393- let view =1566+ let view = crate::decode::VizView::window(
1394- crate::decode::VizView::window(&whole[from..to], from, whole.len(), peak);1567+ &whole[from..to],
1568+ from,
1569+ whole.len(),
1570+ peak,
1571+ per_sec,
1572+ );
1395 let window_frame = crate::decode::visualizer_window_i420(1573 let window_frame = crate::decode::visualizer_window_i420(
1396 &mut scratch,1574 &mut scratch,
1397 &view,1575 &view,