forge
Explore
Log in

Don't you dare go Hollow

24272c3302b88ee1252a0093d2c1921cfbafaec3Ahmet Kaan GümüşParent: 63bf445
  • test
    • avi seek oracle
Show full message
test(probe): avi seek oracle
crates/ec-probe/tests/library.rsmodified+138 -96
@@ -15,7 +15,7 @@ use std::sync::{
1515 };
1616 use std::time::Instant;
1717
18-use ec_core::registry::{MediaType, SeekMode};
18+use ec_core::registry::{CodecId, MediaType, SeekMode};
1919 use ec_core::timebase::{TimeBase, Timestamp};
2020 use ec_probe::Reader;
2121
@@ -92,37 +92,15 @@ fn decode_window(reader: &mut Reader, stream: u32, secs: f64) -> Result<Vec<f32>
9292 Ok(pcm)
9393 }
9494
95-fn reference_window(path: &Path, at: f64, rate: u32, channels: usize) -> Vec<f32> {
96- if std::fs::metadata(path).map(|m| m.len()).unwrap_or(u64::MAX) < 128 * 1024 * 1024 {
97- let out = Command::new("ffmpeg")
98- .args(["-v", "error", "-i"])
99- .arg(path)
100- .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
101- .output()
102- .expect("reference decoder runs");
103- assert!(
104- out.status.success(),
105- "{}",
106- String::from_utf8_lossy(&out.stderr)
107- );
108- let all: Vec<f32> = out
109- .stdout
110- .chunks_exact(4)
111- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
112- .collect();
113- let start = (at * f64::from(rate) * channels as f64) as usize;
114- let end = (start + 2 * rate as usize * channels).min(all.len());
115- return all.get(start..end).unwrap_or(&[]).to_vec();
116- }
95+fn reference_seek_window(path: &Path, at: f64) -> Vec<f32> {
11796 let out = Command::new("ffmpeg")
118- .args(["-v", "error", "-i"])
97+ .args(["-v", "error", "-ss", &format!("{at:.6}"), "-i"])
11998 .arg(path)
120- .args(["-ss", &format!("{at:.6}")])
12199 .args([
122- "-map",
123- "0:a:0",
124100 "-t",
125101 "2",
102+ "-map",
103+ "0:a:0",
126104 "-f",
127105 "f32le",
128106 "-acodec",
@@ -240,6 +218,129 @@ fn corr(a: &[f32], b: &[f32]) -> f64 {
240218 num / (a2.sqrt() * b2.sqrt()).max(1e-12)
241219 }
242220
221+fn best_frame_corr(
222+ ours: &[f32],
223+ theirs: &[f32],
224+ channels: usize,
225+ frame_samples: usize,
226+) -> (i32, f64) {
227+ let frame = channels * frame_samples;
228+ (-1..=1)
229+ .map(|lag| {
230+ let (ours, theirs) = if lag < 0 {
231+ (ours, theirs.get(frame..).unwrap_or(&[]))
232+ } else {
233+ (ours.get(frame * lag as usize..).unwrap_or(&[]), theirs)
234+ };
235+ (lag, corr(ours, theirs))
236+ })
237+ .max_by(|(_, a), (_, b)| a.total_cmp(b))
238+ .unwrap()
239+}
240+
241+fn assert_avi_seeks_match_reference(path: &Path) {
242+ let bytes = Arc::new(AtomicU64::new(0));
243+ let src = CountedFile {
244+ inner: File::open(path).expect("open AVI"),
245+ bytes: bytes.clone(),
246+ };
247+ let mut reader = Reader::new(src, Some("avi")).expect("AVI opens");
248+ let audio = reader
249+ .default_stream(MediaType::Audio)
250+ .expect("AVI audio stream")
251+ .clone();
252+ let rate = audio.params.audio().unwrap().sample_rate.max(1);
253+ let channels = audio.params.audio().unwrap().layout.channel_count().max(1);
254+ let frame_samples = match audio.params.codec {
255+ CodecId::Ac3 | CodecId::EAc3 => 1536,
256+ CodecId::Mp3 => 1152,
257+ _ => 1,
258+ };
259+ let duration = reader.duration().expect("AVI duration").as_secs_f64();
260+ for fraction in [0.10, 0.50, 0.90] {
261+ let target = duration * fraction;
262+ let ticks = (target * f64::from(rate)) as i64;
263+ let before = bytes.load(Ordering::Relaxed);
264+ let started = Instant::now();
265+ let landed = reader
266+ .seek(
267+ audio.index,
268+ Timestamp::new(ticks, TimeBase::from_rate(rate)),
269+ SeekMode::SyncBefore,
270+ )
271+ .expect("AVI seek");
272+ let elapsed = started.elapsed();
273+ let read = bytes.load(Ordering::Relaxed) - before;
274+ let at = landed.as_secs_f64();
275+ let ours = decode_window(&mut reader, audio.index, 2.0).expect("decode after seek");
276+ let theirs = reference_seek_window(path, at);
277+ let (lag, score) = best_frame_corr(&ours, &theirs, channels, frame_samples);
278+ eprintln!(
279+ "{} @{:.0}%: target {target:.3}s landed {at:.3}s read {read} bytes seek {:?} lag {lag} frames corr {score:.6}",
280+ path.display(),
281+ fraction * 100.0,
282+ elapsed
283+ );
284+ assert!(
285+ read < 8 * 1024 * 1024,
286+ "{} @{fraction:.0}%: seek read {read} bytes",
287+ path.display()
288+ );
289+ if !cfg!(debug_assertions) {
290+ assert!(
291+ elapsed.as_millis() < 200,
292+ "{} @{:.0}%: seek took {:?}",
293+ path.display(),
294+ fraction * 100.0,
295+ elapsed
296+ );
297+ }
298+ assert!(
299+ score >= 0.999,
300+ "{} @{:.0}%: target {target:.3}s landed {at:.3}s lag {lag} frames corr vs reference decoder = {score}",
301+ path.display(),
302+ fraction * 100.0,
303+ );
304+ }
305+}
306+
307+fn synthetic_mp3_avi() -> Option<PathBuf> {
308+ if !Command::new("ffmpeg")
309+ .args(["-version"])
310+ .output()
311+ .is_ok_and(|out| out.status.success())
312+ {
313+ eprintln!("reference encoder/decoder absent, skipping synthetic AVI");
314+ return None;
315+ }
316+ let root = PathBuf::from(std::env::var_os("HOME").expect("HOME")).join(".cache/aviseek");
317+ std::fs::create_dir_all(&root).expect("create scratch directory");
318+ let path = root.join(format!("seek-oracle-{}.avi", std::process::id()));
319+ let out = Command::new("ffmpeg")
320+ .args([
321+ "-v",
322+ "error",
323+ "-f",
324+ "lavfi",
325+ "-i",
326+ "sine=frequency=997:sample_rate=48000:duration=30",
327+ "-c:a",
328+ "libmp3lame",
329+ "-f",
330+ "avi",
331+ "-y",
332+ ])
333+ .arg(&path)
334+ .output()
335+ .expect("reference encoder runs");
336+ assert!(
337+ out.status.success(),
338+ "{}",
339+ String::from_utf8_lossy(&out.stderr)
340+ );
341+ Some(path)
342+}
343+
243344 /// Ten files with sound, standalone audio first, then Matroska — opened,
244345 /// decoded and seeked, with a per-file row in the report.
245346 #[test]
@@ -460,78 +561,19 @@ fn avi_seek_matches_reference_decoder_on_real_files() {
460561 return;
461562 }
462563 for path in files {
463- let bytes = Arc::new(AtomicU64::new(0));
464- let src = CountedFile {
465- inner: File::open(&path).expect("open AVI"),
466- bytes: bytes.clone(),
467- };
468- let mut reader = Reader::new(src, Some("avi")).expect("AVI opens");
469- let audio = reader
470- .default_stream(MediaType::Audio)
471- .expect("AVI audio stream")
472- .clone();
473- let rate = audio.params.audio().unwrap().sample_rate.max(1);
474- let Some(duration) = reader.duration() else {
475- eprintln!(
476- "{}: no stated duration, skipping seek check",
477- path.display()
478- );
479- continue;
480- };
481- let duration = duration.as_secs_f64();
482- for fraction in [0.10, 0.50, 0.90] {
483- let target = duration * fraction;
484- let ticks = (target * f64::from(rate)) as i64;
485- let before = bytes.load(Ordering::Relaxed);
486- let started = Instant::now();
487- let landed = reader
488- .seek(
489- audio.index,
490- Timestamp::new(ticks, TimeBase::from_rate(rate)),
491- SeekMode::SyncBefore,
492- )
493- .expect("AVI seek");
494- let elapsed = started.elapsed();
495- let read = bytes.load(Ordering::Relaxed) - before;
496- let at = landed.as_secs_f64();
497- let channels = audio.params.audio().unwrap().layout.channel_count().max(1);
498- let mut ours = decode_window(&mut reader, audio.index, 2.25 + (target - at).max(0.0))
499- .expect("decode after seek");
500- let trim = ((target - at).max(0.0) * f64::from(rate) * channels as f64) as usize;
501- if trim < ours.len() {
502- ours.drain(..trim);
503- }
504- let score = 1.0;
505- eprintln!(
506- "{} @{:.0}%: target {target:.3}s landed {at:.3}s read {read} bytes seek {:?} corr {score:.6}",
507- path.display(),
508- fraction * 100.0,
509- elapsed
510- );
511- assert!(
512- read < 8 * 1024 * 1024,
513- "{} @{fraction:.0}%: seek read {read} bytes",
514- path.display()
515- );
516- if !cfg!(debug_assertions) {
517- assert!(
518- elapsed.as_millis() < 200,
519- "{} @{fraction:.0}%: seek took {:?}",
520- path.display(),
521- elapsed
522- );
523- }
524- assert!(
525- score >= 0.999,
526- "{} @{:.0}%: target {target:.3}s landed {at:.3}s read {read} bytes seek {:?} corr vs reference decoder = {score}",
527- path.display(),
528- fraction * 100.0,
529- elapsed
530- );
531- }
564+ assert_avi_seeks_match_reference(&path);
532565 }
533566 }
534567
568+#[test]
569+fn avi_seek_matches_reference_decoder_on_synthetic_mp3() {
570+ let Some(path) = synthetic_mp3_avi() else {
571+ return;
572+ };
573+ assert_avi_seeks_match_reference(&path);
574+ std::fs::remove_file(path).expect("remove synthetic AVI");
575+}
576+
535577 /// The TrueHD remux in his library: the track decodes through the unified
536578 /// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too.
537579 #[test]