From 1501d34f6efca67171fa617e9d58fd60ea42c574 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 12 Aug 2026 22:24:54 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=85=20test(audio):=20the=20mkv=20seek=20l?= =?UTF-8?q?anding=20is=20measured=20on=20a=20real=20film,=20not=20only=20t?= =?UTF-8?q?he=20fixture?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P7 asked for a fix to a seek that lands ±1.5 s off in content on a real-library AV1/Opus remux. It does not land off any more: `fix(audio): a seek into a Matroska lands on the second it asked for` (90e5ed2, four hours before this) already reopens the reader and re-asks from far enough back to swallow the cue table's overshoot. Measured here rather than taken on trust — the same `seek_dump` example, correlated against ffmpeg's decode of the same window: 600 s 610 s 3600 s before +1.473 s +3.394 s +0.014 s after -0.000 s +0.000 s -0.001 s ("before" is that commit's parent checked out over this tree, so both rows are this machine, this file, this hour.) What was missing is the guard. `audio_seek.rs` proved the rule on a 30 s synthetic chirp with one cluster layout, and the failure it exists for was found on a 5 GB film with a cue table — so the film is what the test now seeks into, at 600, 610 and 3600 s, locating each landing by normalised cross-correlation against ffmpeg (coarse over a decimated ±5 s window, then refined at full rate) and holding it to 50 ms. Verified to fail on the code it is about: with 90e5ed2's parent audio.rs in place it reports "asked 600s, heard 601.473s -- +1.473s of sound against picture" and passes on HEAD. Skipped, never falsely green, on a machine without the film or without ffmpeg. --- crates/engine/tests/audio_seek.rs | 176 ++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) diff --git a/crates/engine/tests/audio_seek.rs b/crates/engine/tests/audio_seek.rs index b15b54e..e409728 100644 --- a/crates/engine/tests/audio_seek.rs +++ b/crates/engine/tests/audio_seek.rs @@ -179,3 +179,179 @@ fn chirp_second(meta: &engine::audio::AudioMeta, samples: impl Iterator = Vec::with_capacity(meta.sample_rate as usize); + for chunk in &rx { + probe.extend( + chunk + .samples + .chunks_exact(channels) + .map(|f| f.iter().sum::() / channels as f32), + ); + if probe.len() >= meta.sample_rate as usize { + break; + } + } + drop(rx); + probe.truncate(meta.sample_rate as usize); + assert_eq!(probe.len(), meta.sample_rate as usize, "a second to locate"); + + let from = want - SEARCH; + let reference = ffmpeg_mono(&film, from, 2.0 * SEARCH + 2.0, meta.sample_rate); + let (lag, score) = best_lag(&probe, &reference); + let at = from + lag as f64 / rate; + eprintln!("asked {want}s, content at {at:.3}s (correlation {score:.3})"); + assert!( + score > 0.5, + "asked {want}s: nothing in the reference window correlates ({score:.3}) -- \ + the measurement, not the seek, is what failed" + ); + assert!( + (at - want).abs() <= 0.05, + "asked {want}s, heard {at:.3}s -- {:+.3}s of sound against picture", + at - want + ); + } +} + +/// `dur` seconds of `path`'s first audio track from `start`, decoded by ffmpeg, +/// summed to mono at `rate`. The reference this engine's own landing is measured +/// against, because a decoder cannot be its own witness about where it landed. +fn ffmpeg_mono(path: &std::path::Path, start: f64, dur: f64, rate: u32) -> Vec { + let out = std::process::Command::new("ffmpeg") + .args(["-v", "error", "-ss"]) + .arg(format!("{start}")) + .arg("-t") + .arg(format!("{dur}")) + .arg("-i") + .arg(path) + .args(["-map", "0:a:0", "-ac", "1", "-ar"]) + .arg(rate.to_string()) + .args(["-f", "f32le", "-"]) + .output() + .expect("ffmpeg runs"); + assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); + out.stdout + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect() +} + +/// Where in `reference` the `probe` sits, and how well: the offset in samples of +/// the best normalised cross-correlation, which is 1.0 for the same content and +/// falls away fast for anything else. +/// +/// Coarse then fine, because the naive product over a ten-second window at +/// 48 kHz is 3e10 multiplies: both signals are averaged down by [`DECIMATE`] +/// first -- a crude low-pass, and the peak of a correlation is broad -- then the +/// winner is refined at full rate over the one block around it. The normalisation +/// is what makes the two comparable at all, since this fold is 7.7 dB quieter +/// than ffmpeg's. +fn best_lag(probe: &[f32], reference: &[f32]) -> (usize, f64) { + const DECIMATE: usize = 32; + let down = |xs: &[f32]| -> Vec { + xs.chunks_exact(DECIMATE) + .map(|c| c.iter().map(|s| f64::from(*s)).sum::() / DECIMATE as f64) + .collect() + }; + let (coarse, at) = scan(&down(probe), &down(reference), 1); + let from = (at * DECIMATE).saturating_sub(DECIMATE); + let span = 3 * DECIMATE + probe.len(); + // The score reported is the coarse one, over the whole search window: the + // fine pass only sharpens the offset inside a block it has already chosen, + // and a score over a window that short says nothing about the match. + let (_, offset) = scan( + &probe.iter().map(|s| f64::from(*s)).collect::>(), + &reference[from.min(reference.len())..(from + span).min(reference.len())] + .iter() + .map(|s| f64::from(*s)) + .collect::>(), + 1, + ); + (from + offset, coarse) +} + +/// The best normalised cross-correlation of `probe` over `reference`, at `step` +/// samples: `(score, offset)`. Both are mean-removed; the denominator is each +/// window's own energy, so a level difference between the two decoders cannot +/// move the peak. +fn scan(probe: &[f64], reference: &[f64], step: usize) -> (f64, usize) { + if reference.len() <= probe.len() || probe.is_empty() { + return (0.0, 0); + } + let mean = |xs: &[f64]| xs.iter().sum::() / xs.len() as f64; + let p: Vec = { + let m = mean(probe); + probe.iter().map(|s| s - m).collect() + }; + let pe = p.iter().map(|s| s * s).sum::().sqrt(); + if pe <= 0.0 { + return (0.0, 0); + } + let (mut best, mut at) = (0.0, 0); + for offset in (0..reference.len() - p.len()).step_by(step) { + let window = &reference[offset..offset + p.len()]; + let m = mean(window); + let (mut dot, mut energy) = (0.0, 0.0); + for (a, b) in p.iter().zip(window) { + let b = b - m; + dot += a * b; + energy += b * b; + } + let score = match energy > 0.0 { + true => dot / (pe * energy.sqrt()), + false => 0.0, + }; + if score > best { + best = score; + at = offset; + } + } + (best, at) +}