From e5f0b93fb5f51f51e17ec8ec8800c1ea6c989408 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 24 Sep 2026 14:41:19 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(engine):=20a=20window=20star?= =?UTF-8?q?ts=20at=20the=20bucket=20the=20decode=20was=20asked=20for?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 28 ++++- crates/engine/src/playback.rs | 44 ++++++- crates/engine/src/waveform.rs | 208 +++++++++++++++++++++++++++++++--- 3 files changed, 257 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 79b615c..ec6b07c 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -650,7 +650,16 @@ impl DecodeSession { // Painted at the canvas's own size, so the composite places nothing: // the picture *is* the canvas, and whatever transform the clip // carries still reaches it through the render below. - let (width, height) = canvas.dims(); + // + // Masked to even dimensions first, and floored at two: that is what the + // painter does to the planes it hands back, so a canvas it cannot divide + // evenly (an odd `resolution 1921 1081` line, or a one-pixel-high one) + // used to be *declared* at a size the picture never had -- and the + // conversion below then indexes a chroma plane that is not there + // (`index out of bounds` on a zero-length slice, in this worker, where + // no frame ever arrives and nothing catches it). + let (canvas_w, canvas_h) = canvas.dims(); + let (width, height) = ((canvas_w & !1).max(2), (canvas_h & !1).max(2)); let worker_cancel = Arc::clone(&cancel); let path = path.to_path_buf(); let handle = thread::Builder::new() @@ -2137,11 +2146,18 @@ pub(crate) fn visualizer_i420( /// measured it against itself would draw the file's end wherever the window /// ended -- and `peak` is the file's loudest bucket, which every column is /// scaled by: no window can derive that from itself. +/// +/// `per_sec` is the rate *this* envelope was drawn at, in buckets per second, +/// and it is carried rather than assumed: the slice is indexed at it, so an +/// envelope drawn at another rate under a painter that hard-coded the +/// visualizer's own would read a tenth of a second of sound as a second. The +/// whole-file constructor is the one place the visualizer's rate is named. pub(crate) struct VizView<'a> { pub(crate) peaks: &'a [(f32, f32)], pub(crate) first: usize, pub(crate) total: usize, pub(crate) peak: f32, + pub(crate) per_sec: f64, } impl<'a> VizView<'a> { @@ -2152,22 +2168,26 @@ impl<'a> VizView<'a> { first: 0, total: peaks.len(), peak: crate::waveform::peak_of(peaks), + per_sec: f64::from(VIZ_BUCKETS_PER_SEC), } } /// One window of an envelope: `peaks` starts at absolute bucket `first`, - /// `total` and `peak` are the whole file's. + /// `total` and `peak` are the whole file's, and `per_sec` is the rate the + /// file's envelope was drawn at. pub(crate) fn window( peaks: &'a [(f32, f32)], first: usize, total: usize, peak: f32, + per_sec: f64, ) -> Self { Self { peaks, first, total, peak, + per_sec, } } @@ -2223,8 +2243,8 @@ pub(crate) fn visualizer_window_i420( scratch.sig.clear(); scratch.sig.resize(w, 0.0); if !view.is_empty() && view.total != 0 { - let duration = view.total as f64 / f64::from(VIZ_BUCKETS_PER_SEC); - let per_sec = f64::from(VIZ_BUCKETS_PER_SEC); + let duration = view.total as f64 / view.per_sec; + let per_sec = view.per_sec; let window = if flags & VIZ_FAST != 0 { VIZ_FAST_SECS } else { diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 960b637..9d05e2d 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -58,10 +58,15 @@ const DISSOLVE_B_TIMEOUT: Duration = Duration::from_millis(200); /// inside it, and short enough that a play pressed after one does not wait. const AUDIO_REARM_AFTER: Duration = Duration::from_secs(1); -/// What a session says when its output dies ([`PlaybackSession::tick`]): the -/// one line a front-end shows for a session that has gone quiet, through the -/// same door a file's own refusal reaches it by -/// ([`PlaybackSession::audio_disabled_reason`]). +/// The reason a session gives for having gone quiet when its output dies +/// ([`PlaybackSession::tick`]), through the same door a file's own refusal +/// reaches a front-end by ([`PlaybackSession::audio_disabled_reason`]). +/// +/// That door is read where a notice is *built* -- at open and at load -- so this +/// is fetchable rather than announced: the engine sets the reason and clears it +/// again when the output comes back, and a front-end that reads the door after +/// the session is open (a per-frame check, or one at the next load) is what +/// shows it. Nothing here pushes a notice. const AUDIO_LOST: &str = "output device went away -- reconnecting the timeline's sound"; /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 -- @@ -4740,6 +4745,37 @@ mod tests { ); } + /// The seat declares the canvas's own size and the painter masks the planes + /// it returns to even dimensions. An odd canvas (a `resolution 1921 1081` + /// line) or a one-pixel-high one leaves those two disagreeing by a row, and + /// the conversion then indexes a chroma plane the size it was told does not + /// have: `index out of bounds` on a zero-length slice, inside the seat's + /// worker, where nothing catches it and no frame ever arrives. + /// + /// An audio-only source, so the span really is a visualizer seat, and a + /// frame really is pulled out of it. + #[test] + fn a_visualizer_seat_paints_a_canvas_it_cannot_evenly_divide() { + for (w, h) in [(1920, 1), (1921, 1081), (320, 1), (321, 181)] { + let mut session = + PlaybackSession::open(asset("test_tone.mp3")).expect("open the audio fixture"); + assert!( + session.set_resolution(w, h), + "{w}x{h} should be a resolution this session takes" + ); + let mut frame = None; + for _ in 0..400 { + if let Some(f) = session.try_frame() { + frame = Some(f); + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas")); + assert_eq!((frame.width, frame.height), (w, h), "a frame at the canvas's own size"); + } + } + /// `blend_bgra` at the two ends and the midpoint of its weight -- `t=0` is /// pure A, `t=1` is pure B, `t=0.5` rounds each byte to its own midpoint. /// Straight alpha (255 in both) survives every weight, which is the one diff --git a/crates/engine/src/waveform.rs b/crates/engine/src/waveform.rs index 0b3e527..066fa5c 100644 --- a/crates/engine/src/waveform.rs +++ b/crates/engine/src/waveform.rs @@ -384,12 +384,21 @@ impl VizWindows { 0.0 }; let first = ((t_secs * per_sec) as usize / per_window) * per_window; + // The decode is asked for from the seek margin *below* the window's own + // first bucket, and the whole of what it returns is served: `from` is + // where the slice starts, absolutely, which is the one thing a caller + // cannot recover from the slice itself. The margin is what the frames at + // the window's own edges read -- the painter's window is two seconds + // wide and centred on the frame -- and it is a *seek* margin rather than + // a served one, because a decode's own first and last buckets can hold + // part of a bucket the neighbouring window covers too. + let from = first.saturating_sub(seek); if first >= total { // Past the end of the file -- which is where a source shorter than // the clip playing it leaves the last frames. Nothing to decode: // the painter measures "past the file" against `total` and draws // silence there, exactly as it did when it held the whole envelope. - return crate::decode::VizView::window(&[], first, total, self.summary.peak); + return crate::decode::VizView::window(&[], first, total, self.summary.peak, per_sec); } if self.current.as_ref().map(|(at, _)| *at) != Some(first) { // A window that will not open keeps the frame's own silence for the @@ -403,18 +412,18 @@ impl VizWindows { &self.key, self.summary.sample_rate, self.buckets_per_sec, - first, + from, per_window + 2 * seek, ) .unwrap_or_else(|_| SharedPeaks::new(Vec::new())); self.current = Some((first, window)); } let (at, peaks) = self.current.as_ref().expect("just set"); - // The slice starts where the decode did, a seek margin below the - // window's own first bucket -- the same arithmetic [`viz_window`] was - // asked with, so the absolute positions line up. - let slice_first = at.saturating_sub(seek); - crate::decode::VizView::window(peaks.as_slice(), slice_first, total, self.summary.peak) + debug_assert_eq!( + *at, first, + "the seat kept a window other than the one it asked for" + ); + crate::decode::VizView::window(peaks.as_slice(), from, total, self.summary.peak, per_sec) } } @@ -468,6 +477,20 @@ fn viz_decodes() -> usize { VIZ_DECODES.load(std::sync::atomic::Ordering::Relaxed) } +/// Test-only: how many frames of *sound* the summary pass folded +/// ([`fold_summary`]); not the window decodes, so a delta across one ask is how +/// many times over the file's own length that pass read. The windows partition +/// the file, so a pass is one file's worth -- and a pass that also folded the +/// ask's whole-file probe would be up to twice that. +#[cfg(test)] +static VIZ_FOLDED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// [`VIZ_FOLDED`], for a test that measures a delta across its own ask. +#[cfg(test)] +fn viz_folded() -> u64 { + VIZ_FOLDED.load(std::sync::atomic::Ordering::Relaxed) +} + /// The visualizer seat's own ask: the whole envelope when the memo holds it, /// and otherwise windows of it. Never decoded per frame either way -- the /// per-frame cost of a look drag is what this exists to remove. @@ -624,11 +647,20 @@ fn viz_summary( .collect::>()?; #[cfg(test)] VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - // Every window folds everything it is handed, the first one included: no - // stop sample, because a stop that dropped a window's own tail could drop - // the loudest sample in the file with it -- and the peak a visualizer frame - // is scaled by is the one thing here that has to be the envelope's own. - let (mut peak, mut samples) = fold_summary(rx, u64::MAX, channels); + // The first window stops at the joint the second one was told to start at, + // exactly as the envelope's own split stops it -- and the windows between + // them are the file, so a pass reads it once. Folding this receiver whole + // (it is the ask's probe, opened at the file's end) would have every later + // window decode the same sound again: measured at 1.5x the file on a + // two-window split and 1.875x at the eight-window ceiling, on the critical + // path of the first look edit. A window with no joint to stop at -- the only + // window there is -- folds everything it is handed, which is what the + // single-threaded envelope ask does with it. + let stop = match jobs { + 1 => u64::MAX, + _ => (window * rate) as u64, + }; + let (mut peak, mut samples) = fold_summary(rx, stop, channels); for handle in rest { let (part_peak, part_samples) = handle.join().map_err(|_| "waveform worker panicked")??; peak = peak.max(part_peak); @@ -736,6 +768,11 @@ fn fold_summary(rx: Receiver, stop_sample: u64, channels: usize) -> if chunk.start_sample >= stop_sample { break; } + #[cfg(test)] + VIZ_FOLDED.fetch_add( + (chunk.samples.len() / channels) as u64, + std::sync::atomic::Ordering::Relaxed, + ); samples = samples.max(chunk.start_sample + (chunk.samples.len() / channels) as u64); for &v in &chunk.samples { peak = peak.max(v.clamp(-1.0, 1.0).abs()); @@ -897,7 +934,7 @@ mod tests { use super::{ memo_decodes, memoize, peak_of, peaks, peaks_over, peaks_shared_capped, viz_decodes, - viz_envelope, viz_envelope_capped, MemoEntry, PeaksKey, PeaksMemo, SharedPeaks, + viz_envelope, viz_envelope_capped, viz_folded, MemoEntry, PeaksKey, PeaksMemo, SharedPeaks, PEAKS_MEMO_BUCKETS, }; @@ -1287,6 +1324,142 @@ mod tests { assert_eq!(memo.len(), 1, "the replace added a second entry"); } + /// A window is where it says it is: on a fixture whose envelope is *not* + /// periodic, so a slice labelled a margin below where it starts cannot hide. + /// A sine hides it -- a shift by a whole number of periods leaves every + /// bucket identical, which is exactly how a +3 s mislabel survived a 440 Hz + /// fixture at 8 kHz (3 s is 1320 whole periods) -- so this is noise, in + /// FLAC (a seek lands on the sample, so the buckets must be *equal*, not + /// merely close). + /// + /// Every place a window can go wrong: the file's head, its middle, both + /// sides of a 30 s grid line, and the last window it has. At each: every + /// bucket a two-second picture can reach is the envelope's, and the frame is + /// byte for byte the one the *export* path paints from the whole envelope + /// ([`crate::decode::visualizer_i420`]). + #[test] + fn a_window_of_a_non_periodic_file_is_where_it_says_it_is() { + let path = + std::env::temp_dir().join(format!("edith-peaks-noise-{}.flac", std::process::id())); + let generated = std::process::Command::new("ffmpeg") + .args(["-y", "-v", "error", "-f", "lavfi", "-i"]) + .arg("anoisesrc=color=white:amplitude=0.5:sample_rate=8000:duration=120") + .args(["-c:a", "flac"]) + .arg(&path) + .status() + .map(|status| status.success() && path.exists()) + .unwrap_or(false); + if !generated { + eprintln!("no ffmpeg: a non-periodic fixture cannot be generated, skipping"); + return; + } + let bps = crate::decode::VIZ_BUCKETS_PER_SEC; + let per_sec = f64::from(bps); + let plain = peaks(&path, 0, bps) + .expect("open") + .expect("the noise is audio"); + assert!( + plain.len().abs_diff(120 * bps as usize) < 100, + "the envelope is {} buckets, not the 120 s it was generated for", + plain.len() + ); + let peak = peak_of(&plain); + let mut scratch = crate::decode::VizScratch::default(); + for secs in [0.0, 15.0, 29.5, 30.5, 60.0, 89.5, 119.0] { + // A ceiling of a thousand buckets, so the windowed route is the one + // walked (the route is what the real ceiling takes for a film). + let mut seat = viz_envelope_capped(&path, 0, bps, 1000).expect("open"); + let view = seat.view_at(secs); + assert!( + !view.peaks.is_empty(), + "t={secs}: the window decoded nothing" + ); + assert_eq!( + view.peak, peak, + "t={secs}: the window's peak is not the file's" + ); + assert_eq!( + view.total, + plain.len(), + "t={secs}: the length is not the file's" + ); + // The buckets the frame at `secs` can reach: a second either way, + // plus the bucket the interpolation reads past the end. + let from = ((secs - 1.0).max(0.0) * per_sec) as usize; + let to = (((secs + 1.0) * per_sec) as usize + 2).min(plain.len()); + let (mut compared, mut wrong, mut out_of_reach) = (0, 0, 0); + for abs in from..to { + match (view.at(abs), plain.get(abs)) { + (Some(window), Some(&whole)) => { + compared += 1; + if window != whole { + wrong += 1; + } + } + _ => out_of_reach += 1, + } + } + assert!( + compared > 1000, + "t={secs}: only {compared} buckets were comparable ({out_of_reach} out of reach)" + ); + assert_eq!( + (wrong, out_of_reach), + (0, 0), + "t={secs}: {wrong} of {compared} windowed buckets are not the envelope's, \ + {out_of_reach} out of reach" + ); + let whole = crate::decode::visualizer_i420(&mut scratch, &plain, secs, 320, 180, 0, 5); + let window = + crate::decode::visualizer_window_i420(&mut scratch, &view, secs, 320, 180, 0, 5); + assert_eq!( + whole, window, + "t={secs}: the window painted a frame the whole envelope does not" + ); + } + let _ = std::fs::remove_file(&path); + } + + /// The summary pass reads the file *once*. Its windows partition it -- the + /// first one stops at the joint the next was told to start at -- so the + /// frames it folds are the file's own, and folding the ask's whole-file + /// probe on top of them (which is what it used to do) is up to twice a file + /// for nothing, on the critical path of the first look edit. + #[test] + fn a_summary_pass_folds_the_file_once() { + let path = + std::env::temp_dir().join(format!("edith-peaks-once-{}.flac", std::process::id())); + let generated = std::process::Command::new("ffmpeg") + .args(["-y", "-v", "error", "-f", "lavfi", "-i"]) + .arg("anoisesrc=color=white:amplitude=0.5:sample_rate=8000:duration=120") + .args(["-c:a", "flac"]) + .arg(&path) + .status() + .map(|status| status.success() && path.exists()) + .unwrap_or(false); + if !generated { + eprintln!("no ffmpeg: a film-length fixture cannot be generated, skipping"); + return; + } + let bps = crate::decode::VIZ_BUCKETS_PER_SEC; + let frames = 120 * 8000; + let before = viz_folded(); + let mut seat = viz_envelope_capped(&path, 0, bps, 1000).expect("open"); + let view = seat.view_at(60.0); + assert!(!view.peaks.is_empty(), "the window decoded nothing"); + let folded = viz_folded() - before; + assert!( + folded >= frames - frames / 10, + "the summary pass folded {folded} frames of a {frames}-frame file: it lost a window" + ); + assert!( + folded <= frames + frames / 20, + "the summary pass folded {folded} frames of a {frames}-frame file, {:.2}x over", + folded as f64 / frames as f64 + ); + let _ = std::fs::remove_file(&path); + } + /// A container that states no sample rate (or a zero one) must not make the /// samples-per-bucket arithmetic zero: `sample / 0.0` is infinite, `as /// usize` saturates, and the fold's own `resize(bucket + 1)` is then a @@ -1390,8 +1563,13 @@ mod tests { // interpolation reads past it. let from = ((secs - 1.0).max(0.0) * per_sec) as usize; let to = (((secs + 1.0) * per_sec) as usize + 2).min(whole.len()); - let view = - crate::decode::VizView::window(&whole[from..to], from, whole.len(), peak); + let view = crate::decode::VizView::window( + &whole[from..to], + from, + whole.len(), + peak, + per_sec, + ); let window_frame = crate::decode::visualizer_window_i420( &mut scratch, &view,