diff --git a/crates/ec-probe/tests/library.rs b/crates/ec-probe/tests/library.rs index ff613932..9f2c7d6a 100644 --- a/crates/ec-probe/tests/library.rs +++ b/crates/ec-probe/tests/library.rs @@ -15,7 +15,7 @@ use std::sync::{ }; use std::time::Instant; -use ec_core::registry::{MediaType, SeekMode}; +use ec_core::registry::{CodecId, MediaType, SeekMode}; use ec_core::timebase::{TimeBase, Timestamp}; use ec_probe::Reader; @@ -92,37 +92,15 @@ fn decode_window(reader: &mut Reader, stream: u32, secs: f64) -> Result Ok(pcm) } -fn reference_window(path: &Path, at: f64, rate: u32, channels: usize) -> Vec { - if std::fs::metadata(path).map(|m| m.len()).unwrap_or(u64::MAX) < 128 * 1024 * 1024 { - let out = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) - .arg(path) - .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"]) - .output() - .expect("reference decoder runs"); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); - let all: Vec = out - .stdout - .chunks_exact(4) - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect(); - let start = (at * f64::from(rate) * channels as f64) as usize; - let end = (start + 2 * rate as usize * channels).min(all.len()); - return all.get(start..end).unwrap_or(&[]).to_vec(); - } +fn reference_seek_window(path: &Path, at: f64) -> Vec { let out = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) + .args(["-v", "error", "-ss", &format!("{at:.6}"), "-i"]) .arg(path) - .args(["-ss", &format!("{at:.6}")]) .args([ - "-map", - "0:a:0", "-t", "2", + "-map", + "0:a:0", "-f", "f32le", "-acodec", @@ -240,6 +218,129 @@ fn corr(a: &[f32], b: &[f32]) -> f64 { num / (a2.sqrt() * b2.sqrt()).max(1e-12) } +fn best_frame_corr( + ours: &[f32], + theirs: &[f32], + channels: usize, + frame_samples: usize, +) -> (i32, f64) { + let frame = channels * frame_samples; + (-1..=1) + .map(|lag| { + let (ours, theirs) = if lag < 0 { + (ours, theirs.get(frame..).unwrap_or(&[])) + } else { + (ours.get(frame * lag as usize..).unwrap_or(&[]), theirs) + }; + (lag, corr(ours, theirs)) + }) + .max_by(|(_, a), (_, b)| a.total_cmp(b)) + .unwrap() +} + +fn assert_avi_seeks_match_reference(path: &Path) { + let bytes = Arc::new(AtomicU64::new(0)); + let src = CountedFile { + inner: File::open(path).expect("open AVI"), + bytes: bytes.clone(), + }; + let mut reader = Reader::new(src, Some("avi")).expect("AVI opens"); + let audio = reader + .default_stream(MediaType::Audio) + .expect("AVI audio stream") + .clone(); + let rate = audio.params.audio().unwrap().sample_rate.max(1); + let channels = audio.params.audio().unwrap().layout.channel_count().max(1); + let frame_samples = match audio.params.codec { + CodecId::Ac3 | CodecId::EAc3 => 1536, + CodecId::Mp3 => 1152, + _ => 1, + }; + let duration = reader.duration().expect("AVI duration").as_secs_f64(); + for fraction in [0.10, 0.50, 0.90] { + let target = duration * fraction; + let ticks = (target * f64::from(rate)) as i64; + let before = bytes.load(Ordering::Relaxed); + let started = Instant::now(); + let landed = reader + .seek( + audio.index, + Timestamp::new(ticks, TimeBase::from_rate(rate)), + SeekMode::SyncBefore, + ) + .expect("AVI seek"); + let elapsed = started.elapsed(); + let read = bytes.load(Ordering::Relaxed) - before; + let at = landed.as_secs_f64(); + let ours = decode_window(&mut reader, audio.index, 2.0).expect("decode after seek"); + let theirs = reference_seek_window(path, at); + let (lag, score) = best_frame_corr(&ours, &theirs, channels, frame_samples); + eprintln!( + "{} @{:.0}%: target {target:.3}s landed {at:.3}s read {read} bytes seek {:?} lag {lag} frames corr {score:.6}", + path.display(), + fraction * 100.0, + elapsed + ); + assert!( + read < 8 * 1024 * 1024, + "{} @{fraction:.0}%: seek read {read} bytes", + path.display() + ); + if !cfg!(debug_assertions) { + assert!( + elapsed.as_millis() < 200, + "{} @{:.0}%: seek took {:?}", + path.display(), + fraction * 100.0, + elapsed + ); + } + assert!( + score >= 0.999, + "{} @{:.0}%: target {target:.3}s landed {at:.3}s lag {lag} frames corr vs reference decoder = {score}", + path.display(), + fraction * 100.0, + ); + } +} + +fn synthetic_mp3_avi() -> Option { + if !Command::new("ffmpeg") + .args(["-version"]) + .output() + .is_ok_and(|out| out.status.success()) + { + eprintln!("reference encoder/decoder absent, skipping synthetic AVI"); + return None; + } + let root = PathBuf::from(std::env::var_os("HOME").expect("HOME")).join(".cache/aviseek"); + std::fs::create_dir_all(&root).expect("create scratch directory"); + let path = root.join(format!("seek-oracle-{}.avi", std::process::id())); + let out = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + "sine=frequency=997:sample_rate=48000:duration=30", + "-c:a", + "libmp3lame", + "-f", + "avi", + "-y", + ]) + .arg(&path) + .output() + .expect("reference encoder runs"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + Some(path) +} + /// Ten files with sound, standalone audio first, then Matroska — opened, /// decoded and seeked, with a per-file row in the report. #[test] @@ -460,78 +561,19 @@ fn avi_seek_matches_reference_decoder_on_real_files() { return; } for path in files { - let bytes = Arc::new(AtomicU64::new(0)); - let src = CountedFile { - inner: File::open(&path).expect("open AVI"), - bytes: bytes.clone(), - }; - let mut reader = Reader::new(src, Some("avi")).expect("AVI opens"); - let audio = reader - .default_stream(MediaType::Audio) - .expect("AVI audio stream") - .clone(); - let rate = audio.params.audio().unwrap().sample_rate.max(1); - let Some(duration) = reader.duration() else { - eprintln!( - "{}: no stated duration, skipping seek check", - path.display() - ); - continue; - }; - let duration = duration.as_secs_f64(); - for fraction in [0.10, 0.50, 0.90] { - let target = duration * fraction; - let ticks = (target * f64::from(rate)) as i64; - let before = bytes.load(Ordering::Relaxed); - let started = Instant::now(); - let landed = reader - .seek( - audio.index, - Timestamp::new(ticks, TimeBase::from_rate(rate)), - SeekMode::SyncBefore, - ) - .expect("AVI seek"); - let elapsed = started.elapsed(); - let read = bytes.load(Ordering::Relaxed) - before; - let at = landed.as_secs_f64(); - let channels = audio.params.audio().unwrap().layout.channel_count().max(1); - let mut ours = decode_window(&mut reader, audio.index, 2.25 + (target - at).max(0.0)) - .expect("decode after seek"); - let trim = ((target - at).max(0.0) * f64::from(rate) * channels as f64) as usize; - if trim < ours.len() { - ours.drain(..trim); - } - let score = 1.0; - eprintln!( - "{} @{:.0}%: target {target:.3}s landed {at:.3}s read {read} bytes seek {:?} corr {score:.6}", - path.display(), - fraction * 100.0, - elapsed - ); - assert!( - read < 8 * 1024 * 1024, - "{} @{fraction:.0}%: seek read {read} bytes", - path.display() - ); - if !cfg!(debug_assertions) { - assert!( - elapsed.as_millis() < 200, - "{} @{fraction:.0}%: seek took {:?}", - path.display(), - elapsed - ); - } - assert!( - score >= 0.999, - "{} @{:.0}%: target {target:.3}s landed {at:.3}s read {read} bytes seek {:?} corr vs reference decoder = {score}", - path.display(), - fraction * 100.0, - elapsed - ); - } + assert_avi_seeks_match_reference(&path); } } +#[test] +fn avi_seek_matches_reference_decoder_on_synthetic_mp3() { + let Some(path) = synthetic_mp3_avi() else { + return; + }; + assert_avi_seeks_match_reference(&path); + std::fs::remove_file(path).expect("remove synthetic AVI"); +} + /// The TrueHD remux in his library: the track decodes through the unified /// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too. #[test]