forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

grain_seek.rs112 lines, 4.2 KiBHistoryRawDownload
1//! Frame-accurate seeking on `test_av1_grain.mkv` (AV1 in Matroska, film grain,
2//! keyframes every 30 frames). The source carries its own timecode burned into
3//! the top-left corner, so a composed frame names the source frame it shows by
4//! that text: `compose_at(f)` must show source frame `f`.
5//!
6//! Was failing: a hardware AV1 open at a mid-stream frame of this file showed a
7//! later source frame (`compose_at(30)` showed source 60). The cause was in the
8//! VA-API plugin, not the seek: AV1 is decoded one OBU per call, and the plugin
9//! dropped the rest of each temporal unit on the Annex-B start-code rule, so no
10//! keyframe was ever decoded and every seek drifted by a GOP. Fixed in
11//! `crates/engine-hw`; the sequential and software paths are unchanged.
12//!
13//! ```text
14//! cargo test -p engine --release --test grain_seek -- --nocapture
15//! ```
16
17use std::path::PathBuf;
18use std::process::Command;
19
20use engine::PlaybackSession;
21
22fn asset(name: &str) -> PathBuf {
23 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
24 .join("../../assets")
25 .join(name)
26}
27
28const W: u32 = 1280;
29const H: u32 = 720;
30/// The timecode box, top-left, in full-size pixels.
31const CW: u32 = 200;
32const CH: u32 = 28;
33const CROP: usize = (CW * CH * 4) as usize;
34
35/// The top-left timecode crop of a full-size BGRA frame, row by row.
36fn crop(full: &[u8], width: u32) -> Vec<f64> {
37 let mut out = Vec::with_capacity(CROP);
38 for y in 0..CH {
39 let row = (y * width * 4) as usize;
40 out.extend(full[row..row + (CW * 4) as usize].iter().map(|b| f64::from(*b)));
41 }
42 out
43}
44
45/// `1 - r` of two crops, `r` their Pearson correlation. Lower is a better match.
46fn distance(a: &[f64], b: &[f64]) -> f64 {
47 let n = a.len() as f64;
48 let (ma, mb) = (a.iter().sum::<f64>() / n, b.iter().sum::<f64>() / n);
49 let (mut sab, mut saa, mut sbb) = (0.0, 0.0, 0.0);
50 for (x, y) in a.iter().zip(b) {
51 sab += (x - ma) * (y - mb);
52 saa += (x - ma) * (x - ma);
53 sbb += (y - mb) * (y - mb);
54 }
55 1.0 - sab / (saa * sbb).sqrt().max(1e-9)
56}
57
58/// The source frame each timeline frame shows, by its timecode crop against an
59/// ffmpeg decode of the same file.
60fn shown_source_frames(session: &PlaybackSession, file: &PathBuf, timeline: &[u32]) -> Vec<(u32, usize, f64)> {
61 let refs_path = std::env::temp_dir().join(format!("grain_ref_{}.bgra", std::process::id()));
62 let status = Command::new("ffmpeg")
63 .args(["-v", "error", "-y", "-i"])
64 .arg(file)
65 .args(["-vf", &format!("crop={CW}:{CH}:0:0"), "-pix_fmt", "bgra", "-f", "rawvideo"])
66 .arg(&refs_path)
67 .status()
68 .expect("ffmpeg on PATH");
69 assert!(status.success(), "ffmpeg reference decode failed");
70 let raw = std::fs::read(&refs_path).expect("read the reference");
71 let _ = std::fs::remove_file(&refs_path);
72 let refs: Vec<Vec<f64>> = raw
73 .as_chunks::<CROP>().0.iter()
74 .map(|c| c.iter().map(|b| f64::from(*b)).collect())
75 .collect();
76
77 timeline
78 .iter()
79 .map(|&f| {
80 let full = session.compose_at(f, W, H).expect("compose");
81 let got = crop(&full.bgra, full.width);
82 let (best, dist) = refs
83 .iter()
84 .enumerate()
85 .map(|(r, c)| (r, distance(&got, c)))
86 .fold((0, f64::MAX), |acc, x| if x.1 < acc.1 { x } else { acc });
87 (f, best, dist)
88 })
89 .collect()
90}
91
92#[test]
93fn composed_frames_show_the_source_frame_they_name() {
94 engine::ao::set_silent_output();
95 let file = asset("test_av1_grain.mkv");
96 let session = PlaybackSession::open(&file).expect("open the grain fixture");
97 let len = (session.timeline_duration() * 30.0).round() as u32;
98 let frames: Vec<u32> = [0u32, 1, 15, 29, 30, 31, 45, 59, 60, 61, 75]
99 .into_iter()
100 .filter(|f| *f < len)
101 .collect();
102 let mut report = String::new();
103 let mut misses = Vec::new();
104 for (f, best, dist) in shown_source_frames(&session, &file, &frames) {
105 report.push_str(&format!("frame {f:>3}: shows source {best:>3} (1-r {dist:.4})\n"));
106 if best != f as usize {
107 misses.push(f);
108 }
109 }
110 println!("{report}");
111 assert!(misses.is_empty(), "composed frames show the wrong source frame:\n{report}");
112}