forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

aom_conformance.rs452 lines, 16.8 KiBHistoryRawDownload
1//! Conformance against the libaom AV1 test vectors (profile 0, 8 and 10 bit).
2//!
3//! The vectors are the `av1-1-b8-*` and `av1-1-b10-*` files listed in libaom's
4//! `test/test_vectors.cc`, fetched from the `aom-test-data` bucket into the
5//! directory named by `EC_AV1_AOM_DIR`. Each `<name>.ivf` (or `.mkv`) comes with a
6//! `<name>.md5` file: one line per SHOWN frame, `md5 <name>-WxH-NNNN.i420`.
7//! The digest covers the cropped planes (Y, then U, then V; chroma `(w+1)/2` by
8//! `(h+1)/2`; Y only for monochrome) and, above 8 bits, each sample is two
9//! little-endian bytes (libaom `test/md5_helper.h`, as used by
10//! `test/test_vector_test.cc`).
11//!
12//! The test decodes every vector, digests every shown picture and compares the
13//! digest with the matching line, in order. A vector is one of three things:
14//!
15//! - exact: every shown frame matches and the frame counts agree;
16//! - refused by name: the stream is outside DONE.md's scope (profiles 1 and 2,
17//! that is 4:4:4, 4:2:2 and 12-bit) or the decoder names the feature as
18//! unsupported; the reason is printed and it is not a failure;
19//! - failed: a digest differs, the frame counts differ, or the decoder errors or
20//! panics without naming an unsupported feature. The first mismatching frame
21//! is listed by vector name.
22//!
23//! Without `EC_AV1_AOM_DIR` the test uses `fixtures/av1-aom` if present, else skips loudly. With `EC_REQUIRE_FIXTURES`
24//! set, a missing directory is a failure.
25
26use ec_av1::stream::decode_stream_with;
27use ec_av1_syntax::Av1Parser;
28use std::path::PathBuf;
29
30/// Environment variable naming the directory of fetched vectors and md5 files.
31const DIR_VAR: &str = "EC_AV1_AOM_DIR";
32
33// ------------------------------------------------------------------ MD5 ----
34
35/// RFC 1321 MD5 of `data`, as lowercase hex.
36fn md5_hex(data: &[u8]) -> String {
37 const S: [u32; 64] = [
38 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20,
39 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
40 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
41 ];
42 let k: Vec<u32> = (0..64)
43 .map(|i| ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32)
44 .collect();
45 let mut a0: u32 = 0x6745_2301;
46 let mut b0: u32 = 0xefcd_ab89;
47 let mut c0: u32 = 0x98ba_dcfe;
48 let mut d0: u32 = 0x1032_5476;
49
50 let mut msg = data.to_vec();
51 let bit_len = (data.len() as u64).wrapping_mul(8);
52 msg.push(0x80);
53 while msg.len() % 64 != 56 {
54 msg.push(0);
55 }
56 msg.extend_from_slice(&bit_len.to_le_bytes());
57
58 for block in msg.as_chunks::<64>().0 {
59 let m: Vec<u32> = block
60 .as_chunks::<4>()
61 .0
62 .iter()
63 .map(|w| u32::from_le_bytes(*w))
64 .collect();
65 let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
66 for i in 0..64 {
67 let (f, g) = match i / 16 {
68 0 => ((b & c) | (!b & d), i),
69 1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
70 2 => (b ^ c ^ d, (3 * i + 5) % 16),
71 _ => (c ^ (b | !d), (7 * i) % 16),
72 };
73 let f = f.wrapping_add(a).wrapping_add(k[i]).wrapping_add(m[g]);
74 a = d;
75 d = c;
76 c = b;
77 b = b.wrapping_add(f.rotate_left(S[i]));
78 }
79 a0 = a0.wrapping_add(a);
80 b0 = b0.wrapping_add(b);
81 c0 = c0.wrapping_add(c);
82 d0 = d0.wrapping_add(d);
83 }
84 [a0, b0, c0, d0]
85 .iter()
86 .flat_map(|w| w.to_le_bytes())
87 .map(|byte| format!("{byte:02x}"))
88 .collect()
89}
90
91/// libaom `md5_helper.h` digest of one picture's cropped planes. A monochrome
92/// picture is digested as libaom's output has it: the luma plane, then two 4:2:0
93/// chroma planes of mid-grey (`1 << (bit_depth - 1)`).
94fn picture_md5(pic: &ec_av1::encode::Picture, bit_depth: u8, mono: bool) -> String {
95 let wide = bit_depth > 8;
96 let chroma_len = pic.width.div_ceil(2) * pic.height.div_ceil(2);
97 let grey = vec![1u16 << (bit_depth - 1); chroma_len];
98 let planes: [&[u16]; 3] = if mono {
99 [&pic.y, &grey, &grey]
100 } else {
101 [&pic.y, &pic.u, &pic.v]
102 };
103 let mut buf = Vec::with_capacity(planes.iter().map(|p| p.len()).sum::<usize>() * 2);
104 for plane in planes {
105 for &s in plane.iter() {
106 if wide {
107 buf.extend_from_slice(&s.to_le_bytes());
108 } else {
109 buf.push(s as u8);
110 }
111 }
112 }
113 md5_hex(&buf)
114}
115
116// --------------------------------------------------------- containers ----
117
118/// Frame payloads of an IVF file (DKIF, 32-byte file header).
119fn ivf_frames(data: &[u8]) -> Result<Vec<&[u8]>, String> {
120 if data.len() < 32 || &data[0..4] != b"DKIF" {
121 return Err("not an IVF file".into());
122 }
123 let hdr_len = u16::from_le_bytes([data[6], data[7]]) as usize;
124 let mut pos = hdr_len;
125 let mut out = Vec::new();
126 while pos + 12 <= data.len() {
127 let sz = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
128 pos += 12;
129 let end = pos
130 .checked_add(sz)
131 .filter(|&e| e <= data.len())
132 .ok_or("truncated IVF frame")?;
133 out.push(&data[pos..end]);
134 pos = end;
135 }
136 Ok(out)
137}
138
139/// Read an EBML variable-length integer at `pos`. Returns `(value, length)`;
140/// `keep_marker` keeps the length marker bit (element IDs) and clears it for
141/// sizes. An all-ones size (unknown) comes back as `u64::MAX`.
142fn ebml_vint(data: &[u8], pos: usize, keep_marker: bool) -> Result<(u64, usize), String> {
143 let first = *data.get(pos).ok_or("EBML truncated")?;
144 if first == 0 {
145 return Err("EBML vint with no marker".into());
146 }
147 let len = first.leading_zeros() as usize + 1;
148 let bytes = data.get(pos..pos + len).ok_or("EBML truncated")?;
149 let mut v = if keep_marker {
150 bytes[0] as u64
151 } else {
152 (bytes[0] as u64) & ((1u64 << (8 - len)) - 1)
153 };
154 for &b in &bytes[1..] {
155 v = (v << 8) | b as u64;
156 }
157 if !keep_marker && v == (1u64 << (7 * len)) - 1 {
158 return Ok((u64::MAX, len));
159 }
160 Ok((v, len))
161}
162
163/// Video frame payloads of a Matroska file. A flat walk: Segment, Cluster and
164/// BlockGroup are entered, SimpleBlock and Block carry one frame each, and
165/// everything else is skipped. Laced blocks are refused. The libaom `.mkv`
166/// vectors have one video track and no lacing.
167fn mkv_frames(data: &[u8]) -> Result<Vec<&[u8]>, String> {
168 const SEGMENT: u64 = 0x1853_8067;
169 const CLUSTER: u64 = 0x1F43_B675;
170 const BLOCK_GROUP: u64 = 0xA0;
171 const BLOCK: u64 = 0xA1;
172 const SIMPLE_BLOCK: u64 = 0xA3;
173
174 let mut out = Vec::new();
175 let mut pos = 0usize;
176 while pos < data.len() {
177 let (id, id_len) = ebml_vint(data, pos, true)?;
178 let (size, size_len) = ebml_vint(data, pos + id_len, false)?;
179 let body = pos + id_len + size_len;
180 match id {
181 SEGMENT | CLUSTER | BLOCK_GROUP => {
182 pos = body;
183 continue;
184 }
185 BLOCK | SIMPLE_BLOCK => {
186 let end = body
187 .checked_add(size as usize)
188 .filter(|&e| e <= data.len())
189 .ok_or("Matroska block runs past the file")?;
190 let (_track, tlen) = ebml_vint(data, body, false)?;
191 let header = body + tlen + 3; // 16-bit timecode + flags
192 let flags = *data
193 .get(body + tlen + 2)
194 .ok_or("Matroska block without flags")?;
195 if (flags >> 1) & 3 != 0 {
196 return Err("laced Matroska block (not produced by libaom)".into());
197 }
198 out.push(&data[header.min(end)..end]);
199 pos = end;
200 }
201 _ => {
202 if size == u64::MAX {
203 return Err("unknown-size non-master element".into());
204 }
205 pos = body
206 .checked_add(size as usize)
207 .ok_or("Matroska element size overflow")?;
208 }
209 }
210 }
211 Ok(out)
212}
213
214// ------------------------------------------------------------- driver ----
215
216/// Vectors the decoder does not yet match, with the cause. The test passes when
217/// exactly these diverge; a vector that starts matching must leave this list.
218/// Empty: every vector in the set is bit-exact (242/242).
219const KNOWN_FAILING: &[(&str, &str)] = &[];
220
221/// What became of one vector.
222enum Outcome {
223 /// Every shown frame matched and the counts agree.
224 Exact { frames: usize },
225 /// Outside DONE.md's scope, or the decoder named the feature unsupported.
226 Refused(String),
227 /// At least one difference; each string names the vector and the frame.
228 Failed(Vec<String>),
229}
230
231/// Profile and chroma format of a vector, read from its first sequence header.
232struct Format {
233 profile: u8,
234 bit_depth: u8,
235 mono: bool,
236 subsampling: (u8, u8),
237}
238
239fn stream_format(stream: &[u8]) -> Option<Format> {
240 let mut parser = Av1Parser::new();
241 let mut pos = 0usize;
242 while pos < stream.len() && parser.sequence_header().is_none() {
243 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
244 break;
245 };
246 pos += obu.total_size.max(1);
247 }
248 let seq = parser.sequence_header()?;
249 let cc = &seq.color_config;
250 Some(Format {
251 profile: seq.seq_profile,
252 bit_depth: cc.bit_depth,
253 mono: cc.mono_chrome,
254 subsampling: (cc.subsampling_x, cc.subsampling_y),
255 })
256}
257
258/// Decode one vector's frames as one OBU stream and compare every shown
259/// picture with the matching md5 line.
260fn check_vector(name: &str, frames: &[&[u8]], expected: &[String]) -> Outcome {
261 // The IVF or Matroska payloads are temporal units of low-overhead OBUs, so
262 // their concatenation is the raw OBU stream the decoder takes.
263 let stream: Vec<u8> = frames.iter().flat_map(|f| f.iter().copied()).collect();
264 let Some(fmt) = stream_format(&stream) else {
265 return Outcome::Failed(vec![format!("{name}: no sequence header in the stream")]);
266 };
267 // DONE.md freezes profiles 1 and 2 (4:4:4, 4:2:2, 12-bit). Refused by name.
268 let frozen = if fmt.profile != 0 {
269 Some(format!("seq_profile {}", fmt.profile))
270 } else if fmt.bit_depth > 10 {
271 Some(format!("{}-bit", fmt.bit_depth))
272 } else if !fmt.mono && fmt.subsampling != (1, 1) {
273 Some(format!("subsampling {}/{}", fmt.subsampling.0, fmt.subsampling.1))
274 } else {
275 None
276 };
277 if let Some(what) = frozen {
278 return Outcome::Refused(format!(
279 "{name}: {what} is Frozen by DONE.md (4:4:4, 4:2:2, 12-bit)"
280 ));
281 }
282 let mut problems = Vec::new();
283 let mut shown = 0usize;
284 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
285 decode_stream_with(&stream, |pic, _decode_idx, is_shown| {
286 if !is_shown {
287 return Ok(());
288 }
289 match expected.get(shown) {
290 None => problems.push(format!("{name}: extra shown frame {shown}")),
291 Some(want) => {
292 let got = picture_md5(pic, fmt.bit_depth, fmt.mono);
293 if &got != want {
294 problems.push(format!(
295 "{name}: first mismatch at frame {shown} ({}x{}): md5 {got} != {want}",
296 pic.width, pic.height
297 ));
298 }
299 }
300 }
301 shown += 1;
302 Ok(())
303 })
304 }));
305 match result {
306 Err(e) => {
307 let msg = e
308 .downcast_ref::<String>()
309 .cloned()
310 .or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string()))
311 .unwrap_or_default();
312 problems.push(format!("{name}: decoder panicked after {shown} frames: {msg}"));
313 }
314 Ok(Err(ec_core::Error::Unsupported { what, why })) => {
315 if problems.is_empty() {
316 return Outcome::Refused(format!("{name}: unsupported {what}: {why}"));
317 }
318 problems.push(format!("{name}: refused after {shown} frames: {what}: {why}"));
319 }
320 Ok(Err(e)) => problems.push(format!("{name}: decode error at frame {shown}: {e}")),
321 Ok(Ok(())) => {}
322 }
323 if problems.is_empty() && shown != expected.len() {
324 problems.push(format!(
325 "{name}: decoded {shown} shown frames, md5 file lists {}",
326 expected.len()
327 ));
328 }
329 if problems.is_empty() {
330 Outcome::Exact { frames: shown }
331 } else {
332 Outcome::Failed(problems)
333 }
334}
335
336/// `EC_AV1_AOM_DIR`, else the workspace's `fixtures/av1-aom` when it exists.
337fn vector_dir() -> Option<PathBuf> {
338 std::env::var_os(DIR_VAR).map(PathBuf::from).or_else(|| {
339 let local = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/av1-aom");
340 local.is_dir().then_some(local)
341 })
342}
343
344#[test]
345fn aom_vectors_match_per_frame_md5() {
346 let require = std::env::var_os("EC_REQUIRE_FIXTURES").is_some();
347 let Some(dir) = vector_dir() else {
348 assert!(!require, "EC_REQUIRE_FIXTURES=1 but {DIR_VAR} is not set and fixtures/av1-aom is missing");
349 eprintln!("SKIP aom_conformance: {DIR_VAR} is not set (libaom av1-1-b8/b10 vectors)");
350 return;
351 };
352 let entries = match std::fs::read_dir(&dir) {
353 Ok(e) => e,
354 Err(e) => {
355 assert!(!require, "EC_REQUIRE_FIXTURES=1 but {}: {e}", dir.display());
356 eprintln!("SKIP aom_conformance: {}: {e}", dir.display());
357 return;
358 }
359 };
360 let mut md5_files: Vec<PathBuf> = entries
361 .filter_map(|e| e.ok().map(|e| e.path()))
362 .filter(|p| p.extension().is_some_and(|x| x == "md5"))
363 .filter(|p| {
364 let n = p.file_name().unwrap_or_default().to_string_lossy();
365 n.starts_with("av1-1-b8-") || n.starts_with("av1-1-b10-")
366 })
367 .collect();
368 md5_files.sort();
369 if md5_files.is_empty() {
370 assert!(!require, "EC_REQUIRE_FIXTURES=1 but no av1-1-b* .md5 files in {}", dir.display());
371 eprintln!("SKIP aom_conformance: no av1-1-b* .md5 files in {}", dir.display());
372 return;
373 }
374
375 let mut exact = Vec::new();
376 let mut refused = Vec::new();
377 let mut known_failing = Vec::new();
378 let mut failed: Vec<String> = Vec::new();
379 let mut frames_total = 0usize;
380 for md5_path in &md5_files {
381 let name = md5_path
382 .file_name()
383 .unwrap_or_default()
384 .to_string_lossy()
385 .trim_end_matches(".md5")
386 .to_string();
387 let vec_path = dir.join(&name);
388 let data = match std::fs::read(&vec_path) {
389 Ok(d) => d,
390 Err(e) => {
391 failed.push(format!("{name}: cannot read vector: {e}"));
392 continue;
393 }
394 };
395 let frames = if name.ends_with(".mkv") {
396 mkv_frames(&data)
397 } else {
398 ivf_frames(&data)
399 };
400 let frames = match frames {
401 Ok(f) => f,
402 Err(e) => {
403 failed.push(format!("{name}: container: {e}"));
404 continue;
405 }
406 };
407 let text = std::fs::read_to_string(md5_path).expect("md5 file is UTF-8");
408 let expected: Vec<String> = text
409 .lines()
410 .filter_map(|l| l.split_whitespace().next().map(str::to_string))
411 .collect();
412 // A decoder panic is caught inside check_vector; anything else here is a
413 // harness bug and fails the run loudly.
414 let known = KNOWN_FAILING.iter().find(|(n, _)| *n == name);
415 match (check_vector(&name, &frames, &expected), known) {
416 (Outcome::Exact { frames }, None) => {
417 frames_total += frames;
418 exact.push(name.clone());
419 }
420 (Outcome::Exact { .. }, Some(_)) => {
421 failed.push(format!("{name}: now exact; remove it from KNOWN_FAILING"));
422 }
423 (Outcome::Refused(why), _) => {
424 eprintln!("REFUSED {why}");
425 refused.push(name.clone());
426 }
427 (Outcome::Failed(problems), Some(_)) => {
428 eprintln!("KNOWN FAILING {name}: {}", problems[0]);
429 known_failing.push(name.clone());
430 }
431 (Outcome::Failed(problems), None) => {
432 eprintln!("FAILED {name}: {}", problems[0]);
433 failed.extend(problems);
434 }
435 }
436 }
437 let total = md5_files.len();
438 eprintln!(
439 "aom vectors: {}/{total} exact ({frames_total} shown frames), {} refused by name, \
440 {} known failing, {} failed",
441 exact.len(),
442 refused.len(),
443 known_failing.len(),
444 failed.len()
445 );
446 assert!(
447 failed.is_empty(),
448 "{} problems:\n{}",
449 failed.len(),
450 failed.join("\n")
451 );
452}