forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

t02.rs4341 lines, 213.7 KiBHistoryRawDownload
1use super::*;
2use super::support::*;
3use super::gates_a::*;
4use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
5use crate::probe::run_with_stdin;
6use std::process::{Command, Stdio};
7
8 /// lane-av1oracledepth: the depth-generic 4:4:4 oracle comparator, armed
9 /// on the same pinned 10-bit 4:4:4 cell
10 /// `a_444_lossy_palette_chroma_unit_window_is_byte_exact_at_352x242_10bit`
11 /// gates (fixture sha256
12 /// `84df2f37cc7982f9a572443d85dfcc13bf366a64f3fb567391dcd5acd58a0ad2`):
13 /// every plane of every SHOWN frame must come back byte-exact against
14 /// ffmpeg's `yuv444p10le` rawvideo of the same bytes, with the depth read
15 /// from the stream's own sequence header, never assumed.
16 ///
17 /// The flip control is the crate's own comparator-liveness shape (the
18 /// same one
19 /// [`every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg`] runs for
20 /// the other helpers): with a thread-local ffmpeg shim that rotates ONE
21 /// byte of the oracle's own rawvideo stdout, the compare must move from
22 /// 0 to EXACTLY 1 differing sample in the tampered plane and stay at 0 in
23 /// the other two -- a comparator that cannot see a one-sample difference
24 /// would make every "byte-exact" claim above vacuous.
25 #[test]
26 fn the_444_depth_helper_is_byte_exact_on_a_pinned_10bit_444_cell() {
27 const NAME: &str = "the_444_depth_helper_is_byte_exact_on_a_pinned_10bit_444_cell";
28 if !have_ffmpeg() {
29 eprintln!("SKIP {NAME}: no ffmpeg");
30 return;
31 }
32 let _gate_lock = lock_gate_counters();
33 let path = crate_pin("444_lossy_palette_chroma_352x242_10b.obu");
34 let stream = read_pin(&path, 24875, 0x7fda_dbb4_3bbf_9af3, NAME);
35 // The fixture is 16 SHOWN frames; ffmpeg's rawvideo muxer emits shown
36 // frames only, and so does decode_stream's return.
37 const W: usize = 352;
38 const H: usize = 242;
39 const FRAMES: usize = 16;
40 assert_eq!(stream_bit_depth(&stream, NAME), 10, "{NAME}: pin depth");
41 let ours = decode_stream(&stream)
42 .unwrap_or_else(|e| panic!("{NAME}: the pinned 10-bit 4:4:4 cell was refused: {e}"));
43 assert_eq!(ours.len(), FRAMES, "{NAME}: decoded frame count");
44 let theirs = ffmpeg_decode_sequence_444_depth(&stream, W, H, FRAMES, 10, "yuv444p10le");
45 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
46 for (plane, x, y) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
47 if let Some(at) = x.iter().zip(y).position(|(p, q)| p != q) {
48 panic!(
49 "{NAME}: {plane} differs from ffmpeg's yuv444p10le at frame {i} sample \
50 {at} (ours {} vs {}); {n} of {m} samples differ",
51 x[at],
52 y[at],
53 n = x.iter().zip(y).filter(|(p, q)| p != q).count(),
54 m = x.len()
55 );
56 }
57 }
58 }
59 eprintln!(
60 "{NAME}: {FRAMES} shown frames byte-exact vs ffmpeg yuv444p10le on the pinned \
61 10-bit 4:4:4 cell"
62 );
63
64 // ---- the flip control: one wrong oracle sample must move the count
65 // 0 -> 1 in exactly the tampered plane -------------------------
66 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
67 let _ = std::fs::remove_dir_all(&dir);
68 std::fs::create_dir_all(&dir).expect("scratch dir");
69 let real = if let Some(p) = std::env::var_os("EC_AV1_FFMPEG") {
70 std::path::PathBuf::from(p)
71 } else {
72 let found = Command::new("ffmpeg")
73 .arg("-version")
74 .stdout(Stdio::null())
75 .stderr(Stdio::null())
76 .status()
77 .is_ok_and(|s| s.success());
78 assert!(found, "{NAME}: no working ffmpeg on PATH to wrap");
79 let path_env = std::env::var_os("PATH").unwrap_or_default();
80 std::env::split_paths(&path_env)
81 .map(|d| d.join("ffmpeg"))
82 .find(|p| p.is_file())
83 .expect("{NAME}: ffmpeg is on PATH but not resolvable to a file")
84 };
85 std::fs::write(dir.join("real-ffmpeg"), real.as_os_str().as_encoded_bytes())
86 .expect("recording the real ffmpeg's path for the shim");
87 let script = r#"#!/bin/sh
88REAL=$(cat "$(dirname "$0")/real-ffmpeg")
89OUT=$(mktemp)
90"$REAL" "$@" > "$OUT" || exit $?
91while read -r o; do
92 [ -n "$o" ] || continue
93 b=$(od -An -tu1 -j "$o" -N 1 "$OUT" 2>/dev/null | tr -d ' \n')
94 [ -n "$b" ] || continue
95 esc=$(printf '\\%03o' $(( (b + 128) % 256 )))
96 printf "$esc" | dd of="$OUT" bs=1 seek="$o" count=1 conv=notrunc 2>/dev/null
97done < "$(dirname "$0")/offsets"
98cat "$OUT"
99rm -f "$OUT"
100exit 0
101"#;
102 let shim = dir.join("one-sample-wrong-ffmpeg.sh");
103 std::fs::write(&shim, script).expect("writing the ffmpeg shim");
104 #[cfg(unix)]
105 {
106 use std::os::unix::fs::PermissionsExt;
107 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755))
108 .expect("the ffmpeg shim must be executable");
109 }
110 let set_offsets = |bytes: &[usize]| {
111 let body: String = bytes
112 .iter()
113 .map(|b| format!("{b}\n"))
114 .collect::<Vec<_>>()
115 .concat();
116 std::fs::write(dir.join("offsets"), body).expect("writing the offsets file");
117 };
118 let count = |theirs_t: &[Pic]| -> [usize; 3] {
119 let mut wrong = [0usize; 3];
120 for (a, b) in ours.iter().zip(theirs_t) {
121 for (plane, (x, y)) in
122 [(0usize, (&a.y, &b.y)), (1, (&a.u, &b.u)), (2, (&a.v, &b.v))]
123 {
124 wrong[plane] += x.iter().zip(y).filter(|(p, q)| p != q).count();
125 }
126 }
127 wrong
128 };
129 // Frame bytes are 3 planes x W*H samples x 2 bytes (10-bit container).
130 let plane_bytes = W * H * 2;
131 let mut blind: Vec<String> = Vec::new();
132 set_ffmpeg_path(Some(shim.clone()));
133 for (plane, base) in [("Y", 0usize), ("U", plane_bytes), ("V", 2 * plane_bytes)] {
134 // Byte 2000 of the named plane: sample 1000, still frame 0 on
135 // every plane at this geometry.
136 set_offsets(&[base + 2000]);
137 let theirs_t =
138 ffmpeg_decode_sequence_444_depth(&stream, W, H, FRAMES, 10, "yuv444p10le");
139 let got = count(&theirs_t);
140 let mut expected = [0usize, 0, 0];
141 expected[match plane {
142 "Y" => 0,
143 "U" => 1,
144 _ => 2,
145 }] = 1;
146 if got != expected {
147 blind.push(format!(
148 "{plane} arm: counted {got:?}, expected {expected:?} (exactly the one \
149 tampered sample)"
150 ));
151 }
152 }
153 set_ffmpeg_path(None);
154 let _ = std::fs::remove_dir_all(&dir);
155 assert!(
156 blind.is_empty(),
157 "{NAME}: {} of 3 flip arms stayed GREEN against an ffmpeg that is wrong by exactly \
158 one sample -- {blind:#?} -- the comparator cannot see a difference, so its \
159 byte-exact verdict proves nothing (class comparator-that-never-reads-the-oracle)",
160 blind.len()
161 );
162 eprintln!(
163 "{NAME}: flip control bites on Y, U and V separately (0 -> 1 per tampered plane)"
164 );
165 }
166
167 /// lane-av1oracledepth: `ffmpeg_decode_sequence_10bit` must REFUSE a
168 /// wrong-depth stream by the stream's OWN sequence header, the way the
169 /// 12-bit gates read `assert_12bit_sequence_header`. An 8-bit 4:2:0
170 /// stream handed to the 10-bit helper is the wrong-depth shape: ffmpeg
171 /// converts it to `yuv420p10le` and sizes no plane differently, so
172 /// without the depth assert a gate could compare a converted 8-bit
173 /// reference against our 10-bit decode and read exact.
174 #[test]
175 fn the_10bit_oracle_helper_refuses_a_wrong_depth_stream() {
176 const NAME: &str = "the_10bit_oracle_helper_refuses_a_wrong_depth_stream";
177 let _gate_lock = lock_gate_counters();
178 let path = crate_pin("mix176_offtile_chroma_clip.obu");
179 let stream = read_pin(&path, 4581, 0x5e31be5efc9c3c1d, NAME);
180 assert_eq!(
181 stream_bit_depth(&stream, NAME),
182 8,
183 "{NAME}: the control pin must really be 8-bit, or this proves nothing"
184 );
185 assert_eq!(
186 stream_subsampling(&stream, NAME),
187 (1, 1),
188 "{NAME}: the control pin must really be 4:2:0, or the refusal below could be the \
189 shape guard instead of the depth guard"
190 );
191 let msg = panic_message(|| {
192 ffmpeg_decode_sequence_10bit(&stream, 176, 144, 1);
193 })
194 .unwrap_or_else(|| {
195 panic!(
196 "{NAME}: ffmpeg_decode_sequence_10bit ACCEPTED an 8-bit stream -- ffmpeg \
197 converted it to yuv420p10le and the helper returned a comparison that could \
198 pass green"
199 )
200 });
201 assert!(
202 msg.contains("not 10-bit"),
203 "{NAME}: the refusal must name the depth guard (\"not 10-bit\"); it said: {msg}"
204 );
205 eprintln!("{NAME}: refused -> {msg}");
206 }
207
208 /// lane-av1rawhelper: `assert_rawvideo_matches` used to pack our samples
209 /// as `u16` for EVERY stream, while `aomdec --rawvideo` writes 8 bits
210 /// per sample for an 8-bit stream. An 8-bit caller therefore died on a
211 /// raw-SIZE assertion (2359296 vs 1179648) without comparing a single
212 /// sample, and a high-bitdepth caller was the only one that could work.
213 ///
214 /// Two arms, both on a real `aomenc` 8-bit stream:
215 ///
216 /// 1. the correct label compares real samples -- the byte counts it
217 /// walks equal the oracle's, so every `u8` in the 8-bit pack is
218 /// zipped against a real oracle byte;
219 /// 2. a WRONG label fails by name, quoting both depths and the fact that
220 /// the pack would compare nothing, rather than by size. Arm 2 is what
221 /// keeps arm 1 from being a green that a reverted check would also
222 /// give.
223 #[test]
224 fn the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth() {
225 const NAME: &str = "the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth";
226 let _gate_lock = lock_gate_counters();
227 if !have_aomenc() || !have_ffmpeg() {
228 eprintln!("SKIP {NAME}: no aomenc/aomdec oracle or no ffmpeg");
229 return;
230 }
231 let (w, h) = (192usize, 128usize);
232 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
233 .args([
234 "-v",
235 "error",
236 "-f",
237 "lavfi",
238 "-i",
239 &gradients_source(7, w, h, "duration=0.24:rate=25"),
240 "-pix_fmt",
241 "yuv420p",
242 "-t",
243 "0.24",
244 "-f",
245 "yuv4mpegpipe",
246 "-",
247 ])
248 .stdin(Stdio::null())
249 .stdout(Stdio::piped())
250 .stderr(Stdio::piped()), None, |c| c.output())
251 .expect("ffmpeg failed to run");
252 assert!(
253 y4m.status.success(),
254 "{NAME}: ffmpeg fixture: {}",
255 String::from_utf8_lossy(&y4m.stderr)
256 );
257 let args: Vec<&str> = vec![
258 "--codec=av1",
259 "--passes=1",
260 "--end-usage=q",
261 "--cq-level=40",
262 "--cpu-used=2",
263 "--threads=1",
264 "--row-mt=0",
265 "--limit=6",
266 "--obu",
267 "-o",
268 "-",
269 "-",
270 ];
271 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
272 assert!(
273 out.status.success(),
274 "{NAME}: aomenc refused the fixture: {}",
275 String::from_utf8_lossy(&out.stderr)
276 );
277 let stream = out.stdout;
278 assert_eq!(
279 stream_bit_depth(&stream, NAME),
280 8,
281 "{NAME}: the fixture must really be 8-bit, or this gate measures nothing"
282 );
283 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-raw8-{}", std::process::id()));
284 let _ = std::fs::remove_dir_all(&dir);
285 std::fs::create_dir_all(&dir).expect("scratch dir");
286 let obu = dir.join("in.obu");
287 std::fs::write(&obu, &stream).expect("writing the stream");
288 let frames = decode_stream(&stream)
289 .unwrap_or_else(|e| panic!("{NAME}: the 8-bit stream no longer decodes: {e}"))
290 .len();
291 assert!(frames > 0, "{NAME}: nothing decoded");
292
293 // ARM 2 first: the wrong label must be refused BY NAME. A helper that
294 // packed u16 unconditionally got this far and then failed on size.
295 let wrong = std::panic::catch_unwind(|| {
296 assert_rawvideo_matches(&obu, &stream, NAME, frames, 10);
297 });
298 let boom = wrong
299 .err()
300 .map(|e| e.downcast_ref::<String>().cloned().unwrap_or_default())
301 .unwrap_or_default();
302 assert!(
303 boom.contains("sequence header says 8-bit") && boom.contains("compares nothing"),
304 "{NAME}: a 10-bit label on an 8-bit stream must be refused by the depth check \
305 naming both depths; the panic read: {boom}"
306 );
307
308 // ARM 1: the correct label compares real samples. The pre-fix helper
309 // reached a size mismatch here (ours 2x the oracle); reaching the
310 // sample compare is what this arm proves.
311 assert_rawvideo_matches(&obu, &stream, NAME, frames, 8);
312 let _ = std::fs::remove_dir_all(&dir);
313 eprintln!("{NAME}: {frames} 8-bit frame(s) byte-identical to aomdec --rawvideo");
314 }
315
316 /// lane-svtinter: an SVT-AV1 screen stream whose frame height is not a
317 /// multiple of the superblock size codes PALETTE blocks in the bottom
318 /// (and right) superblock row that hang off the mi grid. Spec 5.11.50
319 /// `palette_tokens` reads the colour-index map only over the block's
320 /// `onscreenWidth x onscreenHeight` corner and replicates it outward;
321 /// this decoder read the full block grid, so it consumed colour-index
322 /// symbols libaom never wrote and desynced the rest of the tile -- either
323 /// a wrong bottom superblock row (1599 luma samples in this stream's
324 /// frame 0, ~80k per inter frame after) or, further along the same tile,
325 /// a bogus "a Golomb tail longer than this decoder reads" refusal.
326 ///
327 /// Unlike its lane-svt1 sibling above this one BUILDS its stream: the
328 /// recipe is synthetic (`smptebars,drawgrid` through `libsvtav1 -preset 8
329 /// -svtav1-params screen-content-mode=1`), and 384x152 puts a 32x32
330 /// palette block at mi row 32 of a 38-mi-tall frame, 24 of its 32 rows
331 /// on screen. `palette_onscreen_cut_hits` is asserted non-zero so the row
332 /// cannot pass on a stream that never cuts a palette map (class
333 /// gate-blind-to-feature).
334 #[test]
335 fn an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly() {
336 const NAME: &str = "an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly";
337 if !have_ffmpeg() {
338 eprintln!("SKIP {NAME}: no ffmpeg");
339 return;
340 }
341 let (width, height) = (384usize, 152usize);
342 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
343 .args([
344 "-v",
345 "error",
346 "-f",
347 "lavfi",
348 "-i",
349 "smptebars=s=384x152:r=12,drawgrid=w=8:h=8:t=1:c=black",
350 "-frames:v",
351 "4",
352 "-c:v",
353 "libsvtav1",
354 "-preset",
355 "8",
356 "-crf",
357 "30",
358 "-svtav1-params",
359 "lp=1:screen-content-mode=1",
360 "-g",
361 "12",
362 "-f",
363 "obu",
364 "-",
365 ])
366 .stdin(Stdio::null())
367 .stdout(Stdio::piped())
368 .stderr(Stdio::piped()), None, |c| c.output())
369 .expect("ffmpeg failed to run");
370 if !out.status.success() || out.stdout.is_empty() {
371 eprintln!(
372 "SKIP {NAME}: no libsvtav1 in this ffmpeg: {}",
373 String::from_utf8_lossy(&out.stderr)
374 );
375 return;
376 }
377 let stream = out.stdout;
378 crate::decode::reset_palette_onscreen_cut_hits();
379 let decoded = decode_stream(&stream).expect("the SVT-AV1 screen stream decodes");
380 assert_eq!(decoded.len(), 4, "{NAME}: frame count");
381 assert!(
382 crate::decode::palette_onscreen_cut_hits() > 0,
383 "{NAME}: no palette map is cut by the frame edge here -- the gate would pass blind"
384 );
385 let want = ffmpeg_decode_sequence(&stream, width, height, decoded.len());
386 assert_eq!(want.len(), decoded.len(), "{NAME}: ffmpeg frame count");
387 for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
388 assert_eq!(got.y, want.y, "{NAME}: frame {i} luma vs ffmpeg");
389 assert_eq!(got.u, want.u, "{NAME}: frame {i} U vs ffmpeg");
390 assert_eq!(got.v, want.v, "{NAME}: frame {i} V vs ffmpeg");
391 }
392 }
393
394 /// lane-svt1: an SVT-AV1 (v3.1.2, `-preset 8`) screen key frame codes 16x16
395 /// PALETTE blocks with `skip == 1` whose `tx_depth` split the luma
396 /// transform. [`crate::decode::decode_block`] armed the palette prediction
397 /// only when the transform covered the whole block, so that one block
398 /// predicted DC off its own edges instead: the right symbols (the whole mode
399 /// ladder diffs clean against an instrumented aomdec) and the wrong pixels
400 /// -- 812 luma samples in frame 0, carried by the V_PRED blocks under it to
401 /// 10122 samples over the 12-frame stream the defect was found on.
402 ///
403 /// lane-av1pinspec2: the gate used to RIDE an external crop named by
404 /// `EC_AV1_SVT1_STREAM` and SKIP when that was unset, so it never ran on a
405 /// stock box -- which is exactly why its oracle count could not be pinned
406 /// (an assert on a gate that never executes is an unexercised assert wearing
407 /// a pin's clothes). It now runs on the COMMITTED pin
408 /// `crates/ec-av1/fixtures/svt1-split-tx-pin.obu`.
409 ///
410 /// The pin is a REPLAY, not a fresh capture, and the recipe is recorded
411 /// because it reproduces the bytes exactly (two independent encodes on this
412 /// box, SVT-AV1 v3.1.2, both sha256
413 /// `c9d9c0ae934fba72fc9a9374bc36853f290796a8a4d6442140e239669e0b341f`,
414 /// 1838 bytes):
415 ///
416 /// ffmpeg -v error -f lavfi \
417 /// -i "smptehdbars=s=192x152:r=12,drawgrid=w=8:h=8:t=1:c=black" \
418 /// -frames:v 1 -c:v libsvtav1 -preset 8 -crf 50 \
419 /// -svtav1-params "lp=1:screen-content-mode=1" -g 12 -f obu out.obu
420 ///
421 /// `-frames:v 1` is the part lane-svt1's search lacked: its 6x5x6 sweep ran
422 /// FOUR frames per stream, and the ~200k-sample misses that killed every
423 /// candidate were on the INTER frames (`lanes/svt1.report.md`). One key
424 /// frame has no inter frames, and this one reaches the fixed arm
425 /// (`skip_split_tx_override_hits == 1`) and is pixel-exact.
426 ///
427 /// THE COUNT, and why it is derived from the wire rather than from a
428 /// literal. The oracle is handed the number of frame OBUs this stream
429 /// actually codes, counted with `Av1Parser` below -- never our decode's
430 /// length, which is the thing under test. A header count would OVER-count
431 /// a stream carrying `show_existing_frame` (spec 5.9.5: it codes no pixels,
432 /// so the header count is larger than the shown-frame count), so that case
433 /// is asserted impossible on this pin rather than assumed: the loop refuses
434 /// any frame header with `show_existing_frame` set, which is what makes
435 /// "one header == one shown frame" a checked fact here instead of an
436 /// argument.
437 ///
438 /// `EC_AV1_SVT1_STREAM` still overrides the pin, so a re-capture is one env
439 /// var away; `crate_pin` falls back to `pin_dir()` for the same reason.
440 ///
441 /// `skip_split_tx_override_hits` is asserted non-zero so the row cannot
442 /// pass on a stream that never reaches the fixed arm (class
443 /// gate-blind-to-feature).
444 #[test]
445 fn an_svt_screen_palette_block_with_a_split_transform_decodes_exactly() {
446 const NAME: &str = "an_svt_screen_palette_block_with_a_split_transform_decodes_exactly";
447 const PIN: &str = "svt1-split-tx-pin.obu";
448 if !have_ffmpeg() {
449 eprintln!("SKIP {NAME}: no ffmpeg");
450 return;
451 }
452 let path = match std::env::var("EC_AV1_SVT1_STREAM") {
453 Ok(p) => std::path::PathBuf::from(p),
454 // The name is spelled as a LITERAL here even though `PIN` is right
455 // above, on purpose: `gate_coverage::pin_inventory` matches a pin
456 // read by the quote that follows the callee name, so a const
457 // argument would leave this pin outside the "every pin a gate reads
458 // is a committed crate-local copy" invariant. The dup is the
459 // coverage -- and it is also why this comment must NOT quote that
460 // spelling: the scanner reads prose too, and a quoted spelling here
461 // parses as a pin called " and would not see a const argument, ...".
462 Err(_) => crate_pin("svt1-split-tx-pin.obu"),
463 };
464 let data = require_pin(&path, PIN);
465 // The ENCODE's frame count, read off the WIRE: parse this stream's own
466 // OBUs and count the frame headers. `show_existing_frame` is refused
467 // here on purpose -- such a header codes no pixels, so counting it
468 // would make this count larger than the frames the oracle can decode.
469 let mut parser = Av1Parser::new();
470 let mut pos = 0usize;
471 let mut frame_headers = 0usize;
472 while pos < data.len() {
473 let Ok(obu) = parser.parse_obu(&data[pos..]) else {
474 break;
475 };
476 pos += obu.total_size.max(1);
477 let header = match &obu.kind {
478 ObuKind::Frame(h, _) | ObuKind::FrameHeader(h) => h,
479 _ => continue,
480 };
481 assert!(
482 !header.show_existing_frame,
483 "{NAME}: frame header {frame_headers} sets show_existing_frame, so the header \
484 count is not the shown-frame count and this gate's oracle budget would be wrong"
485 );
486 frame_headers += 1;
487 }
488 assert!(
489 frame_headers > 0,
490 "{NAME}: {} carries no frame header at all",
491 path.display()
492 );
493 crate::decode::reset_skip_split_tx_override_hits();
494 let decoded = decode_stream(&data).expect("the pinned SVT-AV1 screen stream decodes");
495 assert!(
496 crate::decode::skip_split_tx_override_hits() > 0,
497 "{NAME}: no skipped split-transform palette block in {} -- the gate would pass blind",
498 path.display()
499 );
500 assert_eq!(
501 decoded.len(),
502 frame_headers,
503 "{NAME}: the stream codes {frame_headers} frame(s), the decode showed {}",
504 decoded.len()
505 );
506 let (width, height) = (decoded[0].width, decoded[0].height);
507 let want = ffmpeg_decode_sequence(&data, width, height, frame_headers);
508 for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
509 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");
510 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");
511 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");
512 }
513 }
514
515 /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an
516 /// independent decoder, not just this crate checking its own tile path.
517 #[test]
518 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
519 let fctx = &crate::decode::FrameCtx::for_encoder();
520 if !have_ffmpeg() {
521 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
522 return;
523 }
524 // lane-av1straddle: 216x96 joins 128x64 because only a size whose
525 // 32x32 blocks straddle the right-hand frame edge can see the writer
526 // coding a transform unit that starts outside the frame -- libdav1d
527 // AND libaom both refused the whole key frame while it did, and this
528 // crate's own (lenient) decoder only differed in the last block's V.
529 for &(width, height) in &[(128usize, 64usize), (216usize, 96usize)] {
530 let pictures: Vec<_> = (0..3)
531 .map(|i| panned_test_card(width, height, i * 3))
532 .collect();
533 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
534 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
535 let decoded = decode_stream(&encoded.stream).unwrap();
536 assert_eq!(decoded.len(), 3);
537 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
538 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
539 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
540 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
541 }
542 // ... and the encoder's own reconstruction is what ffmpeg sees,
543 // so the check fails on a writer-side desync too, not only on a
544 // decoder-side one.
545 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
546 let rec = &frame.reconstruction;
547 assert_eq!(
548 rec.y, want.y,
549 "{width}x{height} frame {i} luma: reconstruction vs ffmpeg"
550 );
551 assert_eq!(
552 rec.u, want.u,
553 "{width}x{height} frame {i} U: reconstruction vs ffmpeg"
554 );
555 assert_eq!(
556 rec.v, want.v,
557 "{width}x{height} frame {i} V: reconstruction vs ffmpeg"
558 );
559 }
560 }
561 }
562
563 /// lane-av1rect: the encoder used to REFUSE every size where a 32x32
564 /// block straddles BOTH true frame edges at once ("straddles the true
565 /// frame edge in a way that needs a rectangular (HORZ/VERT) transform
566 /// this encoder does not code yet"). That refusal was a misreading of
567 /// spec 5.11.4: a block whose `hasRows` and `hasCols` are BOTH false
568 /// reads no partition symbol at all and is `PARTITION_SPLIT` by
569 /// inference, down to the 8x8 leaves whose own mi origin is inside the
570 /// frame -- exactly the leaves this writer already codes for the
571 /// one-axis case, and no rectangular transform anywhere. The sweep walks
572 /// the corners around the 32-multiples (each width has a 16x16 column
573 /// whose right half is outside, each height a row whose bottom half is,
574 /// so the bottom-right 16x16 of every size here is cut on both axes) and
575 /// three-way compares: our decoder, the encoder's own reconstruction and
576 /// ffmpeg, over a 4-frame GOP so the inter writer's copy of the same
577 /// signaling is covered too. `edge_both_cut_hits` proves the decoder
578 /// really took the inferred-split path rather than the gate passing on
579 /// geometry that never fires it.
580 #[test]
581 fn a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg() {
582 let fctx = &crate::decode::FrameCtx::for_encoder();
583 if !have_ffmpeg() {
584 eprintln!(
585 "SKIP a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg: no ffmpeg"
586 );
587 return;
588 }
589 const FRAMES: usize = 4;
590 let mut both_cut = 0usize;
591 for &width in &[200usize, 216, 232, 248] {
592 for &height in &[104usize, 120, 136, 152] {
593 let pictures: Vec<_> = (0..FRAMES as i64)
594 .map(|i| panned_test_card(width, height, i * 3))
595 .collect();
596 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
597 .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
598 // Reset per attempt, never a delta across sizes (class
599 // counter-from-refused-stream).
600 crate::decode::reset_edge_both_cut_hits();
601 let decoded = decode_stream(&encoded.stream)
602 .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
603 both_cut += crate::decode::edge_both_cut_hits().iter().sum::<usize>();
604 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
605 assert_eq!(
606 ffmpeg_frames.len(),
607 FRAMES,
608 "{width}x{height}: ffmpeg decoded {} of {FRAMES} frames",
609 ffmpeg_frames.len()
610 );
611 assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
612 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
613 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
614 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
615 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
616 }
617 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
618 let rec = &frame.reconstruction;
619 assert_eq!(
620 rec.y, want.y,
621 "{width}x{height} frame {i} luma: recon vs ffmpeg"
622 );
623 assert_eq!(
624 rec.u, want.u,
625 "{width}x{height} frame {i} U: recon vs ffmpeg"
626 );
627 assert_eq!(
628 rec.v, want.v,
629 "{width}x{height} frame {i} V: recon vs ffmpeg"
630 );
631 }
632 }
633 }
634 assert!(
635 both_cut > 0,
636 "no partition node in the whole sweep was coded as the both-axes-cut \
637 inferred split -- the gate is blind to the feature it pins"
638 );
639 }
640
641 /// lane-corner: sizes whose LAST superblock is cut by the true frame
642 /// edge on BOTH axes with more than half of each still inside -- so
643 /// `has_cols` and `has_rows` are both true and the spec lets that
644 /// superblock stay a whole 64x64 `PARTITION_NONE` block, which this
645 /// encoder's roots take (`EC_AV1_B64EDGE` on the inter side, the key
646 /// frame's own `Superblock::Whole`). The sibling luma-only test
647 /// (`encoder.rs`'s `a_non_superblock_aligned_clip_...`) is blind to
648 /// chroma (class `metric-blind-to-a-plane`), so this one compares all
649 /// three planes three ways: our decoder, the encoder's own
650 /// reconstruction, and ffmpeg.
651 #[test]
652 fn a_doubly_cut_superblock_root_round_trips_in_every_plane() {
653 let fctx = &crate::decode::FrameCtx::for_encoder();
654 if !have_ffmpeg() {
655 eprintln!("SKIP a_doubly_cut_superblock_root_round_trips_in_every_plane: no ffmpeg");
656 return;
657 }
658 const FRAMES: usize = 4;
659 // Each size leaves MORE than half of its last superblock row (and,
660 // but for 200x120's 8-px column, of its last column) inside, which is
661 // what makes the root legal there at all; 248x168/232x168/248x184 are
662 // cut on BOTH axes at once. 1920x1080 -- the user's own export shape
663 // -- is the same case: 1080 = 16*64 + 56, a 56-px bottom straddle.
664 for &(width, height) in &[(248usize, 168usize), (232, 168), (200, 120), (248, 184)] {
665 let pictures: Vec<_> = (0..FRAMES as i64)
666 .map(|i| panned_test_card(width, height, i * 3))
667 .collect();
668 let _ = crate::encode::take_b64_edge_hits();
669 let _ = crate::encode::take_i64_root_hits();
670 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
671 .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
672 let edges = crate::encode::take_b64_edge_hits();
673 let [i64_whole, i64_offered, i64_edge] = crate::encode::take_i64_root_hits();
674 eprintln!(
675 "{width}x{height}: edge inter 64 roots {edges}, key 64 roots {i64_whole} of \
676 {i64_offered} offered, {i64_edge} of them cut by the frame edge"
677 );
678 // gate-blind-to-feature: without this the three-way compare below
679 // passes on a stream that never coded a whole root at the cut
680 // superblock at all.
681 assert!(
682 i64_edge > 0,
683 "{width}x{height}: no 64x64 root sat on a superblock the frame edge cuts"
684 );
685 let decoded = decode_stream(&encoded.stream)
686 .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
687 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
688 assert_eq!(
689 ffmpeg_frames.len(),
690 FRAMES,
691 "{width}x{height}: ffmpeg frame count"
692 );
693 assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
694 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
695 assert_eq!(
696 got.y, want.y,
697 "{width}x{height} frame {i} luma: ours vs ffmpeg"
698 );
699 assert_eq!(
700 got.u, want.u,
701 "{width}x{height} frame {i} U: ours vs ffmpeg"
702 );
703 assert_eq!(
704 got.v, want.v,
705 "{width}x{height} frame {i} V: ours vs ffmpeg"
706 );
707 }
708 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
709 let rec = &frame.reconstruction;
710 assert_eq!(
711 rec.y, want.y,
712 "{width}x{height} frame {i} luma: recon vs ffmpeg"
713 );
714 assert_eq!(
715 rec.u, want.u,
716 "{width}x{height} frame {i} U: recon vs ffmpeg"
717 );
718 assert_eq!(
719 rec.v, want.v,
720 "{width}x{height} frame {i} V: recon vs ffmpeg"
721 );
722 }
723 }
724 }
725
726 /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME`
727 /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s
728 /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc
729 /// attempts never could: frame 0 is a real key frame (this crate's own
730 /// encoder, real texture), refreshing all 8 DPB slots as spec requires --
731 /// slot 3 keeps that exact picture from here on. Frame 1 is a hand-coded
732 /// inter frame whose lone 32x32 block is *intra* (`DC_PRED`, `skip`),
733 /// refreshing only slot 0 with a flat 128 block -- distinguishable from
734 /// frame 0's real texture, so slot 0 (`LAST_FRAME`) and slot 3
735 /// (`GOLDEN_FRAME`) hold visibly different pictures once frame 2 runs.
736 /// Frame 2 is a hand-coded inter frame naming `ref_frame_idx[3] = 3`
737 /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose
738 /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME`
739 /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy
740 /// of GOLDEN's picture, so its output must equal frame 0's own
741 /// reconstruction exactly, and must differ from frame 1's -- proof the
742 /// decoder actually read the golden plane, not silently substituted
743 /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a
744 /// deblock/MC residue that turned out to be film-grain synthesis
745 /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN);
746 /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing
747 /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so
748 /// this fixture flips back to its round-4 pixel-exact form. ffmpeg
749 /// decodes the identical wire bytes as the foreign oracle
750 /// (shared-oracle-blindness class): this crate's own decoder agreeing
751 /// with itself would prove nothing.
752 #[test]
753 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
754 let fctx = &crate::decode::FrameCtx::new();
755 if !have_ffmpeg() {
756 eprintln!(
757 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
758 );
759 return;
760 }
761 use crate::cdf_state::Cdfs;
762 use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of};
763 use crate::encode::{inter_frame_headers, key_frame_headers};
764 use crate::frame::frame_obu;
765 use crate::msac::SymbolEncoder;
766 use crate::mvstack::{
767 GOLDEN_FRAME, MiGrid, find_mv_stack, single_ref_p1_ctx, single_ref_p3_ctx,
768 single_ref_p5_ctx,
769 };
770 use crate::obu::temporal_delimiter;
771
772 let (width, height) = (32usize, 32usize);
773 let base_q_idx = 100u8;
774 // The whole picture is one 32x32 block: `partition_ctx`/`skip_ctx`/
775 // `intra_inter_ctx`'s neighbour inputs are all "no neighbour yet" --
776 // a fresh `Neighbours`' `above_side_mi`/`left_side_mi` start at `SB`
777 // (64), so `partition_ctx_mi`'s `side_mi * 2 <= side` (32) is false
778 // on both axes (ctx 0), and `above_skip`/`left_skip`/`above_inter`/
779 // `left_inter`/`above_ref`/`left_ref` all start `false`/`-1`
780 // (decode.rs `Neighbours::new`) -- computed here without
781 // constructing the (module-private) `Neighbours` itself.
782 const PARTITION_NONE: usize = 0;
783 let ii_ctx = intra_inter_ctx(false, false, false, false);
784 let sr_p1_ctx = single_ref_p1_ctx(None, None, None, None);
785 let sr_p3_ctx = single_ref_p3_ctx(None, None, None, None);
786 let sr_p5_ctx = single_ref_p5_ctx(None, None, None, None);
787
788 for run in 0..4 {
789 let picture = test_card(width, height);
790 let key = encode_key_frame_with_ctx(&picture, base_q_idx, 0.5, fctx).unwrap();
791 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
792
793 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
794 // 128 block (no neighbours to predict `DC_PRED` from).
795 let (_, mut header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
796 // These two tiles are hand-coded from a FRESH `Cdfs`, so the
797 // frames must not carry CDF state the way the encoder's own inter
798 // frames now do (spec 7.20): with the bit set, what each frame
799 // stores is what it started from -- the defaults -- which is
800 // exactly what the next hand-coded tile assumes.
801 header1.disable_frame_end_update_cdf = true;
802 let tile1 = {
803 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
804 let mut enc = SymbolEncoder::new();
805 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
806 enc.symbol(1, &mut cdfs.skip[0]); // skip
807 enc.symbol(0, &mut cdfs.intra_inter[ii_ctx]); // is_inter = false
808 enc.symbol(0, &mut cdfs.y_mode[3]); // DC_PRED, size group 3 (32x32)
809 enc.symbol(0, &mut cdfs.uv_mode_cfl[0]); // DC_PRED
810 enc.finish()
811 };
812 let mut stream = key.stream.clone();
813 stream.extend(temporal_delimiter());
814 stream.extend(frame_obu(&seq, &header1, &tile1).unwrap());
815
816 // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME,
817 // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0).
818 let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap();
819 header2.disable_frame_end_update_cdf = true;
820 header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1
821 let tile2 = {
822 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
823 let mut enc = SymbolEncoder::new();
824 let grid = MiGrid::new(8, 8);
825 let stack = find_mv_stack(&grid, 0, 0, 8, 8, GOLDEN_FRAME, 8, 8);
826 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
827 enc.symbol(1, &mut cdfs.skip[0]); // skip
828 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter = true
829 enc.symbol(0, &mut cdfs.single_ref[sr_p1_ctx][0]); // p1: LAST/LAST2/LAST3/GOLDEN group
830 enc.symbol(1, &mut cdfs.single_ref[sr_p3_ctx][2]); // p3: GOLDEN/LAST3 sub-group
831 enc.symbol(1, &mut cdfs.single_ref[sr_p5_ctx][4]); // p5: GOLDEN_FRAME
832 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new -> not NEWMV
833 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero -> not GLOBALMV
834 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // nearest -> NEARESTMV, (0, 0)
835 enc.finish()
836 };
837 stream.extend(temporal_delimiter());
838 stream.extend(frame_obu(&seq, &header2, &tile2).unwrap());
839
840 let before = non_last_ref_hits();
841 let decoded = decode_stream(&stream).unwrap();
842 assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures");
843 assert!(
844 non_last_ref_hits() > before,
845 "run {run}: GOLDEN_FRAME never fired"
846 );
847
848 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3);
849 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
850 assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg");
851 assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg");
852 assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg");
853 }
854 assert_eq!(
855 decoded[0].y, key.reconstruction.y,
856 "run {run}: frame 0 vs the encoder's own reconstruction"
857 );
858 assert_eq!(
859 decoded[2].y, key.reconstruction.y,
860 "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names"
861 );
862 assert_ne!(
863 decoded[2].y, decoded[1].y,
864 "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \
865 distinguishable -- the gate proves nothing"
866 );
867 }
868 }
869
870 /// The determinism guard: same seed twice must byte-match ffmpeg's own
871 /// output; different seeds must not. Regresses this fix if it ever
872 /// breaks.
873 #[test]
874 fn gradients_source_is_reproducible_per_seed() {
875 if !have_ffmpeg() {
876 eprintln!("SKIP gradients_source_is_reproducible_per_seed: no ffmpeg");
877 return;
878 }
879 fn render_hash(lavfi: &str) -> Vec<u8> {
880 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
881 .args([
882 "-v",
883 "error",
884 "-f",
885 "lavfi",
886 "-i",
887 lavfi,
888 "-frames:v",
889 "1",
890 "-f",
891 "rawvideo",
892 "-",
893 ])
894 .stdin(Stdio::null())
895 .stdout(Stdio::piped())
896 .stderr(Stdio::piped()), None, |c| c.output())
897 .expect("ffmpeg failed to run");
898 assert!(out.status.success(), "ffmpeg refused {lavfi}");
899 out.stdout
900 }
901 let a1 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
902 let a2 = render_hash(&gradients_source(43, 64, 64, "duration=0.04:rate=25"));
903 let a3 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
904 assert_eq!(a1, a3, "same seed must reproduce byte-identical output");
905 assert_ne!(a1, a2, "different seeds must not collide");
906 }
907
908 /// The end-to-end gate: two real libaom-av1 configs, decoded with
909 /// [`decode_stream`] and checked against ffmpeg's own decode of the same
910 /// bytes. Not every config this encoder writes decodes yet (partitions
911 /// below 16x16, AB partitions, CfL and others remain round-2 gaps per the
912 /// r6 catalogue) -- both configs here pick `cpu-used 8` plus the
913 /// partition/angle-delta/CfL flags r6 found narrow the encoder onto this
914 /// decoder's supported syntax, while still landing on non-`DCT_DCT` tx
915 /// types on gradient content.
916 #[test]
917 fn a_real_libaom_stream_with_adst_decodes_end_to_end() {
918 if !have_ffmpeg() {
919 eprintln!("SKIP a_real_libaom_stream_with_adst_decodes_end_to_end: no ffmpeg");
920 return;
921 }
922 let configs: [(String, usize, usize, u32); 2] = [
923 ("testsrc2=size=64x64:rate=1".to_string(), 64, 64, 15),
924 (gradients_source(42, 64, 64, "rate=1"), 64, 64, 15),
925 ];
926 let mut verdicts = Vec::new();
927 for (lavfi, width, height, crf) in configs {
928 let lavfi = lavfi.as_str();
929 let Some(stream) = libaom_encode(lavfi, width, height, crf) else {
930 verdicts.push(format!("{lavfi}: ffmpeg itself refused to encode"));
931 continue;
932 };
933 match decode_stream(&stream) {
934 Ok(frames) => {
935 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
936 let matches = frames[0].y == ffmpeg_frames[0].y
937 && frames[0].u == ffmpeg_frames[0].u
938 && frames[0].v == ffmpeg_frames[0].v;
939 verdicts.push(format!(
940 "{lavfi}: decoded, {} ffmpeg's own decode",
941 if matches { "MATCHES" } else { "MISMATCHES" }
942 ));
943 // Not a hard `assert!`: libaom's own mode decisions at
944 // `cpu-used 8` are not observed stable run-to-run on this
945 // box (multi-threaded RD search), so a run that happens
946 // to land on a still-unsupported syntax element (e.g. a
947 // partition below 16x16, a separate round-2 gap) can
948 // decode without erroring yet disagree -- that failure
949 // mode belongs to those other gaps, not to this round's
950 // ADST wiring, and the eprintln below reports it either
951 // way rather than hiding it.
952 }
953 Err(e) => {
954 verdicts.push(format!("{lavfi}: still refuses ({e})"));
955 }
956 }
957 }
958 eprintln!("libaom ADST end-to-end verdicts:");
959 for v in &verdicts {
960 eprintln!(" {v}");
961 }
962 }
963
964 /// lane-dgolomb: the `force_integer_mv` gate. libaom turns screen-content
965 /// tools on for DARK, SMOOTH content -- its `av1_set_screen_content_options`
966 /// counts 16x16 blocks with 2..=4 distinct luma values -- and then sets
967 /// `force_integer_mv` on any inter frame whose source is pixel-identical to
968 /// the previously coded source (`av1_is_integer_mv`: `cs_rate >= 0.8` and
969 /// `C == T`, every collocated 8x8 block matching, is the only path that
970 /// returns 1). Both hold on his real AV1 films, and this decoder used to
971 /// drop `lower_mv_precision`'s `is_integer` half as unreachable, so every
972 /// temporal MV candidate on such a frame came out at eighth-pel: the frame
973 /// decoded without any error into a whole-frame prediction mismatch, and
974 /// the desync surfaced blocks later as "a Golomb tail longer than this
975 /// decoder reads".
976 ///
977 /// The source is SYNTHETIC (no film sample lives in `fixtures`): the
978 /// near-flat dark pattern libaom's own screen-content detector counts as
979 /// screen content, at the film-B crop size 1920x1024, SCROLLING globally
980 /// 5 px per frame and frozen on frame 8 -- an exact duplicate of frame 7
981 /// (the `C == T` trigger) whose twin is not among its own references, so
982 /// its blocks still code real motion under `force_integer_mv`.
983 ///
984 /// lane-dpm1 made this gate SENSITIVE: with the `force_integer_mv` branch
985 /// of [`crate::motion_field::lower_mv_precision`] stubbed out (`if false
986 /// &&`) the stream decodes WRONG -- frame 8, luma sample 25695, 20 against
987 /// ffmpeg's 19 -- where the previous patch-in-a-static-background recipe
988 /// (and two others tried) still decoded byte-exact: there the used mv-stack
989 /// slots came from agreeing spatial neighbours and the rounded temporal
990 /// entries never won one. The gate asserts both halves: at least one INTER
991 /// frame really carries `force_integer_mv` (class `gate-blind-to-feature`),
992 /// and every shown frame decodes sample-exact against ffmpeg's own decode.
993 #[test]
994 fn a_libaom_force_integer_mv_stream_decodes_exact() {
995 const NAME: &str = "a_libaom_force_integer_mv_stream_decodes_exact";
996 if !have_ffmpeg() {
997 eprintln!("SKIP {NAME}: no ffmpeg");
998 return;
999 }
1000 let (w, h, frames) = (1920usize, 1024usize, 16usize);
1001 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
1002 let mut off = 0usize;
1003 for f in 0..frames {
1004 // lane-dpm1: the WHOLE picture scrolls 5 px per frame and freezes
1005 // on frame 8, so (a) every block of the frozen frame -- including
1006 // mi(0,0), which has no spatial neighbour at all -- still codes
1007 // real motion against the references that are not its twin, and
1008 // (b) 40 eighth-pels projected over the pyramid's distances lands
1009 // on non-multiples of 8 (40/2 = 20 -> 16). A patch moving inside a
1010 // static background was NOT sensitive: there the used stack slots
1011 // came from spatial neighbours that agreed, and the rounded
1012 // temporal entries never won one.
1013 if f > 0 && f != 8 {
1014 off = (off + 5) % h;
1015 }
1016 let mut y = vec![0u8; w * h];
1017 for row in 0..h {
1018 let src = (row + off) % h;
1019 for col in 0..w {
1020 // 2..=4 distinct values per 16x16 block, all dark: the
1021 // screen-content detector's own counting rule.
1022 y[row * w + col] =
1023 16 + ((col / 32 + src / 32) % 5) as u8 + ((col / 4 + src / 4) % 3) as u8;
1024 }
1025 }
1026 raw.extend_from_slice(&y);
1027 raw.extend(std::iter::repeat_n(128u8, w * h / 2));
1028 }
1029 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
1030 let src = std::env::temp_dir().join(format!("ec-av1-intmv-{}.yuv", std::process::id()));
1031 std::fs::write(&src, &raw).expect("raw source");
1032 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1033 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
1034 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
1035 .arg(&src)
1036 .args(["-an", "-threads", "1", "-g", "16", "-c:v", "libaom-av1"])
1037 .args([
1038 "-cpu-used",
1039 "6",
1040 "-b:v",
1041 "0",
1042 "-crf",
1043 "35",
1044 "-f",
1045 "obu",
1046 "-",
1047 ])
1048 .stdin(Stdio::null())
1049 .stdout(Stdio::piped())
1050 .stderr(Stdio::piped()), None, |c| c.output())
1051 .expect("ffmpeg failed to run");
1052 let _ = std::fs::remove_file(&src);
1053 if !out.status.success() {
1054 eprintln!(
1055 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
1056 String::from_utf8_lossy(&out.stderr)
1057 );
1058 return;
1059 }
1060 let stream = out.stdout;
1061
1062 // Half of the gate: the stream must actually carry the feature.
1063 let mut parser = Av1Parser::new();
1064 let (mut pos, mut int_mv_inter) = (0usize, 0usize);
1065 while pos < stream.len() {
1066 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
1067 pos += obu.total_size.max(1);
1068 let header = match &obu.kind {
1069 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
1070 _ => continue,
1071 };
1072 if header.force_integer_mv && !header.frame_is_intra && header.use_ref_frame_mvs {
1073 int_mv_inter += 1;
1074 }
1075 }
1076 assert!(
1077 int_mv_inter > 0,
1078 "{NAME} went blind: libaom coded no inter frame with force_integer_mv"
1079 );
1080
1081 let ours = decode_stream(&stream).expect("libaom screen-content stream decodes");
1082 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
1083 assert_eq!(ours.len(), frames, "shown frame count");
1084 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
1085 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
1086 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
1087 assert!(
1088 first.is_none(),
1089 "frame {i} plane {plane} differs from ffmpeg at sample {} \
1090 ({int_mv_inter} force_integer_mv inter frames in this stream)",
1091 first.unwrap()
1092 );
1093 assert_eq!(
1094 l.len(),
1095 r.len(),
1096 "frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a short \
1097 plane would zip-truncate the compare above and hide a chroma-span defect",
1098 l.len(),
1099 r.len()
1100 );
1101 }
1102 }
1103 }
1104
1105 /// lane-dpm1: the 128x128-INTRA-inside-an-INTER-frame chroma context gate.
1106 /// A 128x128 block codes its chroma as four TX_32X32 units, one per 64x64
1107 /// mu chunk, and libaom stamps the coefficient context PER UNIT. The two
1108 /// INTER mu-chunk sites set `mu_chroma` so the block tail re-stamps the
1109 /// four units in mu order; the INTRA-in-inter site did not, so the
1110 /// whole-block record left every unit carrying the TOP-LEFT unit's level.
1111 /// The next block then read its `txb_skip` off ctx 11 where libaom reads
1112 /// ctx 10 (class `override-slot-on-one-arm`) -- one symbol on the wrong
1113 /// CDF row, tile desynced, and because the loop-restoration coefficients
1114 /// live in the same tile data the damage showed up as a +-1 luma sample at
1115 /// the TOP of the frame (measured: frame 1, luma sample 66, ours 146 /
1116 /// ffmpeg 145, with 1.7M samples wrong behind it).
1117 ///
1118 /// Source: the repository's own 2160p colour-bar fixture at the native
1119 /// gate's crop (1920x1024 out of the middle), 12 frames, libaom
1120 /// `-cpu-used 6 -crf 45 -g 12` -- the first reference point of
1121 /// `bd_rate_screen_native`'s "bars 2160p" row, which is where the assertion
1122 /// caught it. The gate asserts the tool fired (class
1123 /// `gate-blind-to-feature`) and that every shown frame decodes sample-exact
1124 /// against ffmpeg's own decode.
1125 #[test]
1126 fn a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact() {
1127 const NAME: &str = "a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact";
1128 if !have_ffmpeg() {
1129 eprintln!("SKIP {NAME}: no ffmpeg");
1130 return;
1131 }
1132 // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env
1133 // escape, so on a tree with no root `fixtures/` this 128-intra-block
1134 // gate reported green having decoded nothing.
1135 let Some(clip) = crate::library_fixture::require("video/h264-2160p-23.976-8bit.mp4", NAME)
1136 else {
1137 return;
1138 };
1139 let (w, h, frames) = (1920usize, 1024usize, 12usize);
1140 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
1141 let src = std::env::temp_dir().join(format!("ec-av1-i128-{}.yuv", std::process::id()));
1142 let load = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1143 .args(["-v", "error", "-y", "-i"])
1144 .arg(&clip)
1145 .args([
1146 "-frames:v",
1147 &frames.to_string(),
1148 "-vf",
1149 "crop=1920:1024:960:568",
1150 ])
1151 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
1152 .arg(&src), None, |c| c.output())
1153 .expect("ffmpeg failed to run");
1154 assert!(
1155 load.status.success(),
1156 "{NAME}: {}",
1157 String::from_utf8_lossy(&load.stderr)
1158 );
1159 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1160 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
1161 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
1162 .arg(&src)
1163 .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"])
1164 .args([
1165 "-cpu-used",
1166 "6",
1167 "-b:v",
1168 "0",
1169 "-crf",
1170 "45",
1171 "-f",
1172 "obu",
1173 "-",
1174 ])
1175 .stdin(Stdio::null())
1176 .stdout(Stdio::piped())
1177 .stderr(Stdio::piped()), None, |c| c.output())
1178 .expect("ffmpeg failed to run");
1179 let _ = std::fs::remove_file(&src);
1180 if !out.status.success() {
1181 eprintln!(
1182 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
1183 String::from_utf8_lossy(&out.stderr)
1184 );
1185 return;
1186 }
1187 let stream = out.stdout;
1188 let before = crate::decode::intra_128_in_inter_hits();
1189 let ours = decode_stream(&stream).expect("libaom bars stream decodes");
1190 assert!(
1191 crate::decode::intra_128_in_inter_hits() > before,
1192 "{NAME} went blind: no 128-rooted intra block inside an inter frame"
1193 );
1194 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
1195 assert_eq!(ours.len(), frames, "shown frame count");
1196 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
1197 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
1198 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
1199 assert!(
1200 first.is_none(),
1201 "frame {i} plane {plane} differs from ffmpeg at sample {}",
1202 first.unwrap()
1203 );
1204 assert_eq!(
1205 l.len(),
1206 r.len(),
1207 "frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a short \
1208 plane would zip-truncate the compare above and hide a chroma-span defect",
1209 l.len(),
1210 r.len()
1211 );
1212 }
1213 }
1214 }
1215
1216 /// lane-lossless: the refusal became an implementation, so its gate became
1217 /// a DECODE-EXACT one (class `refusal-lifted-without-a-gate`). libaom at
1218 /// `-crf 0` codes `base_q_idx == 0` -- the same lossless frame his
1219 /// screen-capture row gets at `-crf 5` -- where every plane is TX_4X4 with
1220 /// the Walsh-Hadamard transform, no `tx_type` symbol is coded
1221 /// (`read_tx_type`, `decodetxb.c`: "No need to read transform type for
1222 /// lossless mode(qindex==0)") and `is_cfl_allowed` (`blockd.h`) narrows to
1223 /// a BLOCK_4X4 chroma plane block. The gate asserts the stream really is
1224 /// lossless (class `gate-blind-to-feature`), that every KEY frame decodes
1225 /// sample-exact against ffmpeg, and that the still-unimplemented lossless
1226 /// INTER frame is refused BY NAME rather than decoded wrong.
1227 #[test]
1228 fn a_lossless_libaom_key_frame_decodes_sample_exact() {
1229 const NAME: &str = "a_lossless_libaom_key_frame_decodes_sample_exact";
1230 if !have_ffmpeg() {
1231 eprintln!("SKIP {NAME}: no ffmpeg");
1232 return;
1233 }
1234 let (w, h, frames) = (256usize, 128usize, 2usize);
1235 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
1236 for f in 0..frames {
1237 for row in 0..h {
1238 for col in 0..w {
1239 raw.push(((col * 7 + row * 13 + f * 31) % 251) as u8);
1240 }
1241 }
1242 // lane-lossless2: TEXTURED chroma. A flat chroma plane codes one
1243 // `txb_skip` symbol per 4x4 unit with every context at 0, which
1244 // is blind to both the unit ORDER and the per-unit contexts
1245 // (class `gate-blind-to-feature`).
1246 for row in 0..h / 2 {
1247 for col in 0..w / 2 {
1248 raw.push((((col + f) * 11 + row * 5) % 251) as u8);
1249 }
1250 }
1251 for row in 0..h / 2 {
1252 for col in 0..w / 2 {
1253 raw.push(((col * 3 + (row + f) * 17) % 251) as u8);
1254 }
1255 }
1256 }
1257 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
1258 let src = std::env::temp_dir().join(format!("ec-av1-lossless-{}.yuv", std::process::id()));
1259 std::fs::write(&src, &raw).expect("raw source");
1260 let encode = |gop: &str| {
1261
1262 crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1263 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
1264 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
1265 .arg(&src)
1266 .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
1267 .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"])
1268 .stdin(Stdio::null())
1269 .stdout(Stdio::piped())
1270 .stderr(Stdio::piped()), None, |c| c.output())
1271 .expect("ffmpeg failed to run")
1272 };
1273 let out = encode("1");
1274 let _ = std::fs::remove_file(&src);
1275 if !out.status.success() {
1276 eprintln!(
1277 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
1278 String::from_utf8_lossy(&out.stderr)
1279 );
1280 return;
1281 }
1282 let stream = out.stdout;
1283 // Half of the gate: the stream must really carry a lossless frame
1284 // (class `gate-blind-to-feature`).
1285 let mut parser = Av1Parser::new();
1286 let (mut pos, mut lossless) = (0usize, 0usize);
1287 while pos < stream.len() {
1288 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
1289 pos += obu.total_size.max(1);
1290 let header = match &obu.kind {
1291 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
1292 _ => continue,
1293 };
1294 if header.lossless.iter().all(|&l| l) {
1295 lossless += 1;
1296 }
1297 }
1298 assert_eq!(
1299 lossless, frames,
1300 "{NAME} went blind: libaom coded no lossless key frame at -crf 0"
1301 );
1302 let ours = decode_stream(&stream).expect("a lossless key-frame stream decodes");
1303 let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
1304 assert_eq!(ours.len(), frames, "{NAME}: frame count");
1305 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
1306 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
1307 .iter()
1308 .enumerate()
1309 {
1310 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
1311 assert_eq!(
1312 bad, 0,
1313 "{NAME}: frame {i} plane {plane}: {bad} samples differ"
1314 );
1315 assert_eq!(
1316 g.len(),
1317 r.len(),
1318 "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
1319 short plane would zip-truncate the compare above and hide a chroma-span \
1320 defect",
1321 g.len(),
1322 r.len()
1323 );
1324 }
1325 }
1326 }
1327
1328 /// lane-lossless2: the refusal `a_lossless_inter_frame_is_refused_by_name`
1329 /// pinned became an implementation, so its gate became a DECODE-EXACT one
1330 /// (class `refusal-lifted-without-a-gate`). A lossless INTER frame codes
1331 /// its chroma plane as 4x4 transform units, plane-major inside each 64x64
1332 /// mu chunk (libaom `read_tx_size` returns TX_4X4 for every plane under
1333 /// `xd->lossless[..]`, and `decode_token_recon_block` walks
1334 /// `for (plane..) for (blk_row..) for (blk_col..)`), which is what
1335 /// `decode::read_inter_chroma_lossless` reads. The source carries TEXTURED
1336 /// CHROMA and real motion on purpose: a flat-chroma source codes one
1337 /// `txb_skip` symbol per unit and is blind to both the unit order and the
1338 /// per-unit contexts (class `gate-blind-to-feature`).
1339 #[test]
1340 fn a_lossless_libaom_inter_frame_decodes_sample_exact() {
1341 const NAME: &str = "a_lossless_libaom_inter_frame_decodes_sample_exact";
1342 if !have_ffmpeg() {
1343 eprintln!("SKIP {NAME}: no ffmpeg");
1344 return;
1345 }
1346 // (w, h, frames, gop, bit depth, 128-superblock, screen content)
1347 // lane-lossless2: the SCREEN rows carry palette blocks, which is what
1348 // caught the whole-block palette prediction being handed to a 4x4
1349 // chroma unit.
1350 // lane-lossless3: the last row is a screen source with INTER frames --
1351 // the row that caught both of this lane's defects (a skip 8x8 leaf
1352 // restoring the previous block's luma level band over the zeros
1353 // `av1_reset_entropy_context` writes, and a rect sub-8x8 INTRA leaf
1354 // reading one TX_4X8 unit where a lossless frame codes two TX_4X4).
1355 let cases: [(usize, usize, usize, &str, u32, bool, bool); 7] = [
1356 (256, 128, 8, "4", 8, false, false),
1357 (192, 96, 6, "3", 10, false, false),
1358 (320, 192, 6, "3", 8, false, false),
1359 (256, 256, 4, "2", 8, true, false),
1360 (320, 192, 2, "1", 8, false, true),
1361 (640, 384, 2, "1", 8, false, true),
1362 (640, 384, 6, "3", 8, false, true),
1363 ];
1364 for &(w, h, frames, gop, depth, sb128, screen) in &cases {
1365 let tag = format!(
1366 "{w}x{h} {depth}-bit gop {gop}{}{}",
1367 if sb128 { " sb128" } else { "" },
1368 if screen { " screen" } else { "" }
1369 );
1370 let mut raw: Vec<u8> = Vec::new();
1371 let put = |v: u32, raw: &mut Vec<u8>| {
1372 if depth == 10 {
1373 raw.extend_from_slice(&((v * 4) as u16).to_le_bytes());
1374 } else {
1375 raw.push(v as u8);
1376 }
1377 };
1378 // A screen source is a few flat colours in 16x16 tiles plus
1379 // 1-px text-like rows -- what makes libaom code palette blocks.
1380 const PAL: [u32; 8] = [16, 60, 110, 145, 180, 210, 235, 128];
1381 for f in 0..frames {
1382 for row in 0..h {
1383 for col in 0..w {
1384 let v = if screen {
1385 if row % 7 == 0 && col % 3 == 0 {
1386 if (col / 3 + row + f) % 2 == 1 {
1387 16
1388 } else {
1389 235
1390 }
1391 } else {
1392 PAL[((col + 4 * f) / 16 + row / 16) % PAL.len()]
1393 }
1394 } else {
1395 (((col + 2 * f) * 7 + row * 13) % 251) as u32
1396 };
1397 put(v, &mut raw);
1398 }
1399 }
1400 for plane in 0..2usize {
1401 for row in 0..h / 2 {
1402 for col in 0..w / 2 {
1403 let v = if screen {
1404 PAL[((col + 2 * f) / 8 + row / 8 + plane) % PAL.len()]
1405 } else if plane == 0 {
1406 (((col + f) * 11 + row * 5) % 251) as u32
1407 } else {
1408 ((col * 3 + (row + f) * 17) % 251) as u32
1409 };
1410 put(v, &mut raw);
1411 }
1412 }
1413 }
1414 }
1415 let pix = if depth == 10 {
1416 "yuv420p10le"
1417 } else {
1418 "yuv420p"
1419 };
1420 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
1421 let src = std::env::temp_dir().join(format!(
1422 "ec-av1-lossless2-{}-{w}x{h}-{depth}.yuv",
1423 std::process::id()
1424 ));
1425 std::fs::write(&src, &raw).expect("raw source");
1426 let mut cmd = Command::new("ffmpeg");
1427 cmd.args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", pix])
1428 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
1429 .arg(&src)
1430 .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
1431 .args(["-pix_fmt", pix, "-cpu-used", "6", "-b:v", "0", "-crf", "0"]);
1432 if sb128 {
1433 cmd.args(["-aom-params", "sb-size=128"]);
1434 }
1435 if screen {
1436 cmd.args(["-aom-params", "tune-content=screen"]);
1437 }
1438 let out = crate::tool_cache::cached_output_io(cmd
1439 .args(["-f", "obu", "-"])
1440 .stdin(Stdio::null())
1441 .stdout(Stdio::piped())
1442 .stderr(Stdio::piped()), None, |c| c.output())
1443 .expect("ffmpeg failed to run");
1444 let _ = std::fs::remove_file(&src);
1445 if !out.status.success() {
1446 eprintln!(
1447 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
1448 String::from_utf8_lossy(&out.stderr)
1449 );
1450 return;
1451 }
1452 let stream = out.stdout;
1453 // The stream must really be lossless AND really carry inter frames
1454 // (class `gate-blind-to-feature`).
1455 let mut parser = Av1Parser::new();
1456 let (mut pos, mut lossless, mut inters) = (0usize, 0usize, 0usize);
1457 while pos < stream.len() {
1458 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
1459 pos += obu.total_size.max(1);
1460 let header = match &obu.kind {
1461 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
1462 _ => continue,
1463 };
1464 if header.lossless.iter().all(|&l| l) {
1465 lossless += 1;
1466 }
1467 if header.frame_type == FrameType::Inter {
1468 inters += 1;
1469 }
1470 }
1471 assert!(
1472 lossless >= frames,
1473 "{NAME} [{tag}] went blind: {lossless} lossless frames"
1474 );
1475 assert!(
1476 screen || inters > 0,
1477 "{NAME} [{tag}] went blind: no inter frame at gop {gop}"
1478 );
1479 let ours = decode_stream(&stream)
1480 .unwrap_or_else(|e| panic!("{NAME} [{tag}]: a lossless inter stream decodes: {e}"));
1481 let refs = if depth == 10 {
1482 ffmpeg_decode_sequence_10bit(&stream, w, h, frames)
1483 } else {
1484 ffmpeg_decode_sequence(&stream, w, h, frames)
1485 };
1486 assert_eq!(ours.len(), frames, "{NAME} [{tag}]: frame count");
1487 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
1488 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
1489 .iter()
1490 .enumerate()
1491 {
1492 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
1493 assert_eq!(
1494 bad, 0,
1495 "{NAME} [{tag}]: frame {i} plane {plane}: {bad} samples differ"
1496 );
1497 assert_eq!(
1498 g.len(),
1499 r.len(),
1500 "{NAME} [{tag}]: frame {i} plane {plane}: ours has {} samples, ffmpeg's has \
1501 {} -- a short plane would zip-truncate the compare above and hide a \
1502 chroma-span defect",
1503 g.len(),
1504 r.len()
1505 );
1506 }
1507 }
1508 }
1509 }
1510
1511 /// lane-av1-llband: the pinned 4:4:4 LOSSLESS key frame
1512 /// (`fixtures/ll444-lossless-key.obu`, the `ll444` recipe's frame 0 --
1513 /// `testsrc2 128x96` yuv444p cut to its key frame) decodes sample-exact,
1514 /// and its HORZ/VERT strips really walked their chroma as 4x4 units at
1515 /// subsampling 0/0 (one unit per mi cell). That unit walk used the 4:2:0
1516 /// span (8 luma px per 4x4 chroma unit) unconditionally, so every unit
1517 /// past the first column/row read its `txb_skip` context two mi cells
1518 /// over and stamped a 2-cell smear -- the 178-byte key-frame miss, first
1519 /// divergence at the 16x8 leaf mi (16,24)'s U bc=2 unit (oracle
1520 /// `txb_skip` base 0 off `above[26]`, ours base 1 off the polluted
1521 /// `above[29]`). The counter assertion is the non-vacuity half (class
1522 /// `gate-blind-to-feature`): a stream that never reaches the 4:4:4 unit
1523 /// walk must not pass.
1524 #[test]
1525 fn a_real_aomenc_lossless_444_key_frame_decodes_sample_exact() {
1526 const NAME: &str = "a_real_aomenc_lossless_444_key_frame_decodes_sample_exact";
1527 if !have_ffmpeg() {
1528 eprintln!("SKIP {NAME}: no ffmpeg");
1529 return;
1530 }
1531 // lane-av1pins: committed at crates/ec-av1/fixtures/ll444-lossless-key.obu
1532 // (7845 bytes; sha256
1533 // f496ef0a1171c2bc66d411cc60db05db547dcdb49cd834d4e0543de9db441374),
1534 // re-encoded 2026-09-29 from the recipe this very SKIP line records --
1535 // `testsrc2 128x96` yuv444p 6 frames, aomenc --profile=1 --lossless=1
1536 // --enable-palette=0 --enable-intrabc=0 --bit-depth=8 --cpu-used=0
1537 // --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100, --limit=1
1538 // so the key frame's OBUs are the whole stream (no OBU surgery needed).
1539 //
1540 // lane-av1skipfix: reading the pin from the GITIGNORED root
1541 // `fixtures/` (`pin_dir()`) is what made this gate report green having
1542 // decoded nothing -- a fresh clone, and every linked worktree, can
1543 // never have that directory. The pin is now COMMITTED under the crate
1544 // (the home the other pins use) and read through `CARGO_MANIFEST_DIR`,
1545 // so a missing file is a REPO DEFECT and fails unconditionally: there
1546 // is no environment left to escape, which is strictly stronger than
1547 // the `EC_REQUIRE_FIXTURES` / `EC_AV1_REQUIRE_AOMENC` opt-in hard
1548 // fail this arm used to carry.
1549 let pin = crate_pin("ll444-lossless-key.obu");
1550 let stream = std::fs::read(&pin).unwrap_or_else(|e| {
1551 panic!(
1552 "{NAME}: the pinned 4:4:4 lossless key frame is missing at {} ({e}). A \
1553 COMMITTED pin that is absent is a repo defect and this gate would prove \
1554 nothing. No script generates it -- regenerate it with `testsrc2 128x96` \
1555 yuv444p 6 frames, aomenc --profile=1 --lossless=1 --enable-palette=0 \
1556 --enable-intrabc=0 --bit-depth=8 --cpu-used=0 --threads=1 --row-mt=0 \
1557 --lag-in-frames=0 --kf-max-dist=100 --limit=1, and commit the result.",
1558 pin.display()
1559 )
1560 });
1561 // Blindness guard: the pinned fixture must really be a lossless frame.
1562 let mut parser = Av1Parser::new();
1563 let mut pos = 0usize;
1564 let mut lossless = false;
1565 while pos < stream.len() {
1566 let obu = parser.parse_obu(&stream[pos..]).expect("aomenc OBU parses");
1567 pos += obu.total_size.max(1);
1568 if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = obu.kind {
1569 lossless = h.lossless.iter().all(|&l| l);
1570 }
1571 }
1572 assert!(
1573 lossless,
1574 "{NAME} went blind: the pinned frame is not lossless"
1575 );
1576 let before = crate::decode::rect_split_lossless_chroma444_hits();
1577 let ours = decode_stream(&stream).expect("a 444 lossless key-frame stream decodes");
1578 assert_eq!(ours.len(), 1, "{NAME}: frame count");
1579 assert!(
1580 crate::decode::rect_split_lossless_chroma444_hits() > before,
1581 "{NAME} went blind: no lossless HORZ/VERT strip walked its chroma \
1582 as 4x4 units at subsampling 0/0"
1583 );
1584 let refs = Command::new("ffmpeg")
1585 .args([
1586 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv444p", "-",
1587 ])
1588 .stdin(Stdio::piped())
1589 .stdout(Stdio::piped())
1590 .stderr(Stdio::piped())
1591 .spawn()
1592 .and_then(|mut child| {
1593 use std::io::Write as _;
1594 child.stdin.as_mut().expect("stdin").write_all(&stream)?;
1595 child.wait_with_output()
1596 })
1597 .expect("ffmpeg 444 decode failed");
1598 assert!(
1599 refs.status.success(),
1600 "{}",
1601 String::from_utf8_lossy(&refs.stderr)
1602 );
1603 let frame = &ours[0];
1604 let planes = [
1605 (&frame.y, frame.width * frame.height),
1606 (&frame.u, frame.width * frame.height),
1607 (&frame.v, frame.width * frame.height),
1608 ];
1609 let mut off = 0usize;
1610 for (plane, (g, len)) in planes.iter().enumerate() {
1611 let raw = &refs.stdout[off..off + len];
1612 let bad = g
1613 .iter()
1614 .zip(raw.iter())
1615 .filter(|&(&a, &b)| a != u16::from(b))
1616 .count();
1617 assert_eq!(bad, 0, "{NAME}: plane {plane}: {bad} samples differ");
1618 off += len;
1619 }
1620 }
1621
1622 /// lane-av1-llinter: the firing gate for the lossless 4:4:4 INTER chroma
1623 /// fix. The fixture is the report's dodge2 stream pinned into `fixtures/`:
1624 /// aomenc profile 1 over testsrc2 128x96 yuv444p, `--lossless=1`,
1625 /// `--sb-size=64 --min-partition-size=64 --max-partition-size=64`, 6
1626 /// frames; 37658 bytes, sha256
1627 /// `5a070fa351a3f2109de855234f2b3d0a872970f3e7f658db21f65c12eeb135b4`.
1628 /// The firing counter is the EXISTING `decode::chroma_split_tx_hits` (one
1629 /// bump per lossless chroma TX unit read): with min=max partition 64 the
1630 /// roots stay whole 64x64 inter blocks -- no 8x8 leaf exists in this
1631 /// stream -- so every chroma unit goes through the big-block ss-aware
1632 /// lossless route this lane fixed (fixes 2-5). A 4:2:0 lossless stream
1633 /// fires the same counter, but the fixture bytes are pinned, so the gate
1634 /// cannot run on anything else; the pre-fix 4:2:0-hardcoded math corrupts
1635 /// at 4:4:4, so the pixel-exact compares are what prove the ss-aware path
1636 /// (class `gate-blind-to-feature`). Every frame must come out pixel-exact
1637 /// through BOTH the oracle `aomdec --rawvideo` and ffmpeg. The
1638 /// default-partition ll444 stream is deliberately NOT claimed here: its
1639 /// key frame is still the intra lane's named sub8-chroma stop
1640 /// (lanes/av1llintra.report.md).
1641 #[test]
1642 fn a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact() {
1643 const NAME: &str = "a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact";
1644 const FIXTURE_LEN: usize = 37658;
1645 const FIXTURE_FNV: u64 = 0xf68d_c26f_a14d_283c;
1646 const W: usize = 128;
1647 const H: usize = 96;
1648 const FRAMES: usize = 6;
1649 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1650 .join("fixtures/ll444_minp64_inter.obu");
1651 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
1652 panic!(
1653 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
1654 which is a failure, not a skip",
1655 obu.display()
1656 )
1657 });
1658 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
1659 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
1660
1661 let _guard = lock_gate_counters();
1662 let before = crate::decode::chroma_split_tx_hits();
1663 let frames = decode_stream(&stream)
1664 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
1665 let hits = crate::decode::chroma_split_tx_hits();
1666 assert!(
1667 hits > before,
1668 "{NAME}: gate is vacuous -- no lossless chroma TX unit was read \
1669 (delta {before} -> {hits})"
1670 );
1671 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
1672 for f in &frames {
1673 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
1674 }
1675
1676 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
1677 if aomdec_available(NAME) {
1678 let dir = std::env::temp_dir().join(format!("ec-av1-ll444-{}", std::process::id()));
1679 let _ = std::fs::remove_dir_all(&dir);
1680 std::fs::create_dir_all(&dir).expect("scratch dir");
1681 let raw = dir.join("aomdec.raw");
1682 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
1683 .args(["--codec=av1", "--rawvideo", "-o"])
1684 .arg(&raw)
1685 .arg(&obu)
1686 .stdin(Stdio::null())
1687 .stdout(Stdio::piped())
1688 .stderr(Stdio::piped()), None, |c| c.output())
1689 .expect("aomdec failed to run");
1690 assert!(
1691 out.status.success(),
1692 "{NAME}: the oracle aomdec refused the stream: {}",
1693 String::from_utf8_lossy(&out.stderr)
1694 );
1695 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
1696 let _ = std::fs::remove_dir_all(&dir);
1697 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
1698 for (i, f) in frames.iter().enumerate() {
1699 let base = i * W * H * 3;
1700 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
1701 .into_iter()
1702 .zip(["y", "u", "v"])
1703 {
1704 let want = &ref_raw[base + off..base + off + W * H];
1705 let bad = plane
1706 .iter()
1707 .zip(want)
1708 .filter(|&(&a, &b)| a as u8 != b)
1709 .count();
1710 assert_eq!(
1711 bad, 0,
1712 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ"
1713 );
1714 assert_eq!(
1715 plane.len(),
1716 want.len(),
1717 "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
1718 has {} -- a short plane would zip-truncate the compare above and hide \
1719 a chroma-span defect",
1720 plane.len(),
1721 want.len()
1722 );
1723 }
1724 }
1725 }
1726
1727 // ffmpeg's decoder: same frames, full-resolution chroma.
1728 if have_ffmpeg() {
1729 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
1730 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() {
1731 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
1732 .iter()
1733 .enumerate()
1734 {
1735 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
1736 assert_eq!(
1737 bad, 0,
1738 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
1739 );
1740 assert_eq!(
1741 g.len(),
1742 r.len(),
1743 "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
1744 -- a short plane would zip-truncate the compare above and hide a \
1745 chroma-span defect",
1746 g.len(),
1747 r.len()
1748 );
1749 }
1750 }
1751 } else {
1752 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
1753 }
1754 }
1755
1756 /// lane-av1h5: the 128-ROOT lossless 4:4:4 pin, and the control arm
1757 /// that proves the 128 root is what it needs.
1758 ///
1759 /// Witness: testsrc2 128x96 yuv444p10le, aomenc `--profile=1 --lossless=1
1760 /// --enable-palette=0 --enable-intrabc=0 --cpu-used=0`, 6 frames; 63429
1761 /// bytes, sha256 `bbffb979d20d581deb271aac75b7ee779dde57c024524ed6b1389356f55ca0fa`.
1762 /// Control: the same recipe at `--max-partition-size=64` (61494 bytes,
1763 /// sha256 `4cadce41e1f8967567b32f5cf8abaa46ffdf4fd6d4afe784c8d99a7f6bf1ae4c`),
1764 /// which never reaches a 128 root.
1765 ///
1766 /// libaom's `decode_token_recon_block` (`av1/decoder/decodeframe.c:972`)
1767 /// walks 64x64 "mu" chunks with the PLANE loop inside the chunk loop, on a
1768 /// chunk grid of `mi_size_wide[BLOCK_64X64]` = 16 mi per axis. The var-tx
1769 /// leaf list is a BLOCK-wide raster (32 leaves across at 128), so a chunk's
1770 /// members are not contiguous: leaves 0..15 are chunk (0,0) row 0, but
1771 /// chunk (0,0) rows 1..15 are leaves 32..47, 64..79, ... A chunk test on
1772 /// the given order closed the chunk every SIXTEEN leaves and coded each
1773 /// chunk's chroma sixteen times.
1774 ///
1775 /// The three assertions below are all EXACT and all stay true when the
1776 /// stream becomes byte-exact. None of them is a floor on wrong output:
1777 /// a no-op [`crate::decode::mu_chunk_order`] permutation reads 0 on
1778 /// `mu_chunk_order_hits`, so the first cannot be satisfied by a gate that
1779 /// merely ran; the walk and unit totals are libaom's own per-chunk counts;
1780 /// the control arm is a straight exactness assertion.
1781 #[test]
1782 fn a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major() {
1783 const NAME: &str = "a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major";
1784 const W: usize = 128;
1785 const H: usize = 96;
1786 const FRAMES: usize = 6;
1787 /// 5 inter frames, one unsplit 128 root each; frame 0 splits.
1788 const ROOTS: usize = 5;
1789 /// libaom's chunk grid on a 128x128 root: 2x2 chunks per root.
1790 const CHUNKS_PER_ROOT: usize = 4;
1791 /// Chroma TX_4X4 units per inter frame: 768 per plane over 128x96.
1792 const UNITS_PER_FRAME: usize = 1536;
1793
1794 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1795 .join("fixtures/ll444_128root_lossless.obu");
1796 let stream = read_pin(&obu, 63429, 0xf07d_47fc_fd51_2658, NAME);
1797 let _guard = lock_gate_counters();
1798 let (o0, w0, u0) = (
1799 crate::decode::mu_chunk_order_hits(),
1800 crate::decode::mu_chunk_walks(),
1801 crate::decode::mu_chunk_walk_units(),
1802 );
1803 let frames = decode_stream(&stream)
1804 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
1805 let (o1, w1, u1) = (
1806 crate::decode::mu_chunk_order_hits(),
1807 crate::decode::mu_chunk_walks(),
1808 crate::decode::mu_chunk_walk_units(),
1809 );
1810 // (1) the reorder PERMUTED each root's walk -- a no-op reads 0.
1811 assert_eq!(
1812 o1 - o0,
1813 ROOTS,
1814 "{NAME}: the chunk-major sort permuted {}/{} of the 128 roots -- a no-op \
1815 ordering must read 0 here, so this is what makes the gate non-vacuous",
1816 o1 - o0,
1817 ROOTS
1818 );
1819 // (2) libaom's own per-chunk counts: 4 chroma walks per 128 root, and
1820 // the 1536 chroma units an inter frame codes at 128x96 4:4:4.
1821 assert_eq!(
1822 w1 - w0,
1823 ROOTS * CHUNKS_PER_ROOT,
1824 "{NAME}: {}/{} chunk-major chroma walks; the 16x redundancy (64 per \
1825 frame instead of 4) would read {}",
1826 w1 - w0,
1827 ROOTS * CHUNKS_PER_ROOT,
1828 ROOTS * CHUNKS_PER_ROOT * 16
1829 );
1830 assert_eq!(
1831 u1 - u0,
1832 ROOTS * UNITS_PER_FRAME,
1833 "{NAME}: {}/{} chroma units over the 128 roots; the oracle codes {} \
1834 per inter frame and our pre-fix walk read 16x that",
1835 u1 - u0,
1836 ROOTS * UNITS_PER_FRAME,
1837 UNITS_PER_FRAME
1838 );
1839 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
1840 for f in &frames {
1841 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
1842 }
1843
1844 // (3) the control arm: no 128 root, and byte-exact through the oracle.
1845 let ctrl = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1846 .join("fixtures/ll444_minp64_128root_control.obu");
1847 let ctrl_stream = read_pin(
1848 &ctrl,
1849 61494,
1850 0xf6f5_a3cb_efc7_eb10,
1851 &format!("{NAME} control"),
1852 );
1853 let _ = decode_stream(&ctrl_stream)
1854 .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}"));
1855 if aomdec_available(NAME) {
1856 assert_rawvideo_matches(&ctrl, &ctrl_stream, NAME, FRAMES, 10);
1857 }
1858 }
1859
1860 /// lane-av1lm444loss: a LOSSLESS block's transform-unit grid is clipped at
1861 /// the FRAME edge, exactly as libaom's `max_block_high`/`max_block_wide`
1862 /// clip it (`av1_common_int.h:1565`, `:1579` fold `mb_to_bottom_edge` /
1863 /// `mb_to_right_edge` into `block_size_high/wide` before `>>
1864 /// MI_SIZE_LOG2`), so a block hanging off the bottom/right codes only the
1865 /// units inside the frame. `decode_token_recon_block` then bounds every
1866 /// mu chunk with `unit_height = ROUND_POWER_OF_TWO(AOMMIN(mu_blocks_high
1867 /// + row, max_blocks_high), ss_y)`, so the overflow units are never read
1868 /// there either.
1869 ///
1870 /// Fixture is the sibling [`a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major`]
1871 /// pin -- 128x96 yuv444p 4:4:4 lossless, 6 frames, 63429 bytes -- because
1872 /// 96 is NOT a multiple of the 128 superblock: its five inter frames each
1873 /// carry one unsplit 128 root that overhangs the bottom by 32 px. That is
1874 /// the whole reason this stream is the witness. The frame is 24 mi tall,
1875 /// so `max_blocks_high >> 2` is 24 transform rows where the block's own
1876 /// `side / MI` is 32.
1877 ///
1878 /// The three assertions are all non-vacuous and all EXACT:
1879 ///
1880 /// 1. `lossless_edge_clipped()` fired -- 5, one per inter frame's 128
1881 /// root. It is 0 on any frame whose height and width are multiples of
1882 /// the superblock, so a stream that merely decodes cannot satisfy it.
1883 /// 2. `lossless_edge_clip_units()` is 1280 = 5 x 256: the 8 transform rows
1884 /// x 32 columns the unclipped walk read past the frame bottom, per
1885 /// inter frame. The pre-fix walk read 2560 units per inter frame
1886 /// against the oracle's 2304, and this is that 256.
1887 /// 3. every sample of every frame matches the oracle `aomdec
1888 /// --rawvideo` in decode order -- all six frames, hidden alt-ref
1889 /// included, which the pre-fix tree failed from frame 1 on
1890 /// (5596 wrong samples there, growing to 33561 by frame 5).
1891 ///
1892 /// The control arm pins the other direction of the invariant: the
1893 /// `ll444_minp64_128root_control` stream has no overhanging root, so its
1894 /// clip counters must both read 0 -- the clip cannot fire on a block that
1895 /// fits, which is what keeps every other lossless pin byte-identical.
1896 #[test]
1897 fn a_lossless_block_clips_its_transform_grid_at_the_frame_edge() {
1898 const NAME: &str = "a_lossless_block_clips_its_transform_grid_at_the_frame_edge";
1899 const W: usize = 128;
1900 const H: usize = 96;
1901 const FRAMES: usize = 6;
1902 /// 5 inter frames, one unsplit 128 root each; frame 0 splits.
1903 const ROOTS: usize = 5;
1904 /// `max_blocks_high >> 2` = 24 rows (96 px / 4), against the block's
1905 /// own `side / MI` = 32 -- so 8 rows x 32 columns = 256 units per root
1906 /// were read past the frame bottom before the clip.
1907 const CLIP_UNITS_PER_ROOT: usize = 256;
1908
1909 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1910 .join("fixtures/ll444_128root_lossless.obu");
1911 let stream = read_pin(&obu, 63429, 0xf07d_47fc_fd51_2658, NAME);
1912 let _guard = lock_gate_counters();
1913 let (c0, u0) = (
1914 crate::decode::lossless_edge_clipped(),
1915 crate::decode::lossless_edge_clip_units(),
1916 );
1917 let frames = decode_stream(&stream)
1918 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
1919 let (c1, u1) = (
1920 crate::decode::lossless_edge_clipped(),
1921 crate::decode::lossless_edge_clip_units(),
1922 );
1923 assert_eq!(
1924 c1 - c0,
1925 ROOTS,
1926 "{NAME}: the frame-edge clip fired on {}/{} of the 128 roots -- it must be 0 \
1927 on a frame that fits, so this is what makes the gate non-vacuous",
1928 c1 - c0,
1929 ROOTS
1930 );
1931 assert_eq!(
1932 u1 - u0,
1933 ROOTS * CLIP_UNITS_PER_ROOT,
1934 "{NAME}: the clip removed {}/{} transform units; the unclipped walk read {} \
1935 per inter frame past the 96 px frame bottom (8 rows x 32 columns)",
1936 u1 - u0,
1937 ROOTS * CLIP_UNITS_PER_ROOT,
1938 CLIP_UNITS_PER_ROOT
1939 );
1940 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
1941 for f in &frames {
1942 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
1943 }
1944 if aomdec_available(NAME) {
1945 assert_rawvideo_matches(&obu, &stream, NAME, FRAMES, 10);
1946 }
1947
1948 // Control: a stream whose roots all fit must not clip at all.
1949 let ctrl = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1950 .join("fixtures/ll444_minp64_128root_control.obu");
1951 let ctrl_stream = read_pin(
1952 &ctrl,
1953 61494,
1954 0xf6f5_a3cb_efc7_eb10,
1955 &format!("{NAME} control"),
1956 );
1957 let (c2, u2) = (
1958 crate::decode::lossless_edge_clipped(),
1959 crate::decode::lossless_edge_clip_units(),
1960 );
1961 let _ = decode_stream(&ctrl_stream)
1962 .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}"));
1963 assert_eq!(
1964 crate::decode::lossless_edge_clipped() - c2,
1965 0,
1966 "{NAME} control: the clip fired on a stream whose blocks all fit -- the clip \
1967 must be a no-op there, which is what keeps every other lossless pin \
1968 byte-identical"
1969 );
1970 assert_eq!(
1971 crate::decode::lossless_edge_clip_units() - u2,
1972 0,
1973 "{NAME} control: the clip removed units from a stream whose blocks all fit"
1974 );
1975 }
1976
1977 /// lane-av1lm444loss-corr: the MI STEP at which `decode_intrabc_rect`'s
1978 /// lossless chroma replay walks the plane block.
1979 ///
1980 /// `lane-whtshape` (`f541d062`, merged `afa13bcf`) gave this route the
1981 /// per-TX_4X4 lossless chroma walk and the tail replay that re-stamps
1982 /// each unit's own coefficient context over the whole-block record. The
1983 /// replay stepped by `4 >> ss_y(fctx)` mi cells, which is 4:2:0-only
1984 /// arithmetic: at ss (1,1) it reads 2 and the ss-aware form
1985 /// `(4 << ss_y) / MI` also reads 2, so 4:2:0 agrees by construction; at
1986 /// ss (0,0) it reads 4 mi, i.e. 16 luma px per 4x4 chroma unit, where the
1987 /// unit covers `4 << 0` = 4 luma px = ONE mi. Every replayed unit was
1988 /// therefore stamped at 4x its own mi origin on a 4:4:4 lossless frame,
1989 /// writing over cells that belong to other blocks.
1990 ///
1991 /// This gate is the WIRNESS stream, not a vacuous one. The 4:2:0
1992 /// 4x4-identity is stated in the step's own comment and measured by the
1993 /// `4:2:0` arm of the lane's invariant battery, not asserted here --
1994 /// a 4:2:0 stream cannot fail this gate, by construction, and pretending
1995 /// otherwise would be a floor on wrong output.
1996 ///
1997 /// Fixture `ll444_intrabc_rect_l2.obu`, 121844 bytes, sha256
1998 /// `f0de080edce35d34cdd628b71f63dc452f946e8328352b69d3c1da090a54ec67`:
1999 /// `testsrc2 512x128 yuv444p`, aomenc `--lossless=1 --cpu-used=2
2000 /// --lag-in-frames=0 --kf-max-dist=100 --limit=6`, 6 frames. On main's
2001 /// step this stream is 10604 samples wrong in the KEY frame, first at
2002 /// byte 33216 (Y(64,448)) -- the corrupted chroma context desyncs the
2003 /// following luma, which is why the first divergence is luma at all.
2004 ///
2005 /// Assertions:
2006 ///
2007 /// 1. `(subsampling_x, subsampling_y, bit_depth) == (0, 0, 8)` from the
2008 /// stream's OWN parsed sequence header. At (1,1) the corrected step
2009 /// and the old one are the same number, so without this every
2010 /// assertion below would pass on a stream that cannot fail.
2011 /// 2. `intrabc_rect_lossless_chroma4_hits()` (lane-whtshape's own
2012 /// counter) is nonzero -- the replayed arm really ran, so the
2013 /// corrected expression was evaluated.
2014 /// 3. the U and V plane extents are luma-sized, which is the geometry
2015 /// the step indexes into.
2016 /// 4. `decode_all_frames_vs_oracle`: decode-order frame-count parity,
2017 /// then byte-exactness on every frame.
2018 ///
2019 /// Control: the sibling 128x96 4:4:4 lossless pin, whose blocks are
2020 /// whole and square, must not take the lossless chroma walk at all --
2021 /// its chroma plane block IS one TX_4X4, so there is no step to replay.
2022 #[test]
2023 fn a_lossless_444_intrabc_rect_replay_steps_by_the_units_own_mi_footprint() {
2024 const NAME: &str = "a_lossless_444_intrabc_rect_replay_steps_by_the_units_own_mi_footprint";
2025 const W: usize = 512;
2026 const H: usize = 128;
2027 const FRAMES: usize = 6;
2028
2029 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2030 .join("fixtures/ll444_intrabc_rect_l2.obu");
2031 let stream = read_pin(&obu, 121844, 0x38bf_968e_979c_7a0a, NAME);
2032 assert_eq!(
2033 subsampled_header_shape(&stream, NAME),
2034 (0, 0, 8),
2035 "{NAME}: the stream is not 8-bit 4:4:4 -- at ss (1,1) the corrected \
2036 step and the 4:2:0-only one are the SAME number (2 mi), so this gate \
2037 cannot fail on a 4:2:0 stream and would prove nothing there"
2038 );
2039 let _guard = lock_gate_counters();
2040 crate::decode::reset_intrabc_rect_lossless_chroma4_hits();
2041 let h0 = crate::decode::intrabc_rect_lossless_chroma4_hits();
2042 let frames = decode_stream(&stream)
2043 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
2044 let walked = crate::decode::intrabc_rect_lossless_chroma4_hits() - h0;
2045 assert!(
2046 walked > 0,
2047 "{NAME}: lane-whtshape's lossless per-TX_4X4 chroma walk never ran, so the \
2048 replayed MI step -- the thing this gate exists for -- was never evaluated"
2049 );
2050 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
2051 for f in &frames {
2052 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
2053 assert_eq!(
2054 f.u.len(),
2055 W * H,
2056 "{NAME}: U extent must be luma-sized at 4:4:4 -- the replay steps mi \
2057 cells through this grid"
2058 );
2059 assert_eq!(
2060 f.v.len(),
2061 W * H,
2062 "{NAME}: V extent must be luma-sized at 4:4:4"
2063 );
2064 }
2065 // lane-3c-a: the oracle-presence scan (wave 3b, 7a865ee7) rejects a
2066 // bare `aomdec_path().is_file()` outside the probe that owns it -- this
2067 // gate would otherwise report green under EC_AV1_REQUIRE_AOMENC=1 with
2068 // the pixel compare never run. `aomdec_available` carries both the
2069 // env-escape assertion and the SKIP line, so the else-arm is dropped.
2070 if aomdec_available(NAME) {
2071 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2072 assert_eq!(
2073 decoded, FRAMES,
2074 "{NAME}: decoded {decoded} frames in decode order, expected {FRAMES}"
2075 );
2076 eprintln!(
2077 "{NAME}: {decoded} frames byte-exact vs aomdec ({hidden} hidden), \
2078 {walked} lossless chroma replays"
2079 );
2080 }
2081
2082 // Control: whole square blocks have no multi-unit plane block to step.
2083 let ctrl = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2084 .join("fixtures/ll444_128root_lossless.obu");
2085 let ctrl_stream = read_pin(
2086 &ctrl,
2087 63429,
2088 0xf07d_47fc_fd51_2658,
2089 &format!("{NAME} control"),
2090 );
2091 crate::decode::reset_intrabc_rect_lossless_chroma4_hits();
2092 let _ = decode_stream(&ctrl_stream)
2093 .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}"));
2094 assert_eq!(
2095 crate::decode::intrabc_rect_lossless_chroma4_hits(),
2096 0,
2097 "{NAME} control: the lossless chroma walk ran on a stream of whole square \
2098 blocks -- there is no multi-unit chroma plane block to replay, so the \
2099 corrected step is not exercised there at all"
2100 );
2101 }
2102
2103 /// lane-av1llpredgate2: the debug-exact pin for the ss-aware
2104 /// `obmc_skip_chroma_above` decision (lane-av1-llpred2). Fixture is the
2105 /// llpred/llpred2 reports' stream pinned into `fixtures/`: testsrc2
2106 /// 128x96 yuv444p, aomenc `--profile=1 --lossless=1 --enable-palette=0
2107 /// --enable-intrabc=0 --min-partition-size=8 --max-partition-size=64`,
2108 /// 6 frames; 34037 bytes, sha256
2109 /// `04fb6d38de5382e647bfb70b6a17802f1fccc5502e6698c0394167891f2b27dc`.
2110 ///
2111 /// This is a DEBUG-build path by construction: the old ratio-based ss
2112 /// derivation read `write_h >> trailing_zeros(0)` = `>> 64` on this
2113 /// stream's 4:4:4 OBMC rect strips, a panic ONLY under
2114 /// debug_assertions (release wraps and was already byte-exact), so
2115 /// `cargo test`'s default dev profile is the profile where the defect
2116 /// class reproduces and where the parent's byte-exact proof was
2117 /// measured.
2118 ///
2119 /// No skip-arm counter gate is possible on this stream, measured:
2120 /// OBMC runs 77 times with 20 rect leaves, but
2121 /// `obmc_skip_chroma_above` returns true 0 times -- at 4:4:4 the skip
2122 /// needs a 4x4/8x4/4x8 PLANE block and min-partition-8 never codes one.
2123 /// So per the lane ticket the proof splits in two: the decision TABLE
2124 /// (4:2:0 rect strips still skip, 4:4:4 shifts never leave `usize`)
2125 /// stays pinned by `decode::obmc_skip_chroma_tests::
2126 /// rect_strips_skip_above_chroma_at_420_and_shift_never_overflows`,
2127 /// and THIS stream gate pins the end-to-end behaviour -- every sample
2128 /// of every frame must match the oracle aomdec exactly, so a returning
2129 /// chroma diff (the lane-av1-llpred ss-blind re-blend class
2130 /// `obmc-ss-blind-chroma-above`) or the debug shift panic goes red
2131 /// here by name.
2132 #[test]
2133 fn a_lossless_444_min_partition8_inter_stream_decodes_sample_exact() {
2134 const NAME: &str = "a_lossless_444_min_partition8_inter_stream_decodes_sample_exact";
2135 const FIXTURE_LEN: usize = 34037;
2136 const FIXTURE_FNV: u64 = 0x2c8f_4a2c_c025_52da;
2137 const W: usize = 128;
2138 const H: usize = 96;
2139 const FRAMES: usize = 6;
2140 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2141 .join("fixtures/ll444_minp8_inter.obu");
2142 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
2143 panic!(
2144 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
2145 which is a failure, not a skip",
2146 obu.display()
2147 )
2148 });
2149 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
2150 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
2151
2152 let _guard = lock_gate_counters();
2153 let frames = decode_stream(&stream)
2154 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
2155 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
2156 for f in &frames {
2157 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
2158 }
2159
2160 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
2161 if aomdec_available(NAME) {
2162 let dir = std::env::temp_dir().join(format!("ec-av1-llminp8-{}", std::process::id()));
2163 let _ = std::fs::remove_dir_all(&dir);
2164 std::fs::create_dir_all(&dir).expect("scratch dir");
2165 let raw = dir.join("aomdec.raw");
2166 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
2167 .args(["--codec=av1", "--rawvideo", "-o"])
2168 .arg(&raw)
2169 .arg(&obu)
2170 .stdin(Stdio::null())
2171 .stdout(Stdio::piped())
2172 .stderr(Stdio::piped()), None, |c| c.output())
2173 .expect("aomdec failed to run");
2174 assert!(
2175 out.status.success(),
2176 "{NAME}: the oracle aomdec refused the stream: {}",
2177 String::from_utf8_lossy(&out.stderr)
2178 );
2179 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
2180 let _ = std::fs::remove_dir_all(&dir);
2181 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
2182 for (i, f) in frames.iter().enumerate() {
2183 let base = i * W * H * 3;
2184 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
2185 .into_iter()
2186 .zip(["y", "u", "v"])
2187 {
2188 let want = &ref_raw[base + off..base + off + W * H];
2189 let bad = plane
2190 .iter()
2191 .zip(want)
2192 .filter(|&(&a, &b)| a as u8 != b)
2193 .count();
2194 assert_eq!(
2195 bad, 0,
2196 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \
2197 (class obmc-ss-blind-chroma-above)"
2198 );
2199 assert_eq!(
2200 plane.len(),
2201 want.len(),
2202 "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
2203 has {} -- a short plane would zip-truncate the compare above and hide \
2204 a chroma-span defect",
2205 plane.len(),
2206 want.len()
2207 );
2208 }
2209 }
2210 }
2211
2212 // ffmpeg's decoder: same frames, full-resolution chroma.
2213 if have_ffmpeg() {
2214 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
2215 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() {
2216 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
2217 .iter()
2218 .enumerate()
2219 {
2220 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
2221 assert_eq!(
2222 bad, 0,
2223 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
2224 );
2225 assert_eq!(
2226 g.len(),
2227 r.len(),
2228 "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
2229 -- a short plane would zip-truncate the compare above and hide a \
2230 chroma-span defect",
2231 g.len(),
2232 r.len()
2233 );
2234 }
2235 }
2236 } else {
2237 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
2238 }
2239 }
2240
2241 /// lane-av1444altref: the 4:4:4 LOSSLESS + altref chroma residual this
2242 /// lane closed -- 317 wrong bytes, Y exact, on
2243 /// `fixtures/ll444_c_altref_leaf8_warp.obu` (512220 bytes, sha256
2244 /// `999a41d88a092840456d5e9de83590ab819a8a14686a694889e63c2258ff2bb8`;
2245 /// the cell is committed here byte for byte, never re-encoded, and its
2246 /// `aomenc` recipe is still unrecorded -- see
2247 /// `lanes/av1444altref.report.md`).
2248 ///
2249 /// The defect: `decode_inter_block8`'s COMPOUND arm warped its LUMA
2250 /// intermediates (`warp_affine_compound`) and left BOTH CHROMA arms
2251 /// translational. libaom warps per PLANE
2252 /// (`build_inter_predictors_8x8_and_bigger`,
2253 /// reconinter_template.inc:230, runs `av1_init_warp_params` +
2254 /// `av1_warp_plane` inside the plane loop with that plane's
2255 /// subsampling and origin). A GLOBALMV (affine) 8x8 leaf's MV is the
2256 /// affine's local derivative, so a translation agrees with the warp at
2257 /// the block's top-left corner and drifts apart toward its bottom-right
2258 /// -- the measured signature, a bottom-right-biased +/-1 gradient in a
2259 /// few 8x8 chroma cells of hidden altref pictures while luma stayed exact.
2260 ///
2261 /// The assertion is BYTE-EXACTNESS on all three planes of all 16
2262 /// displayed frames against the oracle aomdec, never a route counter. The
2263 /// `flip` arm is the oracle-flip control: it rotates ONE byte of the
2264 /// oracle's own rawvideo output and requires the same comparator to
2265 /// report exactly that one sample, so the zeros above are a live
2266 /// comparison and not an empty or short zip (class
2267 /// `stale-output-faked-measurement`). `compound_warp_hits_8`'s delta is
2268 /// the supplementary reachability witness: it proves the 8x8 compound
2269 /// warp-leaf arm -- the body the fix lives in -- actually ran on this
2270 /// cell (class `gate-blind-to-feature`).
2271 #[test]
2272 fn a_lossless_444_altref_leaf8_warp_chroma_is_byte_exact() {
2273 const NAME: &str = "a_lossless_444_altref_leaf8_warp_chroma_is_byte_exact";
2274 const FIXTURE_LEN: usize = 512_220;
2275 const FIXTURE_FNV: u64 = 0xbe0a_569f_3d13_1026;
2276 const W: usize = 320;
2277 const H: usize = 240;
2278 const FRAMES: usize = 16;
2279 let stream =
2280 std::fs::read(crate_pin("ll444_c_altref_leaf8_warp.obu")).unwrap_or_else(|e| {
2281 panic!(
2282 "{NAME}: pinned fixture ll444_c_altref_leaf8_warp.obu is missing ({e}) -- \
2283 the gate cannot run, which is a failure, not a skip"
2284 )
2285 });
2286 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
2287 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
2288 assert_eq!(
2289 stream_bit_depth(&stream, NAME),
2290 8,
2291 "{NAME}: this cell is 8-bit"
2292 );
2293
2294 let _guard = lock_gate_counters();
2295 // The pin is 18 decode-order pictures for 16 displayed frames (two
2296 // hidden altrefs); the geometry assert is on the DISPLAYED frames,
2297 // which is what aomdec's --rawvideo emits and what the comparator
2298 // packs.
2299 let frames = decode_stream(&stream)
2300 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
2301 assert_eq!(frames.len(), FRAMES, "{NAME}: displayed frame count");
2302 for (i, f) in frames.iter().enumerate() {
2303 assert_eq!((f.width, f.height), (W, H), "{NAME}: frame {i} dimensions");
2304 }
2305
2306 if !aomdec_available(NAME) {
2307 return;
2308 }
2309 // ---- arm 1: the real oracle, every plane byte-identical ----------
2310 let (wy, wu, wv, n, exact) =
2311 count_rawvideo_diffs(&stream, NAME, None).unwrap_or_else(|| {
2312 panic!(
2313 "{NAME}: the two sides are not the same size -- a zip-truncated compare \
2314 would report zero and hide the whole chroma span"
2315 )
2316 });
2317 assert_eq!(
2318 (wy, wu, wv),
2319 (0, 0, 0),
2320 "{NAME}: {wy} Y / {wu} U / {wv} V samples differ from the oracle \
2321 (class altref-444-leaf8-chroma-unwarped)"
2322 );
2323 assert_eq!(
2324 (n, exact),
2325 (FRAMES, FRAMES),
2326 "{NAME}: every displayed frame must be byte-identical to the oracle's"
2327 );
2328
2329 // ---- arm 2: the ORACLE-FLIP CONTROL -----------------------------
2330 // One byte of the oracle's own output (the first U sample of frame 0),
2331 // rotated in the comparator. The count MUST move, by exactly one, in
2332 // the U plane only: a comparator that ignored the reference, or zipped
2333 // a truncated buffer, would still report zero here.
2334 let (cy, cu, cv, cn, _) = count_rawvideo_diffs(&stream, NAME, Some(W * H))
2335 .unwrap_or_else(|| panic!("{NAME}: the control arm could not compare at all"));
2336 assert_eq!(
2337 (cy, cu, cv),
2338 (0, 1, 0),
2339 "{NAME}: the oracle-flip control did not move the count -- this gate's zero is \
2340 vacuous, not exact"
2341 );
2342 assert_eq!(
2343 cn, FRAMES,
2344 "{NAME}: the control arm must still see every frame"
2345 );
2346
2347 // ---- supplementary reachability witness -------------------------
2348 let before8 = crate::decode::compound_warp_hits_8();
2349 let _ = decode_stream(&stream).expect("the reachability witness re-decodes the pin");
2350 assert!(
2351 crate::decode::compound_warp_hits_8() > before8,
2352 "{NAME}: no 8x8 compound warp leaf ran on this cell, so the fixed body was never \
2353 reached and the byte compare above proved nothing (class gate-blind-to-feature)"
2354 );
2355 }
2356
2357 /// lane-av1-444sb: the byte-exact pin for the ss-aware 128-rect chroma
2358 /// unit walk (`decode_block_128rect`). The parent walk hardcoded the
2359 /// 4:2:0 mu-chunk span -- one 32x32 chroma unit per 64x64 chunk, chunk
2360 /// offsets `*32`, clip step `*8` -- so at 4:4:4 a 128-root HORZ/VERT
2361 /// intra block coded HALF its chroma units, left the remaining units'
2362 /// coefficients unread and desynced the tile from the first such block
2363 /// on; every superblock after SB(0,0) carried damage and the chroma
2364 /// first-diffs sat on the 64/128 grid.
2365 ///
2366 /// `crates/ec-av1/fixtures/444_sb128rect_lr_witness.obu`, 794 bytes,
2367 /// sha256
2368 /// `27825e14633a4b23e37d48a2acdc7f5d814ca4fadd0b8797d72a1ffb34061e80`:
2369 /// `ffmpeg -i bands444.y4m -frames:v 3 -vf scale=192:160 -pix_fmt
2370 /// yuv444p -f yuv4mpegpipe` piped to `aomenc --codec=av1 --profile=1
2371 /// --passes=1 --end-usage=q --cq-level=32 --cpu-used=0 --threads=1
2372 /// --row-mt=0 --sb-size=128 --lag-in-frames=0 --auto-alt-ref=0
2373 /// --kf-max-dist=1000 --i444 --enable-restoration=1 --obu --limit=3`.
2374 /// Real content is required: the synthetic lavfi sources this lane swept
2375 /// (testsrc2/testsrc/smptebars/mandelbrot/gradients) all decode frame 0
2376 /// exact because they never force a 128-root rect; bands does (kf
2377 /// PARTITION_VERT 64x128 at mi(0,32) plus an intra-in-inter 64x128).
2378 ///
2379 /// Non-vacuity via the `decode::intra_sb128_hits` delta: a stream that
2380 /// stopped coding 128-axis intra blocks reads 0 and the gate fails
2381 /// instead of passing over a decode that never reached the fixed body
2382 /// (class `gate-blind-to-feature`). The oracle arms pin every sample of
2383 /// every frame against both aomdec and ffmpeg, so a returning chroma
2384 /// span regression goes red here by name.
2385 #[test]
2386 fn a_444_sb128_root_rect_stream_with_restoration_decodes_pixel_exact() {
2387 const NAME: &str = "a_444_sb128_root_rect_stream_with_restoration_decodes_pixel_exact";
2388 const FIXTURE_LEN: usize = 794;
2389 const FIXTURE_FNV: u64 = 0xf5a7_27f4_3fa7_abc3;
2390 const W: usize = 192;
2391 const H: usize = 160;
2392 const FRAMES: usize = 3;
2393 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2394 .join("fixtures/444_sb128rect_lr_witness.obu");
2395 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
2396 panic!(
2397 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
2398 which is a failure, not a skip",
2399 obu.display()
2400 )
2401 });
2402 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
2403 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
2404
2405 let _guard = lock_gate_counters();
2406 let before = crate::decode::intra_sb128_hits();
2407 let before_replay = crate::decode::sb128rect_chroma_replay_hits();
2408 let frames = decode_stream(&stream)
2409 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
2410 let (horz, vert, _) = crate::decode::intra_sb128_hits();
2411 assert!(
2412 horz - before.0 + (vert - before.1) > 0,
2413 "{NAME}: this stream coded NO 128-axis intra block -- the fixed body \
2414 never ran (class gate-blind-to-feature)"
2415 );
2416 // lane-av1-128rectspan: the block-level `record_split_luma_rect`
2417 // above clobbers the per-unit chroma contexts, so every coded unit
2418 // replays its own state after it -- the arm the span fix sits on.
2419 // The delta keeps THAT arm non-vacuous (a 128-root rect stream that
2420 // stopped replaying reads 0), and the mismatch half is the 4:2:2
2421 // signature: this stream is 4:4:4 (ss 0,0), where the unit's luma
2422 // width and height are equal, so a replay that stamped one axis with
2423 // decoded now, so this counter no longer "names the day 4:2:2 is
2424 // admitted" -- it fires there. **DO NOT copy this zero assert onto a
2425 // 4:2:2 stream**: measured on this branch's tip, the two
2426 // `422_intrabc_sb128_strip*` pins each read `mismatch = 9` while
2427 // being byte-exact against ffmpeg, because the mismatch half counts
2428 // the replay's own designed 4:2:2 case rather than a defect. What
2429 // stops the 8-row spill below the block from corrupting the next
2430 // block's `txb_skip` is the per-axis span itself, and the 4:2:2
2431 // exactness gates (`the_pinned_422_intrabc_sb128_strip_witnesses_
2432 // decode_pixel_exact`) are what hold it -- not this counter.
2433 let after_replay = crate::decode::sb128rect_chroma_replay_hits();
2434 assert!(
2435 after_replay.0 > before_replay.0,
2436 "{NAME}: no 128-root rect block replayed a chroma unit's own mi state -- the \
2437 replay arm never ran (class gate-blind-to-feature)"
2438 );
2439 assert_eq!(
2440 after_replay.1,
2441 before_replay.1,
2442 "{NAME}: the tail replay stamped {} unit(s) over a height that was not the \
2443 unit's own luma height (4:2:2 spans leaked into an admitted stream)",
2444 after_replay.1 - before_replay.1
2445 );
2446 eprintln!(
2447 "{NAME}: replayed {} chroma unit(s), {} span mismatch(es)",
2448 after_replay.0 - before_replay.0,
2449 after_replay.1 - before_replay.1
2450 );
2451 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
2452 for f in &frames {
2453 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
2454 }
2455 // All three frames are pinned byte-exact against both oracles (the
2456 // aomdec/ffmpeg arms below run over `.take(3)`): frame 0's keyframe
2457 // PARTITION_VERT 64x128, frame 1's inter pieces, and frame 2 -- whose
2458 // right superblock column (the 128-root VERT piece at the frame edge)
2459 // is three intra blocks (64x64, 64x32, 64x32) whose chroma units ride
2460 // the inter-frame intra tail. That tail read ONE whole-plane chroma
2461 // unit with the block-level context where 4:4:4 codes four
2462 // plane-major TX_32X32 units with per-unit contexts and the
2463 // offset-10 `get_txb_ctx` rows, which left three quarters of the
2464 // planes' residual unread and misaligned the symbol stream from the
2465 // first chroma unit on (f2 PREFILT Y 6952 / U 9568 / V 13496, first
2466 // diffs entering at column 128). Fixed on lane-av1-rect128recon;
2467 // the earlier "LR never restores RU row 0" attribution on this frame
2468 // was a stage-ladder mixup, refuted in lane-av1lrflush r3.
2469
2470 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
2471 if aomdec_available(NAME) {
2472 let dir = std::env::temp_dir().join(format!("ec-av1-444sb-{}", std::process::id()));
2473 let _ = std::fs::remove_dir_all(&dir);
2474 std::fs::create_dir_all(&dir).expect("scratch dir");
2475 let raw = dir.join("aomdec.raw");
2476 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
2477 .args(["--codec=av1", "--rawvideo", "-o"])
2478 .arg(&raw)
2479 .arg(&obu)
2480 .stdin(Stdio::null())
2481 .stdout(Stdio::piped())
2482 .stderr(Stdio::piped()), None, |c| c.output())
2483 .expect("aomdec failed to run");
2484 assert!(
2485 out.status.success(),
2486 "{NAME}: the oracle aomdec refused the stream: {}",
2487 String::from_utf8_lossy(&out.stderr)
2488 );
2489 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
2490 let _ = std::fs::remove_dir_all(&dir);
2491 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
2492 for (i, f) in frames.iter().enumerate().take(3) {
2493 let base = i * W * H * 3;
2494 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
2495 .into_iter()
2496 .zip(["y", "u", "v"])
2497 {
2498 let want = &ref_raw[base + off..base + off + W * H];
2499 let bad = plane
2500 .iter()
2501 .zip(want)
2502 .filter(|&(&a, &b)| a as u8 != b)
2503 .count();
2504 assert_eq!(
2505 bad, 0,
2506 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \
2507 (class 444-128rect-chroma-span)"
2508 );
2509 assert_eq!(
2510 plane.len(),
2511 want.len(),
2512 "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
2513 has {} -- a short plane would zip-truncate the compare above and hide \
2514 a chroma-span defect",
2515 plane.len(),
2516 want.len()
2517 );
2518 }
2519 }
2520 }
2521
2522 // ffmpeg's decoder: same frames, full-resolution chroma. Same
2523 // three-frame scope as the aomdec arm above.
2524 if have_ffmpeg() {
2525 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
2526 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate().take(3) {
2527 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
2528 .iter()
2529 .enumerate()
2530 {
2531 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
2532 assert_eq!(
2533 bad, 0,
2534 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
2535 );
2536 assert_eq!(
2537 g.len(),
2538 r.len(),
2539 "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
2540 -- a short plane would zip-truncate the compare above and hide a \
2541 chroma-span defect",
2542 g.len(),
2543 r.len()
2544 );
2545 }
2546 }
2547 } else {
2548 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
2549 }
2550 }
2551
2552 /// lane-av1444rect (H1): the 4:4:4 LOSSY cell with a 1:4 (HORZ_4 /
2553 /// VERT_4) partition -- the largest correctness gap the chroma-format
2554 /// sweep left, and the first 4:4:4 lossy exactness gate in the crate.
2555 ///
2556 /// **The defect.** `decode_inter_block`'s `around_c` gathered a 1:4
2557 /// strip's chroma coefficient context at the 4:2:0 PAIR extent
2558 /// (`(16, 8)` HORZ / `(8, 16)` VERT) with no `ss` gate, so at ss (0,0)
2559 /// it read one extra luma mi row of LEFT chroma context. At 4:4:4
2560 /// `is_chroma_reference` (av1_common_int.h:1454) reduces both parity
2561 /// clauses to `!subsampling_y` / `!subsampling_x`, so every block is its
2562 /// own chroma reference and no pair exists: the strip codes its own
2563 /// 16x4 chroma over its own context. Our U unit's `get_txb_ctx` then saw
2564 /// a neighbour libaom does not have, and the arithmetic coder forked.
2565 ///
2566 /// **The recipe** (sha256
2567 /// `77f727e76d81fe48cd03709f799131677c04869b163e18d78e96bc742ec69153`,
2568 /// 6441 bytes, 2 frames, `testsrc2 128x96 rate=25` yuv444p):
2569 /// ```text
2570 /// ffmpeg -f lavfi -i "testsrc2=size=128x96:rate=25" -frames:v 2 \
2571 /// -pix_fmt yuv444p -f yuv4mpegpipe - | \
2572 /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=20 \
2573 /// --cpu-used=2 --threads=1 --row-mt=0 --lag-in-frames=0 \
2574 /// --kf-max-dist=100 --limit=2 - out.obu
2575 /// ```
2576 /// (`rate=25` is load-bearing: `testsrc2`'s pattern is time-parameterised,
2577 /// so `rate=1` produces a different, already-exact stream.)
2578 ///
2579 /// Red before the fix: frame 1, 8884 of 36864 samples wrong, first at
2580 /// Y(91,32); the first wrong symbol was read 26263 of the frame, both
2581 /// sides at mi (8,16) -- ours a luma-shaped `txb_skip` row (our
2582 /// re-indexed chroma ctx 1), the oracle `decodetxb.c:158` on the U plane
2583 /// with `txb_skip_ctx = 7`.
2584 ///
2585 /// Non-vacuity, three ways: the pinned stream must really be ss (0,0)
2586 /// (asserted through the oracle aomdec's own sequence header, below);
2587 /// `decode::rect4_inter_own_chroma444_hits()` must be non-zero, so the
2588 /// 1:4-strip route the fix sits on really ran; and the SAME source and
2589 /// flags at 4:2:0 must leave that counter at zero, which is what makes
2590 /// it the 4:4:4-only route rather than a tally every strip bumps.
2591 #[test]
2592 fn a_444_lossy_rect4_inter_stream_decodes_pixel_exact() {
2593 const NAME: &str = "a_444_lossy_rect4_inter_stream_decodes_pixel_exact";
2594 const FIXTURE_LEN: usize = 6441;
2595 const FIXTURE_FNV: u64 = 0x0436_8b2d_2e91_72b0;
2596 const W: usize = 128;
2597 const H: usize = 96;
2598 const FRAMES: usize = 2;
2599 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2600 .join("fixtures/444_lossy_rect4_inter_witness.obu");
2601 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
2602 panic!(
2603 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
2604 which is a failure, not a skip",
2605 obu.display()
2606 )
2607 });
2608 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
2609 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
2610
2611 let _guard = lock_gate_counters();
2612 crate::decode::reset_rect4_inter_own_chroma444_hits();
2613 let frames = decode_stream(&stream).unwrap_or_else(|e| {
2614 panic!("{NAME}: the pinned 4:4:4 lossy stream no longer decodes cleanly: {e}")
2615 });
2616 let own_chroma = crate::decode::rect4_inter_own_chroma444_hits();
2617 assert!(
2618 own_chroma > 0,
2619 "{NAME}: no 1:4 inter strip read its chroma context over its own \
2620 extent -- the corrected route never ran (class gate-blind-to-feature)"
2621 );
2622 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
2623 for (i, f) in frames.iter().enumerate() {
2624 assert_eq!((f.width, f.height), (W, H), "{NAME}: frame {i} dimensions");
2625 // At 4:4:4 the chroma planes are full resolution. A decoder that
2626 // kept the 4:2:0 extent would hand quarter-size chroma planes to
2627 // the byte compare below, which cannot pass -- but say so here
2628 // rather than let the compare stand in for the shape claim.
2629 assert_eq!(
2630 f.u.len(),
2631 W * H,
2632 "{NAME}: frame {i} chroma plane is {} samples; at 4:4:4 it must be \
2633 full resolution ({W}x{H})",
2634 f.u.len()
2635 );
2636 }
2637 if aomdec_available(NAME) {
2638 let (decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2639 eprintln!(
2640 "{NAME}: {decoded} frame(s) byte-exact vs aomdec, {own_chroma} \
2641 own-extent 1:4 chroma gather(s)"
2642 );
2643 }
2644
2645 // The specificity arm: the SAME source, flags and 1:4 partitions at
2646 // 4:2:0 must not touch the 4:4:4-only route. If a later change made
2647 // the counter fire everywhere, this arm is what catches it.
2648 if !have_aomenc() {
2649 eprintln!("{NAME}: no aomenc, 4:2:0 specificity arm skipped");
2650 return;
2651 }
2652 let source = format!("testsrc2=size={W}x{H}:rate=25");
2653 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2654 .args([
2655 "-v",
2656 "error",
2657 "-f",
2658 "lavfi",
2659 "-i",
2660 &source,
2661 "-frames:v",
2662 "2",
2663 "-pix_fmt",
2664 "yuv420p",
2665 "-strict",
2666 "-1",
2667 "-f",
2668 "yuv4mpegpipe",
2669 "-",
2670 ])
2671 .stdin(Stdio::null())
2672 .stdout(Stdio::piped())
2673 .stderr(Stdio::piped()), None, |c| c.output())
2674 .expect("ffmpeg failed to run");
2675 assert!(
2676 y4m.status.success(),
2677 "{NAME}: ffmpeg refused the 4:2:0 control source: {}",
2678 String::from_utf8_lossy(&y4m.stderr)
2679 );
2680 let out = run_with_stdin(
2681 Command::new(aomenc_path()).args([
2682 "--codec=av1",
2683 "--passes=1",
2684 "--end-usage=q",
2685 "--cq-level=20",
2686 "--cpu-used=2",
2687 "--threads=1",
2688 "--row-mt=0",
2689 "--lag-in-frames=0",
2690 "--kf-max-dist=100",
2691 "--limit=2",
2692 "--obu",
2693 "-o",
2694 "-",
2695 "-",
2696 ]),
2697 &y4m.stdout,
2698 );
2699 assert!(
2700 out.status.success(),
2701 "{NAME}: aomenc refused the 4:2:0 control recipe: {}",
2702 String::from_utf8_lossy(&out.stderr)
2703 );
2704 crate::decode::reset_rect4_inter_own_chroma444_hits();
2705 decode_stream(&out.stdout)
2706 .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control stream was refused: {e}"));
2707 let (h4, v4, _, _) = crate::decode::inter16_rect4_counters();
2708 // The control must actually code 1:4 inter strips, or it says nothing
2709 // about the arm the fix touches. Measured: 16 HORZ_4, 28 VERT_4.
2710 assert!(
2711 h4 + v4 > 0,
2712 "{NAME}: the 4:2:0 control coded NO 1:4 inter strip ({h4} HORZ_4, {v4} \
2713 VERT_4) -- the identity arm below would say nothing about 1:4 strips"
2714 );
2715 assert_eq!(
2716 crate::decode::rect4_inter_own_chroma444_hits(),
2717 0,
2718 "{NAME}: the 4:2:0 control fired the ss_x-0 own-extent route -- the route \
2719 is not specific to the 4:4:4 cell it was fixed for"
2720 );
2721 // The identity half: the fix adds an arm gated on `ss_x == 0`, so a
2722 // 4:2:0 stream must stay byte-exact through it. This is the arm that
2723 // would go red if the new arm were ever widened past ss_x 0.
2724 if aomdec_available(NAME) {
2725 decode_all_frames_vs_oracle(&out.stdout, &format!("{NAME}-420"));
2726 }
2727 eprintln!("{NAME}: 4:2:0 control {h4} HORZ_4 / {v4} VERT_4 strips, 0 own-extent gathers");
2728 }
2729
2730 /// lane-av1gates444 cell 1: **odd coded dims, 66x66** -- the partial-frame
2731 /// walk in BOTH axes (66 is not a multiple of 8, so the frame is a
2732 /// partial superblock column AND a partial row). Measured EXACT 4/4 by
2733 /// the chroma-format sweep (§6.2, 5938 bytes) and unpinned: nothing in
2734 /// the crate would go red if the odd-dimension 4:4:4 walk regressed,
2735 /// and the only red-before evidence was a lane report nobody re-runs.
2736 #[test]
2737 fn a_444_lossy_odd_66x66_stream_decodes_pixel_exact() {
2738 gate_444_lossy_live_exact("a_444_lossy_odd_66x66_stream_decodes_pixel_exact", 66, 66);
2739 }
2740
2741 /// lane-av1gates444 cell 2: **odd coded dims, 130x122** -- the
2742 /// partial-frame RIGHT edge that the sweep found DIVERGENT (first wrong
2743 /// sample Y(128,16), 11521 samples on frame 3) until lane-av1444rect's
2744 /// 4:4:4 own-chroma-extent fix landed. It measures EXACT 4/4 on this
2745 /// tree and is the discriminating geometry: 66x66 was exact at the same
2746 /// settings while this was not, so the pair is what keeps "the 4:4:4
2747 /// partial-frame walk is right" from being a one-geometry accident.
2748 #[test]
2749 fn a_444_lossy_odd_130x122_stream_decodes_pixel_exact() {
2750 gate_444_lossy_live_exact(
2751 "a_444_lossy_odd_130x122_stream_decodes_pixel_exact",
2752 130,
2753 122,
2754 );
2755 }
2756
2757 /// lane-av1gates444 cell 3: **256x128**, the sweep's cell recorded as
2758 /// "4:4:4 superres 256x128 (`--superres-mode=1`)".
2759 ///
2760 /// IT IS NOT A SUPERRES CELL, and this gate is named for what it is
2761 /// instead. Measured here, live: encoding 256x128 with and without
2762 /// `--superres-mode=1` produces BYTE-IDENTICAL OBU (15239 bytes,
2763 /// sha256 06621606…, both), so the flag is a no-op on this aomenc build
2764 /// and the sweep's cell was a plain 4:4:4 lossy cq-20 stream that
2765 /// happened to carry the flag. The cell's actual value is the geometry
2766 /// plus the filter stages: 256x128 is two full 128 superblock columns,
2767 /// and the strip walk runs there with the post-deblock/CDEF/LR chain
2768 /// live on the later frames -- so this is the third witness for the
2769 /// 4:4:4 lossy strip class at a geometry the 128x96 rect4 gate does not
2770 /// cover.
2771 #[test]
2772 fn a_444_lossy_256x128_stream_decodes_pixel_exact() {
2773 gate_444_lossy_live_exact("a_444_lossy_256x128_stream_decodes_pixel_exact", 256, 128);
2774 }
2775
2776 /// lane-av1txctxband — the 4:4:4 lossy `--sb-size=128` stream whose
2777 /// `EC_SYMR` ladder forked at read 32813, and the gate that makes the fix
2778 /// non-vacuous.
2779 ///
2780 /// **The defect.** `get_tx_size_context` (libaom
2781 /// `av1/common/pred_common.h:361-370`) gates its "an inter neighbour
2782 /// contributes its own BLOCK size" override on `xd->above_mbmi` /
2783 /// `xd->left_mbmi`, which `set_mi_offsets`
2784 /// (`av1_common_int.h:1381-1389`) takes as `xd->mi[-xd->mi_stride]` /
2785 /// `xd->mi[-1]`. `setup_mbs` (`decodeframe.c:355-361`) writes the covering
2786 /// block's own `MB_MODE_INFO` pointer into EVERY mi cell the block covers,
2787 /// so libaom's granularity is the covering block PER CELL. This decoder
2788 /// read the per-COLUMN `above_inter`/`left_inter` bands and the matching
2789 /// `above_side_mi`/`left_side_mi` bands instead — the LAST block written in
2790 /// that column, which names the abutting block only for the block directly
2791 /// below it. On this witness the 8x4 intra leaf at mi(57,52) (SB row 1,
2792 /// col 1) read a stale `above_inter=true` with `above_side=4`, took the
2793 /// override, got `above = (4 >= 8) = 0` where libaom keeps
2794 /// `above = (above_txfm_context[0] >= 8) = 1`, and read
2795 /// `tx_size_cat0[1]` where libaom reads `tx_size_cdf[...][2]`.
2796 ///
2797 /// **The fork signature that identifies it** (a CDF-row error, not a
2798 /// unit-enumeration one): the two sides held the IDENTICAL pre-state
2799 /// `pre=(7550, 45492)` and the IDENTICAL width/value `n=2 s=1`; only
2800 /// `cdf0` differed, ours 6424 (`32768-6424 = 26344`) vs the oracle's
2801 /// 19938, so the ICDF mirror convention does not reconcile it either.
2802 ///
2803 /// **Non-vacuity.** The pixel assert alone would be green on the old code
2804 /// for any stream where the bands happened to be right, so the gate also
2805 /// asserts `txctx_inter_cell_band_divergence_hits() > 0` — the number of
2806 /// `get_tx_size_context` reads where the per-CELL cover and the
2807 /// per-COLUMN band DISAGREE, i.e. exactly the reads the old code resolved
2808 /// off a different CDF row. Reverting either reader to the bands drives
2809 /// this to 0 and the gate red, with the oracle compare as the second,
2810 /// independent arm.
2811 ///
2812 /// **Fixture provenance** (`444_lossy_sb128_txctx_witness.obu`, 6186 B,
2813 /// sha256 `14acb74e825a2bb3ef195a52cc2abc67794d9c4d92080b66c739d318177fc7c6`):
2814 /// ```text
2815 /// ffmpeg -f lavfi -i "testsrc2=size=256x256:rate=25" -frames:v 2 \
2816 /// -pix_fmt yuv444p -strict -1 -f yuv4mpegpipe -y src.y4m
2817 /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=62 --cpu-used=2 \
2818 /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 \
2819 /// --sb-size=128 --profile=1 --obu -o t256.obu src.y4m
2820 /// ```
2821 /// 256x256 is the smallest geometry that gives `--sb-size=128` a SECOND
2822 /// superblock row and column, which is where the stale band bites: a cell
2823 /// whose abutting block is not the last block written in its column. The
2824 /// cq level is load-bearing — this cell is entropy-exact at cq 20..58 and
2825 /// forks at 54/56/60/62 depending on the frame count (12 of the 99 cells
2826 /// swept in `lanes/av1txctxband.report.md` §4 forked, all of them at
2827 /// cq >= 54 on 256x256/320x240/256x384). `--sb-size=128` is load-bearing
2828 /// too: at the default 64 the two superblock columns are 4 mi wide, so a
2829 /// column band and a per-cell cover coincide for every 4-column run.
2830 #[test]
2831 fn a_444_lossy_sb128_txctx_reads_the_covering_block_per_cell() {
2832 const NAME: &str = "a_444_lossy_sb128_txctx_reads_the_covering_block_per_cell";
2833 let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2834 .join("fixtures/444_lossy_sb128_txctx_witness.obu");
2835 let bytes = std::fs::read(&path).unwrap_or_else(|e| {
2836 panic!(
2837 "{NAME}: pinned fixture {} is missing ({e}) -- a failure, not a skip",
2838 path.display()
2839 )
2840 });
2841 assert_eq!(bytes.len(), 6186, "{NAME}: fixture length moved");
2842 assert_eq!(
2843 fnv1a64(&bytes),
2844 0x2ec1_bb1b_5196_c4b3,
2845 "{NAME}: fixture bytes moved"
2846 );
2847
2848 let _guard = lock_gate_counters();
2849 crate::decode::reset_txctx_inter_cell_band_divergence_hits();
2850 let frames = decode_stream(&bytes)
2851 .unwrap_or_else(|e| panic!("{NAME}: the pinned 4:4:4 stream was refused: {e}"));
2852 assert_eq!(frames.len(), 2, "{NAME}: frame count");
2853 let diverged = crate::decode::txctx_inter_cell_band_divergence_hits();
2854 assert!(
2855 diverged > 0,
2856 "{NAME}: no `get_tx_size_context` read on this stream had the \
2857 per-CELL cover and the per-COLUMN band disagree, so the witness \
2858 does not exercise the corrected read at all (class \
2859 gate-blind-to-feature) -- re-encode per the recipe above"
2860 );
2861 if aomdec_available(NAME) {
2862 decode_all_frames_vs_oracle(&bytes, NAME);
2863 }
2864 eprintln!(
2865 "{NAME}: {diverged} tx_depth read(s) where the per-cell cover and \
2866 the per-column band disagreed (the 8x4 intra leaf at mi(57,52) is \
2867 the one that forked the ladder at read 32813)"
2868 );
2869 }
2870
2871 /// lane-arfchroma: 4:2:0 **lossless** with an alt-ref frame and 1:4 inter
2872 /// strips. Ordinary, user-reachable aomenc output, no bypass: before the
2873 /// fix this cell diverged in 15 of 16 shown frames (1 088 573 wrong
2874 /// samples, only frames 0-1 exact) or -- one knob away, e.g.
2875 /// `--sb-size=64`, `--enable-dual-filter=0`, `--max-reference-frames=3`,
2876 /// or the same stream cut to 5-12 frames -- REFUSED outright with
2877 /// `a Golomb tail longer than this decoder reads`. The refusal was this
2878 /// divergence arriving at a named guard, not an independent gap: the
2879 /// `16-frame` variant of this exact cell now decodes byte-exact.
2880 ///
2881 /// Mechanism (paired rungs, `EC_COEFF_STEP` / `EC_ECDUMP` against
2882 /// aomdec, 320x240, 5 frames): the first forked read is frame 2's 8x8
2883 /// inter block at mi (4,0) (ref0 = 7 = ALTREF, mv (36,0), NEWMV), its
2884 /// CHROMA U `txb_skip` read. All four LUMA units match read for read, and
2885 /// the chroma read's pre-state `(rng 35592)` is IDENTICAL on both sides --
2886 /// only the context differs: ours 2, libaom 8
2887 /// (`7 + get_entropy_context`, `txb_common.h:360`). `EC_ECDUMP` names the
2888 /// cause: libaom's chroma left neighbour is `[0]` and ours is coded. The
2889 /// publisher is the 16x4 (1:4) strip above it: `record_mi_chroma`
2890 /// published the unit at the BLOCK's mi origin, but a 4x4 chroma unit is
2891 /// `1 << ss` luma mi per axis, so a strip whose mi row is ODD at 4:2:0
2892 /// starts mid-cell and its state landed one mi row too low -- into the
2893 /// cell of the block that read it. libaom's per-plane
2894 /// `left/above_context_map` is indexed in the PLANE's own 4x4 units
2895 /// (`entropy.h:87`, `txb_common.h:429`), so the cell's origin is the
2896 /// step-aligned mi, which is what the fix aligns to.
2897 ///
2898 /// The gate asserts three things, in this order: the pin's identity, the
2899 /// mid-cell route counter (so it cannot pass on a stream whose chroma
2900 /// units all start on a cell boundary -- class
2901 /// gate-blind-to-feature), and then BOTH comparisons: decode order
2902 /// (which sees the hidden alt-ref frame no shown-frame gate can) and the
2903 /// per-plane shown-frame count.
2904 ///
2905 /// Recipe (both sides reproducible, 28394 bytes):
2906 /// ```text
2907 /// ffmpeg -f lavfi -i testsrc2=size=320x240:rate=25 -frames:v 5 \
2908 /// -pix_fmt yuv420p y.yuv
2909 /// aomenc --codec=av1 --obu --lossless=1 -w 320 -h 240 \
2910 /// --lag-in-frames=25 --auto-alt-ref=1 --limit=5 -o w.obu y.yuv
2911 /// ```
2912 /// sha256 c5507ed97f74ca495b71449fda24f5fe2fcfa34eed38988a69141d45b126627c.
2913 /// The tree pins fixture identity by fnv1a64; a `const SHA256` compared
2914 /// against itself would be the tautology lane-av1422anom exists to kill.
2915 #[test]
2916 fn a_420_lossless_alt_ref_1to4_strip_witness_is_byte_exact_in_decode_order() {
2917 const NAME: &str =
2918 "a_420_lossless_alt_ref_1to4_strip_witness_is_byte_exact_in_decode_order";
2919 // lane-av1cmpaudit2: same mutex as every other oracle gate.
2920 let _gate_lock = lock_gate_counters();
2921 const FILE: &str = "420_lossless_arf_1to4_320x240_5f.obu";
2922 const BYTES: usize = 28394;
2923 const FNV1A64: u64 = 16971188390893372935;
2924 let path = crate_pin("420_lossless_arf_1to4_320x240_5f.obu");
2925 let data = std::fs::read(&path)
2926 .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})"));
2927 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
2928 assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted");
2929 crate::decode::reset_chroma_midcell_pub_hits();
2930 let (decoded, hidden) = decode_all_frames_vs_oracle(&data, NAME);
2931 assert_eq!(
2932 decoded, 6,
2933 "{NAME}: the oracle decoded {decoded} frames in DECODE order; the 5-frame recipe \
2934 carries 5 source frames, one of them a hidden alt-ref picture plus a \
2935 `show_existing_frame` header"
2936 );
2937 assert_eq!(
2938 hidden, 1,
2939 "{NAME}: this cell exists for the HIDDEN alt-ref frame -- {decoded} decode-order \
2940 dumps against {decoded} - {hidden} shown outputs means the gate saw the picture no \
2941 shown-frame compare can reach"
2942 );
2943 let mid = crate::decode::chroma_midcell_pub_hits();
2944 assert!(
2945 mid[2] > 0 || mid[0] + mid[1] > 0,
2946 "{NAME}: no chroma transform unit was published from a mid-cell origin \
2947 ({mid:?} = [row, col, both]), so this witness does not exercise the origin \
2948 alignment at all (class gate-blind-to-feature) -- re-encode per the recipe above"
2949 );
2950 let (wy, wu, wv, shown, exact) =
2951 count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
2952 assert_eq!(
2953 (wy, wu, wv, exact),
2954 (0, 0, 0, shown),
2955 "{NAME}: shown-frame per-plane diff vs `aomdec --rawvideo`"
2956 );
2957 eprintln!(
2958 "{NAME}: {decoded} decode-order frame(s) byte-exact ({hidden} hidden), \
2959 {shown} shown frame(s) exact per plane, mid-cell chroma publications {mid:?}"
2960 );
2961 }
2962
2963 /// lane-av1mixllfork: per-segment MIXED LOSSLESS + an alt-ref structure.
2964 /// The first fork was entropy read **30889** of f1 (paired `EC_SYMR`:
2965 /// identical `pre[0..1]`, `n`, `s` on both sides, `post_rng` 42076 vs
2966 /// 54010), and the pre-fix `cdf0` at that read was 22401 vs the oracle's
2967 /// 15299 -- **not** the usual `32768 - x` ICDF mirror, i.e. two different
2968 /// reads, not one wrong CDF row.
2969 ///
2970 /// What each side read there: libaom `decodetxb.c:158`, the luma `txb_skip`
2971 /// of a TX_4X4 unit at `mi=(6,1)` `bc=0 br=0`; ours an untagged `n=2`
2972 /// symbol that a `set_symr_cdf` sweep over all six MV-stack copies
2973 /// (`ii16/newmv16/…/refmvB`, `inter8` phase inherited) ruled out as every
2974 /// inter mode-info read, leaving the one read that block makes *between*
2975 /// its `refmv` and its coefficients: the var-tx tree's `tx_size_cat1`.
2976 /// libaom's own reason it reads nothing: `parse_decode_block`
2977 /// (`decodeframe.c:1237`) carries `!xd->lossless[mbmi->segment_id]` as a
2978 /// **conjunct** of the tx-mode-select condition, and `read_tx_size`
2979 /// (`:1208`) answers TX_4X4 on the same flag. This tree tested
2980 /// `tx_select && !skip` and put `lossless(fctx) && !skip` in the `else if`
2981 /// arm instead, so on a lossless SEGMENT of a mixed-lossless frame it read
2982 /// a `tx_size_cat1` symbol libaom never reads, and the very next block's
2983 /// `txb_skip` forked. `SUB8_LOSSLESS_NO_VARTX` counts the leaves that
2984 /// newly take the lossless arm, so this gate cannot pass vacuously on a
2985 /// stream whose sub-8 leaves all sit in lossy segments. (Corrected
2986 /// 2026-09-30: the counter is now guarded on `tx_select_inter`, because the
2987 /// refutation pass measured 33 hits on a build with the conjunct REMOVED --
2988 /// the arm also serves leaves whose tx-select is off. The pin's own delta
2989 /// is 10, not the 40 the lane first reported; both numbers are measured.)
2990 ///
2991 /// The trigger really is the CONJUNCTION: `--cq-level=0` with AQ makes
2992 /// *some* segments lossless and others not (`--cq-level=20`, `--cq-level=32`,
2993 /// `--lossless=1` and `--aq-mode=0` are all byte-exact on this recipe), and
2994 /// `--auto-alt-ref=0` makes it exact at 5, 6, 8 and 12 frames. After the
2995 /// fix the whole-stream `EC_SYMR` ladder is bit-identical: **96997 reads,
2996 /// 96997 paired, zero divergence** -- not just up to the fork.
2997 ///
2998 /// Recipe (ffmpeg 8.1.3 `testsrc2`, shared oracle `aomenc`, 18525 bytes):
2999 /// ```text
3000 /// ffmpeg -f lavfi -i testsrc2=size=256x128:rate=25 -frames:v 5 \
3001 /// -pix_fmt yuv420p src5b.y4m
3002 /// aomenc --codec=av1 --obu -o c_mix5.obu --passes=1 --cpu-used=4 \
3003 /// --limit=5 --end-usage=q --cq-level=0 --aq-mode=1 src5b.y4m
3004 /// ```
3005 /// sha256 `3e06b5641e6a0f5a3f4ac8f114d4ee48c88638429e9eaafe6b4483e24f1dbc3a`.
3006 /// The tree pins fixture identity by fnv1a64; a `const SHA256` compared
3007 /// against itself would be the tautology lane-av1422anom exists to kill.
3008 #[test]
3009 fn a_420_mixed_lossless_alt_ref_sub8_vartx_witness_is_byte_exact_in_decode_order() {
3010 const NAME: &str =
3011 "a_420_mixed_lossless_alt_ref_sub8_vartx_witness_is_byte_exact_in_decode_order";
3012 let _gate_lock = lock_gate_counters();
3013 const FILE: &str = "420_mixll_altref_256x128_5f.obu";
3014 const BYTES: usize = 18525;
3015 const FNV1A64: u64 = 16348502764482216576;
3016 let path = crate_pin(FILE);
3017 let data = std::fs::read(&path)
3018 .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})"));
3019 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
3020 assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted");
3021 let before = crate::decode::sub8_lossless_no_vartx();
3022 let (decoded, hidden) = decode_all_frames_vs_oracle(&data, NAME);
3023 let suppressed = crate::decode::sub8_lossless_no_vartx() - before;
3024 assert_eq!(
3025 decoded, 6,
3026 "{NAME}: the oracle decoded {decoded} frames in DECODE order; the 5-frame \
3027 altref recipe codes 5 source frames plus a hidden alt-ref picture"
3028 );
3029 assert_eq!(
3030 hidden, 1,
3031 "{NAME}: {decoded} decode-order dumps against {decoded} - {hidden} shown outputs \
3032 means the gate saw the hidden picture no shown-frame compare can reach"
3033 );
3034 assert!(
3035 suppressed > 0,
3036 "{NAME}: no sub-8 (4x8/8x4) inter leaf on a LOSSLESS segment read no var-tx \
3037 symbol ({suppressed} of them did), so this witness does not exercise the \
3038 ordering at all (class gate-blind-to-feature) -- re-encode per the recipe above"
3039 );
3040 let (wy, wu, wv, shown, exact) =
3041 count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
3042 assert_eq!(
3043 (wy, wu, wv, exact),
3044 (0, 0, 0, shown),
3045 "{NAME}: shown-frame per-plane diff vs `aomdec --rawvideo`"
3046 );
3047 eprintln!(
3048 "{NAME}: {decoded} decode-order frame(s) byte-exact ({hidden} hidden), \
3049 {shown} shown frame(s) exact per plane, {suppressed} sub-8 leaf/leaves on a \
3050 lossless segment read no var-tx symbol"
3051 );
3052 }
3053
3054 /// lane-av1txctxband2: the 640x480 cell of the same mixed-lossless
3055 /// recipe — the THIRD defect `lanes/av1mixllconj.report.md` §4.3 /
3056 /// §11 handed over, class `context-band-not-published`.
3057 ///
3058 /// libaom's `parse_decode_block` (`decodeframe.c:1251-1261`) is an
3059 /// EITHER/OR: the var-tx branch's condition carries
3060 /// `!xd->lossless[mbmi->segment_id]` as a conjunct, and the `else` branch
3061 /// runs `read_tx_size` **and then `set_txfm_ctxs`**. `read_tx_size`'s
3062 /// FIRST line (`decodeframe.c:1214`) returns `TX_4X4` on a lossless
3063 /// segment — so a lossless block skips the symbol read, NOT the publish.
3064 /// This decoder's `read_block_tx_size` returned from its own lossless early
3065 /// return with nothing written, so on a MIXED frame every lossless square
3066 /// block left the `TXFM_CONTEXT` above band holding whatever an earlier,
3067 /// lossy block had put there. The RECT twin (`read_block_tx_size_rect`)
3068 /// has published on the same arm since lane-av1lm444loss; only the square
3069 /// arm had the hole.
3070 ///
3071 /// Measured on `420_mixll_altref_640x480_5f.obu`: the abutting 8x8 INTRA
3072 /// lossless block at mi(78,110) left `above_txfm[110]` at the 16 a skipped
3073 /// 16-px inter block at mi(36,108) had written 43 mi rows earlier, and the
3074 /// 8x4 intra leaf with `use_filter_intra` at mi(80,110) then read
3075 /// `tx_size_cat0[2]` where libaom reads row 1 — the oracle's own
3076 /// `EC_TXCTXB` prints `mi=80,110 abv=4 lft=8 above=0 left=1 ctx=1` against
3077 /// our `above_txfm=16 left_txfm=8 above=1 left=1 ctx=2`. The tile desynced
3078 /// there and the frame REFUSED (`a Golomb tail longer than this decoder
3079 /// reads`); at base the same cell decoded every frame but got 70–92 % of
3080 /// every inter frame wrong.
3081 ///
3082 /// `LOSSLESS_SQ_TXFM_BAND_OVERWRITE_HITS` counts the lossless square inter
3083 /// blocks whose publish actually OVERWROTE a size an earlier block of the
3084 /// same frame had left in the column — so the gate cannot pass vacuously
3085 /// on a stream that merely decodes a lossless fixture. After the fix the
3086 /// whole-stream paired `EC_SYMR` ladder is bit-identical: **457 907 reads,
3087 /// 457 907 paired, zero divergence** — not just up to the fork.
3088 ///
3089 /// Recipe (ffmpeg 8.1.3 `testsrc2`, shared oracle `aomenc`, 87537 bytes):
3090 /// ```text
3091 /// ffmpeg -f lavfi -i testsrc2=size=640x480:rate=25 -frames:v 5 \
3092 /// -pix_fmt yuv420p src640.y4m
3093 /// aomenc --codec=av1 --obu -o 420_mixll_altref_640x480_5f.obu --passes=1 \
3094 /// --cpu-used=4 --limit=5 --end-usage=q --cq-level=0 --aq-mode=1 src640.y4m
3095 /// ```
3096 /// sha256 `3d505fd2e0bbb7ca3680a8e338d712a81defc947b955a4b7b82de6718301e73c`;
3097 /// the tree pins fixture identity by fnv1a64, not a `const SHA256` compared
3098 /// against itself.
3099 #[test]
3100 fn a_420_mixed_lossless_alt_ref_640x480_txfm_band_publish_is_byte_exact_in_decode_order() {
3101 const NAME: &str = "a_420_mixed_lossless_alt_ref_640x480_txfm_band_publish_is_byte_exact_\
3102 in_decode_order";
3103 let _gate_lock = lock_gate_counters();
3104 const FILE: &str = "420_mixll_altref_640x480_5f.obu";
3105 const BYTES: usize = 87537;
3106 const FNV1A64: u64 = 12707865649077681891;
3107 let path = crate_pin(FILE);
3108 let data = std::fs::read(&path)
3109 .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})"));
3110 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
3111 assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted");
3112 let before = crate::decode::lossless_sq_txfm_band_overwrite_hits();
3113 let (decoded, hidden) = decode_all_frames_vs_oracle(&data, NAME);
3114 let overwrote = crate::decode::lossless_sq_txfm_band_overwrite_hits() - before;
3115 assert_eq!(
3116 decoded, 6,
3117 "{NAME}: the oracle decoded {decoded} frames in DECODE order; the 5-frame \
3118 altref recipe codes 5 source frames plus a hidden alt-ref picture"
3119 );
3120 assert_eq!(
3121 hidden, 1,
3122 "{NAME}: {decoded} decode-order dumps against {decoded} - {hidden} shown outputs \
3123 means the gate saw the hidden picture no shown-frame compare can reach"
3124 );
3125 assert!(
3126 overwrote > 0,
3127 "{NAME}: no lossless square block on an inter frame published a txfm band that \
3128 OVERWROTE an earlier block's size ({overwrote} of them did), so this witness does \
3129 not exercise the missing publish at all (class gate-blind-to-feature) -- re-encode \
3130 per the recipe above"
3131 );
3132 let (wy, wu, wv, shown, exact) =
3133 count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
3134 assert_eq!(
3135 (wy, wu, wv, exact),
3136 (0, 0, 0, shown),
3137 "{NAME}: shown-frame per-plane diff vs `aomdec --rawvideo`"
3138 );
3139 eprintln!(
3140 "{NAME}: {decoded} decode-order frame(s) byte-exact ({hidden} hidden), \
3141 {shown} shown frame(s) exact per plane, {overwrote} lossless square inter \
3142 block(s) overwrote a stale above-band size"
3143 );
3144 }
3145
3146 /// lane-av1txctxband2 r2: the SAME one-line publish, three MORE cells —
3147 /// the mixed-lossless RESIDUE `lanes/av1mixllconj.report.md` §7 left
3148 /// explicitly unnamed ("separate defects this change shrinks but does not
3149 /// remove"). **They are the same defect.** All three are this recipe's
3150 /// mixed-lossless+altref stream at 256x128 (6 frames) and 320x240 (5 and 6
3151 /// frames); each has a lossy block whose `get_tx_size_context` /
3152 /// `txfm_partition_context` read a band a lossless block above should have
3153 /// published into and did not.
3154 ///
3155 /// Measured on `f2dd27b0~1` (= `0bfee517`, the tip before this lane's
3156 /// publish) against `aomdec`'s `EC_AV1_FINAL_DUMP`, decode order, per
3157 /// differing frame:
3158 ///
3159 /// ```text
3160 /// 420_mixll_256x128_6f.obu 7 dumps red f1..f6: 6051 / 4115 / 2962 / 26566 / 41876 / 14749
3161 /// 420_mixll_320x240_5f.obu 6 dumps red f1..f5: 15031 / 16259 / 21932 / 65405 / 90077
3162 /// 420_mixll_320x240_6f.obu 7 dumps red f6 only: 19398
3163 /// ```
3164 ///
3165 /// With the publish: **7/7, 6/6 and 7/7 byte-exact**, 0 differing bytes on
3166 /// every plane of every decode-order frame. `m5_320x240`'s f2/f3 here
3167 /// (16259 / 21932) differ from the 16006 / 21930 `lane-av1mixllconj` §7
3168 /// records, because that table was taken before `lane-av1offtile`'s
3169 /// chroma-plane clip merged; f1/f4/f5 and both other cells match it exactly.
3170 ///
3171 /// Recipe (ffmpeg 8.1.3 `testsrc2`, shared oracle `aomenc`; `--limit` is the
3172 /// only variable per cell):
3173 /// ```text
3174 /// ffmpeg -f lavfi -i testsrc2=size=<W>x<H>:rate=25 -frames:v <N> -pix_fmt yuv420p src.y4m
3175 /// aomenc --codec=av1 --obu -o <cell>.obu --passes=1 --cpu-used=4 --limit=<N> \
3176 /// --end-usage=q --cq-level=0 --aq-mode=1 src.y4m
3177 /// ```
3178 /// sha256 `8a203e52…` (22336 B), `40d613fd…` (28716 B), `37fbe7cb…`
3179 /// (38686 B); pinned below by fnv1a64, not a `const SHA256` compared
3180 /// against itself.
3181 #[test]
3182 fn a_420_mixed_lossless_residue_arms_are_byte_exact_in_decode_order() {
3183 const NAME: &str = "a_420_mixed_lossless_residue_arms_are_byte_exact_in_decode_order";
3184 let _gate_lock = lock_gate_counters();
3185 // (file, bytes, fnv1a64, decode-order frames, hidden)
3186 const CELLS: [(&str, usize, u64, usize, usize); 3] = [
3187 ("420_mixll_256x128_6f.obu", 22336, 5694016005779287373, 7, 1),
3188 ("420_mixll_320x240_5f.obu", 28716, 5855109243102450179, 6, 1),
3189 ("420_mixll_320x240_6f.obu", 38686, 49021385186397678, 7, 1),
3190 ];
3191 for (file, bytes, fnv, frames, hidden) in CELLS {
3192 let path = crate_pin(file);
3193 let data = std::fs::read(&path)
3194 .unwrap_or_else(|e| panic!("{NAME}: the committed pin {file} is missing ({e})"));
3195 assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
3196 assert_eq!(fnv1a64(&data), fnv, "{NAME}: {file} bytes drifted");
3197 let before = crate::decode::lossless_sq_txfm_band_overwrite_hits();
3198 let (decoded, got_hidden) = decode_all_frames_vs_oracle(&data, file);
3199 let overwrote = crate::decode::lossless_sq_txfm_band_overwrite_hits() - before;
3200 assert_eq!(
3201 decoded, frames,
3202 "{NAME}/{file}: the oracle decoded {decoded} frames in DECODE order"
3203 );
3204 assert_eq!(
3205 got_hidden, hidden,
3206 "{NAME}/{file}: {decoded} decode-order dumps against {decoded} - {got_hidden} \
3207 shown outputs means the gate saw {hidden} hidden alt-ref picture/ies"
3208 );
3209 assert!(
3210 overwrote > 0,
3211 "{NAME}/{file}: no lossless square block on an inter frame published a txfm \
3212 band that OVERWROTE an earlier block's size ({overwrote} of them did), so this \
3213 cell does not exercise the missing publish at all (class \
3214 gate-blind-to-feature) -- re-encode per the recipe above"
3215 );
3216 eprintln!(
3217 "{NAME}/{file}: {decoded} decode-order frame(s) byte-exact ({got_hidden} hidden), \
3218 {overwrote} lossless square inter block(s) overwrote a stale above-band size"
3219 );
3220 }
3221 }
3222
3223 /// lane-av1444rect r2 — the SAME class as the gate above, second
3224 /// instance: `decode_rect4_16_intrabc` applied the 4:2:0 pair geometry at
3225 /// ss (0,0), where `is_chroma_reference` makes an intra-BC 1:4 strip its
3226 /// own chroma reference. It predicted and coded an 8x4 chroma block at
3227 /// `(lmi - 1) * MI / 2` where libaom codes 16x4 at the strip's origin.
3228 ///
3229 /// **This is a PROGRESS gate, not an exactness gate, and it says so.** The
3230 /// 4:4:4 intra-BC cell is still divergent: after the ss gate the LUMA
3231 /// plane is exact to sample 205264 (it was 164416) and the entropy fork
3232 /// moves from read 11750 to 12465, but both CHROMA planes still first
3233 /// diverge at index 20532 and 390380 of 921600 samples are wrong. So the
3234 /// assertion is a prefix floor on the plane the gate actually moved —
3235 /// which only ever grows, and which the next lane's fix cannot turn red —
3236 /// and the untouched chroma divergence is named, never asserted exact.
3237 ///
3238 /// Recipe (both fixtures, one frame, `testsrc2 640x480 r=25`):
3239 /// ```text
3240 /// aomenc --codec=av1 --bit-depth=8 --input-bit-depth=8 --passes=1
3241 /// --end-usage=q --cpu-used=0 --lag-in-frames=0 --kf-max-dist=1
3242 /// --limit=1 --threads=1 --enable-rect-partitions=1
3243 /// --enable-1to4-partitions=1 --min-partition-size=4
3244 /// --max-partition-size=64 --sb-size=64 --tune-content=screen
3245 /// --enable-intrabc=1 --enable-palette=1 --cq-level=60
3246 /// --enable-tx-size-search=0 --obu [--profile=1] -o out.obu src.y4m
3247 /// ```
3248 /// 4:4:4 (1016 B, sha256 7fe888ed…) carries 17 intrabc 16x4 strips at
3249 /// ss (0,0); the 4:2:0 twin (890 B, sha256 d01352af…) is byte-exact and
3250 /// is the identity arm — the ss gate cannot reach it, and the whole frame
3251 /// is compared with the length asserted first.
3252 #[test]
3253 fn a_444_intrabc_rect4_reads_its_own_chroma_plane_block() {
3254 const NAME: &str = "a_444_intrabc_rect4_reads_its_own_chroma_plane_block";
3255 let read = |name: &str, file: &str, len: usize, fnv: u64| -> Vec<u8> {
3256 let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3257 .join(format!("fixtures/{file}"));
3258 let bytes = std::fs::read(&path).unwrap_or_else(|e| {
3259 panic!(
3260 "{name}: pinned fixture {} is missing ({e}) -- a failure, not a skip",
3261 path.display()
3262 )
3263 });
3264 assert_eq!(bytes.len(), len, "{name}: {file} length moved");
3265 assert_eq!(fnv1a64(&bytes), fnv, "{name}: {file} bytes moved");
3266 bytes
3267 };
3268 let stream444 = read(
3269 NAME,
3270 "444_intrabc_rect4_witness.obu",
3271 1016,
3272 0x27c2_fad5_4047_2994,
3273 );
3274 let stream420 = read(
3275 NAME,
3276 "420_intrabc_rect4_witness.obu",
3277 890,
3278 0x57ec_3da2_a63b_403a,
3279 );
3280
3281 let _guard = lock_gate_counters();
3282 crate::decode::reset_intrabc_rect4_own_chroma444_hits();
3283 let frames = decode_stream(&stream444)
3284 .unwrap_or_else(|e| panic!("{NAME}: the pinned 4:4:4 stream was refused: {e}"));
3285 let own = crate::decode::intrabc_rect4_own_chroma444_hits();
3286 assert!(
3287 own > 0,
3288 "{NAME}: no intra-BC 1:4 strip coded its own chroma plane block -- the \
3289 corrected route never ran (class gate-blind-to-feature)"
3290 );
3291 assert_eq!(frames.len(), 1, "{NAME}: frame count");
3292
3293 // The identity arm FIRST and in full: the 4:2:0 twin must stay
3294 // byte-exact. `decode_all_frames_vs_oracle` asserts the two frame
3295 // lengths match before it compares anything -- the check whose absence
3296 // turned an out-of-window divergence into a reported EXACT in this
3297 // lane's own round 1.
3298 if aomdec_available(NAME) {
3299 decode_all_frames_vs_oracle(&stream420, &format!("{NAME}-420"));
3300 crate::decode::reset_intrabc_rect4_own_chroma444_hits();
3301 decode_stream(&stream420)
3302 .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 twin was refused: {e}"));
3303 assert_eq!(
3304 crate::decode::intrabc_rect4_own_chroma444_hits(),
3305 0,
3306 "{NAME}: the 4:2:0 twin fired the ss (0,0)-only route"
3307 );
3308
3309 // NO 4:4:4 pixel assert here, and deliberately so. The cell is
3310 // still divergent (390380 of 921600 samples; both chroma planes
3311 // first wrong at index 20532, x=52 y=32; entropy fork read 12465
3312 // at mi (90,108)) and an assertion of the form "our output is
3313 // wrong by exactly N" would encode the defect as expected
3314 // behaviour -- the shape this suite refuses everywhere else, and
3315 // one that outlives the memory of why. The true assertions this
3316 // gate can make today are the two above: the route is reached at
3317 // 4:4:4 and is not reached at 4:2:0, and the 4:2:0 twin is
3318 // byte-exact. The open chroma root and its numbers live in
3319 // lanes/av1444rect.report.md §6, not in an assertion.
3320 eprintln!(
3321 "{NAME}: {own} own-chroma intra-BC strip(s) at 4:4:4, 0 at 4:2:0; \
3322 4:2:0 twin byte-exact; 4:4:4 intra-BC CHROMA still OPEN \
3323 (U/V first wrong at index 20532, entropy fork read 12465 at \
3324 mi (90,108)) -- see lanes/av1444rect.report.md \u{00a7}6"
3325 );
3326 }
3327 }
3328
3329 /// lane-av1-444interband: the DEFAULT-partition lossless 4:4:4 pin for
3330 /// the inter 16x4/4x16 strip's chroma band stamping (the pair_chroma
3331 /// 4:2:0-only gate, commit d5325172). Fixture pinned into `fixtures/`:
3332 /// testsrc2 128x96 yuv444p, aomenc `--profile=1 --lossless=1
3333 /// --enable-palette=0 --enable-intrabc=0 --passes=1 --cpu-used=4
3334 /// --limit=6 --obu` (the av1llkf.report.md recipe), 6 frames; 32487
3335 /// bytes, sha256
3336 /// `1e6dd4e05038c8d51e2c8d29f8c337130c4fea0aed629415535e6e53af9a2c72`.
3337 ///
3338 /// This is the stream whose frame 1 desynced at the 16x4 inter strip
3339 /// mi(2,8) -- its U bc=0 `txb_skip` read base 0 where aom reads base 1,
3340 /// because the skipped strip (1,8)'s pair-form context stamp smeared
3341 /// zero over `left[2][1]`. Two pins, both measured at d5325172:
3342 /// end-to-end, every sample of every frame must match the oracle
3343 /// aomdec exactly (the pre-fix tree refuses mid-frame-1, so the gate
3344 /// is red by refusal, not by silent pass), and the 1:4 counter delta
3345 /// must show the strips decoded WITHOUT the pair rewrite firing
3346 /// (`horz4=20 vert4=28 chroma_pairs=0` -- chroma_pairs > 0 on this
3347 /// pairless 4:4:4 stream is the defect reappearing, the
3348 /// class `pair-rewrite-at-ss0`).
3349 #[test]
3350 fn a_lossless_444_defaultp_inter_strip_stream_decodes_byte_exact() {
3351 const NAME: &str = "a_lossless_444_defaultp_inter_strip_stream_decodes_byte_exact";
3352 const FIXTURE_LEN: usize = 32487;
3353 const FIXTURE_FNV: u64 = 0x5278_9f0f_ce2d_1e52;
3354 const W: usize = 128;
3355 const H: usize = 96;
3356 const FRAMES: usize = 6;
3357 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3358 .join("fixtures/ll444_defaultp_inter_strip.obu");
3359 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
3360 panic!(
3361 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
3362 which is a failure, not a skip",
3363 obu.display()
3364 )
3365 });
3366 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
3367 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
3368
3369 let _guard = lock_gate_counters();
3370 let strips_before = decode::inter16_rect4_counters();
3371 let frames = decode_stream(&stream)
3372 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
3373 let strips_after = decode::inter16_rect4_counters();
3374 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
3375 for f in &frames {
3376 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
3377 }
3378 // The 1:4 strips must have fired, and the 4:2:0 pair rewrite must
3379 // NOT have (there are no chroma pairs at ss 0/0).
3380 let (horz4, vert4, chroma_pairs) = (
3381 strips_after.0 - strips_before.0,
3382 strips_after.1 - strips_before.1,
3383 strips_after.2 - strips_before.2,
3384 );
3385 assert_eq!(horz4, 20, "{NAME}: HORZ_4 strip count moved");
3386 assert_eq!(vert4, 28, "{NAME}: VERT_4 strip count moved");
3387 assert_eq!(
3388 chroma_pairs, 0,
3389 "{NAME}: chroma pairs closed on a 4:4:4 stream \
3390 (class pair-rewrite-at-ss0)"
3391 );
3392
3393 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
3394 if aomdec_available(NAME) {
3395 let dir = std::env::temp_dir().join(format!("ec-av1-ll444dp-{}", std::process::id()));
3396 let _ = std::fs::remove_dir_all(&dir);
3397 std::fs::create_dir_all(&dir).expect("scratch dir");
3398 let raw = dir.join("aomdec.raw");
3399 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
3400 .args(["--codec=av1", "--rawvideo", "-o"])
3401 .arg(&raw)
3402 .arg(&obu)
3403 .stdin(Stdio::null())
3404 .stdout(Stdio::piped())
3405 .stderr(Stdio::piped()), None, |c| c.output())
3406 .expect("aomdec failed to run");
3407 assert!(
3408 out.status.success(),
3409 "{NAME}: the oracle aomdec refused the stream: {}",
3410 String::from_utf8_lossy(&out.stderr)
3411 );
3412 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
3413 let _ = std::fs::remove_dir_all(&dir);
3414 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
3415 for (i, f) in frames.iter().enumerate() {
3416 let base = i * W * H * 3;
3417 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
3418 .into_iter()
3419 .zip(["y", "u", "v"])
3420 {
3421 let want = &ref_raw[base + off..base + off + W * H];
3422 let bad = plane
3423 .iter()
3424 .zip(want)
3425 .filter(|&(&a, &b)| a as u8 != b)
3426 .count();
3427 assert_eq!(
3428 bad, 0,
3429 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \
3430 (class pair-rewrite-at-ss0)"
3431 );
3432 }
3433 }
3434 }
3435 }
3436
3437 /// lane-av1-leaf8oob: the OOB pin for [`decode_leaf8`]'s intrabc chroma
3438 /// frame-copy buffers. The closure hardcoding the leaf's chroma
3439 /// prediction at `4x4` (`vec![0u16; 4 * 4]`, `predict_with_filter` at
3440 /// `4, 4`) carried the 4:2:0 halving of an 8x8 luma leaf into every
3441 /// subsampling: at 4:4:4 the leaf's own chroma plane block is 8x8
3442 /// (`csz == 8`), so the 16-sample override reached
3443 /// [`PlaneBuf::reconstruct`] as an 8x8 prediction and indexed
3444 /// `prediction[16]` of a 16-sample buffer --
3445 /// `index out of bounds: the len is 16 but the index is 16` at the
3446 /// reconstruct call, on every conformant stream of this shape (a panic,
3447 /// never a refusal). Same signature class as lane-lossless128's
3448 /// 128-axis lossless extent (`len 16, index 16` there too).
3449 ///
3450 /// `crates/ec-av1/fixtures/444_leaf8_oob.obu`, 3577 bytes, sha256
3451 /// `72bed2791d1ceba8be7926a052c7838c5d96d4f9d56d28fb69789a753d3593af`
3452 /// (force-added past the `fixtures` gitignore like every sibling
3453 /// fixture): the lane ticket's witness-hunt reproducer (s1a/s2e) -- a
3454 /// 320x256, 3-frame, 8-bit 4:4:4 screen-content keyframe run whose
3455 /// census pins 4 intrabc 8x8 leaves (the oracle's own MB dump opens on
3456 /// unbroken inter-classified intra = intrabc blocks). The encoding
3457 /// recipe is not independently recoverable in this lane; the bytes are
3458 /// pinned by length + FNV-1a64 here and by the oracle raw fingerprint
3459 /// below.
3460 ///
3461 /// WHAT THIS GATE DOES NOT CLAIM: sample-exactness -- and it pins no
3462 /// pixel baseline. Measured against the oracle aomdec (`--rawvideo`;
3463 /// comparison method ground-truthed by the green
3464 /// `a_lossless_sb128_rect_intra_block_decodes_sample_exact` and
3465 /// `a_lossless_444_min_partition8_inter_stream_decodes_sample_exact`
3466 /// witnesses on this same tree), this stream DIVERGES and its output is
3467 /// not even self-deterministic: frame 0's first differing LUMA sample
3468 /// is at (275,128), the (y, u, v) differing counts per frame are
3469 /// (20811, 35467, 32320)/(20308, 39177, 35994)/(20131, 39588, 36601) of
3470 /// 81920 samples per plane, and under `EC_AV1_PLANE_SENTINEL=1` the
3471 /// chroma counts move (u f0 35467 -> 35630) while luma stays put.
3472 /// Sentinel-vs-uninit output diffing localises that dependence to 458
3473 /// WHOLE 8x8 chroma blocks (frame 0: chroma x >= 96, y >= 64) reading
3474 /// samples this decode never wrote -- ambient memory in those slots,
3475 /// hence any pixel-exact assert here drifts run to run with the batch.
3476 /// Both facts belong to ONE pre-existing defect this lane must not
3477 /// chase (the ticket's fix touches only leaf8's chroma prediction
3478 /// buffers, which cannot feed a luma sample, and the pre-fix run never
3479 /// got past the panicked leaf): a decode desync on this stream around
3480 /// frame-0 SB (3..4, 2), after which samples diverge from the oracle
3481 /// and the misread layout leaves chroma blocks unreconstructed.
3482 /// Disposition: `deferred(unblock: divergence lane -- EC trace pairing
3483 /// against the oracle on this fixture)`. So this gate pins exactly what
3484 /// its ticket owns: fixture identity, a decode that RUNS TO COMPLETION
3485 /// where the old code died with `len 16, index 16`, and the arm counter.
3486 ///
3487 /// Assertions (all before/without any skip path):
3488 /// 1. fixture bytes: exact length + FNV-1a64;
3489 /// 2. `decode_stream` succeeds -- 3 frames, 320x256 (the pre-fix run
3490 /// died here with the len-16/index-16 panic);
3491 /// 3. non-vacuity: `leaf8_intrabc_hits` moves (measured 0 -> 4), so the
3492 /// arm owning the fixed buffers really fired;
3493 /// 4. the oracle aomdec still decodes the pinned bytes (raw size +
3494 /// fingerprint), anchoring the deferred divergence comparison.
3495 #[test]
3496 fn an_intrabc_8x8_leaf_chroma_frame_copy_at_444_decodes_without_the_oob() {
3497 const NAME: &str = "an_intrabc_8x8_leaf_chroma_frame_copy_at_444_decodes_without_the_oob";
3498 const FIXTURE_LEN: usize = 3577;
3499 const FIXTURE_FNV: u64 = 0x86b9_3a51_fe16_353c;
3500 const W: usize = 320;
3501 const H: usize = 256;
3502 const FRAMES: usize = 3;
3503 let obu =
3504 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures/444_leaf8_oob.obu");
3505 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
3506 panic!(
3507 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
3508 which is a failure, not a skip",
3509 obu.display()
3510 )
3511 });
3512 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
3513 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
3514
3515 let _guard = lock_gate_counters();
3516 crate::decode::reset_leaf8_intrabc_hits();
3517 let frames = decode_stream(&stream)
3518 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
3519 assert!(
3520 crate::decode::leaf8_intrabc_hits() > 0,
3521 "{NAME}: gate is vacuous -- no intrabc 8x8 leaf was decoded, so the arm \
3522 owning the fixed chroma buffers never fired"
3523 );
3524 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
3525 for f in &frames {
3526 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
3527 }
3528
3529 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
3530 if aomdec_available(NAME) {
3531 let dir = std::env::temp_dir().join(format!("ec-av1-leaf8oob-{}", std::process::id()));
3532 let _ = std::fs::remove_dir_all(&dir);
3533 std::fs::create_dir_all(&dir).expect("scratch dir");
3534 let raw = dir.join("aomdec.raw");
3535 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
3536 .args(["--codec=av1", "--rawvideo", "-o"])
3537 .arg(&raw)
3538 .arg(&obu)
3539 .stdin(Stdio::null())
3540 .stdout(Stdio::piped())
3541 .stderr(Stdio::piped()), None, |c| c.output())
3542 .expect("aomdec failed to run");
3543 assert!(
3544 out.status.success(),
3545 "{NAME}: the oracle aomdec refused the stream: {}",
3546 String::from_utf8_lossy(&out.stderr)
3547 );
3548 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
3549 let _ = std::fs::remove_dir_all(&dir);
3550 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
3551 assert_eq!(
3552 fnv1a64(&ref_raw),
3553 0x3821_0bcb_f572_973c,
3554 "{NAME}: aomdec raw fingerprint moved"
3555 );
3556 }
3557 }
3558
3559 /// lane-av1p1pin: the permanent pin for the 4:4:4 superblock-128
3560 /// 128-root rect witness -- recipe P1 of `lanes/av1witness2recheck.report.md`.
3561 ///
3562 /// Provenance. Encoder: `~/.cache/aom-oracle/build/aomenc --codec=av1
3563 /// --obu -o s1d.obu --passes=1 --threads=1 bands444.y4m --limit=3
3564 /// --kf-max-dist=1 --cpu-used=2 --end-usage=q --cq-level=20 --sb-size=128
3565 /// --enable-rect-partitions=1 --enable-1to4-partitions=1
3566 /// --min-partition-size=4`, over the ffmpeg 8.1.2 lavfi source
3567 /// `nullsrc=s=320x256:rate=30:d=1,geq=lum='mod(floor((Y+T*160)/8)*67,255)':
3568 /// cb='128+20*sin(Y/17+T)':cr='128+20*sin(X/23+T*2)' -pix_fmt yuv444p`
3569 /// (`bands444.y4m`, sha256
3570 /// `fa6218399cce8dd9eaadb6e24642d31cb2d2bde505b39a8df237938492c642ee`).
3571 /// Pinned bytes: `crates/ec-av1/fixtures/444_sb128rect_chroma_tile_witness.obu`,
3572 /// 595 bytes, sha256
3573 /// `68773f2c6e01a2d211bf0213479accb4c2c360132c0e1bc3b326eab7861925b1`
3574 /// (FNV-1a `0xd4fa_ac7b_dccc_520b`). Rebuilt byte-for-byte from the recipe
3575 /// on `9a535ccb` -- the recipe did not drift. 3 frames, 320x256, yuv444p.
3576 /// This is NOT `fixtures/444_sb128rect_lr_witness.obu` (794 B, sha256
3577 /// `27825e14...`), the other in-tree 4:4:4 sb128 stream.
3578 ///
3579 /// What it guards. At the report's old base `fe3e8418` this stream
3580 /// panicked -- rc=101, `decode.rs:17631: assertion failed: lossless_frame
3581 /// || (chroma_w / chroma_tx, chroma_h / chroma_tx) == (nch_x, nch_y)` --
3582 /// because the 128-rect chroma unit walk was hardcoded to the 4:2:0 mu-chunk
3583 /// span, so a 128-root HORZ/VERT block at 4:4:4 coded half its chroma units.
3584 /// Closed by `349b3918` (the per-axis invariant now at `decode.rs:24515`);
3585 /// byte-exactness by `fa70a68c`.
3586 ///
3587 /// Two load-bearing arms, both proven to bite (lanes/av1p1pin.report.md):
3588 /// (1) the census deltas -- 6 gathered edge-VERT 128-roots, 6
3589 /// `PARTITION_VERT` 128 roots, 6 key-frame intra 128-axis blocks, 8 coded
3590 /// `32x32` VERT strips -- so the gate fails, rather than passes, if a
3591 /// future stream stops coding the shape (class `gate-blind-to-feature`);
3592 /// (2) every sample of every frame against ffmpeg `yuv444p` rawvideo, with
3593 /// the plane-length guard that stops a short plane from zip-truncating the
3594 /// compare. Oracle arm is aomdec `--rawvideo` as well; neither is a shim.
3595 #[test]
3596 fn a_444_sb128_rect_chroma_tile_witness_is_byte_exact() {
3597 const NAME: &str = "a_444_sb128_rect_chroma_tile_witness_is_byte_exact";
3598 const FIXTURE_LEN: usize = 595;
3599 const FIXTURE_FNV: u64 = 0xd4fa_ac7b_dccc_520b;
3600 const W: usize = 320;
3601 const H: usize = 256;
3602 const FRAMES: usize = 3;
3603 /// The guarded path: 128-root rect chroma tiling at 4:4:4.
3604 const EDGE_VERT: usize = 6;
3605 const PART128_VERT: usize = 6;
3606 const INTRA128_VERT: usize = 6;
3607 const RECT4_32_VERT: usize = 8;
3608 const RECT4_32_CODED: usize = 8;
3609 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3610 .join("fixtures/444_sb128rect_chroma_tile_witness.obu");
3611 let stream = read_pin(&obu, FIXTURE_LEN, FIXTURE_FNV, NAME);
3612
3613 let _guard = lock_gate_counters();
3614 let rect_before = sb128_rect_counters();
3615 let part_before = part128_census();
3616 let r432_before = rect4_32_counters();
3617 let frames = decode_stream(&stream)
3618 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
3619 let rect_after = sb128_rect_counters();
3620 let part_after = part128_census();
3621 let r432_after = rect4_32_counters();
3622
3623 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
3624 for f in &frames {
3625 assert_eq!(
3626 (f.width, f.height),
3627 (W, H),
3628 "{NAME}: dimensions -- a resized frame would make the oracle \
3629 slices below compare the wrong samples"
3630 );
3631 }
3632
3633 // Non-vacuity: the guarded 128-root VERT path really fired.
3634 assert_eq!(
3635 rect_after.1 - rect_before.1,
3636 EDGE_VERT,
3637 "{NAME}: gathered edge-VERT 128 roots moved (expected {EDGE_VERT}) -- this \
3638 stream is the witness for the 128-rect 4:4:4 chroma tiling, so a \
3639 different count means the shape is gone or the counter moved (class \
3640 gate-blind-to-feature)"
3641 );
3642 assert_eq!(
3643 part_after.3 - part_before.3,
3644 PART128_VERT,
3645 "{NAME}: 128-root PARTITION_VERT blocks moved (expected {PART128_VERT})"
3646 );
3647 assert_eq!(
3648 part_after.6 - part_before.6,
3649 INTRA128_VERT,
3650 "{NAME}: key-frame intra 128-axis blocks moved (expected {INTRA128_VERT})"
3651 );
3652 assert_eq!(
3653 part_after.2 - part_before.2,
3654 0,
3655 "{NAME}: 128-root PARTITION_HORZ fired on this VERT witness"
3656 );
3657 assert_eq!(
3658 rect_after.0 - rect_before.0,
3659 0,
3660 "{NAME}: gathered edge-HORZ 128 roots fired on this VERT witness"
3661 );
3662 assert_eq!(
3663 (r432_after.1 - r432_before.1, r432_after.2 - r432_before.2),
3664 (RECT4_32_VERT, RECT4_32_CODED),
3665 "{NAME}: the 32x32 VERT strip counts moved -- the coded half of the \
3666 chroma tiling is what the old assert under-counted"
3667 );
3668
3669 // Oracle 1: aomdec rawvideo.
3670 if aomdec_available(NAME) {
3671 let dir = std::env::temp_dir().join(format!("ec-av1-p1pin-{}", std::process::id()));
3672 let _ = std::fs::remove_dir_all(&dir);
3673 std::fs::create_dir_all(&dir).expect("scratch dir");
3674 let raw = dir.join("aomdec.raw");
3675 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
3676 .args(["--codec=av1", "--rawvideo", "-o"])
3677 .arg(&raw)
3678 .arg(&obu)
3679 .stdin(Stdio::null())
3680 .stdout(Stdio::piped())
3681 .stderr(Stdio::piped()), None, |c| c.output())
3682 .expect("aomdec failed to run");
3683 assert!(
3684 out.status.success(),
3685 "{NAME}: the oracle aomdec refused the stream: {}",
3686 String::from_utf8_lossy(&out.stderr)
3687 );
3688 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
3689 let _ = std::fs::remove_dir_all(&dir);
3690 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
3691 for (i, f) in frames.iter().enumerate() {
3692 let base = i * W * H * 3;
3693 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
3694 .into_iter()
3695 .zip(["y", "u", "v"])
3696 {
3697 let want = &ref_raw[base + off..base + off + W * H];
3698 assert_eq!(
3699 plane.len(),
3700 want.len(),
3701 "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
3702 has {} -- a short plane would zip-truncate the compare below and \
3703 hide a chroma-span defect",
3704 plane.len(),
3705 want.len()
3706 );
3707 let bad = plane
3708 .iter()
3709 .zip(want)
3710 .filter(|&(&a, &b)| a as u8 != b)
3711 .count();
3712 assert_eq!(
3713 bad, 0,
3714 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ (class \
3715 sb128-rect-chroma-tiling)"
3716 );
3717 }
3718 }
3719 }
3720
3721 // Oracle 2: ffmpeg yuv444p rawvideo. Hard-fails, never skips, when
3722 // EC_AV1_REQUIRE_FFMPEG=1 (see have_ffmpeg).
3723 if have_ffmpeg() {
3724 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
3725 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() {
3726 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
3727 .iter()
3728 .enumerate()
3729 {
3730 assert_eq!(
3731 g.len(),
3732 r.len(),
3733 "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has \
3734 {} -- a short plane would zip-truncate the compare below and hide a \
3735 chroma-span defect",
3736 g.len(),
3737 r.len()
3738 );
3739 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
3740 assert_eq!(
3741 bad, 0,
3742 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ (class \
3743 sb128-rect-chroma-tiling)"
3744 );
3745 }
3746 }
3747 } else {
3748 eprintln!("SKIP {NAME}: no ffmpeg -- the ffmpeg oracle arm only");
3749 }
3750 }
3751
3752 /// lane-lossless128: a LOSSLESS key frame that codes a 128-axis
3753 /// (`BLOCK_64X128`) intra block -- the shape libaom's `read_tx_size` forces
3754 /// to `TX_4X4` on its very first line (`decodeframe.c:1183`), so every plane
3755 /// of the block is a 4x4 transform unit and NO `tx_size_cat3` symbol is
3756 /// coded.
3757 ///
3758 /// On the merged base `decode_block_128rect` had no lossless carve-out: it
3759 /// read `logical_tx = 64` off `depth == 0`, handed `PlaneBuf::reconstruct`
3760 /// a 64x64 geometry with the 16-sample 4x4 residual
3761 /// [`TxParams::run`](crate::decode::TxParams) produced -- `index out of
3762 /// bounds: the len is 16 but the index is 16` at the reconstruction call,
3763 /// on EVERY conformant stream of this shape (a panic, never a refusal).
3764 ///
3765 /// `crates/ec-av1/fixtures/lossless_sb128_rect_kf.obu`, 3471 bytes, sha256
3766 /// `013b07979c8be999c70d47f32768c2bf959be086a893f60dde1b0f5e35d4f475`:
3767 /// `aomenc --codec=av1 --passes=1 --threads=1 --obu --lossless=1
3768 /// --cpu-used=0` over a 320x256, 4-frame source that is flat grey except a
3769 /// textured 64x128 patch in the top-right corner -- which is what makes the
3770 /// 128 root take `PARTITION_VERT` and code the `BLOCK_64X128` at mi(0,64).
3771 ///
3772 /// The counter delta keeps the gate non-vacuous: a stream that stopped
3773 /// coding the shape reads 0 and the gate fails instead of passing on a
3774 /// decode that never reached the fixed body (class
3775 /// `gate-blind-to-feature`).
3776 #[test]
3777 fn a_lossless_sb128_rect_intra_block_decodes_sample_exact() {
3778 const NAME: &str = "a_lossless_sb128_rect_intra_block_decodes_sample_exact";
3779 // The pixel arm needs ffmpeg; the decode and its counter deltas do
3780 // not, so a box without ffmpeg still proves the shape was reached
3781 // (class `gate-skips-on-its-own-failure`) -- the skip is still named.
3782 let ffmpeg = have_ffmpeg();
3783 if !ffmpeg {
3784 eprintln!("SKIP {NAME}: no ffmpeg -- the ffmpeg pixel arm only");
3785 }
3786 let (w, h, frames) = (320usize, 256usize, 4usize);
3787 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3788 .join("fixtures/lossless_sb128_rect_kf.obu");
3789 let stream = std::fs::read(&path)
3790 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
3791 let before = crate::decode::intra128_lossless_hits();
3792 let before_replay = crate::decode::sb128rect_chroma_replay_hits();
3793 let ours = decode_stream(&stream)
3794 .unwrap_or_else(|e| panic!("{NAME}: a lossless 128-axis key frame decodes: {e}"));
3795 let hits = crate::decode::intra128_lossless_hits() - before;
3796 assert!(
3797 hits > 0,
3798 "{NAME}: this stream coded NO lossless 128-axis intra block -- the fixed body \
3799 was never reached (class gate-blind-to-feature)"
3800 );
3801 // lane-av1-128rectspan: the 4:2:0 twin of the 4:4:4 gate's replay
3802 // assertion. This stream codes the 64x128 block at mi(0,64) with
3803 // TX_4X4 chroma units, so the end-of-block replay re-stamps each of
3804 // them over its own luma-mi rows -- the arm the span fix sits on, on
3805 // the OTHER admitted ss (1,1). The mismatch half is the 4:2:2
3806 // signature; lane-av1422lift: 4:2:2 is decoded now, so this is no
3807 // longer "the tripwire for the day it is not". It is a zero this gate
3808 // asserts about the stream in front of it, and nothing else.
3809 // **DO NOT carry it to a 4:2:2 stream**: the two
3810 // `422_intrabc_sb128_strip*` pins read `mismatch = 9` each and are
3811 // byte-exact against ffmpeg, so a 4:2:2 zero assert would red on a
3812 // provably correct cell. The 4:2:2 rows of the corpus gate read
3813 // neither half of this counter.
3814 let after_replay = crate::decode::sb128rect_chroma_replay_hits();
3815 assert!(
3816 after_replay.0 > before_replay.0,
3817 "{NAME}: no 128-axis block replayed a chroma unit's own mi state -- the replay \
3818 arm never ran (class gate-blind-to-feature)"
3819 );
3820 assert_eq!(
3821 after_replay.1,
3822 before_replay.1,
3823 "{NAME}: the tail replay stamped {} unit(s) over a height that was not the \
3824 unit's own luma height (4:2:2 spans leaked into an admitted stream)",
3825 after_replay.1 - before_replay.1
3826 );
3827 eprintln!(
3828 "{NAME}: replayed {} chroma unit(s), {} span mismatch(es)",
3829 after_replay.0 - before_replay.0,
3830 after_replay.1 - before_replay.1
3831 );
3832 if !ffmpeg {
3833 return;
3834 }
3835 let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
3836 assert_eq!(ours.len(), frames, "{NAME}: shown/display frame count");
3837 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
3838 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
3839 .iter()
3840 .enumerate()
3841 {
3842 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
3843 assert_eq!(
3844 bad, 0,
3845 "{NAME}: frame {i} plane {plane}: {bad} samples differ from ffmpeg"
3846 );
3847 assert_eq!(
3848 g.len(),
3849 r.len(),
3850 "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
3851 short plane would zip-truncate the compare above and hide a chroma-span \
3852 defect",
3853 g.len(),
3854 r.len()
3855 );
3856 }
3857 }
3858 eprintln!("{NAME}: {frames} frames sample-exact, intra128_lossless hits {hits}");
3859 }
3860
3861 /// lane-av1-loss64: a lossless superblock-128 frame whose intra blocks
3862 /// overhang the bottom frame edge codes NO coefficient symbols for the
3863 /// chroma transform units whose 4x4 origin sits outside the frame's mi
3864 /// grid -- libaom `decode_reconstruct_tx` returns before any read
3865 /// (`decodeframe.c:299`, `blk_row >= max_blocks_high || blk_col >=
3866 /// max_blocks_wide`, the limits from `max_block_wide/high`,
3867 /// av1_common_int.h:1565). The square multi-transform-unit chroma loop in
3868 /// [`crate::decode`] carried no such clip (the luma loop had one) and read
3869 /// `txb_skip`+coefficients for the phantom units: on the measured stream
3870 /// the first lossless 64x64 `NONE` block, at mi(48,0), overhangs the
3871 /// 240-px frame by 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units,
3872 /// not eight -- 32 phantom unit reads per plane desynced the tile and
3873 /// every later symbol (including partition reads, which is what made
3874 /// aomdec's zero-`value=8/9` census look like a partition-reader defect
3875 /// in the rect14 review) decoded as garbage.
3876 ///
3877 /// Fail-pre-fix, measured on the ed12fe52 probe: both arms differ from
3878 /// ffmpeg at byte 41120 (luma row 128 col 160, the first block decoded
3879 /// after the phantom reads). The counter delta pins non-vacuity (class
3880 /// `gate-blind-to-feature`): 96 clipped units on each arm.
3881 #[test]
3882 fn a_lossless_sb128_square_frame_clips_overhanging_chroma_tus() {
3883 const NAME: &str = "a_lossless_sb128_square_frame_clips_overhanging_chroma_tus";
3884 if !have_ffmpeg() {
3885 eprintln!("SKIP {NAME}: no ffmpeg");
3886 return;
3887 }
3888 // Arm 0 is the rect14 report's `loss320` recipe verbatim; arm 1 is its
3889 // `lnone` companion (1:4 and rect partitions off) -- both coded the
3890 // overhanging 64x64 blocks and both desynced at byte 41120 pre-fix.
3891 let arms: [&[&str]; 2] = [
3892 &["--min-partition-size=4"],
3893 &[
3894 "--min-partition-size=4",
3895 "--enable-1to4-partitions=0",
3896 "--enable-rect-partitions=0",
3897 ],
3898 ];
3899 let mut clips_total = 0usize;
3900 for (arm, extra) in arms.iter().enumerate() {
3901 let stream = lossless_sb128_testsrc2(320, 240, extra);
3902 crate::decode::reset_loss64_hits();
3903 let ours =
3904 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: arm {arm} decodes: {e}"));
3905 let clips = crate::decode::chroma_edge_tu_clip_hits();
3906 assert!(
3907 clips > 0,
3908 "{NAME}: arm {arm} clipped NO overhanging chroma transform unit -- \
3909 the fixed body was never reached (class gate-blind-to-feature)"
3910 );
3911 clips_total += clips;
3912 let refs = ffmpeg_decode_sequence(&stream, 320, 240, 1);
3913 assert_eq!(ours.len(), 1, "{NAME}: arm {arm} frame count");
3914 for (plane, (g, r)) in [
3915 (&ours[0].y, &refs[0].y),
3916 (&ours[0].u, &refs[0].u),
3917 (&ours[0].v, &refs[0].v),
3918 ]
3919 .iter()
3920 .enumerate()
3921 {
3922 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
3923 assert_eq!(
3924 bad, 0,
3925 "{NAME}: arm {arm} plane {plane}: {bad} samples differ from ffmpeg"
3926 );
3927 assert_eq!(
3928 g.len(),
3929 r.len(),
3930 "{NAME}: arm {arm} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
3931 short plane would zip-truncate the compare above and hide a chroma-span \
3932 defect",
3933 g.len(),
3934 r.len()
3935 );
3936 }
3937 }
3938 eprintln!("{NAME}: 2 arms full-frame exact, {clips_total} chroma units clipped");
3939 }
3940
3941 /// lane-av1-loss64: a SKIPPED intrabc rect strip on a lossless frame
3942 /// zeroes its whole entropy-band footprint (libaom
3943 /// `av1_reset_entropy_context`, `if (mbmi->skip_txfm)` decodeframe.c:1262 ->
3944 /// blockd.c:58) instead of leaving the previous occupant's luma bands
3945 /// standing. The skip arm of `decode_intrabc_owned_rect` never wrote the
3946 /// luma bands: the lossless `read_block_tx_size_rect` resolves the 4x4
3947 /// leaf list before it looks at `skip`, so the tail took the
3948 /// per-transform-unit record path (chroma only) with no per-unit luma
3949 /// writes ever run. The next block then read a STALE band: on the 320x242
3950 /// `--min-partition-size=4` sibling of this stream the skipped 8x16
3951 /// intrabc strip at mi(48,66) left a 7 in left[48] and mi(48,68)'s first
3952 /// transform unit read `txb_skip_ctx` 3 where aomdec reads 1 (measured
3953 /// `EC_ECDUMP` against the instrumented aomdec) -- a coefficient-walk
3954 /// desync at byte 61712 with every mode symbol still matching.
3955 ///
3956 /// This gate uses the same `--min-partition-size=4` arm that reaches the
3957 /// sub-8x8 VERT -> 4x8 skipped-intrabc leaf. Post-fix it is full-frame
3958 /// exact: the skip path uses libaom's clamped 4x4 chroma intrabc
3959 /// prediction (`decodeframe.c:1011-1065`, `reconinter_template.inc:186-207`)
3960 /// instead of the ordinary skipped-intra DC predictor. The old route first
3961 /// differed at U(104,92) with the entropy ladder fully synced.
3962 ///
3963 /// Fail-pre-fix, measured on the ed12fe52 probe: differs at byte 41120
3964 /// (the chroma-clip class, fixed in the same lane). Single-mutation on
3965 /// the lane tree with ONLY this gate's walk reverted: differs at byte
3966 /// 61712, the band-leak site.
3967 #[test]
3968 fn a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands() {
3969 const NAME: &str = "a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands";
3970 if !have_ffmpeg() {
3971 eprintln!("SKIP {NAME}: no ffmpeg");
3972 return;
3973 }
3974 let stream = lossless_sb128_testsrc2(320, 242, &["--min-partition-size=4"]);
3975 crate::decode::reset_loss64_hits();
3976 crate::decode::reset_skipped_intrabc_chroma_arm_hits();
3977 let ours = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: decodes: {e}"));
3978 let resets = crate::decode::skip_lossless_band_reset_hits();
3979 let intrabc_skips = crate::decode::skipped_intrabc_chroma_arm_hits();
3980 assert!(
3981 resets > 0,
3982 "{NAME}: this stream coded NO skipped lossless intrabc rect strip -- \
3983 the fixed body was never reached (class gate-blind-to-feature)"
3984 );
3985 assert!(
3986 intrabc_skips > 0,
3987 "{NAME}: this stream coded NO skipped sub-8x8 intrabc chroma leaf -- \
3988 the clamped chroma prediction fix was never reached (class gate-blind-to-feature)"
3989 );
3990 let refs = ffmpeg_decode_sequence(&stream, 320, 242, 1);
3991 assert_eq!(ours.len(), 1, "{NAME}: frame count");
3992 for (plane, (g, r)) in [
3993 (&ours[0].y, &refs[0].y),
3994 (&ours[0].u, &refs[0].u),
3995 (&ours[0].v, &refs[0].v),
3996 ]
3997 .iter()
3998 .enumerate()
3999 {
4000 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
4001 assert_eq!(
4002 bad, 0,
4003 "{NAME}: plane {plane}: {bad} samples differ from ffmpeg"
4004 );
4005 assert_eq!(
4006 g.len(),
4007 r.len(),
4008 "{NAME}: plane {plane}: ours has {} samples, ffmpeg's has {} -- a short plane \
4009 would zip-truncate the compare above and hide a chroma-span defect",
4010 g.len(),
4011 r.len()
4012 );
4013 }
4014 eprintln!(
4015 "{NAME}: full-frame exact, {resets} band resets, \
4016 {intrabc_skips} skipped intrabc chroma predictions"
4017 );
4018 }
4019
4020 /// lane-av1-ibc444rect: an unskipped intrabc `BLOCK_8X4`/`BLOCK_4X8` leaf
4021 /// on a lossless 4:4:4 frame walks its coefficients as per-4x4 inter
4022 /// `TX_4X4` units on every plane -- `read_tx_size`'s lossless first line
4023 /// (`decodeframe.c:1203`) forces TX_4X4 before any tree, the frame's
4024 /// `TxMode` is `ONLY_4X4` so no var-tx tree is read either, and
4025 /// `av1_read_tx_type`'s qindex==0 early return (`decodemv.c:681`) drops
4026 /// the tx_type symbol the lossy 4x4 inter sets carry -- NOT the single
4027 /// `LumaRect8x4Inter`/`ChromaRect8x4` rect unit the non-lossless arm
4028 /// reads, and not the lossy per-unit arm's tx_type read.
4029 ///
4030 /// The pinned fixture `ll444_ibc_rect.obu` (99614 bytes, provenance in
4031 /// `lanes/av1ibc444rect.report.md`) is a lossless `--profile=1 --i444
4032 /// --enable-intrabc=1` key frame. r1 pinned the (then-known) leaf8
4033 /// `palette_window` panic as its alignment witness; with that blocker
4034 /// fixed upstream (lane-av1leaf8oob) the frame decodes to completion and
4035 /// this gate is the FULL-FRAME exact `aomdec` comparison its r1 doc
4036 /// promised, flipped by lane-av1-ibcskip2 -- which also closed the
4037 /// SKIPPED intrabc sub8 chroma cells the r1 measurement called out: a
4038 /// skipped intrabc leaf's chroma is the bare frame copy at the DV
4039 /// (libaom's `av1_build_inter_predictors_sb` runs regardless of `skip`),
4040 /// never the intra-DC push that arm used to run. Fail-before, measured on
4041 /// this tree with the DV-copy arm cut back to the intra push: 2794 U +
4042 /// 2830 V samples differ across 180 distinct 4x4 cells, 175 of them
4043 /// exactly this frame's skipped intrabc leaves, luma clean; with the arm,
4044 /// 0 differing samples on every plane.
4045 #[test]
4046 fn a_lossless_444_intrabc_rect_leaf_walks_per_4x4_units() {
4047 const NAME: &str = "a_lossless_444_intrabc_rect_leaf_walks_per_4x4_units";
4048 const FIXTURE_LEN: usize = 99614;
4049 const FIXTURE_FNV: u64 = 0xa1b6_a84e_ac6a_656f;
4050 const W: usize = 320;
4051 const H: usize = 240;
4052 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
4053 .join("fixtures/ll444_ibc_rect.obu");
4054 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
4055 panic!(
4056 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
4057 which is a failure, not a skip",
4058 obu.display()
4059 )
4060 });
4061 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
4062 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
4063
4064 let _guard = lock_gate_counters();
4065 crate::decode::reset_ibc444rect_hits();
4066 crate::decode::reset_skipped_intrabc_dv_copy_hits();
4067 let frames = decode_stream(&stream).unwrap_or_else(|e| {
4068 panic!(
4069 "{NAME}: the fixture must decode to completion (the leaf8 \
4070 chroma buffers were fixed upstream): {e}"
4071 )
4072 });
4073 assert_eq!(frames.len(), 1, "{NAME}: shown frame count");
4074 let luma = crate::decode::intrabc_rect8_lossless_luma_hits();
4075 let chroma = crate::decode::intrabc_rect8_lossless_chroma_hits();
4076 assert_eq!(
4077 (luma, chroma),
4078 (339, 339),
4079 "{NAME}: the per-4x4 walk must fire on the fixture's full unskipped \
4080 intrabc rect census (got luma {luma}, chroma {chroma}) -- zero \
4081 means the fixture no longer reaches the fixed body (class \
4082 gate-blind-to-feature), more means the entropy desynced and \
4083 garbage blocks read as intrabc rect leaves"
4084 );
4085 let dv_skips = crate::decode::skipped_intrabc_dv_copy_hits();
4086 assert_eq!(
4087 dv_skips, 150,
4088 "{NAME}: the skipped-intrabc DV-copy chroma arm must fire on every \
4089 one of the fixture's 150 skipped intrabc leaves (got {dv_skips}) \
4090 -- zero means the arm is unreachable (class gate-blind-to-feature)"
4091 );
4092
4093 // The oracle aomdec, rawvideo out: one concatenated yuv444p frame.
4094 if aomdec_available(NAME) {
4095 let dir = std::env::temp_dir().join(format!("ec-av1-ibcskip2-{}", std::process::id()));
4096 let _ = std::fs::remove_dir_all(&dir);
4097 std::fs::create_dir_all(&dir).expect("scratch dir");
4098 let raw = dir.join("aomdec.raw");
4099 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
4100 .args(["--codec=av1", "--rawvideo", "-o"])
4101 .arg(&raw)
4102 .arg(&obu)
4103 .stdin(Stdio::null())
4104 .stdout(Stdio::piped())
4105 .stderr(Stdio::piped()), None, |c| c.output())
4106 .expect("aomdec failed to run");
4107 assert!(
4108 out.status.success(),
4109 "{NAME}: the oracle aomdec refused the stream: {}",
4110 String::from_utf8_lossy(&out.stderr)
4111 );
4112 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
4113 let _ = std::fs::remove_dir_all(&dir);
4114 assert_eq!(ref_raw.len(), W * H * 3, "{NAME}: aomdec raw size");
4115 let f = &frames[0];
4116 for (plane, off, p) in [
4117 (&f.y, 0usize, "Y"),
4118 (&f.u, W * H, "U"),
4119 (&f.v, 2 * W * H, "V"),
4120 ] {
4121 let want = &ref_raw[off..off + W * H];
4122 let bad = plane
4123 .iter()
4124 .zip(want)
4125 .filter(|&(&a, &b)| a as u8 != b)
4126 .count();
4127 assert_eq!(
4128 bad, 0,
4129 "{NAME}: aomdec plane {p}: {bad} samples differ -- a \
4130 regression here reopens the skipped-intrabc sub8 chroma \
4131 predictor or the rect walk"
4132 );
4133 }
4134 }
4135 eprintln!(
4136 "{NAME}: frame sample-exact vs oracle aomdec; {luma}+{chroma} rect \
4137 walks, {dv_skips} skipped-intrabc DV copies"
4138 );
4139 }
4140
4141 /// lane-dkey: the palette-neighbour-band gate. A palette-Y block's size and
4142 /// colours used to stay standing in the mi-granular above/left bands after a
4143 /// sub-8x8 group was decoded next to it -- the sub-8x8 readers published
4144 /// skip/lf/mode state but no palette state, while libaom's mi grid carries
4145 /// `palette_size == 0` in exactly those cells (`av1_allow_palette` needs
4146 /// BLOCK_8X8 and up). The next intra block then read `palette_y_mode` off
4147 /// CDF row 1 where libaom reads row 0 (class `cdf-row-held-constant`),
4148 /// decoded a palette libaom never coded, and skipped the `use_filter_intra`
4149 /// symbol a palette block has none of: one symbol short, tile desynced.
4150 ///
4151 /// Measured on the instrumented aomdec at KEY-frame block mi(76,88) of this
4152 /// very stream (`EC_PALSYN_AOM ... ctx=0 y=0` against our `mode_ctx=1`).
4153 /// Without the fix every one of the 12 frames differs from ffmpeg's decode
4154 /// from luma sample 491904 on.
4155 ///
4156 /// The source is SYNTHETIC (no film sample lives in `fixtures`): the dark,
4157 /// near-flat background libaom's own screen-content detector counts as
4158 /// screen content (2..=4 distinct luma values per 16x16 block), which is
4159 /// what turns palette on, plus one textured patch at a HALF-PEL position on
4160 /// half the frames so the encoder splits that region down to 4x4 groups
4161 /// beside its palette blocks.
4162 #[test]
4163 fn a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact() {
4164 const NAME: &str =
4165 "a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact";
4166 if !have_ffmpeg() {
4167 eprintln!("SKIP {NAME}: no ffmpeg");
4168 return;
4169 }
4170 let (w, h, frames) = (1920usize, 1024usize, 12usize);
4171 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
4172 for f in 0..frames {
4173 let mut y = vec![0u8; w * h];
4174 for row in 0..h {
4175 for col in 0..w {
4176 y[row * w + col] =
4177 16 + ((col / 32 + row / 32) % 5) as u8 + ((col / 4 + row / 4) % 3) as u8;
4178 }
4179 }
4180 // 2.5 px per pair of frames: integer on one pair, half a pixel off
4181 // on the next (linear interpolation), so the patch's edges land
4182 // mid-sample and the encoder splits there.
4183 let x0 = 200.0 + 2.5 * (f / 2) as f64;
4184 let (fx, ix) = (x0.fract(), x0.floor() as usize);
4185 for row in 300..428 {
4186 for col in 0..192 {
4187 let tex = |u: f64| -> f64 {
4188 let v = (row - 300) as f64;
4189 30.0 + 100.0 * (0.5 + 0.5 * ((u * 0.35).sin() * (v * 0.21).cos()))
4190 };
4191 let s = tex(col as f64) * (1.0 - fx) + tex(col as f64 - 1.0) * fx;
4192 y[row * w + ix + col] = s.round().clamp(0.0, 255.0) as u8;
4193 }
4194 }
4195 raw.extend_from_slice(&y);
4196 raw.extend(std::iter::repeat_n(128u8, w * h / 2));
4197 }
4198 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
4199 let src = std::env::temp_dir().join(format!("ec-av1-palsub8-{}.yuv", std::process::id()));
4200 std::fs::write(&src, &raw).expect("raw source");
4201 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
4202 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
4203 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
4204 .arg(&src)
4205 .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"])
4206 .args([
4207 "-cpu-used",
4208 "6",
4209 "-b:v",
4210 "0",
4211 "-crf",
4212 "35",
4213 "-f",
4214 "obu",
4215 "-",
4216 ])
4217 .stdin(Stdio::null())
4218 .stdout(Stdio::piped())
4219 .stderr(Stdio::piped()), None, |c| c.output())
4220 .expect("ffmpeg failed to run");
4221 let _ = std::fs::remove_file(&src);
4222 if !out.status.success() {
4223 eprintln!(
4224 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
4225 String::from_utf8_lossy(&out.stderr)
4226 );
4227 return;
4228 }
4229 let stream = out.stdout;
4230 let ours = decode_stream(&stream).expect("libaom screen-content stream decodes");
4231 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
4232 assert_eq!(ours.len(), frames, "{NAME}: shown frame count");
4233 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
4234 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
4235 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
4236 assert!(
4237 first.is_none(),
4238 "{NAME}: frame {i} plane {plane} differs from ffmpeg at sample {}",
4239 first.unwrap()
4240 );
4241 assert_eq!(
4242 l.len(),
4243 r.len(),
4244 "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
4245 short plane would zip-truncate the compare above and hide a chroma-span \
4246 defect",
4247 l.len(),
4248 r.len()
4249 );
4250 }
4251 }
4252 }
4253
4254 /// Hardened past the report-only test above: a real libaom-av1 gradients
4255 /// stream, pinned deterministic (`gradients`' own `seed=`, plus
4256 /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search
4257 /// cannot pick a different mode set run to run) and with CDEF turned off
4258 /// (this decoder's tile path never applies that in-loop filter -- see
4259 /// `cdef_is_active` in `decode_stream` -- so a stream that leaves it on
4260 /// decodes-but-wrong instead of refusing at cdef_bits==0; ffmpeg's
4261 /// `-enable-cdef 0` keeps this fixture out of that gap rather than this
4262 /// test working around it). Asserts pixel-exact against ffmpeg's own
4263 /// decode of the identical bytes, not just "decoded without error".
4264 #[test]
4265 fn a_real_libaom_gradients_stream_decodes_pixel_exact() {
4266 if !have_ffmpeg() {
4267 eprintln!("SKIP a_real_libaom_gradients_stream_decodes_pixel_exact: no ffmpeg");
4268 return;
4269 }
4270 let (width, height) = (64, 64);
4271 let stream = libaom_encode_with(
4272 &gradients_source(42, width, height, "rate=1"),
4273 width,
4274 height,
4275 15,
4276 &[
4277 "-threads",
4278 "1",
4279 "-row-mt",
4280 "0",
4281 "-tile-columns",
4282 "0",
4283 "-tile-rows",
4284 "0",
4285 "-enable-cdef",
4286 "0",
4287 ],
4288 )
4289 .expect("ffmpeg encode");
4290 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
4291 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4292 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
4293 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
4294 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
4295 }
4296
4297 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but at
4298 /// 32x32 (below `is_cfl_allowed`'s 32x32 luma bound as a *single*
4299 /// undivided block, spec 5.11.5) rather than 64x64 -- a whole 64x64 SB
4300 /// is never CFL-eligible itself, only its <=32x32 partitions, and
4301 /// `testsrc2`/`gradients` at 64x64 with rect/ab/1to4/angle-delta search
4302 /// disabled reliably pick a whole-SB `PARTITION_NONE` (probed
4303 /// lane-av1real r2), so no fixture at that size exercises CfL at all.
4304 /// A 32x32 frame is exactly the whole-block, CFL-allowed case, and
4305 /// lane-av1real r2 found `gradients` there reliably selects
4306 /// `UV_CFL_PRED` (`uv_mode=13`) across a crf sweep -- `testsrc2` there
4307 /// stays DC. Proves the CfL port this round added, not just DC-chroma
4308 /// decode: pixel-exact against ffmpeg's own decode, not just "decoded".
4309 ///
4310 #[test]
4311 fn a_real_libaom_cfl_stream_decodes_pixel_exact() {
4312 if !have_ffmpeg() {
4313 eprintln!("SKIP a_real_libaom_cfl_stream_decodes_pixel_exact: no ffmpeg");
4314 return;
4315 }
4316 let (width, height) = (32, 32);
4317 let stream = libaom_encode_with(
4318 &gradients_source(42, width, height, "rate=1"),
4319 width,
4320 height,
4321 15,
4322 &[
4323 "-threads",
4324 "1",
4325 "-row-mt",
4326 "0",
4327 "-tile-columns",
4328 "0",
4329 "-tile-rows",
4330 "0",
4331 "-enable-cdef",
4332 "0",
4333 ],
4334 )
4335 .expect("ffmpeg encode");
4336 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
4337 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4338 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
4339 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
4340 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
4341 }