forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

real_library.rs339 lines, 11.2 KiBHistoryRawDownload
1//! The personal media library, AV1 half: every `av1` row of
2//! `fixtures/real-library-manifest.tsv` is extracted as a low-overhead OBU
3//! stream, its first `FRAMES` shown pictures are decoded (film grain applied,
4//! as the decoder outputs it), and each frame is compared sample for sample with
5//! ffmpeg's `libdav1d` decoder at the same pixel format.
6//!
7//! Every file either decodes bit-exactly, is refused by name (a pixel format
8//! outside 4:2:0 8/10-bit, or a decoder refusal that says "unsupported", such as
9//! profile 1 or 2), or fails. A refusal is reported, not counted as a failure.
10//!
11//! LOCAL ONLY and ignored: the manifest is generated from the user's own media
12//! by `scripts/scan-real-library.sh` and is gitignored, so no other host has it.
13//! cargo test -p ec-av1 --test real_library -- --ignored --nocapture
14
15use std::io::Read;
16use std::path::{Path, PathBuf};
17use std::process::{Child, ChildStdout, Command, Stdio};
18
19use ec_av1::encode::Picture;
20
21/// Shown pictures compared per file.
22const FRAMES: usize = 300;
23
24/// Pixel formats inside the decoder's scope: 4:2:0 at 8 or 10 bits.
25const IN_SCOPE_PIX_FMTS: [&str; 2] = ["yuv420p", "yuv420p10le"];
26
27fn have_ffmpeg() -> bool {
28 Command::new("ffmpeg")
29 .arg("-version")
30 .stdout(Stdio::null())
31 .stderr(Stdio::null())
32 .status()
33 .is_ok_and(|s| s.success())
34}
35
36fn scratch(tag: &str) -> PathBuf {
37 let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
38 let dir = base.join(format!("ec-av1-{tag}-{}", std::process::id()));
39 std::fs::create_dir_all(&dir).expect("scratch dir");
40 dir
41}
42
43/// One manifest row: the columns the sweep reads.
44struct Entry {
45 path: PathBuf,
46 container: String,
47 width: String,
48 height: String,
49 pix_fmt: String,
50}
51
52fn manifest_av1_entries() -> Vec<Entry> {
53 let manifest =
54 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
55 let text = std::fs::read_to_string(&manifest).unwrap_or_else(|e| {
56 panic!(
57 "{}: {e}. This test sweeps the personal library; generate the manifest with \
58 scripts/scan-real-library.sh on the machine that holds the media.",
59 manifest.display()
60 )
61 });
62 let mut out = Vec::new();
63 for line in text.lines().skip(1) {
64 let f: Vec<&str> = line.split('\t').collect();
65 if f.len() < 6 || f[2] != "av1" || !Path::new(f[0]).is_file() {
66 continue;
67 }
68 out.push(Entry {
69 path: PathBuf::from(f[0]),
70 container: f[1].to_string(),
71 width: f[3].to_string(),
72 height: f[4].to_string(),
73 pix_fmt: f[5].to_string(),
74 });
75 }
76 out
77}
78
79/// The planes of a picture as the bytes of a planar rawvideo frame: one byte per
80/// sample at 8 bits, little-endian u16 above.
81fn frame_bytes(pic: &Picture, bps: usize) -> Vec<u8> {
82 let mut out = Vec::with_capacity((pic.y.len() + pic.u.len() + pic.v.len()) * bps);
83 for plane in [&pic.y, &pic.u, &pic.v] {
84 for &s in plane.iter() {
85 if bps == 1 {
86 out.push(s as u8);
87 } else {
88 out.extend_from_slice(&s.to_le_bytes());
89 }
90 }
91 }
92 out
93}
94
95/// Where byte `offset` of a frame lies: plane name, x and y in that plane.
96fn locate(offset: usize, bps: usize, pic: &Picture) -> (&'static str, usize, usize) {
97 let s = offset / bps;
98 let (w, cw) = (pic.width, pic.u.len() / pic.height.div_ceil(2).max(1));
99 let luma = pic.y.len();
100 if s < luma {
101 ("Y", s % w, s / w)
102 } else if s < luma + pic.u.len() {
103 let c = s - luma;
104 ("U", c % cw.max(1), c / cw.max(1))
105 } else {
106 let c = s - luma - pic.u.len();
107 ("V", c % cw.max(1), c / cw.max(1))
108 }
109}
110
111/// Running comparison of decoded frames against the oracle's rawvideo stream.
112struct Sweep {
113 out: ChildStdout,
114 child: Child,
115 open: bool,
116 compared: usize,
117 differing_frames: usize,
118 first_diff: Option<String>,
119 oracle_short: bool,
120 index: usize,
121 frame_len: usize,
122 bps: usize,
123 max_sample: u16,
124}
125
126impl Sweep {
127 fn take(&mut self, pic: &Picture) {
128 let index = self.index;
129 self.index += 1;
130 if !self.open || self.index > FRAMES {
131 return;
132 }
133 if let Some(&s) = pic.y.iter().chain(&pic.u).chain(&pic.v).max()
134 && s > self.max_sample
135 {
136 self.differing_frames += 1;
137 self.first_diff.get_or_insert(format!(
138 "frame {index}: sample {s} above the maximum {}",
139 self.max_sample
140 ));
141 }
142 let want = frame_bytes(pic, self.bps);
143 self.frame_len = want.len();
144 let mut oracle = vec![0u8; want.len()];
145 if self.out.read_exact(&mut oracle).is_err() {
146 self.open = false;
147 self.oracle_short = true;
148 return;
149 }
150 self.compared += 1;
151 if want != oracle {
152 self.differing_frames += 1;
153 if self.first_diff.is_none() {
154 let at = want
155 .iter()
156 .zip(&oracle)
157 .position(|(a, b)| a != b)
158 .unwrap_or(0);
159 let (plane, x, y) = locate(at, self.bps, pic);
160 self.first_diff = Some(format!("frame {index} plane {plane} x={x} y={y}"));
161 }
162 }
163 }
164
165 fn finish(mut self) -> Sweep {
166 if self.open && self.frame_len > 0 {
167 let mut probe = vec![0u8; self.frame_len];
168 if self.out.read_exact(&mut probe).is_ok() {
169 self.first_diff.get_or_insert(format!(
170 "decoder produced {} frames, ffmpeg produced more",
171 self.index
172 ));
173 self.differing_frames += 1;
174 }
175 }
176 let _ = self.child.kill();
177 let _ = self.child.wait();
178 self
179 }
180}
181
182fn short_name(path: &Path) -> String {
183 path.file_name()
184 .map(|n| n.to_string_lossy().chars().take(38).collect())
185 .unwrap_or_default()
186}
187
188/// Extracts the first `FRAMES` pictures of the video as a low-overhead OBU stream.
189fn extract(src: &Path, dst: &Path) -> bool {
190 Command::new("ffmpeg")
191 .args(["-v", "error", "-y", "-i"])
192 .arg(src)
193 .args([
194 "-map",
195 "0:v:0",
196 "-c",
197 "copy",
198 "-frames:v",
199 &FRAMES.to_string(),
200 "-f",
201 "obu",
202 ])
203 .arg(dst)
204 .status()
205 .is_ok_and(|s| s.success())
206}
207
208/// Decodes one OBU stream and compares it with ffmpeg's libdav1d output.
209fn sweep_file(es: &Path, pix_fmt: &str, bit_depth: u32) -> Result<Sweep, String> {
210 let bps = if bit_depth > 8 { 2 } else { 1 };
211 let mut child = Command::new("ffmpeg")
212 .args(["-v", "error", "-c:v", "libdav1d", "-i"])
213 .arg(es)
214 .args([
215 "-frames:v",
216 &FRAMES.to_string(),
217 "-f",
218 "rawvideo",
219 "-pix_fmt",
220 pix_fmt,
221 "-",
222 ])
223 .stdout(Stdio::piped())
224 .stderr(Stdio::null())
225 .spawn()
226 .map_err(|e| e.to_string())?;
227 let out = child.stdout.take().expect("piped stdout");
228 let mut sweep = Sweep {
229 out,
230 child,
231 open: true,
232 compared: 0,
233 differing_frames: 0,
234 first_diff: None,
235 oracle_short: false,
236 index: 0,
237 frame_len: 0,
238 bps,
239 max_sample: ((1u32 << bit_depth) - 1) as u16,
240 };
241 let data = std::fs::read(es).map_err(|e| e.to_string())?;
242 let result = ec_av1::stream::decode_stream_with(&data, |pic, _decode_index, shown| {
243 if shown {
244 sweep.take(pic);
245 }
246 Ok(())
247 });
248 let sweep = sweep.finish();
249 if let Err(e) = result {
250 return Err(format!("{e}"));
251 }
252 Ok(sweep)
253}
254
255#[test]
256#[ignore = "sweeps the PERSONAL media library (fixtures/real-library-manifest.tsv, av1 rows) through ffmpeg/libdav1d; minutes of wall time. Local only: run with --ignored."]
257fn real_library_av1_streams_match_ffmpeg() {
258 assert!(have_ffmpeg(), "ffmpeg is required to sweep the library");
259 let entries = manifest_av1_entries();
260 assert!(!entries.is_empty(), "the manifest lists no av1 rows");
261 let dir = scratch("real-library-av1");
262 let mut table = String::new();
263 let mut decoded = 0usize;
264 let mut refused = 0usize;
265 let mut failures = Vec::new();
266
267 for entry in &entries {
268 let name = short_name(&entry.path);
269 let res = format!("{}x{}", entry.width, entry.height);
270 let bit_depth: u32 = if entry.pix_fmt == "yuv420p10le" {
271 10
272 } else {
273 8
274 };
275 if !IN_SCOPE_PIX_FMTS.contains(&entry.pix_fmt.as_str()) {
276 refused += 1;
277 table.push_str(&format!(
278 "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: pixel format {} is outside 4:2:0 8/10-bit\n",
279 entry.container, "-", entry.pix_fmt
280 ));
281 continue;
282 }
283 let es = dir.join("stream.obu");
284 if !extract(&entry.path, &es) {
285 failures.push(format!("{name}: extraction failed"));
286 table.push_str(&format!(
287 "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR extraction\n",
288 entry.container, "-"
289 ));
290 continue;
291 }
292 match sweep_file(&es, &entry.pix_fmt, bit_depth) {
293 Ok(s) if s.differing_frames > 0 => {
294 failures.push(format!("{name}: {} frames differ", s.differing_frames));
295 table.push_str(&format!(
296 "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} MISMATCH {} of {} frames; first: {}\n",
297 entry.container, s.compared, s.differing_frames, s.compared,
298 s.first_diff.clone().unwrap_or_default()
299 ));
300 }
301 Ok(s) => {
302 decoded += 1;
303 table.push_str(&format!(
304 "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} bit-exact{}\n",
305 entry.container,
306 s.compared,
307 if s.oracle_short {
308 " (ffmpeg stopped early)"
309 } else {
310 ""
311 }
312 ));
313 }
314 Err(e) if e.contains("unsupported") => {
315 refused += 1;
316 table.push_str(&format!(
317 "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: {e}\n",
318 entry.container, "-"
319 ));
320 }
321 Err(e) => {
322 failures.push(format!("{name}: {e}"));
323 table.push_str(&format!(
324 "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR {e}\n",
325 entry.container, "-"
326 ));
327 }
328 }
329 let _ = std::fs::remove_file(&es);
330 }
331 let _ = std::fs::remove_dir_all(&dir);
332 eprintln!("{table}");
333 eprintln!(
334 "real library av1: {decoded} bit-exact, {refused} refused by name, {} failed",
335 failures.len()
336 );
337 assert!(failures.is_empty(), "{failures:#?}");
338 assert!(decoded >= 1, "no real AV1 file was swept end to end");
339}