The mkv seek landing is measured on a real film, not only the fixture
Browse files at this commit1501d34f6efca67171fa617e9d58fd60ea42c574Parent: c94ba8b- test
- the mkv seek landing is measured on a real film, not only the fixture
1 changed file +176 -0
crates/engine/tests/audio_seek.rsmodified+176 -0
| @@ -179,3 +179,179 @@ fn chirp_second(meta: &engine::audio::AudioMeta, samples: impl Iterator<Item = f | |||
| 179 | // The window's *midpoint* is what its mean frequency dates. | 179 | // The window's *midpoint* is what its mean frequency dates. |
| 180 | (crossings as f64 / 2.0 / WINDOW - 200.0) / 160.0 - WINDOW / 2.0 | 180 | (crossings as f64 / 2.0 / WINDOW - 200.0) / 160.0 - WINDOW / 2.0 |
| 181 | } | 181 | } |
| 182 | + | ||
| 183 | +/// A real film, which is where the desync was measured and where the fixture | ||
| 184 | +/// cannot follow: a 5 GB AV1 remux with a 5.1 Opus track and a cue table, seeked | ||
| 185 | +/// to three seconds spread across two hours and correlated against ffmpeg's | ||
| 186 | +/// decode of the same window. | ||
| 187 | +/// | ||
| 188 | +/// The chirp fixture above proves the rule on 30 seconds of one cluster layout. | ||
| 189 | +/// This proves it where it broke: `fix(audio): a seek into a Matroska lands on | ||
| 190 | +/// the second it asked for` measured +1.473 s at 600 s and +3.394 s at 610 s on | ||
| 191 | +/// this file and left no runnable check behind it, so a regression would come | ||
| 192 | +/// back the way the original did -- through the ears, after a scrub. | ||
| 193 | +/// | ||
| 194 | +/// Skipped, not failed, without the film or without ffmpeg: a claim about a | ||
| 195 | +/// library cannot be made by a machine that does not have it. | ||
| 196 | +#[test] | ||
| 197 | +fn a_seek_into_real_film_lands_on_the_second_it_asked_for() { | ||
| 198 | + let film = PathBuf::from( | ||
| 199 | + "/path/to/a-real-av1-opus-5.1-film.mkv", | ||
| 200 | + ); | ||
| 201 | + if !film.exists() { | ||
| 202 | + eprintln!("skipped: {} is not on this machine", film.display()); | ||
| 203 | + return; | ||
| 204 | + } | ||
| 205 | + if std::process::Command::new("ffmpeg") | ||
| 206 | + .arg("-version") | ||
| 207 | + .stdout(std::process::Stdio::null()) | ||
| 208 | + .stderr(std::process::Stdio::null()) | ||
| 209 | + .status() | ||
| 210 | + .is_err() | ||
| 211 | + { | ||
| 212 | + eprintln!("skipped: no ffmpeg to decode the reference window with"); | ||
| 213 | + return; | ||
| 214 | + } | ||
| 215 | + // Five seconds either side of the request: the landings this exists to catch | ||
| 216 | + // were +1.5 and +3.4 s, and a narrow search is a search that cannot pick the | ||
| 217 | + // wrong repeat of a phrase. | ||
| 218 | + const SEARCH: f64 = 5.0; | ||
| 219 | + for want in [600.0, 610.0, 3600.0] { | ||
| 220 | + let (meta, rx) = AudioSession::open_at(&film, want) | ||
| 221 | + .expect("open") | ||
| 222 | + .expect("the film has audio"); | ||
| 223 | + let rate = f64::from(meta.sample_rate); | ||
| 224 | + let channels = usize::from(meta.channels); | ||
| 225 | + // One second of what came out, summed to mono: what is being located is | ||
| 226 | + // the content, and a fold's channel balance is not part of that. Taken a | ||
| 227 | + // chunk at a time and then dropped -- this window is open-ended, and | ||
| 228 | + // draining it is decoding the rest of a two-hour film. | ||
| 229 | + let mut probe: Vec<f32> = Vec::with_capacity(meta.sample_rate as usize); | ||
| 230 | + for chunk in &rx { | ||
| 231 | + probe.extend( | ||
| 232 | + chunk | ||
| 233 | + .samples | ||
| 234 | + .chunks_exact(channels) | ||
| 235 | + .map(|f| f.iter().sum::<f32>() / channels as f32), | ||
| 236 | + ); | ||
| 237 | + if probe.len() >= meta.sample_rate as usize { | ||
| 238 | + break; | ||
| 239 | + } | ||
| 240 | + } | ||
| 241 | + drop(rx); | ||
| 242 | + probe.truncate(meta.sample_rate as usize); | ||
| 243 | + assert_eq!(probe.len(), meta.sample_rate as usize, "a second to locate"); | ||
| 244 | + | ||
| 245 | + let from = want - SEARCH; | ||
| 246 | + let reference = ffmpeg_mono(&film, from, 2.0 * SEARCH + 2.0, meta.sample_rate); | ||
| 247 | + let (lag, score) = best_lag(&probe, &reference); | ||
| 248 | + let at = from + lag as f64 / rate; | ||
| 249 | + eprintln!("asked {want}s, content at {at:.3}s (correlation {score:.3})"); | ||
| 250 | + assert!( | ||
| 251 | + score > 0.5, | ||
| 252 | + "asked {want}s: nothing in the reference window correlates ({score:.3}) -- \ | ||
| 253 | + the measurement, not the seek, is what failed" | ||
| 254 | + ); | ||
| 255 | + assert!( | ||
| 256 | + (at - want).abs() <= 0.05, | ||
| 257 | + "asked {want}s, heard {at:.3}s -- {:+.3}s of sound against picture", | ||
| 258 | + at - want | ||
| 259 | + ); | ||
| 260 | + } | ||
| 261 | +} | ||
| 262 | + | ||
| 263 | +/// `dur` seconds of `path`'s first audio track from `start`, decoded by ffmpeg, | ||
| 264 | +/// summed to mono at `rate`. The reference this engine's own landing is measured | ||
| 265 | +/// against, because a decoder cannot be its own witness about where it landed. | ||
| 266 | +fn ffmpeg_mono(path: &std::path::Path, start: f64, dur: f64, rate: u32) -> Vec<f32> { | ||
| 267 | + let out = std::process::Command::new("ffmpeg") | ||
| 268 | + .args(["-v", "error", "-ss"]) | ||
| 269 | + .arg(format!("{start}")) | ||
| 270 | + .arg("-t") | ||
| 271 | + .arg(format!("{dur}")) | ||
| 272 | + .arg("-i") | ||
| 273 | + .arg(path) | ||
| 274 | + .args(["-map", "0:a:0", "-ac", "1", "-ar"]) | ||
| 275 | + .arg(rate.to_string()) | ||
| 276 | + .args(["-f", "f32le", "-"]) | ||
| 277 | + .output() | ||
| 278 | + .expect("ffmpeg runs"); | ||
| 279 | + assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); | ||
| 280 | + out.stdout | ||
| 281 | + .chunks_exact(4) | ||
| 282 | + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) | ||
| 283 | + .collect() | ||
| 284 | +} | ||
| 285 | + | ||
| 286 | +/// Where in `reference` the `probe` sits, and how well: the offset in samples of | ||
| 287 | +/// the best normalised cross-correlation, which is 1.0 for the same content and | ||
| 288 | +/// falls away fast for anything else. | ||
| 289 | +/// | ||
| 290 | +/// Coarse then fine, because the naive product over a ten-second window at | ||
| 291 | +/// 48 kHz is 3e10 multiplies: both signals are averaged down by [`DECIMATE`] | ||
| 292 | +/// first -- a crude low-pass, and the peak of a correlation is broad -- then the | ||
| 293 | +/// winner is refined at full rate over the one block around it. The normalisation | ||
| 294 | +/// is what makes the two comparable at all, since this fold is 7.7 dB quieter | ||
| 295 | +/// than ffmpeg's. | ||
| 296 | +fn best_lag(probe: &[f32], reference: &[f32]) -> (usize, f64) { | ||
| 297 | + const DECIMATE: usize = 32; | ||
| 298 | + let down = |xs: &[f32]| -> Vec<f64> { | ||
| 299 | + xs.chunks_exact(DECIMATE) | ||
| 300 | + .map(|c| c.iter().map(|s| f64::from(*s)).sum::<f64>() / DECIMATE as f64) | ||
| 301 | + .collect() | ||
| 302 | + }; | ||
| 303 | + let (coarse, at) = scan(&down(probe), &down(reference), 1); | ||
| 304 | + let from = (at * DECIMATE).saturating_sub(DECIMATE); | ||
| 305 | + let span = 3 * DECIMATE + probe.len(); | ||
| 306 | + // The score reported is the coarse one, over the whole search window: the | ||
| 307 | + // fine pass only sharpens the offset inside a block it has already chosen, | ||
| 308 | + // and a score over a window that short says nothing about the match. | ||
| 309 | + let (_, offset) = scan( | ||
| 310 | + &probe.iter().map(|s| f64::from(*s)).collect::<Vec<f64>>(), | ||
| 311 | + &reference[from.min(reference.len())..(from + span).min(reference.len())] | ||
| 312 | + .iter() | ||
| 313 | + .map(|s| f64::from(*s)) | ||
| 314 | + .collect::<Vec<f64>>(), | ||
| 315 | + 1, | ||
| 316 | + ); | ||
| 317 | + (from + offset, coarse) | ||
| 318 | +} | ||
| 319 | + | ||
| 320 | +/// The best normalised cross-correlation of `probe` over `reference`, at `step` | ||
| 321 | +/// samples: `(score, offset)`. Both are mean-removed; the denominator is each | ||
| 322 | +/// window's own energy, so a level difference between the two decoders cannot | ||
| 323 | +/// move the peak. | ||
| 324 | +fn scan(probe: &[f64], reference: &[f64], step: usize) -> (f64, usize) { | ||
| 325 | + if reference.len() <= probe.len() || probe.is_empty() { | ||
| 326 | + return (0.0, 0); | ||
| 327 | + } | ||
| 328 | + let mean = |xs: &[f64]| xs.iter().sum::<f64>() / xs.len() as f64; | ||
| 329 | + let p: Vec<f64> = { | ||
| 330 | + let m = mean(probe); | ||
| 331 | + probe.iter().map(|s| s - m).collect() | ||
| 332 | + }; | ||
| 333 | + let pe = p.iter().map(|s| s * s).sum::<f64>().sqrt(); | ||
| 334 | + if pe <= 0.0 { | ||
| 335 | + return (0.0, 0); | ||
| 336 | + } | ||
| 337 | + let (mut best, mut at) = (0.0, 0); | ||
| 338 | + for offset in (0..reference.len() - p.len()).step_by(step) { | ||
| 339 | + let window = &reference[offset..offset + p.len()]; | ||
| 340 | + let m = mean(window); | ||
| 341 | + let (mut dot, mut energy) = (0.0, 0.0); | ||
| 342 | + for (a, b) in p.iter().zip(window) { | ||
| 343 | + let b = b - m; | ||
| 344 | + dot += a * b; | ||
| 345 | + energy += b * b; | ||
| 346 | + } | ||
| 347 | + let score = match energy > 0.0 { | ||
| 348 | + true => dot / (pe * energy.sqrt()), | ||
| 349 | + false => 0.0, | ||
| 350 | + }; | ||
| 351 | + if score > best { | ||
| 352 | + best = score; | ||
| 353 | + at = offset; | ||
| 354 | + } | ||
| 355 | + } | ||
| 356 | + (best, at) | ||
| 357 | +} | ||