forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

t03.rs4567 lines, 212.7 KiBHistoryRawDownload
1use super::*;
2use super::support::*;
3use super::gates_a::*;
4use crate::probe::run_with_stdin;
5use std::process::{Command, Stdio};
6
7 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves
8 /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
9 /// proves `apply_cdef` itself, not just that this decoder still works
10 /// when the filter never fires. Gradient content at a low crf reliably
11 /// gives libaom something to dering.
12 ///
13 /// lane-av1skipfix: the attempt-loop shape. A single-SB 64x64 frame can
14 /// never make libaom write `cdef_bits > 0` (nothing to differentiate per
15 /// superblock), so this recipe is MULTI-SB and MULTI-FRAME, and it sweeps
16 /// (size, cpu-used, crf) until one attempt reads a real `cdef_idx` literal
17 /// -- MEASURED 2026-09-29 on `a21f3680`: 64x64 at every crf/cpu reads
18 /// ZERO `cdef_idx` (single superblock, `bits == 0`, though `apply_cdef`
19 /// does filter with a nonzero strength pair), while 128x64/128x128 at
20 /// 24 frames read 2-8. Every attempt that decodes is ALWAYS pixel-
21 /// compared against ffmpeg's own decode of the identical bytes; a decode
22 /// error is a named refusal recorded per attempt, never a SKIP, and
23 /// exhausting every attempt -- or decoding without ever reading a
24 /// `cdef_idx` -- is a hard FAILURE (an unfired gate is a vacuous gate,
25 /// class `gate-skips-on-its-own-failure`).
26 #[test]
27 fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
28 const NAME: &str = "a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact";
29 let _gate_lock = lock_gate_counters();
30 if !have_ffmpeg() {
31 eprintln!("SKIP {NAME}: no ffmpeg");
32 return;
33 }
34 // (width, height, frames, cpu-used, crf). The frame count is what
35 // gives libaom's cdef search more than one superblock to price.
36 const RECIPES: [(usize, usize, usize, &str, u32); 8] = [
37 (128, 64, 24, "0", 20),
38 (128, 64, 24, "2", 20),
39 (128, 64, 24, "0", 16),
40 (128, 128, 24, "2", 20),
41 (128, 128, 24, "0", 16),
42 (128, 128, 24, "0", 24),
43 (128, 64, 24, "2", 24),
44 (128, 128, 24, "2", 24),
45 ];
46 let mut refusals = Vec::new();
47 let mut counted_exact = 0u32;
48 let mut uncounted_exact = 0u32;
49 for (w, h, frames, cpu, crf) in RECIPES {
50 let Some(stream) = libaom_encode_with(
51 &gradients_source(42, w, h, "rate=25"),
52 w,
53 h,
54 crf,
55 &[
56 "-cpu-used",
57 cpu,
58 "-frames:v",
59 &frames.to_string(),
60 "-threads",
61 "1",
62 "-row-mt",
63 "0",
64 "-tile-columns",
65 "0",
66 "-tile-rows",
67 "0",
68 ],
69 ) else {
70 refusals.push(format!(
71 "{w}x{h} cpu-used {cpu} crf {crf}: ffmpeg itself refused"
72 ));
73 continue;
74 };
75 let before = decode::cdef_idx_hits();
76 let decoded = match decode_stream(&stream) {
77 Ok(frames) => frames,
78 Err(e) => {
79 refusals.push(format!("{w}x{h} cpu-used {cpu} crf {crf}: {e}"));
80 continue;
81 }
82 };
83 // A decode that succeeded is ALWAYS pixel-compared; the hit
84 // counter only decides whether the attempt counts as firing
85 // (class `counter-from-refused-stream`).
86 let counted = decode::cdef_idx_hits() != before;
87 if counted {
88 counted_exact += 1;
89 } else {
90 uncounted_exact += 1;
91 }
92 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, w, h, frames);
93 assert_eq!(decoded.len(), frames);
94 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
95 assert_eq!(
96 got.y, want.y,
97 "{NAME} frame {i} luma vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
98 cdef_idx fired: {counted})"
99 );
100 assert_eq!(
101 got.u, want.u,
102 "{NAME} frame {i} U vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
103 cdef_idx fired: {counted})"
104 );
105 assert_eq!(
106 got.v, want.v,
107 "{NAME} frame {i} V vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
108 cdef_idx fired: {counted})"
109 );
110 }
111 if counted_exact >= 2 {
112 break;
113 }
114 }
115 gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
116 assert!(
117 counted_exact > 0,
118 "{NAME}: no attempt of {} read a cdef_idx literal -- CDEF is not exercised \
119 (class gate-blind-to-feature):\n{}",
120 RECIPES.len(),
121 refusals.join("\n")
122 );
123 }
124
125 /// lane-av1422h232: the non-vacuity test for [`count_rawvideo_diffs`].
126 ///
127 /// A cell-classifying counter that cannot report a difference is worse
128 /// than no counter, because it reports "exact" for everything -- that is
129 /// exactly how lane-av1422remeasure's "18/18 byte-exact" table was
130 /// produced (it compared our own packed samples against the same
131 /// samples, never reading `aomdec`'s output).
132 ///
133 /// It used to lean on the pinned witness DIFFERING to prove the counting
134 /// path fires. That witness is byte-exact now (lane-av1422hrtx fixed the
135 /// 32-point inter chroma `tx_type`), so "it differs" is no longer
136 /// available and a witness-based version of this test would be vacuous by
137 /// construction. Instead this proves the same property directly and
138 /// unconditionally: flipping ONE bit of the ORACLE's own bytes must move
139 /// the count by exactly one, in the plane that bit is in, and knock exactly
140 /// one frame out of `frames_exact`. A comparator that had stopped reading
141 /// the oracle reports the baseline numbers again and fails by name.
142 #[test]
143 fn the_counting_oracle_diff_detects_one_flipped_oracle_byte() {
144 const NAME: &str = "the_counting_oracle_diff_detects_one_flipped_oracle_byte";
145 // lane-av1cmpaudit2: same mutex as every other oracle gate -- this
146 // one reads `aomdec_path()`, so it must not overlap a sibling's
147 // tampered-oracle run.
148 let _gate_lock = lock_gate_counters();
149 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
150 .join("fixtures")
151 .join("420_oddheight_320x232.obu");
152 let data = std::fs::read(&path).expect("the pinned witness is missing");
153 let (wy, wu, wv, frames, exact) =
154 count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
155 assert_eq!(
156 (wy, wu, wv, exact),
157 (0, 0, 0, frames),
158 "{NAME}: the pinned witness must decode byte-exactly against `aomdec --rawvideo`"
159 );
160 // Frame 0 byte 0 is luma; byte 90_000 is inside frame 0's chroma.
161 for (idx, plane) in [(0usize, 0usize), (90_000, 1)] {
162 let (wy, wu, wv, _, exact) = count_rawvideo_diffs(&data, NAME, Some(idx))
163 .expect("the two sides must be byte-comparable");
164 let got = [wy, wu, wv];
165 assert_eq!(
166 got.iter().sum::<usize>(),
167 1,
168 "{NAME}: flipping oracle byte {idx} must report exactly ONE wrong sample \
169 across all planes -- got {got:?}. Reporting the unflipped numbers means \
170 the comparison stopped reading the oracle's bytes"
171 );
172 assert_eq!(got[plane], 1, "{NAME}: byte {idx} is in plane {plane}");
173 assert_eq!(
174 exact,
175 frames - 1,
176 "{NAME}: one flipped byte spoils one frame"
177 );
178 }
179 eprintln!("{NAME}: baseline exact, each flipped oracle byte reported as exactly 1");
180 }
181
182 /// lane-av1cmpframe: the control for the class
183 /// `comparator-that-attributes-the-wrong-plane`.
184 ///
185 /// [`count_rawvideo_diffs`] used to derive its plane split from the FIRST
186 /// decoded picture and compare every byte index against those frame-0
187 /// thresholds. On a multi-frame stream that attributes every sample after
188 /// frame 0's luma to the LAST plane: on the pinned 320x236 stream below
189 /// (16 frames of 320x236 4:2:0, 113 280 bytes per frame, so plane V holds
190 /// 302 080 bytes in total) it reported `wrong_v = 330 673` -- more wrong V
191 /// bytes than exist. The per-frame totals and the frame-exact count were
192 /// sound, so the defect was invisible to every gate that only asserted
193 /// zeros; it corrupted exactly the numbers a per-plane report exists to
194 /// give.
195 ///
196 /// Three arms, each of which the old attribution FAILS:
197 ///
198 /// 1. **Arithmetic.** Each plane's count must be at most that plane's own
199 /// byte capacity summed over frames, and the three must sum to the
200 /// independently computed total. The old code reported 330 673 wrong V
201 /// bytes in a 302 080-byte plane.
202 /// 2. **A later frame's U.** Flipping one byte inside frame 5's U plane
203 /// must move U by exactly one and leave Y and V at their baseline.
204 /// The old code has no frame-5 U at all -- byte 600 000 is past every
205 /// frame-0 threshold, so it landed in V.
206 /// 3. **Frame attribution.** `frames_exact` must equal the number of
207 /// frames this test counts itself, per frame, from the decoded
208 /// pictures' own plane lengths.
209 ///
210 /// The pin is asserted only for IDENTITY (bytes + fnv1a64) and for
211 /// comparability. Whether the stream currently diverges is deliberately
212 /// NOT asserted: this is a control for the INSTRUMENT, and it must keep
213 /// biting after the odd-height entropy fork is fixed.
214 #[test]
215 fn the_counting_oracle_diff_attributes_planes_per_frame() {
216 const NAME: &str = "the_counting_oracle_diff_attributes_planes_per_frame";
217 let _gate_lock = lock_gate_counters();
218 const FILE: &str = "420_oddheight_320x236.obu";
219 const BYTES: usize = 16562;
220 // sha256 84e4d1ab56620af1c5b78e1aa3d2d67496a492f2e127198c82dd1d68b01c6200.
221 // The tree pins fixture identity by fnv1a64; a `const SHA256`
222 // compared against itself would be the tautology this lane exists to
223 // kill, so it is not written.
224 const FNV1A64: u64 = 521889434652397870;
225 let data = crate_pin("420_oddheight_320x236.obu");
226 let data = std::fs::read(&data)
227 .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})"));
228 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
229 assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted");
230 let bit_depth = stream_bit_depth(&data, NAME);
231 let bpp = if bit_depth == 8 { 1 } else { 2 };
232
233 // ---- this test's own reading of the oracle, from scratch ---------
234 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
235 let _ = std::fs::remove_dir_all(&dir);
236 std::fs::create_dir_all(&dir).expect("scratch dir");
237 let obu = dir.join("in.obu");
238 std::fs::write(&obu, &data).expect("writing the stream");
239 let raw = dir.join("aomdec.raw");
240 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
241 .args(["--codec=av1", "--rawvideo", "-o"])
242 .arg(&raw)
243 .arg(&obu)
244 .stdin(Stdio::null())
245 .stdout(Stdio::piped())
246 .stderr(Stdio::piped()), None, |c| c.output())
247 .expect("aomdec failed to run");
248 assert!(
249 out.status.success(),
250 "{NAME}: the oracle aomdec refused the stream: {}",
251 String::from_utf8_lossy(&out.stderr)
252 );
253 let want = std::fs::read(&raw).expect("aomdec rawvideo output");
254 let _ = std::fs::remove_dir_all(&dir);
255 let decoded = decode_stream(&data).expect("the pinned stream decodes");
256 let ours = pack_rawvideo(&decoded, bit_depth, NAME);
257 assert_eq!(
258 ours.len(),
259 want.len(),
260 "{NAME}: the two sides differ in size"
261 );
262
263 // The per-frame plane table, built from each decoded picture's OWN
264 // plane lengths -- the same source `pack_rawvideo` lays the bytes out
265 // from, and never a formula.
266 let mut spans: Vec<[usize; 4]> = Vec::with_capacity(decoded.len());
267 let mut capacity = [0usize; 3];
268 let mut off = 0usize;
269 for f in &decoded {
270 let (y, u, v) = (f.y.len() * bpp, f.u.len() * bpp, f.v.len() * bpp);
271 spans.push([off, off + y, off + y + u, off + y + u + v]);
272 capacity[0] += y;
273 capacity[1] += u;
274 capacity[2] += v;
275 off += y + u + v;
276 }
277 assert_eq!(off, ours.len(), "{NAME}: the plane table covers the buffer");
278
279 // The truth, counted here with no help from the helper under test.
280 let mut truth = [0usize; 3];
281 let mut truth_exact = 0usize;
282 for s in &spans {
283 let mut frame_exact = true;
284 for (p, a, b) in [(0usize, s[0], s[1]), (1, s[1], s[2]), (2, s[2], s[3])] {
285 let n = ours[a..b]
286 .iter()
287 .zip(&want[a..b])
288 .filter(|(x, y)| x != y)
289 .count();
290 truth[p] += n;
291 frame_exact &= n == 0;
292 }
293 truth_exact += usize::from(frame_exact);
294 }
295
296 let (wy, wu, wv, frames, exact) =
297 count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
298 eprintln!(
299 "{NAME}: pinned {FILE} as wrongY={wy} wrongU={wu} wrongV={wv} over {frames} frames, \
300 {exact} exact; this test's own count {truth:?} with {truth_exact} exact frames; \
301 plane capacities {capacity:?}"
302 );
303 assert_eq!(frames, decoded.len(), "{NAME}: frame count");
304 assert_eq!(
305 [wy, wu, wv],
306 truth,
307 "{NAME}: the helper's per-plane split must equal an independent per-frame count"
308 );
309 assert_eq!(exact, truth_exact, "{NAME}: frames_exact");
310 for p in 0..3 {
311 assert!(
312 truth[p] <= capacity[p],
313 "{NAME}: plane {p} counts {} wrong bytes but holds only {}",
314 truth[p],
315 capacity[p]
316 );
317 }
318
319 // ---- arm 2: a byte inside a LATER frame's U plane. --------------
320 // Frame 5's U plane's first byte. The old first-picture attribution
321 // has no frame-5 U at all: that byte is past every frame-0 threshold,
322 // so it landed in V.
323 let u5 = spans[5][1];
324 let (fy, fu, fv, fframes, fexact) = count_rawvideo_diffs(&data, NAME, Some(u5))
325 .expect("the two sides must be byte-comparable");
326 let flipped = [fy, fu, fv];
327 assert_eq!(fframes, frames, "{NAME}: frame count under the flip");
328 assert_eq!(
329 flipped.iter().sum::<usize>(),
330 truth.iter().sum::<usize>() + 1,
331 "{NAME}: flipping one byte inside frame 5's U plane must add exactly one wrong \
332 byte -- got {flipped:?} against this test's own count {truth:?}"
333 );
334 assert_eq!(
335 flipped[1],
336 truth[1] + 1,
337 "{NAME}: byte {u5} is inside frame 5's U plane"
338 );
339 assert_eq!(flipped[0], truth[0], "{NAME}: byte {u5} is not in luma");
340 assert_eq!(
341 flipped[2], truth[2],
342 "{NAME}: byte {u5} must NOT be attributed to V -- the first-picture attribution \
343 puts every byte past frame 0's luma in V"
344 );
345 let want_exact = if truth_exact < frames {
346 truth_exact
347 } else {
348 frames - 1
349 };
350 assert_eq!(
351 fexact, want_exact,
352 "{NAME}: one flipped byte inside frame 5 leaves frames_exact at {want_exact}"
353 );
354 }
355
356 /// lane-av1cmpaudit2: the permanent CONTROL for the class
357 /// `comparator-that-never-reads-the-oracle`.
358 ///
359 /// The retracted predecessor lane's per-cell counter reported "0 wrong"
360 /// on 18/18 cells -- including cells that differ from `aomdec
361 /// --rawvideo` in 17658 samples -- because it packed OUR decoded samples
362 /// into a buffer and compared that buffer against the same samples.
363 /// `aomdec`'s output was written, length-checked, and never read.
364 /// Nothing about that mistake is visible from the outside: the helper's
365 /// signature, its panic text and its return type are all exactly what a
366 /// working comparator has, and no amount of reading the source of a
367 /// healthy-looking helper proves the next one is healthy.
368 ///
369 /// So the class is pinned here from the other direction.
370 /// `EC_AV1_AOMDEC` is already the crate's oracle override, so this test
371 /// points every oracle helper at a shim that runs the REAL `aomdec` and
372 /// then corrupts exactly ONE byte of whatever it wrote -- the
373 /// `--rawvideo` output and the `EC_AV1_FINAL_DUMP` frame 0 -- leaving
374 /// every other sample a genuine decode. On a pin that IS byte-exact
375 /// against the real oracle:
376 ///
377 /// 1. **arm 1, real oracle: every helper is GREEN.** Without this arm,
378 /// arm 2's red could just be a stream that was never exact.
379 /// 2. **arm 2, one-byte-wrong oracle: every helper is RED.** A helper
380 /// that stays green here is the retracted defect itself: it cannot
381 /// fail, so its green is worth nothing.
382 ///
383 /// One test, five helpers, and it goes red for the exact mistake that
384 /// was retracted. Measured over this file: the other 62 tests that
385 /// reach an oracle helper all take `lock_gate_counters()` before their
386 /// first oracle call, which is what makes the process-global
387 /// `EC_AV1_AOMDEC` safe to flip here.
388 #[test]
389 fn every_oracle_comparator_reds_on_a_one_byte_wrong_oracle() {
390 const NAME: &str = "every_oracle_comparator_reds_on_a_one_byte_wrong_oracle";
391 let _gate_lock = lock_gate_counters();
392 if !aomdec_available(NAME) {
393 return;
394 }
395 let pin = crate_pin("420_odd65x65_key.obu");
396 let stream = std::fs::read(&pin).unwrap_or_else(|e| {
397 panic!(
398 "{NAME}: the control's pin {} is missing ({e}) -- restore the committed copy",
399 pin.display()
400 )
401 });
402 assert_eq!(
403 stream_bit_depth(&stream, NAME),
404 8,
405 "{NAME}: the control's pin must be the 8-bit cell the shim corrupts"
406 );
407 let plane_samples = {
408 let frames = decode_stream(&stream).expect("the control's pin must decode");
409 let f = &frames[0];
410 [f.y.len(), f.u.len(), f.v.len()]
411 };
412
413 // ---- arm 1: the real oracle, every comparator green ------------
414 {
415 let obu = std::env::temp_dir().join(format!("{NAME}-arm1.obu"));
416 std::fs::write(&obu, &stream).expect("writing the pin for arm 1");
417 assert_rawvideo_matches(&obu, &stream, "oracle-control-arm1-rawvideo", 1, 8);
418 let _ = std::fs::remove_file(&obu);
419 let (frames, hidden) =
420 decode_all_frames_vs_oracle(&stream, "oracle-control-arm1-alldumps");
421 assert_eq!(
422 (frames, hidden),
423 (1, 0),
424 "{NAME}: arm 1 expects one decode-order frame and no hidden frames"
425 );
426 let (wy, wu, wv, n, exact) =
427 count_rawvideo_diffs(&stream, "oracle-control-arm1-count", None)
428 .expect("arm 1: the two sides must be byte-comparable");
429 assert_eq!(
430 (wy, wu, wv),
431 (0, 0, 0),
432 "{NAME}: arm 1 runs against the REAL oracle, so every plane must be zero"
433 );
434 assert_eq!(
435 (n, exact),
436 (1, 1),
437 "{NAME}: arm 1 expects one shown frame that is byte-identical"
438 );
439 let (differing, first) = key_frame_diffs(&stream, "oracle-control-arm1-kf");
440 assert_eq!(
441 (differing, first),
442 (0, None),
443 "{NAME}: arm 1's key frame must be byte-identical to the oracle's"
444 );
445 let [y, u, v] =
446 oracle_plane_diffs(&stream, "oracle-control-arm1-planes", plane_samples);
447 assert_eq!(
448 [y, u, v],
449 [0, 0, 0],
450 "{NAME}: arm 1 must be zero on every plane against the real oracle"
451 );
452 }
453
454 // ---- the one-byte-wrong oracle ---------------------------------
455 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
456 let _ = std::fs::remove_dir_all(&dir);
457 std::fs::create_dir_all(&dir).expect("scratch dir");
458 let shim = dir.join("one-byte-wrong-aomdec.sh");
459 // The real oracle's path rides in a sibling file rather than inside
460 // the script, so a path with a quote or a space cannot mangle it and
461 // the script body needs no `format!` escaping at all.
462 std::fs::write(
463 dir.join("real-aomdec"),
464 aomdec_path().as_os_str().as_encoded_bytes(),
465 )
466 .expect("recording the real oracle's path for the shim");
467 // Byte 7 of both the `--rawvideo` output and the `EC_AV1_FINAL_DUMP`
468 // frame 0 is inside the Y plane, and its value is rotated by 128 so
469 // the write always changes it. Nothing else is touched: the stream,
470 // the geometry, the frame count and every other sample are a genuine
471 // `aomdec` decode.
472 let script = r#"#!/bin/sh
473REAL=$(cat "$(dirname "$0")/real-aomdec")
474rawvideo=0
475out=""
476prev=""
477for a in "$@"; do
478 if [ "$a" = "--rawvideo" ]; then rawvideo=1; fi
479 if [ "$prev" = "-o" ]; then out="$a"; fi
480 prev="$a"
481done
482"$REAL" "$@" || exit $?
483flip() {
484 [ -s "$1" ] || return 0
485 b=$(od -An -tu1 -j 7 -N 1 "$1" 2>/dev/null | tr -d ' \n')
486 [ -n "$b" ] || return 0
487 esc=$(printf '\\%03o' $(( (b + 128) % 256 )))
488 printf "$esc" | dd of="$1" bs=1 seek=7 count=1 conv=notrunc 2>/dev/null
489 return 0
490}
491[ "$rawvideo" = 1 ] && flip "$out"
492[ -n "$EC_AV1_FINAL_DUMP" ] && flip "$EC_AV1_FINAL_DUMP.f0"
493exit 0
494"#;
495 std::fs::write(&shim, script).expect("writing the oracle shim");
496 #[cfg(unix)]
497 {
498 use std::os::unix::fs::PermissionsExt;
499 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755))
500 .expect("the oracle shim must be executable");
501 }
502
503 // ---- arm 2: same pin, oracle off by ONE byte -------------------
504 // The override is THREAD-LOCAL, so the tampered oracle is confined
505 // to this thread and no sibling test can see it; it is still cleared
506 // before any result is asserted, so a red arm cannot leave this
507 // test's own later work reading a wrong oracle.
508 let reds: [bool; 5];
509 {
510 set_oracle_path(Some(shim.clone()));
511 let panicked =
512 |f: &dyn Fn()| std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).is_err();
513 let rawvideo_red = panicked(&|| {
514 let obu = std::env::temp_dir().join(format!("{NAME}-arm2.obu"));
515 std::fs::write(&obu, &stream).expect("writing the pin for arm 2");
516 assert_rawvideo_matches(&obu, &stream, "oracle-control-arm2-rawvideo", 1, 8);
517 });
518 let _ = std::fs::remove_file(std::env::temp_dir().join(format!("{NAME}-arm2.obu")));
519 let dumps_red = panicked(&|| {
520 decode_all_frames_vs_oracle(&stream, "oracle-control-arm2-alldumps");
521 });
522 let count_red = {
523 let counted = count_rawvideo_diffs(&stream, "oracle-control-arm2-count", None)
524 .unwrap_or_else(|| {
525 panic!(
526 "{NAME}: a single flipped oracle byte must NOT change the buffer \
527 LENGTH -- returning None means the shim corrupted more than the \
528 comparison"
529 )
530 });
531 counted.0 + counted.1 + counted.2 > 0 && counted.4 < counted.3
532 };
533 let kf_red = {
534 let (differing, first) = key_frame_diffs(&stream, "oracle-control-arm2-kf");
535 differing > 0 && first.is_some()
536 };
537 let planes_red = {
538 let [y, u, v] =
539 oracle_plane_diffs(&stream, "oracle-control-arm2-planes", plane_samples);
540 y + u + v > 0
541 };
542 set_oracle_path(None);
543 let _ = std::fs::remove_dir_all(&dir);
544 reds = [rawvideo_red, dumps_red, count_red, kf_red, planes_red];
545 }
546 // One assert, naming EVERY comparator that stayed green: a partial
547 // run would report the first and hide whether the other four are
548 // covered.
549 let blind: Vec<&str> = [
550 ("assert_rawvideo_matches", reds[0]),
551 ("decode_all_frames_vs_oracle", reds[1]),
552 ("count_rawvideo_diffs", reds[2]),
553 ("key_frame_diffs", reds[3]),
554 ("oracle_plane_diffs", reds[4]),
555 ]
556 .into_iter()
557 .filter(|(_, red)| !red)
558 .map(|(what, _)| what)
559 .collect();
560 assert!(
561 blind.is_empty(),
562 "{NAME}: {} of 5 oracle comparators stayed GREEN against an oracle that is wrong \
563 by exactly one byte -- {blind:?} -- they cannot fail, so their green proves \
564 nothing (class `comparator-that-never-reads-the-oracle`)",
565 blind.len()
566 );
567 eprintln!("{NAME}: all five oracle comparators red on a one-byte-wrong oracle");
568 }
569
570 /// lane-film10fix: the permanent CONTROL for the ffmpeg half of the class
571 /// `comparator-that-never-reads-the-oracle`.
572 ///
573 /// Its sibling above covers the five `aomdec` comparators. The `ffmpeg`
574 /// half had no such control, and it is the half the two 10-bit FILM gates
575 /// rest on: `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...`
576 /// and `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_...`
577 /// both declare "pixel-exact" purely as
578 /// `assert_eq!(ours.<plane>, ffmpeg_decode_sequence_10bit(...).<plane>)`
579 /// over 15 and 33 shown frames. If `ffmpeg_decode_sequence_10bit` ever
580 /// stopped reading ffmpeg's stdout -- packed our own samples into the
581 /// buffer it returns, say -- both gates would report exact on a decoder
582 /// that could be arbitrarily wrong, and nothing in the crate would go
583 /// red. Reading the helper's source proves it is live TODAY; only a
584 /// deliberately wrong reference proves it can FAIL.
585 ///
586 /// So this is the same two-arm shape, pointed at ffmpeg. The shim runs the
587 /// REAL ffmpeg and then rotates ONE byte of its rawvideo stdout per
588 /// offset in a sibling file, leaving the stream, the geometry, the frame
589 /// count and every other sample a genuine decode. On a pin that IS
590 /// byte-exact against real ffmpeg:
591 ///
592 /// 1. **arm 1, real ffmpeg: every helper is GREEN.** Without this arm,
593 /// arm 2's red could just be a stream that was never exact.
594 /// 2. **arm 2, one-sample-wrong ffmpeg, PER PLANE: every helper is RED
595 /// and the red names the plane that was tampered with.** Three arms,
596 /// one per plane, because a helper that only ever compared luma would
597 /// pass the Y arm and fail U and V -- and a 10-bit film gate that
598 /// reported "exact" while ignoring chroma entirely would be exactly
599 /// the class this controls.
600 ///
601 /// The three helpers are the whole reference surface in this module:
602 /// `ffmpeg_decode_sequence` (4:2:0 8-bit), `ffmpeg_decode_gray_sequence`
603 /// (monochrome, one plane) and `ffmpeg_decode_sequence_10bit` (the
604 /// `yuv420p10le` family both film gates use). Each is driven on a pin it
605 /// is known to be exact against: the 8-bit `420_odd65x65_key.obu` for the
606 /// first, the same stream for the third's shape arithmetic, and the
607 /// monochrome recipe the mono gate already builds for the second. The
608 /// override is thread-local, so a red arm cannot leave a tampered ffmpeg
609 /// behind for a sibling test on another thread.
610 #[test]
611 fn every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg() {
612 const NAME: &str = "every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg";
613 if !have_ffmpeg() {
614 eprintln!("SKIP {NAME}: no ffmpeg");
615 return;
616 }
617 // Same mutex the oracle control takes: this test's shim is
618 // thread-local, but the SCREAM it produces must not interleave with a
619 // sibling's decode in the captured log.
620 let _gate_lock = lock_gate_counters();
621
622 // The 4:2:0 8-bit arm. It BUILDS its stream with the same
623 // `libaom-av1` lavfi recipe the mono gate below uses rather than
624 // pinning one: `ffmpeg_decode_sequence` derives its frame size as
625 // `w*h + 2*(w*h/4)`, which is only right for EVEN dimensions -- on a
626 // 65x65 stream 4:2:0 chroma is ceil(65/2)^2 = 1089, not 4225/4 =
627 // 1056, and the helper's length assert fires (loudly, by design --
628 // see `frame_count_diagnosis`). 320x240 keeps the offsets below
629 // exact: luma 76800 samples, chroma 160x120 = 19200 each.
630 let (w, h) = (320usize, 240usize);
631 let (ys, cs) = (w * h, (w / 2) * (h / 2));
632 assert_eq!(
633 (ys, cs),
634 (76800, 19200),
635 "{NAME}: the byte offsets in this test are computed from this geometry"
636 );
637 let build_8bit = {
638 let out = crate::tool_cache::cached_output_io(Command::new(ffmpeg_path())
639 .args([
640 "-v",
641 "error",
642 "-f",
643 "lavfi",
644 "-i",
645 "testsrc2=size=320x240:rate=30:duration=1",
646 "-pix_fmt",
647 "yuv420p",
648 "-c:v",
649 "libaom-av1",
650 "-cpu-used",
651 "8",
652 "-b:v",
653 "300k",
654 "-f",
655 "obu",
656 "-",
657 ])
658 .stdin(Stdio::null())
659 .stdout(Stdio::piped())
660 .stderr(Stdio::piped()), None, |c| c.output())
661 .expect("ffmpeg failed to build the 4:2:0 8-bit arm");
662 assert!(
663 out.status.success(),
664 "{NAME}: ffmpeg could not build the 8-bit arm: {}",
665 String::from_utf8_lossy(&out.stderr)
666 );
667 out.stdout
668 };
669 assert_eq!(
670 stream_bit_depth(&build_8bit, NAME),
671 8,
672 "{NAME}: this arm is the 8-bit cell the byte offsets below are computed for"
673 );
674 let our_8bit =
675 decode_stream(&build_8bit).expect("the 8-bit arm must decode -- arm 1 needs it exact");
676 assert!(
677 !our_8bit.is_empty(),
678 "{NAME}: the 8-bit arm decoded nothing"
679 );
680 let frames_8bit = our_8bit.len();
681
682 // The monochrome recipe, byte-identical to the one
683 // `a_real_libaom_monochrome_key_frame_decodes_pixel_exact` builds, so
684 // the gray helper is driven on a stream that gate already proves
685 // exact. A MONOCHROME stream is also this test's 4:2:0 4:2:0-free
686 // arm: `ffmpeg_decode_gray_sequence` returns a flat luma buffer, so
687 // the one flipped offset must be attributed to Y and to nothing else.
688 let gray_stream = {
689 let out = crate::tool_cache::cached_output_io(Command::new(ffmpeg_path())
690 .args([
691 "-v",
692 "error",
693 "-f",
694 "lavfi",
695 "-i",
696 "testsrc2=size=64x64:rate=30:duration=1",
697 "-pix_fmt",
698 "gray",
699 "-c:v",
700 "libaom-av1",
701 "-cpu-used",
702 "8",
703 "-b:v",
704 "100k",
705 "-f",
706 "obu",
707 "-",
708 ])
709 .stdin(Stdio::null())
710 .stdout(Stdio::piped())
711 .stderr(Stdio::piped()), None, |c| c.output())
712 .expect("ffmpeg failed to build the monochrome arm");
713 assert!(
714 out.status.success(),
715 "{NAME}: ffmpeg could not build the monochrome arm: {}",
716 String::from_utf8_lossy(&out.stderr)
717 );
718 out.stdout
719 };
720 let our_gray = decode_stream(&gray_stream).expect("the monochrome arm must decode");
721 assert!(
722 !our_gray.is_empty(),
723 "{NAME}: the monochrome arm decoded nothing"
724 );
725 let frames_gray = our_gray.len();
726
727 // ---- the one-sample-wrong ffmpeg shim ---------------------------
728 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
729 let _ = std::fs::remove_dir_all(&dir);
730 std::fs::create_dir_all(&dir).expect("scratch dir");
731 // The real ffmpeg's path rides in a sibling file rather than inside
732 // the script, so a path with a space or a quote cannot mangle it and
733 // the script body needs no `format!` escaping.
734 let real = if let Some(p) = std::env::var_os("EC_AV1_FFMPEG") {
735 std::path::PathBuf::from(p)
736 } else {
737 let found = Command::new("ffmpeg")
738 .arg("-version")
739 .stdout(Stdio::null())
740 .stderr(Stdio::null())
741 .status()
742 .is_ok_and(|s| s.success());
743 assert!(found, "{NAME}: no working ffmpeg on PATH to wrap");
744 // Resolve the bare name through PATH so the shim does not depend
745 // on inheriting whatever PATH the test runner had.
746 let path = std::env::var_os("PATH").unwrap_or_default();
747 std::env::split_paths(&path)
748 .map(|d| d.join("ffmpeg"))
749 .find(|p| p.is_file())
750 .expect("{NAME}: ffmpeg is on PATH but not resolvable to a file")
751 };
752 std::fs::write(dir.join("real-ffmpeg"), real.as_os_str().as_encoded_bytes())
753 .expect("recording the real ffmpeg's path for the shim");
754 // Each line of `offsets` is one byte of the rawvideo stdout to rotate
755 // by 128, so the write always changes it. Everything else -- the
756 // stream, the geometry, the frame count, every other sample -- is a
757 // genuine ffmpeg decode. stdin is inherited so the shim is a drop-in
758 // for the helpers' `run_with_stdin` call.
759 let script = r#"#!/bin/sh
760REAL=$(cat "$(dirname "$0")/real-ffmpeg")
761OUT=$(mktemp)
762"$REAL" "$@" > "$OUT" || exit $?
763while read -r o; do
764 [ -n "$o" ] || continue
765 b=$(od -An -tu1 -j "$o" -N 1 "$OUT" 2>/dev/null | tr -d ' \n')
766 [ -n "$b" ] || continue
767 esc=$(printf '\\%03o' $(( (b + 128) % 256 )))
768 printf "$esc" | dd of="$OUT" bs=1 seek="$o" count=1 conv=notrunc 2>/dev/null
769done < "$(dirname "$0")/offsets"
770cat "$OUT"
771rm -f "$OUT"
772exit 0
773"#;
774 let shim = dir.join("one-sample-wrong-ffmpeg.sh");
775 std::fs::write(&shim, script).expect("writing the ffmpeg shim");
776 #[cfg(unix)]
777 {
778 use std::os::unix::fs::PermissionsExt;
779 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755))
780 .expect("the ffmpeg shim must be executable");
781 }
782 let set_offsets = |bytes: &[usize]| {
783 let body: String = bytes
784 .iter()
785 .map(|b| format!("{b}\n"))
786 .collect::<Vec<_>>()
787 .concat();
788 std::fs::write(dir.join("offsets"), body).expect("writing the offsets file");
789 };
790 // A comparator that cannot report a difference is worse than none, so
791 // each arm is scored as a COUNT of differing samples, not as a panic.
792 let count8 = |theirs: &[Pic]| -> [usize; 3] {
793 let mut wrong = [0usize; 3];
794 for (plane, (x, y)) in [
795 (0usize, (&our_8bit[0].y, &theirs[0].y)),
796 (1, (&our_8bit[0].u, &theirs[0].u)),
797 (2, (&our_8bit[0].v, &theirs[0].v)),
798 ] {
799 wrong[plane] = x.iter().zip(y).filter(|(a, b)| a != b).count();
800 }
801 wrong
802 };
803
804 // The 10-bit FILM pin, and the comparator both charter-named film
805 // gates rest on. Driven on the real stream rather than a synthetic
806 // one: `ffmpeg_decode_sequence_10bit` is the only reference helper
807 // with a per-plane split, so it is the one that could silently lose a
808 // plane. 1920x792 at 10 bits: luma 1920*792*2 bytes per frame, chroma
809 // 960*396*2.
810 let film = std::fs::read(crate_pin("reelc_sb128_inter_witness.obu")).unwrap_or_else(|e| {
811 panic!(
812 "{NAME}: the 10-bit film pin reelc_sb128_inter_witness.obu is missing ({e}) -- \
813 restore the committed copy"
814 )
815 });
816 assert_eq!(
817 stream_bit_depth(&film, NAME),
818 10,
819 "{NAME}: this arm is the 10-bit cell the byte offsets below are computed for"
820 );
821 let our_10bit =
822 decode_stream(&film).expect("the 10-bit film pin must decode -- arm 1 needs it exact");
823 let (fw, fh) = (1920usize, 792usize);
824 let film_frames = our_10bit.len();
825 let (fys, fcs) = (fw * fh * 2, (fw / 2) * (fh / 2) * 2);
826 let count10 = |theirs: &[Pic]| -> [usize; 3] {
827 let mut wrong = [0usize; 3];
828 for (a, b) in our_10bit.iter().zip(theirs) {
829 for (plane, (x, y)) in
830 [(0usize, (&a.y, &b.y)), (1, (&a.u, &b.u)), (2, (&a.v, &b.v))]
831 {
832 wrong[plane] += x.iter().zip(y).filter(|(p, q)| p != q).count();
833 }
834 }
835 wrong
836 };
837 let count_gray = |theirs: &[u8]| -> usize {
838 our_gray[0]
839 .y
840 .iter()
841 .zip(theirs)
842 .filter(|(a, b)| **a != u16::from(**b))
843 .count()
844 };
845
846 // ---- arm 1: the real ffmpeg, every comparator GREEN ------------
847 {
848 set_offsets(&[]);
849 set_ffmpeg_path(None);
850 let theirs = ffmpeg_decode_sequence(&build_8bit, w, h, frames_8bit);
851 assert_eq!(
852 count8(&theirs),
853 [0, 0, 0],
854 "{NAME}: arm 1 runs against the REAL ffmpeg, so every plane must be zero -- if \
855 this is red the stream is not the byte-exact pin this control needs"
856 );
857 let their_gray = ffmpeg_decode_gray_sequence(&gray_stream, 64, 64, frames_gray);
858 assert_eq!(
859 count_gray(&their_gray),
860 0,
861 "{NAME}: arm 1's monochrome plane must be zero against the real ffmpeg"
862 );
863 // arm 1's 10-bit half: the film pin is byte-exact against real
864 // ffmpeg on every plane of every shown frame -- that is exactly
865 // what `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...`
866 // asserts -- so this is the cell the two charter-named film gates
867 // claim.
868 let their_10bit = ffmpeg_decode_sequence_10bit(&film, fw, fh, film_frames);
869 assert_eq!(
870 count10(&their_10bit),
871 [0, 0, 0],
872 "{NAME}: arm 1's 10-bit film pin must be zero on every plane against the real \
873 ffmpeg -- if this is red the control's pin is not the byte-exact stream it needs"
874 );
875 }
876
877 // ---- arm 2: one sample wrong, PER PLANE -------------------------
878 // The shim is thread-local, so the tampered reference is confined to
879 // this thread; it is cleared before anything is asserted, so a red arm
880 // cannot leave this test's own later work reading a wrong ffmpeg.
881 let mut blind: Vec<String> = Vec::new();
882 {
883 set_ffmpeg_path(Some(shim.clone()));
884 for (plane, (_name, base)) in [("Y", 0usize), ("U", ys), ("V", ys + cs)]
885 .into_iter()
886 .enumerate()
887 {
888 // Byte 1000 of the named plane: inside the 4:2:0 8-bit pin's
889 // luma (4225), inside its chroma (1024), or past both.
890 set_offsets(&[base + 1000]);
891 let theirs = ffmpeg_decode_sequence(&build_8bit, w, h, frames_8bit);
892 let got = count8(&theirs);
893 let want = [0usize, 0, 0];
894 let mut expected = want;
895 expected[plane] = 1;
896 if got != expected {
897 blind.push(format!(
898 "ffmpeg_decode_sequence {plane} arm: counted {got:?}, expected \
899 {expected:?} (exactly the one tampered sample)"
900 ));
901 }
902 }
903 // The 10-bit helper, per plane, on the 10-bit FILM pin. This is the
904 // arm that matters for the charter: both
905 // `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...`
906 // and
907 // `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_...`
908 // declare "pixel-exact on every plane" using nothing but this
909 // helper's output. A helper that dropped U or V would leave both
910 // gates green while chroma went unchecked for 15 and 33 frames.
911 for (plane, (_name, base)) in [("Y", 0usize), ("U", fys), ("V", fys + fcs)]
912 .into_iter()
913 .enumerate()
914 {
915 // Sample 1000 of the named plane, two bytes per sample.
916 set_offsets(&[base + 2000]);
917 let theirs = ffmpeg_decode_sequence_10bit(&film, fw, fh, film_frames);
918 let got = count10(&theirs);
919 let mut expected = [0usize, 0, 0];
920 expected[plane] = 1;
921 if got != expected {
922 blind.push(format!(
923 "ffmpeg_decode_sequence_10bit {plane} arm: counted {got:?}, expected \
924 {expected:?} (exactly the one tampered sample)"
925 ));
926 }
927 }
928 // The monochrome helper: one plane, so the single flipped offset
929 // must show up as luma and nothing else can absorb it.
930 set_offsets(&[1000]);
931 let their_gray = ffmpeg_decode_gray_sequence(&gray_stream, 64, 64, frames_gray);
932 if count_gray(&their_gray) != 1 {
933 blind.push(format!(
934 "ffmpeg_decode_gray_sequence arm: counted {} differing luma samples, expected \
935 exactly 1",
936 count_gray(&their_gray)
937 ));
938 }
939 set_ffmpeg_path(None);
940 }
941 let _ = std::fs::remove_dir_all(&dir);
942 // One assert, naming EVERY helper that failed to notice: a partial run
943 // would report the first and hide whether the others are covered.
944 assert!(
945 blind.is_empty(),
946 "{NAME}: {} of 7 ffmpeg comparator arms stayed GREEN against an ffmpeg that is wrong \
947 by exactly one sample -- {blind:#?} -- they cannot fail, so their green proves \
948 nothing (class `comparator-that-never-reads-the-oracle`)",
949 blind.len()
950 );
951 eprintln!(
952 "{NAME}: ffmpeg_decode_sequence red on a one-sample-wrong Y, U and V separately; \
953 ffmpeg_decode_gray_sequence red on one wrong luma sample; \
954 ffmpeg_decode_sequence_10bit red on a one-sample-wrong Y, U and V of the 10-bit \
955 film pin"
956 );
957 }
958
959 /// lane-av1422chrtx: the odd-frame-HEIGHT 4:2:0 witness, pinned and now
960 /// EXACT (lane-av1422anom had pinned it as a ratchet on its own defect).
961 ///
962 /// This is NOT a 4:2:2 cell and needs no bypass -- it is ordinary 4:2:0,
963 /// reachable by any user. lane-av1422anom pinned it as a RATCHET asserting
964 /// its own measured defect `(0, 200, 17658)`, and said whoever fixed it
965 /// must flip that to exactness. That is done, and the flip is the
966 /// deliverable:
967 ///
968 /// the defect was a chroma `tx_type`, not a geometry. libaom's
969 /// `av1_get_ext_tx_set_type` (`blockd.h`) resolves a **32-point** chroma
970 /// unit to `EXT_TX_SET_DCT_IDTX` when the block `is_inter` -- so an
971 /// Intra-Block-Copy block whose luma coded `IDTX` runs the identity
972 /// transform on its chroma. `read_plane`'s `side >= 32` clamp forced
973 /// `DCT_DCT` there (its `DCT_DCT` cap is really libaom's
974 /// `txsize_sqr_up_map[tx_size] > TX_32X32`, i.e. 64 and up), so the
975 /// residual was a 32-point IDCT where libaom's was a plain copy of the
976 /// dequantized coefficients `>>2`. The wrong samples sat in one 64x64
977 /// IBC block's 32x32 chroma unit at chroma (128,96) on frame 0, and
978 /// propagated from there through the inter frames.
979 ///
980 /// `the_counting_oracle_diff_detects_one_flipped_oracle_byte` is the
981 /// non-vacuity control that keeps the `0` above worth anything.
982 #[test]
983 fn the_pinned_420_oddheight_witness_is_pinned_and_decodes_byte_exact() {
984 const NAME: &str = "the_pinned_420_oddheight_witness_is_pinned_and_decodes_byte_exact";
985 // lane-av1cmpaudit2: same mutex as every other oracle gate.
986 let _gate_lock = lock_gate_counters();
987 const FILE: &str = "420_oddheight_320x232.obu";
988 const BYTES: usize = 15773;
989 // sha256 6832c3cd867f5fc491b45fd67f77c38453db0ca6d461e7d225e6276f4d0784c8,
990 // recorded in `lanes/av1422anom.report.md`. The tree pins fixture
991 // identity by fnv1a64, asserted below. A `const SHA256` compared
992 // against itself would be a tautology -- the exact bug this lane
993 // exists to kill -- so it is not written.
994 const FNV1A64: u64 = 0x37877f15307c3b;
995 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
996 .join("fixtures")
997 .join(FILE);
998 let data = std::fs::read(&path)
999 .unwrap_or_else(|e| panic!("{NAME}: pinned witness {FILE} is missing ({e})"));
1000 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
1001 assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted");
1002 let (wy, wu, wv, frames, exact) =
1003 count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
1004 assert_eq!(
1005 (wy, wu, wv),
1006 (0, 0, 0),
1007 "{NAME}: the pinned 320x232 witness must decode byte-exactly against \
1008 `aomdec --rawvideo` on every plane. It was a RATCHET asserting its own \
1009 measured defect (0, 200, 17658); lane-av1422chrtx flipped it to exactness \
1010 when the 32-point INTER chroma `tx_type` (EXT_TX_SET_DCT_IDTX, not \
1011 EXT_TX_SET_DCTONLY) was fixed. Any non-zero value here is a regression -- \
1012 name it in the report."
1013 );
1014 assert_eq!(frames, 16, "{NAME}: shown frame count");
1015 assert_eq!(
1016 exact, frames,
1017 "{NAME}: every shown frame must be byte-exact"
1018 );
1019 }
1020
1021 /// lane-av1oddheightfork3: the 320x236 cell this lane CLOSED, as a
1022 /// permanent BYTE-EXACTNESS gate against the live oracle -- not a route
1023 /// counter, not a source scan. It compares our decoded samples with
1024 /// `aomdec --rawvideo`'s own bytes plane by plane, and asserts every
1025 /// frame is byte-exact.
1026 ///
1027 /// **The defect it pins.** Before the fix this cell measured
1028 /// `Y 234349 / U 56957 / V 52981, 0 of 16 frames exact` -- reproduced on
1029 /// this lane's own tree by reverting the fix, matching
1030 /// `lanes/av1oddluma.report.md` and `lanes/av1cmpframe.report.md` digit
1031 /// for digit. The first divergent read is the `txfm_partition` symbol of
1032 /// the INTRABC 8x16 block at mi(44,60): our `TXFM_CONTEXT` grid held the
1033 /// BLOCK's own `16` in `left_txfm[44]` where libaom holds the split
1034 /// leaf's `8` (the operand pair is printed by the oracle rung
1035 /// `EC_VARTXCTX`, `scripts/instrument-aom-oracle.sh`), so `ctx` was 12
1036 /// against libaom's 13 and `is_split` 0 against 1.
1037 ///
1038 /// **Non-vacuity.** `the_counting_oracle_diff_detects_one_flipped_oracle_byte`
1039 /// is the comparator control and does not depend on any witness
1040 /// diverging; the mutation proof that this gate BITES the defect it
1041 /// names is in `lanes/av1oddheightfork3.report.md` (revert the
1042 /// `fill_lf_grid_rect_after_vartx` call sites -> this test reds BY NAME
1043 /// with the numbers above).
1044 #[test]
1045 fn the_pinned_420_oddheight_320x236_witness_decodes_byte_exact() {
1046 const NAME: &str = "the_pinned_420_oddheight_320x236_witness_decodes_byte_exact";
1047 let _gate_lock = lock_gate_counters();
1048 const FILE: &str = "420_oddheight_320x236.obu";
1049 const BYTES: usize = 16562;
1050 // sha256 84e4d1ab56620af1c5b78e1aa3d2d67496a492f2e127198c82dd1d68b01c6200.
1051 // Identity is pinned by fnv1a64 (the same value
1052 // `the_counting_oracle_diff_attributes_planes_per_frame` asserts) --
1053 // a `const SHA256` compared against itself would be the tautology
1054 // this lane exists to kill.
1055 const FNV1A64: u64 = 521889434652397870;
1056 let data = crate_pin("420_oddheight_320x236.obu");
1057 let data = std::fs::read(&data)
1058 .unwrap_or_else(|e| panic!("{NAME}: the committed pin {FILE} is missing ({e})"));
1059 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
1060 assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted");
1061 let (wy, wu, wv, frames, exact) =
1062 count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
1063 assert_eq!(
1064 (wy, wu, wv),
1065 (0, 0, 0),
1066 "{NAME}: the pinned 320x236 cell must decode byte-exactly against \
1067 `aomdec --rawvideo` on every plane. It measured \
1068 (234349, 56957, 52981) with 0 of 16 frames exact until \
1069 lane-av1oddheightfork3 fixed the TXFM_CONTEXT whole-block \
1070 publish that overwrote a var-tx tree's per-leaf sizes. Any \
1071 non-zero value here is a regression -- name it in the report."
1072 );
1073 assert_eq!(frames, 16, "{NAME}: shown frame count");
1074 assert_eq!(
1075 exact, frames,
1076 "{NAME}: every shown frame must be byte-exact"
1077 );
1078 }
1079
1080 /// The repo's first hidden-frame pixel gate. Every other aomenc gate
1081 /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and
1082 /// both sides emit SHOWN frames only -- so an alt-ref frame that is
1083 /// decoded, stored into a reference slot and never displayed was, until
1084 /// this gate, never compared to anything (class
1085 /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the
1086 /// default `--lag-in-frames`, so they are full of exactly these frames.
1087 ///
1088 /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc
1089 /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's
1090 /// temporal filter on, this fixture's alt-ref candidates get filtered
1091 /// away and the encoder emits ZERO hidden frames (measured: 0 hidden
1092 /// with the filter on, 3 with it off), which would have made the gate
1093 /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so
1094 /// a recipe that stops producing hidden frames fails rather than skips.
1095 #[test]
1096 fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() {
1097 const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact";
1098 let _gate_lock = lock_gate_counters();
1099 if !have_ffmpeg() {
1100 eprintln!("SKIP {NAME}: no ffmpeg");
1101 return;
1102 }
1103 if !have_aomenc() {
1104 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1105 return;
1106 }
1107 for bit_depth in [8u32, 10u32] {
1108 let (width, height, frames) = (64usize, 64usize, 40usize);
1109 let duration = frames as f64 / 25.0;
1110 let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25");
1111 let pix_fmt = if bit_depth == 10 {
1112 "yuv420p10le"
1113 } else {
1114 "yuv420p"
1115 };
1116 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1117 .args([
1118 "-v",
1119 "error",
1120 "-f",
1121 "lavfi",
1122 "-i",
1123 &source,
1124 "-t",
1125 &duration.to_string(),
1126 "-pix_fmt",
1127 pix_fmt,
1128 "-strict",
1129 "-1",
1130 "-f",
1131 "yuv4mpegpipe",
1132 "-",
1133 ])
1134 .stdin(Stdio::null())
1135 .stdout(Stdio::piped())
1136 .stderr(Stdio::piped()), None, |c| c.output())
1137 .expect("ffmpeg failed to run");
1138 assert!(
1139 y4m.status.success(),
1140 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1141 String::from_utf8_lossy(&y4m.stderr)
1142 );
1143 let depth_arg = format!("--bit-depth={bit_depth}");
1144 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1145 let out = run_with_stdin(
1146 Command::new(aomenc_path()).args([
1147 // lane-defon r1: the repo's only gate that decodes hidden
1148 // frames is also the only place a FORWARD KEYFRAME can be
1149 // proven -- a KEY frame with `show_frame == 0`, which is
1150 // exactly the shape this gate already compares in decode
1151 // order. On-values go before the base list (aomenc keeps
1152 // the FIRST occurrence of a repeated flag).
1153 "--enable-fwd-kf=1",
1154 "--fwd-kf-dist=8",
1155 "--codec=av1",
1156 "--passes=1",
1157 "--end-usage=q",
1158 "--cq-level=45",
1159 "--cpu-used=0",
1160 "--threads=1",
1161 "--row-mt=0",
1162 "--kf-max-dist=1000",
1163 "--enable-order-hint=1",
1164 "--auto-alt-ref=1",
1165 "--lag-in-frames=25",
1166 "--arnr-maxframes=0",
1167 &depth_arg,
1168 &input_depth_arg,
1169 // The same tool set every sibling inter gate pins -- the
1170 // open capability gaps (rect/AB partitions, warped/OBMC,
1171 // masked compound, palette, ...) are other lanes' work;
1172 // this gate is about hidden frames, not about them.
1173 "--enable-warped-motion=0",
1174 // OBMC stays off HERE (this gate is about hidden frames);
1175 // the tool's own coverage is the `obmc*` gates and, on a
1176 // 16x8/8x16 leaf, the `--enable-obmc=1` arm of
1177 // `..._with_a_16_level_rect_leaf_...` (lane-inter4 r4).
1178 "--enable-obmc=0",
1179 "--enable-masked-comp=0",
1180 "--enable-interintra-comp=0",
1181 "--enable-onesided-comp=0",
1182 "--enable-interintra-wedge=0",
1183 "--enable-smooth-interintra=0",
1184 "--enable-rect-partitions=0",
1185 "--enable-ab-partitions=0",
1186 "--enable-1to4-partitions=0",
1187 "--enable-filter-intra=0",
1188 "--enable-smooth-intra=0",
1189 "--enable-paeth-intra=0",
1190 "--enable-directional-intra=0",
1191 "--enable-angle-delta=0",
1192 "--enable-tx-size-search=0",
1193 "--enable-cdef=0",
1194 "--enable-restoration=0",
1195 "--max-partition-size=32",
1196 "--min-partition-size=32",
1197 "--enable-palette=0",
1198 "--enable-intrabc=0",
1199 "--enable-cfl-intra=0",
1200 "--enable-ref-frame-mvs=0",
1201 "--obu",
1202 "-o",
1203 "-",
1204 "-",
1205 ]),
1206 &y4m.stdout,
1207 );
1208 assert!(
1209 out.status.success(),
1210 "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}",
1211 String::from_utf8_lossy(&out.stderr)
1212 );
1213 let stream = out.stdout;
1214 let fwd_kf_before = crate::decode::fwd_kf_hits();
1215 let (total, hidden) =
1216 decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit"));
1217 let fwd_kf = crate::decode::fwd_kf_hits() - fwd_kf_before;
1218 assert!(
1219 hidden >= 2,
1220 "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \
1221 {total} decoded -- the gate would be vacuous (class \
1222 gate-blind-to-hidden-frames)"
1223 );
1224 // lane-defon r1: `--enable-fwd-kf=1` is spelled on this recipe, so
1225 // a KEY frame with `show_frame == 0` must actually have been
1226 // decoded -- otherwise the on-value proves nothing.
1227 assert!(
1228 fwd_kf > 0,
1229 "{NAME}: the {bit_depth}-bit recipe decoded {total} frames ({hidden} hidden) but \
1230 zero forward keyframes -- --enable-fwd-kf=1 --fwd-kf-dist=8 never reached the \
1231 bitstream"
1232 );
1233 eprintln!(
1234 "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, {fwd_kf} \
1235 forward keyframes, all pixel-exact vs the oracle in decode order"
1236 );
1237 }
1238 }
1239
1240 /// A real `aomenc` filter-intra fixture: every other intra mode disabled
1241 /// (smooth/paeth/directional/angle-delta) and
1242 /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s
1243 /// <=32x32 bound means `use_filter_intra` never reads at all, spec
1244 /// 5.11.14), so the only way this frame codes is `DC_PRED` with filter
1245 /// intra on top -- `--loopfilter-control=0` is required too: this
1246 /// decoder has no in-loop deblocking filter at all, and libaom's default
1247 /// (on) smooths every block-boundary column, which first looked like a
1248 /// filter-intra math bug (mismatches straddling the 32-pixel block
1249 /// seam) until the recipe without it round-tripped byte-exact.
1250 ///
1251 /// lane-av1skipfix: the attempt-loop shape this gate's single recipe
1252 /// lacked. It sweeps (seed, cq) and REQUIRES at least one attempt to both
1253 /// decode and read `use_filter_intra`: a decode error on EVERY attempt is
1254 /// a hard failure carrying the refusal texts, not a printed SKIP, and an
1255 /// attempt that decodes without the symbol firing is still pixel-compared
1256 /// (class `gate-skips-on-its-own-failure`). MEASURED 2026-09-29 on
1257 /// `a21f3680`: seed 42 cq 40 and seed 43 cq 40 read the symbol 3x each,
1258 /// pixel-exact, while seed 44 cq 45 and seed 45 cq 30 decode WITHOUT it --
1259 /// so the one fixed recipe really did carry the whole gate.
1260 ///
1261 /// The per-attempt decode error the old single recipe SKIPped on is
1262 /// `screen_content_tools_determination` (libaom `encoder_utils.c`): a real
1263 /// internal trial-encode/PSNR comparison, not a flag this CLI exposes a
1264 /// knob for -- on this flat gradient fixture it lands on
1265 /// `allow_screen_content_tools=0` most runs but occasionally trips over
1266 /// its 0.9 dB threshold the other way even with palette/intrabc both
1267 /// disabled. That is a genuine separate gap (`decode_stream` never reads
1268 /// `intrabc`/`palette_mode_info`), so it is a NAMED REFUSAL counted per
1269 /// attempt, never a silent skip and never a pass.
1270 #[test]
1271 fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {
1272 const NAME: &str = "a_real_aomenc_filter_intra_stream_decodes_pixel_exact";
1273 let _gate_lock = lock_gate_counters();
1274 if !have_ffmpeg() {
1275 eprintln!("SKIP {NAME}: no ffmpeg");
1276 return;
1277 }
1278 if !have_aomenc() {
1279 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1280 return;
1281 }
1282 let (width, height) = (64usize, 64usize);
1283 // Recipe-search hooks: with the encoder pinned to one thread the stream
1284 // is a deterministic function of (seed, cq), so a firing recipe can be
1285 // searched for without a rebuild. These pin attempt 0 for a bisect; the
1286 // sweep walks the same axes regardless.
1287 let fi_seed: u32 = std::env::var("EC_FI_SEED")
1288 .ok()
1289 .and_then(|v| v.parse().ok())
1290 .unwrap_or(42);
1291 let fi_cq: u32 = std::env::var("EC_FI_CQ")
1292 .ok()
1293 .and_then(|v| v.parse().ok())
1294 .unwrap_or(40);
1295 // Two seeds x three quantisers, so "every attempt refused" and "no
1296 // attempt ever read `use_filter_intra`" are distinguishable failures
1297 // rather than one unlucky recipe.
1298 const CQS: [u32; 3] = [40, 35, 30];
1299 let mut refusals = Vec::new();
1300 let mut counted_exact = 0u32;
1301 let mut uncounted_exact = 0u32;
1302 'attempts: for round in 0..2u32 {
1303 for (i, &walked) in CQS.iter().enumerate() {
1304 let seed = fi_seed + round;
1305 let cq = if round == 0 && i == 0 { fi_cq } else { walked };
1306 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
1307 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1308 .args([
1309 "-v",
1310 "error",
1311 "-f",
1312 "lavfi",
1313 "-i",
1314 &source,
1315 "-pix_fmt",
1316 "yuv420p",
1317 "-f",
1318 "yuv4mpegpipe",
1319 "-",
1320 ])
1321 .stdin(Stdio::null())
1322 .stdout(Stdio::piped())
1323 .stderr(Stdio::piped()), None, |c| c.output())
1324 .expect("ffmpeg failed to run");
1325 assert!(
1326 y4m.status.success(),
1327 "ffmpeg refused to generate the y4m fixture: {}",
1328 String::from_utf8_lossy(&y4m.stderr)
1329 );
1330 let cq_arg = format!("--cq-level={cq}");
1331 let out = run_with_stdin(
1332 Command::new(aomenc_path()).args([
1333 "--codec=av1",
1334 "--passes=1",
1335 "--end-usage=q",
1336 &cq_arg,
1337 "--cpu-used=0",
1338 // Every sibling gate pins these; this one did not, and a
1339 // multi-threaded aomenc is not deterministic, so each run
1340 // encoded a slightly different stream and the gate flaked
1341 // against whichever features that run happened to pick.
1342 // Pinning them makes seed 42 mean one stream (class
1343 // `parallel-flake-is-attempt-selection`).
1344 "--threads=1",
1345 "--row-mt=0",
1346 "--enable-filter-intra=1",
1347 "--enable-smooth-intra=0",
1348 "--enable-paeth-intra=0",
1349 "--enable-directional-intra=0",
1350 "--enable-angle-delta=0",
1351 "--enable-tx-size-search=0",
1352 "--enable-cdef=0",
1353 "--max-partition-size=32",
1354 "--loopfilter-control=0",
1355 "--enable-palette=0",
1356 "--enable-intrabc=0",
1357 "--obu",
1358 "-o",
1359 "-",
1360 "-",
1361 ]),
1362 &y4m.stdout,
1363 );
1364 assert!(
1365 out.status.success(),
1366 "{NAME}: aomenc refused the seed {seed} cq {cq} fixture: {}",
1367 String::from_utf8_lossy(&out.stderr)
1368 );
1369 let stream = out.stdout;
1370 let before = decode::filter_intra_hits();
1371 let frames = match decode_stream(&stream) {
1372 Ok(frames) => frames,
1373 Err(e) => {
1374 refusals.push(format!("seed {seed} cq {cq}: {e}"));
1375 continue;
1376 }
1377 };
1378 // A decode that succeeded is ALWAYS pixel-compared; the hit
1379 // counter only decides whether the attempt counts as firing
1380 // (class `counter-from-refused-stream`).
1381 let counted = decode::filter_intra_hits() != before;
1382 if counted {
1383 counted_exact += 1;
1384 } else {
1385 uncounted_exact += 1;
1386 }
1387 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1388 assert_eq!(
1389 frames[0].y, ffmpeg_frames[0].y,
1390 "luma vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
1391 );
1392 assert_eq!(
1393 frames[0].u, ffmpeg_frames[0].u,
1394 "U vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
1395 );
1396 assert_eq!(
1397 frames[0].v, ffmpeg_frames[0].v,
1398 "V vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
1399 );
1400 if counted_exact >= 2 {
1401 break 'attempts;
1402 }
1403 }
1404 }
1405 gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
1406 assert!(
1407 counted_exact > 0,
1408 "{NAME}: none of {} attempts decoded a stream that read use_filter_intra -- the \
1409 gate would prove nothing (class gate-blind-to-feature):\n{}",
1410 CQS.len() * 2,
1411 refusals.join("\n")
1412 );
1413 }
1414
1415 /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`
1416 /// (SMPTE colour bars -- a handful of large flat luma regions, exactly
1417 /// the "flat, few-colour, repetitive" content `av1_choose_palette_map`'s
1418 /// RD trial rewards) with `hue=s=0` to flatten chroma to one constant
1419 /// value, so `DC_PRED` already nails every chroma block with zero
1420 /// residual and the encoder's own RD never has a reason to spend bits on
1421 /// a *UV* palette too (a real symbol this decoder still refuses --
1422 /// lane-palette r3's own scope is Y only). `smptebars` has no seed to
1423 /// vary, so the fixture is deterministic by construction; hashed twice
1424 /// below to prove it rather than assert it. `--enable-rect-partitions=0`
1425 /// / `-ab-` / `-1to4-` keep every intra block square, sidestepping the
1426 /// rect-strip screen-content refusal at `read_intra_mode_rect`
1427 /// (decode.rs ~2226) -- that refusal is this lane's own next milestone,
1428 /// not this gate's. `--sb-size=64` and `--threads=1 --row-mt=0` are the
1429 /// sibling-lane facts this charter paid for: a single 64x64 frame is one
1430 /// superblock either way, but pinning them keeps the recipe identical to
1431 /// every other gate in this file. HARD-asserts
1432 /// [`decode::palette_hits`] moved -- a stream that never reads a real
1433 /// palette block would refuse (or not) by construction without proving
1434 /// this milestone at all.
1435 ///
1436 /// lane-palette r4/r6/r7: r3/r4 found that this fixture's reconstructed
1437 /// pixels did not match ffmpeg's decode of the same bytes even though
1438 /// every symbol read by `decode_color_index_map` checked line-for-line
1439 /// against the oracle and matched. r6's range trace (`compare-range-not-tell`)
1440 /// pinned the real cause: `decode_color_index_map` was called from the
1441 /// wrong syntax position -- inline right after the Y colours, instead of
1442 /// after the whole mode-info read (UV palette mode_info + `filter_intra`,
1443 /// `av1_visit_palette`'s real call order). r7 ported the UV palette
1444 /// mode_info read and moved the colour-index-map decode after
1445 /// `filter_intra`; this gate now asserts a real pixel match instead of
1446 /// the old named refusal.
1447 #[test]
1448 fn a_real_aomenc_stream_with_palette_y_decodes_pixel_exact() {
1449 const NAME: &str = "a_real_aomenc_stream_with_palette_y_decodes_pixel_exact";
1450 if !have_ffmpeg() {
1451 eprintln!("SKIP {NAME}: no ffmpeg");
1452 return;
1453 }
1454 if !have_aomenc() {
1455 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1456 return;
1457 }
1458 let source = "smptebars=size=64x64:rate=25";
1459 fn render(source: &str) -> Vec<u8> {
1460 crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1461 .args([
1462 "-v",
1463 "error",
1464 "-f",
1465 "lavfi",
1466 "-i",
1467 source,
1468 "-vf",
1469 "hue=s=0",
1470 "-pix_fmt",
1471 "yuv420p",
1472 "-t",
1473 "0.04",
1474 "-f",
1475 "yuv4mpegpipe",
1476 "-",
1477 ])
1478 .stdin(Stdio::null())
1479 .stdout(Stdio::piped())
1480 .stderr(Stdio::piped()), None, |c| c.output())
1481 .expect("ffmpeg failed to run")
1482 .stdout
1483 }
1484 let y4m_a = render(source);
1485 let y4m_b = render(source);
1486 assert_eq!(
1487 y4m_a, y4m_b,
1488 "smptebars must render byte-identical across two runs"
1489 );
1490 let y4m = y4m_a;
1491 let out = run_with_stdin(
1492 Command::new(aomenc_path()).args([
1493 "--codec=av1",
1494 "--passes=1",
1495 "--end-usage=q",
1496 "--cq-level=30",
1497 "--cpu-used=0",
1498 "--threads=1",
1499 "--row-mt=0",
1500 "--sb-size=64",
1501 "--tune-content=screen",
1502 "--enable-palette=1",
1503 "--enable-intrabc=0",
1504 "--enable-rect-partitions=0",
1505 "--enable-ab-partitions=0",
1506 "--enable-1to4-partitions=0",
1507 "--min-partition-size=32",
1508 "--max-partition-size=32",
1509 "--enable-filter-intra=0",
1510 "--enable-smooth-intra=0",
1511 "--enable-paeth-intra=0",
1512 "--enable-directional-intra=0",
1513 "--enable-angle-delta=0",
1514 "--enable-cfl-intra=0",
1515 "--enable-cdef=0",
1516 "--enable-restoration=0",
1517 "--enable-tx-size-search=0",
1518 "--loopfilter-control=0",
1519 "--obu",
1520 "-o",
1521 "-",
1522 "-",
1523 ]),
1524 &y4m,
1525 );
1526 assert!(
1527 out.status.success(),
1528 "aomenc refused the fixture: {}",
1529 String::from_utf8_lossy(&out.stderr)
1530 );
1531 let stream = out.stdout;
1532 let before = decode::palette_hits();
1533 let frames = match decode_stream(&stream) {
1534 Ok(frames) => frames,
1535 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1536 };
1537 assert!(
1538 decode::palette_hits() > before,
1539 "palette_y_mode never fired decoding this stream -- gate is vacuous"
1540 );
1541 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1);
1542 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
1543 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
1544 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
1545 }
1546
1547 /// lane-kf900 r3: the palette colour reader at BOTH bit depths.
1548 ///
1549 /// `read_palette_colors_y`/`_uv` (decode.rs, mirroring `decodemv.c:478`
1550 /// and `:509`) size every raw literal they read by the sequence's
1551 /// `bit_depth`: the first colour is `bit_depth` bits, `min_bits` is
1552 /// `bit_depth - 3` (Y/U) or `bit_depth - 4` (V), `range` starts at
1553 /// `1 << bit_depth`, and the clamp/wrap bound is `(1 << bit_depth) - 1`.
1554 /// Ours hardcoded 8, so every 10-bit palette block read TWO BITS TOO FEW
1555 /// per transmitted colour and silently decoded the rest of the tile from
1556 /// the wrong bit position.
1557 ///
1558 /// It was silent because raw literals are EQUIPROBABLE: at the ranges
1559 /// this content reaches an equiprobable read maps the msac range onto
1560 /// itself (62728 -> 31364 -> renormalised 62728), so a cross-decoder
1561 /// RANGE ladder stays bit-identical straight through the miscount and
1562 /// only the decoded VALUE moves. Pinned on a 256x192 10-bit
1563 /// `--cq-level=59` stream whose first block is a 32x16 palette: aomdec's
1564 /// `EC_PAL` ladder and ours agreed on every range and disagreed on the
1565 /// very first colour index (0 vs 1); after the fix all 1024 `EC_PAL`
1566 /// lines of that block match aomdec line for line.
1567 ///
1568 /// The recipe is the 8-bit `..._with_palette_y_...` gate's, with the
1569 /// depth as the only variable, so a failure here is the depth and
1570 /// nothing else. HARD-asserts [`decode::palette_hits`] moved on each arm
1571 /// (a stream with no real palette block would prove nothing) and
1572 /// compares all three planes against ffmpeg's decode of the same bytes.
1573 #[test]
1574 fn a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit() {
1575 const NAME: &str = "a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit";
1576 if !have_ffmpeg() {
1577 eprintln!("SKIP {NAME}: no ffmpeg");
1578 return;
1579 }
1580 if !have_aomenc() {
1581 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1582 return;
1583 }
1584 let (width, height) = (64usize, 64usize);
1585 for depth in [8usize, 10] {
1586 let pix_fmt = if depth == 10 {
1587 "yuv420p10le"
1588 } else {
1589 "yuv420p"
1590 };
1591 let render = || {
1592 crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1593 .args([
1594 "-v",
1595 "error",
1596 "-f",
1597 "lavfi",
1598 "-i",
1599 "smptebars=size=64x64:rate=25",
1600 "-vf",
1601 "hue=s=0",
1602 "-pix_fmt",
1603 pix_fmt,
1604 "-strict",
1605 "-1",
1606 "-t",
1607 "0.04",
1608 "-f",
1609 "yuv4mpegpipe",
1610 "-",
1611 ])
1612 .stdin(Stdio::null())
1613 .stdout(Stdio::piped())
1614 .stderr(Stdio::piped()), None, |c| c.output())
1615 .expect("ffmpeg failed to run")
1616 .stdout
1617 };
1618 let y4m_a = render();
1619 let y4m_b = render();
1620 assert_eq!(
1621 y4m_a, y4m_b,
1622 "{NAME}: smptebars must render byte-identical across two runs at {depth}-bit"
1623 );
1624 let y4m = y4m_a;
1625 let depth_arg = format!("--bit-depth={depth}");
1626 let input_depth_arg = format!("--input-bit-depth={depth}");
1627 let out = run_with_stdin(
1628 Command::new(aomenc_path())
1629 .args([
1630 "--codec=av1",
1631 "--passes=1",
1632 "--end-usage=q",
1633 "--cq-level=30",
1634 "--cpu-used=0",
1635 "--threads=1",
1636 "--row-mt=0",
1637 "--sb-size=64",
1638 "--tune-content=screen",
1639 "--enable-palette=1",
1640 "--enable-intrabc=0",
1641 "--enable-rect-partitions=0",
1642 "--enable-ab-partitions=0",
1643 "--enable-1to4-partitions=0",
1644 "--min-partition-size=32",
1645 "--max-partition-size=32",
1646 "--enable-filter-intra=0",
1647 "--enable-smooth-intra=0",
1648 "--enable-paeth-intra=0",
1649 "--enable-directional-intra=0",
1650 "--enable-angle-delta=0",
1651 "--enable-cfl-intra=0",
1652 "--enable-cdef=0",
1653 "--enable-restoration=0",
1654 "--enable-tx-size-search=0",
1655 "--loopfilter-control=0",
1656 "--limit=1",
1657 ])
1658 // Per-arm overrides go AFTER the base recipe: aomenc keeps the
1659 // LAST occurrence of a repeated flag.
1660 .args([&depth_arg, &input_depth_arg])
1661 .args(["--obu", "-o", "-", "-"]),
1662 &y4m,
1663 );
1664 assert!(
1665 out.status.success(),
1666 "{NAME}: aomenc refused the {depth}-bit fixture: {}",
1667 String::from_utf8_lossy(&out.stderr)
1668 );
1669 let stream = out.stdout;
1670 let before = decode::palette_hits();
1671 let frames = match decode_stream(&stream) {
1672 Ok(frames) => frames,
1673 Err(e) => panic!("{NAME}: decode_stream refused the {depth}-bit stream: {e}"),
1674 };
1675 assert!(
1676 decode::palette_hits() > before,
1677 "{NAME}: no real palette block at {depth}-bit -- gate is vacuous"
1678 );
1679 let ffmpeg_frames = if depth == 10 {
1680 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
1681 } else {
1682 ffmpeg_decode_sequence(&stream, width, height, 1)
1683 };
1684 assert_eq!(
1685 frames[0].y, ffmpeg_frames[0].y,
1686 "{NAME}: luma at {depth}-bit"
1687 );
1688 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U at {depth}-bit");
1689 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V at {depth}-bit");
1690 }
1691 }
1692
1693 /// lane-pal8 r1, the gate for a palette on a SQUARE 8x8 LEAF.
1694 ///
1695 /// `read_palette_mode_info` (decodemv.c:567) reads `palette_y_mode` for
1696 /// every `DC_PRED` block whose `av1_get_palette_bsize_ctx`
1697 /// (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`, 0 at 8x8) exists, and
1698 /// `av1_decode_palette_tokens` (decodeframe.c:1135, `av1_visit_palette`)
1699 /// reads the colour-index map after the WHOLE mode-info read. Ours passed
1700 /// `None`/`&[]` from [`decode::decode_leaf8`], reading the mode symbol off
1701 /// CDF row 0 and refusing "a block that actually uses a palette (Y) --
1702 /// reconstruction is out of scope" the moment it fired -- and at 8 bit
1703 /// aomenc palettes SQUARE blocks, so with `--min-partition-size=8` every
1704 /// 8-bit screen-content stream stopped there (lane-kf900 r4's measurement).
1705 ///
1706 /// Sweeps both bit depths x cq 30/40/55 x `--enable-tx-size-search` 0/1 x
1707 /// two lavfi sources (+ a `--tile-columns=1` arm, per the neighbour-map
1708 /// rule: the palette bands are per-mi and tile-guarded). Key frame only
1709 /// (`--limit=1`): the inter frames of these recipes stop on OTHER lanes'
1710 /// open refusals (8x8 inter leaf chroma mode, inter 1:4 partitions).
1711 /// HARD-asserts the 8x8-leaf palette counter moved on the compared arms
1712 /// and that no arm mismatched, in or out of scope.
1713 #[test]
1714 fn a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact() {
1715 const NAME: &str = "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact";
1716 if !have_ffmpeg() {
1717 eprintln!("SKIP {NAME}: no ffmpeg");
1718 return;
1719 }
1720 if !have_aomenc() {
1721 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1722 return;
1723 }
1724 let (width, height) = (128usize, 128usize);
1725 let (mut leaf8_total, mut fired_arms, mut compared, mut frames_compared) =
1726 (0usize, 0u32, 0u32, 0usize);
1727 let (mut out_of_scope, mut out_of_scope_mismatch, mut refusals) = (0u32, 0u32, 0u32);
1728 let (mut sb_strip_total, mut sb_strip_arms) = (0usize, 0u32);
1729 // lane-t900 r34 LIFTED this shape; the counter stays so the gate
1730 // fails loudly if the refusal ever comes back.
1731 let mut sb_strip_refusals = 0u32;
1732 for src in ["testsrc2", "smptebars"] {
1733 for depth in [8usize, 10usize] {
1734 for cq in [30usize, 40, 55] {
1735 for txs in [0usize, 1] {
1736 for tiles in [0usize, 1] {
1737 let arm = format!("{src}-{depth}bit-cq{cq}-txs{txs}-tc{tiles}");
1738 let pix_fmt = if depth == 10 {
1739 "yuv420p10le"
1740 } else {
1741 "yuv420p"
1742 };
1743 let size = format!("{src}=size={width}x{height}:rate=25");
1744 let render = || {
1745 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1746 .args([
1747 "-v",
1748 "error",
1749 "-f",
1750 "lavfi",
1751 "-i",
1752 &size,
1753 "-t",
1754 "0.04",
1755 "-pix_fmt",
1756 pix_fmt,
1757 "-strict",
1758 "-1",
1759 "-f",
1760 "yuv4mpegpipe",
1761 "-",
1762 ])
1763 .stdin(Stdio::null())
1764 .stdout(Stdio::piped())
1765 .stderr(Stdio::piped()), None, |c| c.output())
1766 .expect("ffmpeg failed to run");
1767 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
1768 out.stdout
1769 };
1770 let y4m_a = render();
1771 let y4m_b = render();
1772 assert_eq!(
1773 y4m_a, y4m_b,
1774 "{NAME}: {arm} must render byte-identical across two runs"
1775 );
1776 let y4m = y4m_a;
1777 let depth_arg = format!("--bit-depth={depth}");
1778 let input_depth_arg = format!("--input-bit-depth={depth}");
1779 let cq_arg = format!("--cq-level={cq}");
1780 let txs_arg = format!("--enable-tx-size-search={txs}");
1781 let tiles_arg = format!("--tile-columns={tiles}");
1782 let out = run_with_stdin(
1783 Command::new(aomenc_path())
1784 .args([
1785 "--codec=av1",
1786 "--passes=1",
1787 "--end-usage=q",
1788 "--cpu-used=0",
1789 "--threads=1",
1790 "--row-mt=0",
1791 "--lag-in-frames=0",
1792 "--limit=1",
1793 "--sb-size=64",
1794 "--tune-content=screen",
1795 "--enable-palette=1",
1796 "--enable-intrabc=0",
1797 "--min-partition-size=8",
1798 "--enable-cdef=0",
1799 "--enable-restoration=0",
1800 "--loopfilter-control=0",
1801 ])
1802 // aomenc keeps the LAST occurrence of a repeated flag,
1803 // so per-arm overrides go after the base recipe.
1804 .args([
1805 &depth_arg,
1806 &input_depth_arg,
1807 &cq_arg,
1808 &txs_arg,
1809 &tiles_arg,
1810 ])
1811 .args(["--obu", "-o", "-", "-"]),
1812 &y4m,
1813 );
1814 assert!(
1815 out.status.success(),
1816 "{NAME}: aomenc refused {arm}: {}",
1817 String::from_utf8_lossy(&out.stderr)
1818 );
1819 let stream = out.stdout;
1820 decode::reset_palette_leaf8_hits();
1821 decode::reset_palette_sb_strip_hits();
1822 let decoded = decode_stream(&stream);
1823 let leaf8 = decode::palette_leaf8_hits();
1824 let sb_strip = decode::palette_sb_strip_hits();
1825 leaf8_total += leaf8;
1826 sb_strip_total += sb_strip;
1827 match decoded {
1828 Ok(frames) => {
1829 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
1830 // The ENCODE's frame count: the per-arm
1831 // render (10417) builds
1832 // `{src}=size=128x128:rate=25` with `-t 0.04`
1833 // (10427) -- one frame -- and the aomenc args
1834 // carry `--limit=1` (10467), so every
1835 // (src, depth, cq, txs, tiles) arm codes
1836 // exactly 1 frame. Asserted ABOVE the oracle
1837 // call.
1838 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
1839 let theirs = if depth == 10 {
1840 ffmpeg_decode_sequence_10bit(
1841 &stream,
1842 width,
1843 height,
1844 frames.len(),
1845 )
1846 } else {
1847 ffmpeg_decode_sequence(&stream, width, height, frames.len())
1848 };
1849 assert_eq!(
1850 frames.len(),
1851 theirs.len(),
1852 "{NAME}: {arm} frame count"
1853 );
1854 let mut same = true;
1855 for (i, (ours, ref_f)) in
1856 frames.iter().zip(theirs.iter()).enumerate()
1857 {
1858 let ok = ours.y == ref_f.y
1859 && ours.u == ref_f.u
1860 && ours.v == ref_f.v;
1861 if !ok {
1862 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
1863 }
1864 same &= ok;
1865 frames_compared += 1;
1866 }
1867 compared += 1;
1868 if sb_strip > 0 {
1869 sb_strip_arms += 1;
1870 assert!(
1871 same,
1872 "{NAME}: {arm} decoded {sb_strip} non-skip palette \
1873 block(s) on a superblock-level strip and did not \
1874 match ffmpeg"
1875 );
1876 }
1877 if leaf8 > 0 || sb_strip > 0 {
1878 fired_arms += 1;
1879 assert!(
1880 same,
1881 "{NAME}: {arm} decoded {leaf8} 8x8-leaf palette \
1882 block(s) and did not match ffmpeg"
1883 );
1884 } else {
1885 out_of_scope += 1;
1886 if !same {
1887 out_of_scope_mismatch += 1;
1888 }
1889 }
1890 eprintln!(
1891 "{NAME}: {arm} {} frame(s), {leaf8} 8x8-leaf palette \
1892 block(s), {sb_strip} superblock-strip palette \
1893 block(s), exact={same}",
1894 frames.len()
1895 );
1896 }
1897 Err(e) => {
1898 let msg = e.to_string();
1899 assert!(
1900 msg.contains("unsupported"),
1901 "{NAME}: {arm} decode failed: {e}"
1902 );
1903 // Named, counted, never turned into a skip.
1904 if msg.contains("superblock-level HORZ/VERT strip") {
1905 sb_strip_refusals += 1;
1906 }
1907 eprintln!("{NAME}: {arm} REFUSED: {e}");
1908 refusals += 1;
1909 }
1910 }
1911 }
1912 }
1913 }
1914 }
1915 }
1916 eprintln!(
1917 "{NAME}: {leaf8_total} 8x8-leaf palette block(s) across {fired_arms} arm(s), \
1918 {compared} arms compared ({frames_compared} frames), {sb_strip_total} \
1919 superblock-strip palette block(s) across {sb_strip_arms} arm(s), \
1920 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
1921 {refusals} refused ({sb_strip_refusals} superblock-strip palette)"
1922 );
1923 assert!(
1924 leaf8_total > 0 && fired_arms > 0,
1925 "{NAME}: gate is vacuous -- no compared arm decoded an 8x8-leaf palette block"
1926 );
1927 assert_eq!(
1928 sb_strip_refusals, 0,
1929 "{NAME}: the superblock-strip palette refusal is back (lane-t900 r34 lifted it)"
1930 );
1931 assert!(
1932 sb_strip_arms > 0 && sb_strip_total > 0,
1933 "{NAME}: no arm decoded a non-skip palette block on a superblock-level strip -- \
1934 the shape r34 lifted is no longer exercised"
1935 );
1936 assert_eq!(
1937 out_of_scope_mismatch, 0,
1938 "{NAME}: an out-of-scope arm mismatched ffmpeg -- a defect, never a skip"
1939 );
1940 assert!(
1941 frames_compared > 0,
1942 "{NAME}: no frame was compared pixel-exact"
1943 );
1944 }
1945
1946 /// lane-av1toolgates: `enable-rect-tx` at 8 BITS. See
1947 /// [`rect_tx_tool_gate`] for what the flag does and does not prove, and
1948 /// why the recipe is spelled here rather than in the helper.
1949 ///
1950 /// The whole recipe is inline: `--passes=1` has to be findable in this
1951 /// segment for the coverage derivation to count the gate at all, and
1952 /// `--enable-rect-tx=1` has to be findable here for it to count the
1953 /// TOOL. The quantiser and the tx-size-search setting are swept as two
1954 /// arms so the witness cannot rest on one RD interaction.
1955 #[test]
1956 fn a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact() {
1957 let mut totals = (0usize, 0usize);
1958 for (cq, tx_search) in [("20", "1"), ("40", "0")] {
1959 let args: Vec<String> = [
1960 "--codec=av1",
1961 "--passes=1",
1962 "--end-usage=q",
1963 "--cpu-used=0",
1964 "--threads=1",
1965 "--row-mt=0",
1966 "--lag-in-frames=0",
1967 "--auto-alt-ref=0",
1968 "--kf-max-dist=1000",
1969 "--error-resilient=1",
1970 "--sb-size=64",
1971 // The tool under test, spelled explicitly. CONTEXT, per
1972 // `rect_tx_tool_gate`: aomenc was ALLOWED rect tx sizes.
1973 "--enable-rect-tx=1",
1974 "--enable-rect-partitions=1",
1975 "--enable-ab-partitions=0",
1976 "--enable-1to4-partitions=0",
1977 "--enable-restoration=0",
1978 "--enable-palette=0",
1979 "--enable-cdef=0",
1980 "--enable-cfl-intra=0",
1981 "--enable-intrabc=0",
1982 "--enable-order-hint=0",
1983 "--min-partition-size=8",
1984 "--max-partition-size=32",
1985 ]
1986 .map(String::from)
1987 .into_iter()
1988 .chain([
1989 format!("--cq-level={cq}"),
1990 format!("--enable-tx-size-search={tx_search}"),
1991 ])
1992 // The output tail comes LAST: aomenc stops reading flags at the
1993 // first bare argument, so a sweep flag appended after `-o - -` is
1994 // silently dropped and the arm encodes a different recipe than the
1995 // one this gate claims to have run.
1996 .chain(["--obu", "-o", "-", "-"].map(String::from))
1997 .collect();
1998 let name = format!(
1999 "a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact[cq{cq}/tx{tx_search}]"
2000 );
2001 let (p, t) = rect_tx_tool_gate(&name, false, &args);
2002 totals.0 += p;
2003 totals.1 += t;
2004 }
2005 assert_rect_tx_witness(
2006 "a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact",
2007 totals.0,
2008 totals.1,
2009 );
2010 eprintln!(
2011 "a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact: 2 arms \
2012 pixel-exact; parsed rect partitions {}, rect coefficient TUs {}",
2013 totals.0, totals.1
2014 );
2015 }
2016
2017 /// lane-av1toolgates: `enable-rect-tx` at 10 BITS -- the same recipe, the
2018 /// same parsed-shape witness, at the depth the 8-bit arm says nothing
2019 /// about (the per-depth rule `NEVER_EXERCISED_10BIT` is built on:
2020 /// lane-hbdinter's two 10-bit-only defects survived because every 10-bit
2021 /// gate pinned the filters off). The depth is spelled in THIS body,
2022 /// which is what files the gate in the 10-bit bucket.
2023 #[test]
2024 fn a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact() {
2025 let mut totals = (0usize, 0usize);
2026 for (cq, tx_search) in [("20", "1"), ("40", "0")] {
2027 let args: Vec<String> = [
2028 "--codec=av1",
2029 "--passes=1",
2030 "--end-usage=q",
2031 "--cpu-used=0",
2032 "--threads=1",
2033 "--row-mt=0",
2034 "--lag-in-frames=0",
2035 "--auto-alt-ref=0",
2036 "--kf-max-dist=1000",
2037 "--error-resilient=1",
2038 "--sb-size=64",
2039 "--input-bit-depth=10",
2040 "--bit-depth=10",
2041 // The tool under test, spelled explicitly. CONTEXT, per
2042 // `rect_tx_tool_gate`: aomenc was ALLOWED rect tx sizes.
2043 "--enable-rect-tx=1",
2044 "--enable-rect-partitions=1",
2045 "--enable-ab-partitions=0",
2046 "--enable-1to4-partitions=0",
2047 "--enable-restoration=0",
2048 "--enable-palette=0",
2049 "--enable-cdef=0",
2050 "--enable-cfl-intra=0",
2051 "--enable-intrabc=0",
2052 "--enable-order-hint=0",
2053 "--min-partition-size=8",
2054 "--max-partition-size=32",
2055 ]
2056 .map(String::from)
2057 .into_iter()
2058 .chain([
2059 format!("--cq-level={cq}"),
2060 format!("--enable-tx-size-search={tx_search}"),
2061 ])
2062 // The output tail comes LAST: aomenc stops reading flags at the
2063 // first bare argument, so a sweep flag appended after `-o - -` is
2064 // silently dropped and the arm encodes a different recipe than the
2065 // one this gate claims to have run.
2066 .chain(["--obu", "-o", "-", "-"].map(String::from))
2067 .collect();
2068 let name = format!(
2069 "a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact[cq{cq}/tx{tx_search}]"
2070 );
2071 let (p, t) = rect_tx_tool_gate(&name, true, &args);
2072 totals.0 += p;
2073 totals.1 += t;
2074 }
2075 assert_rect_tx_witness(
2076 "a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact",
2077 totals.0,
2078 totals.1,
2079 );
2080 eprintln!(
2081 "a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact: 2 arms \
2082 pixel-exact; parsed rect partitions {}, rect coefficient TUs {}",
2083 totals.0, totals.1
2084 );
2085 }
2086
2087 /// lane-kf900 r5, the gate for the rect-strip `use_intrabc` read.
2088 ///
2089 /// `av1_allow_intrabc` is a FRAME-level test (`decodemv.c:892`,
2090 /// `read_intra_frame_mode_info`): on an intra frame whose header set
2091 /// `allow_intrabc`, EVERY intra block reads a `use_intrabc` symbol right
2092 /// after `skip`/`cdef`/`delta_q` and before `mbmi->mode`. There is no
2093 /// block-shape term, so rect strips read it exactly like square leaves --
2094 /// `read_intra_mode_rect` never did, and the arithmetic decoder desynced
2095 /// at the FIRST symbol of the first rect block of every
2096 /// `--tune-content=screen` key frame (measured: `testsrc2` 256x192 cq59
2097 /// 8-bit decoded "OK" with all 49152 luma samples wrong).
2098 ///
2099 /// Arm 0 is that recipe at cq50 without palette: its rect strips really do
2100 /// use intrabc. lane-av1-rect14 reconstructs those strips (2:1 and the
2101 /// 16x4/4x16 pair), so the arm must now decode pixel-exact -- and it must
2102 /// still have read the symbol. The named refusal remains only for a
2103 /// 128-superblock strip (`decode_block_128rect`), which this sb64 recipe
2104 /// does not reach.
2105 /// Arm 1 is the same recipe without palette and without tx-size search --
2106 /// it decodes the whole frame, reading the symbol dozens of times.
2107 /// Arm 2 is a screen-tools key frame whose header does NOT set
2108 /// `allow_intrabc` (cq63): it stays pixel-exact, proving the new read is
2109 /// not taken when libaom does not write it.
2110 ///
2111 /// PIXEL RESIDUE (open, lane-kf900 r5): arm 1's frame is entropy-exact
2112 /// against the instrumented aomdec for 429 mode-ladder elements and then
2113 /// diverges inside the DV read of a SQUARE intrabc block at mi(32,44), so
2114 /// its pixels are not compared here. That is a separate defect in
2115 /// `read_intrabc_dv`, not in the read this gate covers.
2116 #[test]
2117 fn a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips() {
2118 const NAME: &str = "a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips";
2119 if !have_ffmpeg() {
2120 eprintln!("SKIP {NAME}: no ffmpeg");
2121 return;
2122 }
2123 if !have_aomenc() {
2124 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2125 return;
2126 }
2127 let (width, height) = (256usize, 192usize);
2128 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
2129 // must_read_use_intrabc)
2130 const TS: &str = "testsrc2=s=256x192:r=25";
2131 const SB: &str = "smptebars=size=256x192:rate=25";
2132 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
2133 // must_read_use_intrabc_on_a_rect_strip)
2134 let arms: [(&str, &str, &[&str], bool, bool); 8] = [
2135 // lane-av1-intrabc (2026-09-20): this arm used to REFUSE here -- the
2136 // 16x8 rect strip it decodes is the first block on main that reaches
2137 // `decode_intrabc_rect`, so the whole arm stopped at a named refusal.
2138 // Reconstruction is ported now, so the arm decodes pixel-exact and
2139 // the `rect_total` assert below keeps it from quietly falling back
2140 // to an ordinary-intra decode of the same block.
2141 (
2142 "testsrc2-cq50-txs0",
2143 TS,
2144 &[
2145 "--cq-level=50",
2146 "--enable-palette=0",
2147 "--enable-tx-size-search=0",
2148 ],
2149 false,
2150 true,
2151 ),
2152 (
2153 "smptebars-cq40-txs0",
2154 SB,
2155 &[
2156 "--cq-level=40",
2157 "--enable-palette=0",
2158 "--enable-tx-size-search=0",
2159 ],
2160 false,
2161 false,
2162 ),
2163 (
2164 "smptebars-cq45-txs0",
2165 SB,
2166 &[
2167 "--cq-level=45",
2168 "--enable-palette=0",
2169 "--enable-tx-size-search=0",
2170 ],
2171 false,
2172 true,
2173 ),
2174 (
2175 "smptebars-cq45-txs1",
2176 SB,
2177 &[
2178 "--cq-level=45",
2179 "--enable-palette=0",
2180 "--enable-tx-size-search=1",
2181 ],
2182 false,
2183 false,
2184 ),
2185 (
2186 "smptebars-cq50-txs1",
2187 SB,
2188 &[
2189 "--cq-level=50",
2190 "--enable-palette=0",
2191 "--enable-tx-size-search=1",
2192 ],
2193 false,
2194 false,
2195 ),
2196 (
2197 "smptebars-cq55-txs0",
2198 SB,
2199 &[
2200 "--cq-level=55",
2201 "--enable-palette=0",
2202 "--enable-tx-size-search=0",
2203 ],
2204 false,
2205 false,
2206 ),
2207 (
2208 "testsrc2-cq63-txs1",
2209 TS,
2210 &[
2211 "--cq-level=63",
2212 "--enable-palette=0",
2213 "--enable-tx-size-search=1",
2214 ],
2215 false,
2216 false,
2217 ),
2218 // lane-kf900 r7: the 8x8-LEAF intrabc arm. Rect and 1:4
2219 // partitions off (so no rect strip refuses first), palette on,
2220 // `TxMode::Largest`: aomenc puts exactly one `use_intrabc` block
2221 // on a `BLOCK_8X8` leaf here, the shape `decode_leaf8` decoded as
2222 // ordinary intra before this round.
2223 (
2224 "testsrc2-cq55-leaf8",
2225 TS,
2226 &[
2227 "--cq-level=55",
2228 "--enable-palette=1",
2229 "--enable-tx-size-search=0",
2230 "--enable-rect-partitions=0",
2231 "--enable-1to4-partitions=0",
2232 ],
2233 false,
2234 false,
2235 ),
2236 ];
2237 let (mut reads_total, mut refused, mut frames_compared) = (0usize, 0u32, 0usize);
2238 let (mut blocks_total, mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) =
2239 (0usize, 0u32, 0u32, 0u32);
2240 let mut leaf8_total = 0usize;
2241 let mut rect_total = 0usize;
2242 for (arm, src, extra, expect_refusal, must_read) in &arms {
2243 let render = || {
2244 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2245 .args([
2246 "-v",
2247 "error",
2248 "-f",
2249 "lavfi",
2250 "-i",
2251 *src,
2252 "-t",
2253 "0.2",
2254 "-pix_fmt",
2255 "yuv420p",
2256 "-strict",
2257 "-1",
2258 "-f",
2259 "yuv4mpegpipe",
2260 "-",
2261 ])
2262 .stdin(Stdio::null())
2263 .stdout(Stdio::piped())
2264 .stderr(Stdio::piped()), None, |c| c.output())
2265 .expect("ffmpeg failed to run");
2266 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
2267 out.stdout
2268 };
2269 let y4m_a = render();
2270 let y4m_b = render();
2271 assert_eq!(
2272 y4m_a, y4m_b,
2273 "{NAME}: {arm} must render byte-identical across two runs"
2274 );
2275 let y4m = y4m_a;
2276 let out = run_with_stdin(
2277 Command::new(aomenc_path())
2278 .args([
2279 "--codec=av1",
2280 "--bit-depth=8",
2281 "--input-bit-depth=8",
2282 "--passes=1",
2283 "--end-usage=q",
2284 "--cpu-used=0",
2285 "--lag-in-frames=0",
2286 "--kf-max-dist=1",
2287 "--limit=1",
2288 "--threads=1",
2289 "--tile-columns=0",
2290 "--enable-rect-partitions=1",
2291 "--enable-1to4-partitions=1",
2292 "--min-partition-size=8",
2293 "--max-partition-size=32",
2294 "--sb-size=64",
2295 // `allow_screen_content_tools` (and with it the frame
2296 // header's `allow_intrabc` bit) comes from here.
2297 "--tune-content=screen",
2298 // Spelled so `gate_coverage` counts the tool as exercised
2299 // rather than defaulted (class `tool-disabled-in-every-gate`).
2300 "--enable-intrabc=1",
2301 ])
2302 // aomenc keeps the LAST occurrence of a repeated flag.
2303 .args(*extra)
2304 .args(["--obu", "-o", "-", "-"]),
2305 &y4m,
2306 );
2307 assert!(
2308 out.status.success(),
2309 "{NAME}: aomenc refused {arm}: {}",
2310 String::from_utf8_lossy(&out.stderr)
2311 );
2312 let stream = out.stdout;
2313 decode::reset_rect_intrabc_reads();
2314 crate::decode::reset_intrabc_hits();
2315 crate::decode::reset_leaf8_intrabc_hits();
2316 crate::decode::reset_intrabc_rect_hits();
2317 let decoded = decode_stream(&stream);
2318 let reads = decode::rect_intrabc_reads();
2319 // Blocks that decoded `use_intrabc == 1` (square path), i.e. that
2320 // read a DV and predicted from the current frame -- distinct from
2321 // `reads`, which counts rect strips that merely READ the flag.
2322 let blocks = crate::decode::intrabc_hits();
2323 reads_total += reads;
2324 blocks_total += blocks;
2325 // The 8x8-leaf shape has its own counter: without it this gate's
2326 // other arms (all rect/32x32 intrabc) would stay green while the
2327 // leaf path decoded an intrabc block as ordinary intra (class
2328 // `gate-blind-to-feature`).
2329 let leaf8 = crate::decode::leaf8_intrabc_hits();
2330 leaf8_total += leaf8;
2331 rect_total += crate::decode::intrabc_rect_hits();
2332 if *arm == "testsrc2-cq55-leaf8" {
2333 assert!(
2334 leaf8 > 0,
2335 "{NAME}: {arm} decoded no intrabc block at an 8x8 leaf -- the arm no longer exercises `decode_leaf8`'s intrabc path"
2336 );
2337 }
2338 if *must_read {
2339 assert!(
2340 reads > 0,
2341 "{NAME}: {arm} read no use_intrabc symbol on a rect strip -- the \
2342 arm no longer exercises the fix (allow_intrabc not set?)"
2343 );
2344 }
2345 match decoded {
2346 Ok(frames) => {
2347 assert!(
2348 !*expect_refusal,
2349 "{NAME}: {arm} decoded a frame whose rect strips use intrabc -- \
2350 reconstruction is not ported, it must refuse by name"
2351 );
2352 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
2353 // The ENCODE's frame count, asserted ABOVE the oracle call:
2354 // the per-arm render (11100) uses `-t 0.2` at TS/SB's
2355 // `rate=25` (10987, 10988) -- 5 input frames -- and the aomenc
2356 // args carry `--limit=1` (11145), so all eight arms code
2357 // exactly 1 frame. The old comment below claimed a count
2358 // assert here would be tautological; that is true of
2359 // `ffmpeg_frames.len() == frames.len()` and false of this:
2360 // `frames.len() == 1` is a fact about the ENCODE, checked
2361 // before `frames.len()` is spent as ffmpeg's frame budget.
2362 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
2363 let ffmpeg_frames =
2364 ffmpeg_decode_sequence(&stream, width, height, frames.len());
2365 // EVERY frame is compared; an arm whose decode never hit an
2366 // intrabc block proves nothing about the DV/prediction path,
2367 // so it is counted OUT OF SCOPE -- but a mismatch there is
2368 // still a failure (`out_of_scope_mismatch == 0`), never a skip.
2369 let mut same = true;
2370 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
2371 let ok = ours.y == theirs.y && ours.u == theirs.u && ours.v == theirs.v;
2372 if !ok {
2373 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
2374 }
2375 same &= ok;
2376 frames_compared += 1;
2377 }
2378 if blocks > 0 {
2379 fired_arms += 1;
2380 assert!(
2381 same,
2382 "{NAME}: {arm} decoded {blocks} intrabc block(s) and did not match ffmpeg"
2383 );
2384 } else {
2385 out_of_scope += 1;
2386 if !same {
2387 out_of_scope_mismatch += 1;
2388 }
2389 }
2390 eprintln!(
2391 "{NAME}: {arm} {} frame(s), {reads} rect use_intrabc reads, \
2392 {blocks} intrabc block(s), exact={same}",
2393 frames.len()
2394 );
2395 }
2396 Err(e) => {
2397 let msg = e.to_string();
2398 assert!(
2399 msg.contains("unsupported"),
2400 "{NAME}: {arm} decode failed: {e}"
2401 );
2402 assert!(
2403 *expect_refusal,
2404 "{NAME}: {arm} was expected to decode, it refused: {e}"
2405 );
2406 assert!(
2407 msg.contains("intra block copy") || msg.contains("intrabc"),
2408 "{NAME}: {arm} refused for an unrelated reason: {e}"
2409 );
2410 eprintln!("{NAME}: {arm} REFUSED (expected): {e}");
2411 refused += 1;
2412 }
2413 }
2414 }
2415 eprintln!(
2416 "{NAME}: {reads_total} rect-strip use_intrabc symbol(s) read, \
2417 {blocks_total} intrabc block(s) decoded across {fired_arms} arm(s), \
2418 {refused} refused by name, {frames_compared} frames compared, \
2419 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched)"
2420 );
2421 eprintln!(
2422 "{NAME}: {rect_total} intrabc block(s) on a HORZ/VERT rect strip (decode_intrabc_rect)"
2423 );
2424 assert!(
2425 reads_total > 0,
2426 "{NAME}: gate is vacuous -- no arm read the symbol"
2427 );
2428 assert!(
2429 leaf8_total > 0,
2430 "{NAME}: no arm decoded an intrabc block at an 8x8 leaf -- lane-kf900 r7's fix is untested"
2431 );
2432 assert!(
2433 blocks_total > 0 && fired_arms > 0,
2434 "{NAME}: gate is vacuous -- no compared arm actually decoded an intrabc block"
2435 );
2436 assert!(
2437 rect_total > 0,
2438 "{NAME}: no arm decoded an intrabc block on a HORZ/VERT rect strip -- \
2439 `decode_intrabc_rect` is untested"
2440 );
2441 // lane-av1-intrabc: this used to be exactly one -- the 2:1 rect strips
2442 // now reconstruct. The 1:4 pair strips (`decode_rect4_16_strip` et al.)
2443 // still refuse by name, but no arm HERE reaches that shape; it stays
2444 // pinned by `refusal_inventory`'s own gate.
2445 assert_eq!(refused, 0, "{NAME}: an arm still refuses by name");
2446 assert!(
2447 frames_compared > 0,
2448 "{NAME}: no frame was compared pixel-exact"
2449 );
2450 assert_eq!(
2451 out_of_scope_mismatch, 0,
2452 "{NAME}: an arm without an intrabc block still mismatched ffmpeg"
2453 );
2454 }
2455
2456 /// lane-av1-rect14: the 16x4/4x16 intrabc pair. libaom codes the pair's
2457 /// chroma on the odd-mi strip only (`is_chroma_reference`,
2458 /// av1_common_int.h:1454). The witness is the report recipe: testsrc2
2459 /// 640x480 cq60 palette, txs off, which places a 16x4 intrabc strip at
2460 /// mi(76,108). Pre-fix this refused by name. VERT_4 was not produced by
2461 /// any fully-decoded recipe tried here (the allintra stream codes four
2462 /// `PARTITION_VERT_4` at bsize 6 and then stops on the unrelated var-tx
2463 /// mixed-leaf refusal); the VERT arm is the same body with the axes
2464 /// swapped.
2465 #[test]
2466 fn a_16x4_intrabc_pair_strip_decodes_pixel_exact() {
2467 const NAME: &str = "a_16x4_intrabc_pair_strip_decodes_pixel_exact";
2468 if !have_ffmpeg() || !have_aomenc() {
2469 eprintln!("SKIP {NAME}: ffmpeg/aomenc missing");
2470 return;
2471 }
2472 let (width, height) = (640usize, 480usize);
2473 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2474 .args([
2475 "-v",
2476 "error",
2477 "-f",
2478 "lavfi",
2479 "-i",
2480 "testsrc2=s=640x480:r=25",
2481 "-frames:v",
2482 "1",
2483 "-pix_fmt",
2484 "yuv420p",
2485 "-strict",
2486 "-1",
2487 "-f",
2488 "yuv4mpegpipe",
2489 "-",
2490 ]), None, |c| c.output())
2491 .expect("ffmpeg")
2492 .stdout;
2493 let out = run_with_stdin(
2494 Command::new(aomenc_path()).args([
2495 "--codec=av1",
2496 "--bit-depth=8",
2497 "--input-bit-depth=8",
2498 "--passes=1",
2499 "--end-usage=q",
2500 "--cpu-used=0",
2501 "--lag-in-frames=0",
2502 "--kf-max-dist=1",
2503 "--limit=1",
2504 "--threads=1",
2505 "--tile-columns=0",
2506 "--enable-rect-partitions=1",
2507 "--enable-1to4-partitions=1",
2508 "--min-partition-size=4",
2509 "--max-partition-size=64",
2510 "--sb-size=64",
2511 "--tune-content=screen",
2512 "--enable-intrabc=1",
2513 "--cq-level=60",
2514 "--enable-palette=1",
2515 "--enable-tx-size-search=0",
2516 "--obu",
2517 "-o",
2518 "-",
2519 "-",
2520 ]),
2521 &y4m,
2522 );
2523 assert!(out.status.success(), "{NAME}: aomenc failed");
2524 crate::decode::reset_rect4_16_pair_hits();
2525 let frames = decode_stream(&out.stdout).unwrap_or_else(|e| panic!("{NAME}: {e}"));
2526 assert!(
2527 crate::decode::rect4_16_intrabc_hits() > 0,
2528 "{NAME}: no 16x4/4x16 intrabc strip -- the pair body was not reached"
2529 );
2530 // The ENCODE's frame count, asserted ABOVE the oracle call: the y4m is
2531 // rendered with `-frames:v 1` (11333) -- a single frame of
2532 // `testsrc2=s=640x480:r=25` -- and aomenc runs with
2533 // `--limit=1 --kf-max-dist=1` (11355, 11356), so the stream codes
2534 // exactly 1 key frame. Below the call this assert could not fire
2535 // first: `ffmpeg_decode_sequence` was already handed `frames.len()`.
2536 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame");
2537 let refs = ffmpeg_decode_sequence(&out.stdout, width, height, frames.len());
2538 assert_eq!(frames[0].y, refs[0].y, "{NAME}: luma");
2539 assert_eq!(frames[0].u, refs[0].u, "{NAME}: u");
2540 assert_eq!(frames[0].v, refs[0].v, "{NAME}: v");
2541 }
2542
2543 /// lane-av1-rect14: lossless 16x4/4x16 chroma is two TX_4X4s, not one
2544 /// TX_8X4. The measured site is luma col 108 of a 320x240 sb128 lossless
2545 /// key frame (lanes/av1lossless128.report.md §6). Rows 0-127 of that
2546 /// frame -- the first superblock row, which contains the site -- must
2547 /// match ffmpeg. A later mismatch is the pre-existing 64x64 square
2548 /// lossless residue (base fails at byte 108; this lane's first remaining
2549 /// mismatch is row 128). The gate fails if that residue moves back into
2550 /// the repaired region.
2551 #[test]
2552 fn a_lossless_16x4_chroma_pair_repairs_the_measured_site() {
2553 const NAME: &str = "a_lossless_16x4_chroma_pair_repairs_the_measured_site";
2554 if !have_ffmpeg() || !have_aomenc() {
2555 eprintln!("SKIP {NAME}: ffmpeg/aomenc missing");
2556 return;
2557 }
2558 let (width, height) = (320usize, 240usize);
2559 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2560 .args([
2561 "-v",
2562 "error",
2563 "-f",
2564 "lavfi",
2565 "-i",
2566 "testsrc2=s=320x240:r=25",
2567 "-frames:v",
2568 "1",
2569 "-pix_fmt",
2570 "yuv420p",
2571 "-strict",
2572 "-1",
2573 "-f",
2574 "yuv4mpegpipe",
2575 "-",
2576 ]), None, |c| c.output())
2577 .expect("ffmpeg")
2578 .stdout;
2579 let out = run_with_stdin(
2580 Command::new(aomenc_path()).args([
2581 "--codec=av1",
2582 "--cpu-used=0",
2583 "--lossless=1",
2584 "--sb-size=128",
2585 "--lag-in-frames=0",
2586 "--kf-max-dist=1",
2587 "--limit=1",
2588 "--threads=1",
2589 "--passes=1",
2590 "--enable-1to4-partitions=1",
2591 "--min-partition-size=4",
2592 "--enable-rect-partitions=1",
2593 "--obu",
2594 "-o",
2595 "-",
2596 "-",
2597 ]),
2598 &y4m,
2599 );
2600 assert!(out.status.success(), "{NAME}: aomenc failed");
2601 crate::decode::reset_rect4_16_pair_hits();
2602 let frames = decode_stream(&out.stdout).unwrap_or_else(|e| panic!("{NAME}: {e}"));
2603 assert!(
2604 crate::decode::rect4_16_lossless_chroma_hits() > 0,
2605 "{NAME}: no lossless 16x4/4x16 chroma pair -- the walk was not reached"
2606 );
2607 // The ENCODE's frame count: the y4m is rendered with `-frames:v 1`
2608 // (11414) -- a single frame of `testsrc2=s=320x240:r=25` -- and aomenc
2609 // runs with `--limit=1 --kf-max-dist=1` (11434, 11435), so the stream
2610 // codes exactly 1 lossless key frame. Asserted ABOVE the oracle call:
2611 // this gate then indexes `frames[0]`/`refs[0]`, which a zero-frame
2612 // decode would panic on rather than report.
2613 assert_eq!(frames.len(), 1, "{NAME}: expected one lossless key frame");
2614 let refs = ffmpeg_decode_sequence(&out.stdout, width, height, frames.len());
2615 let repaired = 128 * width;
2616 assert_eq!(
2617 &frames[0].y[..repaired],
2618 &refs[0].y[..repaired],
2619 "{NAME}: luma rows 0-127 (the measured col-108 site) diverged"
2620 );
2621 let chroma_rows = 64 * (width / 2);
2622 assert_eq!(
2623 &frames[0].u[..chroma_rows],
2624 &refs[0].u[..chroma_rows],
2625 "{NAME}: u"
2626 );
2627 assert_eq!(
2628 &frames[0].v[..chroma_rows],
2629 &refs[0].v[..chroma_rows],
2630 "{NAME}: v"
2631 );
2632 // The col-108 byte specifically, so a shift of the old site still fails
2633 // even if some other prefix sample happens to match.
2634 assert_eq!(
2635 frames[0].y[108], refs[0].y[108],
2636 "{NAME}: measured byte 108"
2637 );
2638 }
2639
2640 /// lane-av1tilerows: the 4:4:4 LOSSLESS rect-pair chroma REACH fix --
2641 /// the defect lane `av1formatsweep` filed as **H4** ("4:4:4 lossless +
2642 /// `--tile-rows=1`, frame 3 onward the whole plane goes flat") and this
2643 /// lane's red-before actually measured.
2644 ///
2645 /// **The H4 label was wrong; the defect it points at is real.** Two
2646 /// corrections to the sweep's framing, both measured:
2647 ///
2648 /// 1. `--tile-rows=1` at 256x128 is a **no-op**. aomenc's default
2649 /// superblock is 128px, so 256x128 is 2x1 superblocks -- there is no
2650 /// second superblock ROW to split, and aomenc silently emits a
2651 /// stream BYTE-IDENTICAL to `--tile-columns=0 --tile-rows=0`
2652 /// (verified: both 64828 bytes, `cmp` equal). The sweep's "tiled"
2653 /// fixture contained no tile rows at all. Tile rows at 4:4:4
2654 /// lossless are exact here: measured pixel-exact at 1, 2 and 4 tile
2655 /// rows, both axes (2x2), at 256x128 / 256x256 / 128x256 / 512x128,
2656 /// on a recipe that is exact without tiles.
2657 /// 2. The "frames 0-2 byte-exact, frame 3 onward flat, Y(0,0) 128 vs
2658 /// 81" signature is a **harness frame-order mismatch, not a decode
2659 /// defect**: with altref on, aomdec's `EC_AV1_FINAL_DUMP` writes 7
2660 /// frames in DECODE order while `ffmpeg -f rawvideo` writes 6 in
2661 /// DISPLAY order. Indexing one against the other makes frame 1 differ
2662 /// by 29109 samples (30%) -- and aomdec-vs-ffmpeg ALONE reproduces
2663 /// the identical 29109/24412/20046/19906 counts with no edith
2664 /// decoder in the loop. Our decode-order output is byte-exact against
2665 /// the oracle on all 7.
2666 ///
2667 /// The defect IS real, is in the class the sweep named (a hardcoded
2668 /// 4:2:0-shaped walk at 4:4:4), and is tile-INDEPENDENT: it reproduces
2669 /// on the zero-tile stream. `decode.rs`'s lossless 16x4/4x16 chroma-pair
2670 /// walk passed `tu_reach` a hardcoded 4:2:0 luma footprint
2671 /// (`ox * 2, oy * 2, 8`) for every chroma transform unit. At 4:4:4 a
2672 /// 4x4 chroma unit is 4x4 LUMA, so the footprint is doubled:
2673 /// `Reach::of_tu`'s `col_off + tx_w < bw` test then answers against a
2674 /// block twice its real width and every unit past the midpoint wrongly
2675 /// reports `above_right = false`, so a directional chroma strip predicts
2676 /// from a neighbour libaom never reads.
2677 ///
2678 /// **Measured site (red-before, `git stash` of the fix, same tree):**
2679 /// `testsrc2 256x128 yuv444p`, aomenc `--profile=1 --lossless=1
2680 /// --passes=1 --end-usage=q --threads=1 --row-mt=0 --limit=6
2681 /// --cpu-used=2 --lag-in-frames=0 --kf-max-dist=100` (pinned below).
2682 /// Frame 0 (the KEY frame) and all five inter frames: **63 samples wrong
2683 /// per frame, U 29 + V 34, first at U(110,26) / V(108,26), deltas -10..+13**,
2684 /// region x108..125 y26..29 -- a 16x4 chroma strip at 4:4:4, whose rows
2685 /// are NOT block-aligned (y26), which is the signature of a REACH
2686 /// answer and not of a coefficient or transform error.
2687 ///
2688 /// **Entropy is bit-identical**: `EC_SYMR` on both sides, 351109 reads
2689 /// compared on `(value, range, symbol, post_rng)` with the CDF-row
2690 /// convention reconciled (`32768 - ours_cdf0 == oracle_cdf0`): **zero
2691 /// divergence**. So this is reconstruction arithmetic, not an entropy
2692 /// fork -- which is what separates it from the H1 rect-partition fork
2693 /// (that one forks `EC_SYMR` at `decodetxb.c:158` `txb_skip`).
2694 ///
2695 /// A second, far worse instance of the SAME defect is the 512x128
2696 /// `--cpu-used=2` stream (18779 wrong in the key frame, growing to
2697 /// 130708 by frame 5) -- but that stream ALSO forks entropy
2698 /// (459866 oracle reads vs 369136 ours), so it is not claimed here;
2699 /// it belongs to the H1 rect-partition lane. The pinned fixture below is
2700 /// the entropy-clean, fully-repaired instance.
2701 ///
2702 /// Non-vacuity: the fixture bytes are pinned (length + FNV-1a, like the
2703 /// other `ll444_*` pins), the header must really be `ss (0,0)` at 8-bit
2704 /// with `lossless == 1` (asserted from the parsed sequence header, not
2705 /// assumed), the tiled sweep gates' counter
2706 /// `decode::rect4_16_lossless_chroma_hits()` must FIRE (measured 80
2707 /// units on this fixture -- a 4:2:0 stream of the same content leaves it
2708 /// at 0, because a 4:2:0 lossless 16x4 pair is an 8x4 chroma block and
2709 /// takes the pair-merge, not this walk), and every frame must be
2710 /// byte-exact through BOTH the oracle `aomdec --rawvideo` (decode order,
2711 /// the 7-frame compare that the hidden-frame gates use) and ffmpeg
2712 /// (display order, 4:4:4 full-resolution chroma).
2713 #[test]
2714 fn a_lossless_444_rect16x4_chroma_reach_is_ss_aware() {
2715 const NAME: &str = "a_lossless_444_rect16x4_chroma_reach_is_ss_aware";
2716 const FIXTURE_LEN: usize = 77918;
2717 const FIXTURE_FNV: u64 = 0xe2a2_90ac_f249_4bf7;
2718 const W: usize = 256;
2719 const H: usize = 128;
2720 const FRAMES: usize = 6;
2721 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2722 .join("fixtures/ll444_rect16x4_chroma_reach.obu");
2723 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
2724 panic!(
2725 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
2726 which is a failure, not a skip",
2727 obu.display()
2728 )
2729 });
2730 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
2731 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
2732
2733 // The header must really be the shape the fix is about: 4:4:4
2734 // (ss 0/0) at 8-bit. A fixture that silently became 4:2:0 would
2735 // take the pair-merge and make every arm below vacuous.
2736 {
2737 let mut p = Av1Parser::new();
2738 let mut pos = 0usize;
2739 let mut seq = None;
2740 while pos < stream.len() {
2741 let Ok(obu) = p.parse_obu(&stream[pos..]) else {
2742 break;
2743 };
2744 pos += obu.total_size;
2745 if matches!(obu.kind, ObuKind::SequenceHeader(_)) {
2746 seq = p.sequence_header();
2747 break;
2748 }
2749 }
2750 let seq = seq.unwrap_or_else(|| panic!("{NAME}: no sequence header parsed"));
2751 assert_eq!(
2752 (
2753 seq.color_config.subsampling_x,
2754 seq.color_config.subsampling_y
2755 ),
2756 (0, 0),
2757 "{NAME}: fixture is not 4:4:4 (ss {}x{})",
2758 seq.color_config.subsampling_x,
2759 seq.color_config.subsampling_y
2760 );
2761 assert_eq!(
2762 seq.color_config.bit_depth, 8,
2763 "{NAME}: fixture bit depth moved"
2764 );
2765 assert_eq!(seq.max_frame_width, W as u32, "{NAME}: fixture width moved");
2766 assert_eq!(
2767 seq.max_frame_height, H as u32,
2768 "{NAME}: fixture height moved"
2769 );
2770 }
2771
2772 let _guard = lock_gate_counters();
2773 crate::decode::reset_rect4_16_pair_hits();
2774 let frames = decode_stream(&stream)
2775 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
2776 let hits = crate::decode::rect4_16_lossless_chroma_hits();
2777 assert!(
2778 hits > 0,
2779 "{NAME}: gate is vacuous -- no lossless 16x4/4x16 chroma-pair unit was \
2780 walked (rect4_16_lossless_chroma_hits = {hits}), so the repaired \
2781 `tu_reach` call site never ran"
2782 );
2783 assert_eq!(frames.len(), FRAMES, "{NAME}: shown frame count");
2784 for f in &frames {
2785 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
2786 }
2787
2788 // The oracle, DECODE order, every frame including hidden alt-ref
2789 // frames. This is the arm that proves the repair against aomdec's
2790 // own reconstruction, not just ffmpeg's.
2791 if aomdec_available(NAME) {
2792 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2793 assert!(
2794 decoded >= FRAMES,
2795 "{NAME}: oracle decoded {decoded} frames, expected at least {FRAMES}"
2796 );
2797 let _ = hidden;
2798 }
2799
2800 // ffmpeg's decoder: DISPLAY order, full-resolution chroma.
2801 if have_ffmpeg() {
2802 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
2803 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() {
2804 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
2805 .iter()
2806 .enumerate()
2807 {
2808 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
2809 assert_eq!(
2810 bad, 0,
2811 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
2812 );
2813 }
2814 }
2815 } else {
2816 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
2817 }
2818 }
2819
2820 /// lane-av1-intrabc r4: the reviewer's unblock witness for the rect-strip
2821 /// reconstruction -- a CODED `use_intrabc` block (so its residual reader
2822 /// runs, not just the prediction copy) on a 2:1 strip in BOTH
2823 /// orientations, plus the `TX_MODE_SELECT` (var-tx) shape, every arm
2824 /// byte-exact against ffmpeg.
2825 ///
2826 /// The orientation counters (`intrabc_rect_coded_hits`) are the
2827 /// non-vacuity instrument: [`intrabc_rect_hits`] counts neither the skip
2828 /// flag nor the orientation, so an arm that silently became an all-skip
2829 /// stream (or a stream with only one orientation) would keep the old gate
2830 /// green while the coded residual path went untested
2831 /// (class `gate-blind-to-feature`).
2832 ///
2833 /// # The VERT arm is also the DV-PREDICTOR regression witness
2834 ///
2835 /// The 512x384 arm is the stream that exposed r4's defect: 528 of 294912
2836 /// luma samples were wrong, all inside one `skip == 1` intrabc copy at
2837 /// `mi(84,104)`. Its coded diff was identical to aomdec's and the post-read
2838 /// range matched exactly (`rng=33207` both), so nothing was misread -- the
2839 /// DV PREDICTOR differed. libaom picks `nearestmv` (`-520`) from the
2840 /// `INTRA_FRAME` MV stack; this decoder picked `-512`, one stack entry
2841 /// lower, because the scan that builds that stack walked further than
2842 /// libaom's. The scans step by the candidate BLOCK's own width
2843 /// (`mi_size_wide[bsize]`) over `xd->mi[]`, which holds an entry for every
2844 /// coded block; this decoder's MV grid held only the intrabc blocks, so a
2845 /// non-intrabc neighbour read as uncovered and the scan advanced that cell
2846 /// by one instead of by its real width. See `MiGrid::cover` for the
2847 /// measured walk. A stream that decodes the DV predictor from the wrong
2848 /// stack entry cannot pass this arm's pixel comparison.
2849 #[test]
2850 fn a_coded_rect_intrabc_block_reconstructs_in_both_orientations() {
2851 const NAME: &str = "a_coded_rect_intrabc_block_reconstructs_in_both_orientations";
2852 if !have_ffmpeg() {
2853 eprintln!("SKIP {NAME}: no ffmpeg");
2854 return;
2855 }
2856 if !have_aomenc() {
2857 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2858 return;
2859 }
2860 const TS256: &str = "testsrc2=s=256x192:r=25";
2861 const TS512: &str = "testsrc2=s=512x384:r=25";
2862 // (arm, source, width, height, per-arm overrides, the coded orientation
2863 // this arm must exercise, and whether the frame must code
2864 // `TX_MODE_SELECT` with `allow_intrabc` still set)
2865 let arms: [(&str, &str, usize, usize, &[&str], u8, bool); 3] = [
2866 // HORZ (16x8) coded strip -- the shape the in-gate witness above
2867 // already reconstructs, pinned here with its own orientation counter.
2868 (
2869 "horz-coded-256-cq45-pal0-txs0",
2870 TS256,
2871 256,
2872 192,
2873 &[
2874 "--cq-level=45",
2875 "--enable-palette=0",
2876 "--enable-tx-size-search=0",
2877 ],
2878 0,
2879 false,
2880 ),
2881 // VERT (8x16) coded strip AND the DV-predictor regression stream.
2882 (
2883 "vert-coded-512-cq45-pal1-txs0",
2884 TS512,
2885 512,
2886 384,
2887 &[
2888 "--cq-level=45",
2889 "--enable-palette=1",
2890 "--enable-tx-size-search=0",
2891 ],
2892 1,
2893 false,
2894 ),
2895 // The `TX_MODE_SELECT` (stream A) shape: `--enable-tx-size-search=1`
2896 // makes the frame code `tx_mode == Select`, so the intrabc block's
2897 // transform size comes off the INTER var-tx tree.
2898 (
2899 "txmode-select-256-cq45-pal0-txs1",
2900 TS256,
2901 256,
2902 192,
2903 &[
2904 "--cq-level=45",
2905 "--enable-palette=0",
2906 "--enable-tx-size-search=1",
2907 ],
2908 0,
2909 true,
2910 ),
2911 ];
2912 let mut coded_total = [0usize; 2];
2913 let mut frames_compared = 0usize;
2914 for (arm, src, width, height, extra, want_orient, want_select) in &arms {
2915 let render = || {
2916 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2917 .args([
2918 "-v",
2919 "error",
2920 "-f",
2921 "lavfi",
2922 "-i",
2923 *src,
2924 "-t",
2925 "0.2",
2926 "-pix_fmt",
2927 "yuv420p",
2928 "-strict",
2929 "-1",
2930 "-f",
2931 "yuv4mpegpipe",
2932 "-",
2933 ])
2934 .stdin(Stdio::null())
2935 .stdout(Stdio::piped())
2936 .stderr(Stdio::piped()), None, |c| c.output())
2937 .expect("ffmpeg failed to run");
2938 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
2939 out.stdout
2940 };
2941 let y4m = render();
2942 let out = run_with_stdin(
2943 Command::new(aomenc_path())
2944 .args([
2945 "--codec=av1",
2946 "--bit-depth=8",
2947 "--input-bit-depth=8",
2948 "--passes=1",
2949 "--end-usage=q",
2950 "--cpu-used=0",
2951 "--lag-in-frames=0",
2952 "--kf-max-dist=1",
2953 "--limit=1",
2954 "--threads=1",
2955 "--tile-columns=0",
2956 "--enable-rect-partitions=1",
2957 "--enable-1to4-partitions=1",
2958 "--min-partition-size=8",
2959 "--max-partition-size=32",
2960 "--sb-size=64",
2961 "--tune-content=screen",
2962 "--enable-intrabc=1",
2963 ])
2964 // aomenc keeps the LAST occurrence of a repeated flag.
2965 .args(*extra)
2966 .args(["--obu", "-o", "-", "-"]),
2967 &y4m,
2968 );
2969 assert!(
2970 out.status.success(),
2971 "{NAME}: aomenc refused {arm}: {}",
2972 String::from_utf8_lossy(&out.stderr)
2973 );
2974 let stream = out.stdout;
2975 if *want_select {
2976 let (select, premise) = tx_select_and_intrabc_frames(&stream);
2977 assert!(
2978 select > 0 && premise > 0,
2979 "{NAME}: {arm} no longer codes a frame with both tx_mode == Select and \
2980 allow_intrabc (select={select} premise={premise}), so the TX_MODE_SELECT \
2981 shape is untested here"
2982 );
2983 }
2984 crate::decode::reset_intrabc_rect_hits();
2985 let frames =
2986 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {arm} refused: {e}"));
2987 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
2988 let coded = crate::decode::intrabc_rect_coded_hits();
2989 coded_total[0] += coded[0];
2990 coded_total[1] += coded[1];
2991 assert!(
2992 coded[*want_orient as usize] > 0,
2993 "{NAME}: {arm} reconstructed no CODED ({}) rect intrabc block -- the residual \
2994 reader for this orientation is untested (coded horz/vert = {coded:?})",
2995 if *want_orient == 0 { "HORZ" } else { "VERT" }
2996 );
2997 // The ENCODE's frame count: the per-arm render (11756) uses `-t 0.2`
2998 // at TS256/TS512's `rate=25` (11700, 11701) -- 5 input frames -- and
2999 // the aomenc args carry `--limit=1` (11797), so all three arms code
3000 // exactly 1 frame. Asserted ABOVE the oracle call.
3001 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
3002 let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len());
3003 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
3004 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
3005 assert!(
3006 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
3007 "{NAME}: {arm} frame {i} does not match ffmpeg"
3008 );
3009 frames_compared += 1;
3010 }
3011 eprintln!(
3012 "{NAME}: {arm} {} frame(s) exact, coded rect intrabc horz={} vert={}",
3013 frames.len(),
3014 coded[0],
3015 coded[1]
3016 );
3017 }
3018 assert!(
3019 coded_total[0] > 0 && coded_total[1] > 0,
3020 "{NAME}: gate is vacuous -- coded rect intrabc blocks seen: horz={} vert={}",
3021 coded_total[0],
3022 coded_total[1]
3023 );
3024 assert!(
3025 frames_compared > 0,
3026 "{NAME}: no frame was compared pixel-exact"
3027 );
3028
3029 // lane-av1-intrabc r5: the SKIPPED VERT 2:1 strip -- the arm the
3030 // reviewer's sweep panicked on (a skipped 8x32 strip passed a
3031 // `bw * bh`-sized ZERO_RESIDUAL slice at stride `side`, and
3032 // `reconstruct_mc_rect` indexed `row * side + w` past its end).
3033 // Skip-heavy recipes (low cq, palette off AND on), each decoded
3034 // byte-exact vs ffmpeg on the inline reconstruction path (the arm
3035 // that panicked pre-fix). The skipped-orientation
3036 // counter is asserted per arm (`gate-blind-to-feature`): a recipe
3037 // that stops producing a skipped VERT strip fails instead of passing
3038 // vacuously.
3039 let _par_lock = lock_gate_counters();
3040 let skip_arms: [(&str, &str, usize, usize, &[&str]); 2] = [
3041 (
3042 "vert-skip-512-cq30-pal0-txs0",
3043 TS512,
3044 512,
3045 384,
3046 &[
3047 "--cq-level=30",
3048 "--enable-palette=0",
3049 "--enable-tx-size-search=0",
3050 ],
3051 ),
3052 (
3053 "vert-skip-512-cq30-pal1-txs0",
3054 TS512,
3055 512,
3056 384,
3057 &[
3058 "--cq-level=30",
3059 "--enable-palette=1",
3060 "--enable-tx-size-search=0",
3061 ],
3062 ),
3063 ];
3064 for (arm, src, width, height, extra) in &skip_arms {
3065 let y4m = {
3066 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3067 .args([
3068 "-v",
3069 "error",
3070 "-f",
3071 "lavfi",
3072 "-i",
3073 *src,
3074 "-t",
3075 "0.2",
3076 "-pix_fmt",
3077 "yuv420p",
3078 "-strict",
3079 "-1",
3080 "-f",
3081 "yuv4mpegpipe",
3082 "-",
3083 ])
3084 .stdin(Stdio::null())
3085 .stdout(Stdio::piped())
3086 .stderr(Stdio::piped()), None, |c| c.output())
3087 .expect("ffmpeg failed to run");
3088 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
3089 out.stdout
3090 };
3091 let out = run_with_stdin(
3092 Command::new(aomenc_path())
3093 .args([
3094 "--codec=av1",
3095 "--bit-depth=8",
3096 "--input-bit-depth=8",
3097 "--passes=1",
3098 "--end-usage=q",
3099 "--cpu-used=0",
3100 "--lag-in-frames=0",
3101 "--kf-max-dist=1",
3102 "--limit=1",
3103 "--threads=1",
3104 "--tile-columns=0",
3105 "--enable-rect-partitions=1",
3106 "--enable-1to4-partitions=1",
3107 "--min-partition-size=8",
3108 "--max-partition-size=32",
3109 "--sb-size=64",
3110 "--tune-content=screen",
3111 "--enable-intrabc=1",
3112 ])
3113 // aomenc keeps the LAST occurrence of a repeated flag.
3114 .args(*extra)
3115 .args(["--obu", "-o", "-", "-"]),
3116 &y4m,
3117 );
3118 assert!(
3119 out.status.success(),
3120 "{NAME}: aomenc refused {arm}: {}",
3121 String::from_utf8_lossy(&out.stderr)
3122 );
3123 let stream = out.stdout;
3124 // The inline reconstruction path (the arm that panicked
3125 // pre-fix) must match ffmpeg.
3126 let mut skipped_vert = 0usize;
3127 for threads in [1usize] {
3128 crate::decode::reset_intrabc_rect_hits();
3129 let frames = match decode_stream(&stream) {
3130 Ok(frames) => frames,
3131 Err(e) => {
3132 panic!("{NAME}: {arm} refused at {threads} recon thread(s): {e}")
3133 }
3134 };
3135 let skipped = crate::decode::intrabc_rect_skipped_hits();
3136 assert!(
3137 !frames.is_empty(),
3138 "{NAME}: {arm} decoded no frame at {threads} recon thread(s)"
3139 );
3140 // The ENCODE's frame count: the skip_arms encode (11904) renders
3141 // TS512 with `-t 0.2` at `rate=25` (11907) and its aomenc runs
3142 // with `--limit=1` (11945), so the stream holds 1 coded frame --
3143 // and this loop re-decodes those SAME bytes at each `threads`
3144 // value, so the count is arm-invariant. Asserted ABOVE the call.
3145 assert_eq!(
3146 frames.len(),
3147 1,
3148 "{NAME}: {arm} key frame at {threads} recon thread(s)"
3149 );
3150 let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len());
3151 assert_eq!(
3152 frames.len(),
3153 theirs.len(),
3154 "{NAME}: {arm} frame count at {threads} recon thread(s)"
3155 );
3156 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
3157 assert!(
3158 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
3159 "{NAME}: {arm} frame {i} does not match ffmpeg at {threads} recon thread(s)"
3160 );
3161 }
3162 skipped_vert = skipped[1];
3163 eprintln!(
3164 "{NAME}: {arm} {} frame(s) exact at {threads} recon thread(s), skipped rect intrabc horz={} vert={}",
3165 frames.len(),
3166 skipped[0],
3167 skipped[1]
3168 );
3169 }
3170 assert!(
3171 skipped_vert > 0,
3172 "{NAME}: {arm} reconstructed no SKIPPED VERT rect intrabc strip -- the r5 stride arm is untested"
3173 );
3174 }
3175 }
3176
3177 /// lane-t900 r34, the WITNESS (r33 pinned it ignored) that intrabc under
3178 /// a 128x128 superblock decodes pixel-exact.
3179 ///
3180 /// All four arms of r33's census -- `--sb-size=128 --tune-content=screen
3181 /// --enable-intrabc=1` over both `--enable-tx-size-search` settings and
3182 /// two quantisers, on a 2x2 tiling of a 128x96 bar pattern (256x192,
3183 /// 8-bit, `--cpu-used=0 --min-partition-size=8 --max-partition-size=32`,
3184 /// rect and 1:4 off) -- code `use_128x128_superblock && allow_intrabc`.
3185 ///
3186 /// The lift was one constant: `av1_find_ref_dv` (mvref_common.c) takes
3187 /// `mib_size`, the SEQUENCE's superblock size in mi units, so the
3188 /// fallback DV is one 128-px superblock up (or 128 + `INTRABC_DELAY_PIXELS`
3189 /// left on the tile's first superblock row) under a 128 superblock, where
3190 /// [`crate::decode::read_intrabc_dv`] hardcoded 64. Every arm is compared
3191 /// to ffmpeg and the decoded-intrabc-block counter is asserted non-zero,
3192 /// so a stream that stopped using intrabc could not make this vacuous.
3193 ///
3194 /// lane-av1-intrabc (2026-09-17): the four recipes now run at 10 bits as
3195 /// well, and both depths must SHOW the engagement -- `blocks_at_depth`
3196 /// below hard-asserts a decoded intrabc block per depth. The 10-bit
3197 /// coverage the guard records for `enable-intrabc` used to rest on a gate
3198 /// that only SPELLED `--enable-intrabc=1`: measured (same round), all five
3199 /// arms of `a_real_aomenc_rect_strip_palette_decodes_pixel_exact` decode
3200 /// ZERO intrabc blocks at BOTH depths, so the spelling proved nothing and
3201 /// the entry was one encoder-RD change away from being vacuous again
3202 /// (class `tool-disabled-in-every-gate`). An arm here that stops engaging
3203 /// intrabc now fails this gate instead of retiring the entry unproven.
3204 #[test]
3205 fn an_sb128_screen_stream_with_intrabc_decodes_pixel_exact() {
3206 const NAME: &str = "an_sb128_screen_stream_with_intrabc_decodes_pixel_exact";
3207 if !have_ffmpeg() || !have_aomenc() {
3208 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
3209 return;
3210 }
3211 let (width, height) = (256usize, 192usize);
3212 let _guard = lock_gate_counters();
3213 let (mut blocks_total, mut frames_compared) = (0usize, 0u32);
3214 let mut blocks_at_depth = [0usize; 2];
3215 for depth in [8usize, 10] {
3216 for txs in ["0", "1"] {
3217 for cq in ["30", "45"] {
3218 let arm = format!("sb128 {depth}-bit txs={txs} cq={cq}");
3219 let stream = screen_intrabc_stream_at_depth(
3220 "smptebars=size=128x96:rate=25",
3221 cq,
3222 txs,
3223 true,
3224 true,
3225 depth,
3226 &["--sb-size=128"],
3227 );
3228 let (sb128, intrabc_frames) = sb128_and_intrabc_frames(&stream);
3229 assert!(
3230 sb128 && intrabc_frames > 0,
3231 "{NAME}: {arm} no longer codes sb128 + allow_intrabc"
3232 );
3233 crate::decode::reset_intrabc_hits();
3234 let frames =
3235 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {arm}: {e}"));
3236 let blocks = crate::decode::intrabc_hits();
3237 blocks_total += blocks;
3238 blocks_at_depth[usize::from(depth == 10)] += blocks;
3239 // The ENCODE's frame count:
3240 // `screen_intrabc_stream_at_depth` (12203) renders
3241 // `smptebars=size=128x96:rate=25` with `-t 0.2` and
3242 // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame
3243 // out at 256x192 -- and its aomenc runs with `--limit=1`
3244 // (12101), so all eight (depth, txs, cq) arms code exactly
3245 // 1 frame. Asserted ABOVE the oracle call.
3246 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
3247 let theirs = if depth == 10 {
3248 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
3249 } else {
3250 ffmpeg_decode_sequence(&stream, width, height, frames.len())
3251 };
3252 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
3253 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
3254 assert!(
3255 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
3256 "{NAME}: {arm} frame {i} does not match ffmpeg"
3257 );
3258 frames_compared += 1;
3259 }
3260 eprintln!(
3261 "{NAME}: {arm} intrabc_frames={intrabc_frames} intrabc_blocks={blocks} \
3262 DECODED {} frame(s) exact",
3263 frames.len()
3264 );
3265 }
3266 }
3267 }
3268 assert!(frames_compared > 0, "{NAME}: no frame was compared");
3269 assert!(
3270 blocks_total > 0,
3271 "{NAME}: gate is vacuous -- no arm decoded a single intrabc block"
3272 );
3273 assert!(
3274 blocks_at_depth[0] > 0 && blocks_at_depth[1] > 0,
3275 "{NAME}: 8-bit={} 10-bit={} -- an arm at that depth no longer decodes an intrabc \
3276 block, so `enable-intrabc` coverage there would rest on the flag spelling alone",
3277 blocks_at_depth[0],
3278 blocks_at_depth[1]
3279 );
3280 }
3281
3282 /// lane-av1-ibcrect: `use_intrabc` on a 128-root HORZ/VERT strip
3283 /// (BLOCK_128X64 / BLOCK_64X128) decodes PIXEL-EXACT against the
3284 /// instrumented oracle -- the witness the refusal inventory names after
3285 /// `decode_block_128rect`'s rect-strip intrabc refusal was lifted
3286 /// (`decode_intrabc_128rect`). The square-block twin is
3287 /// [`an_sb128_screen_stream_with_intrabc_decodes_pixel_exact`] above.
3288 ///
3289 /// The recipes are the hunt's proven arms (lanes/ibcrect r1/r2, the same
3290 /// `--sb-size=128 --min-partition-size=64 --enable-rect-partitions=1
3291 /// --enable-ab-partitions=0 --enable-1to4-partitions=0` partition recipe
3292 /// [`a_real_aomenc_sb128_intra_rect_block_decodes_pixel_exact`] uses, plus
3293 /// `--tune-content=screen --enable-intrabc=1` over the DETERMINISTIC geq
3294 /// sinusoid sources -- lavfi `gradients` ignores its seed and re-rolls
3295 /// every run, so a "flake" there was really this):
3296 ///
3297 /// * HORZ arm: 384x320 cq32, 5 all-key frames -- 14 unskipped 128x64
3298 /// intrabc blocks (`skip=false`, real residual reads);
3299 /// * VERT arm: 512x512 cq45, 5 all-key frames -- an unskipped 64x128
3300 /// intrabc block at mi(64,96).
3301 ///
3302 /// Both arms HARD-assert `intrabc_128rect_hits() > 0` and decode-order
3303 /// pixel-exactness of EVERY frame (hidden alt-refs included) against the
3304 /// oracle's own dump, so a stream that stopped engaging the shape fails
3305 /// the gate instead of passing vacuously (class `gate-blind-to-feature`).
3306 ///
3307 /// The 10-bit arm engages the shape. Hunt r2 and the witness re-run both
3308 /// measured `intrabc_128rect_hits` +15 on arm 3, so aomenc does take a
3309 /// 128-root HORZ/VERT strip at 10 bit under this recipe. There is no
3310 /// per-depth coverage gap to print. The gate's hard asserts already
3311 /// cover that arm.
3312 ///
3313 /// The chroma context this shape reads was the r2 defect: per-unit chroma
3314 /// entropy states were stamped inside the mu-chunk loop, then the
3315 /// end-of-block `record_split_luma_rect_mi` re-stamped BOTH planes over
3316 /// the whole 128x64 span with ONE composed state -- level = the SUM of
3317 /// both 64x64 chunks' units, dc = chunk-0's top-left (class
3318 /// `override-slot-on-one-arm`; the inter-128 path fixed the same class
3319 /// with its `mu_chroma_units` replay, decode.rs). The next block then
3320 /// read `txb_skip` off the smeared state.
3321 #[test]
3322 fn an_sb128_rect_strip_with_intrabc_decodes_pixel_exact() {
3323 const NAME: &str = "an_sb128_rect_strip_with_intrabc_decodes_pixel_exact";
3324 let _gate_lock = lock_gate_counters();
3325 if !have_ffmpeg() {
3326 eprintln!("SKIP {NAME}: no ffmpeg");
3327 return;
3328 }
3329 if !have_aomenc() {
3330 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3331 return;
3332 }
3333 // (tag, width, height, cq, geq luma, 10-bit)
3334 // The geq sources are the hunt's GEO_SMOOTH / GEO_SMOOTH_512,
3335 // byte-identical across runs (see the sb128 intra-rect gate's note).
3336 let arms: [(u32, usize, usize, &str, &str, bool); 3] = [
3337 (
3338 1,
3339 384,
3340 320,
3341 "32",
3342 "128+90*sin((X+2*N)/37)+30*sin(Y/29)",
3343 false,
3344 ),
3345 (
3346 2,
3347 512,
3348 512,
3349 "45",
3350 "128+80*sin((X+3*N)/17)+50*sin(Y/29)+30*sin((X+Y)/13)",
3351 false,
3352 ),
3353 (
3354 3,
3355 384,
3356 320,
3357 "32",
3358 "128+90*sin((X+2*N)/37)+30*sin(Y/29)",
3359 true,
3360 ),
3361 ];
3362 let mut engaged_arms = 0u32;
3363 let mut vert_arms = 0u32;
3364 for (tag, width, height, cq, lum, ten_bit) in arms {
3365 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
3366 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3367 .args([
3368 "-v",
3369 "error",
3370 "-f",
3371 "lavfi",
3372 "-i",
3373 &format!(
3374 "nullsrc=size={width}x{height}:rate=25,format=yuv420p,\
3375 geq=lum='{lum}':\
3376 cb='128+30*sin(X/23)':cr='128+30*sin((Y+N)/19)'"
3377 ),
3378 "-pix_fmt",
3379 pix,
3380 "-strict",
3381 "-1",
3382 "-t",
3383 "0.2",
3384 "-f",
3385 "yuv4mpegpipe",
3386 "-",
3387 ])
3388 .stdin(Stdio::null())
3389 .stdout(Stdio::piped())
3390 .stderr(Stdio::piped()), None, |c| c.output())
3391 .expect("ffmpeg failed to run");
3392 assert!(
3393 y4m.status.success(),
3394 "{NAME}: ffmpeg fixture: {}",
3395 String::from_utf8_lossy(&y4m.stderr)
3396 );
3397 let cq_arg = format!("--cq-level={cq}");
3398 let mut args: Vec<&str> = vec![
3399 "--codec=av1",
3400 "--passes=1",
3401 "--end-usage=q",
3402 &cq_arg,
3403 "--cpu-used=0",
3404 "--threads=1",
3405 "--row-mt=0",
3406 "--lag-in-frames=0",
3407 "--kf-max-dist=1",
3408 "--limit=5",
3409 "--tile-columns=0",
3410 "--sb-size=128",
3411 "--min-partition-size=64",
3412 "--enable-rect-partitions=1",
3413 "--enable-ab-partitions=0",
3414 "--enable-1to4-partitions=0",
3415 "--enable-palette=0",
3416 "--tune-content=screen",
3417 "--enable-intrabc=1",
3418 "--deltaq-mode=0",
3419 "--enable-tx-size-search=0",
3420 ];
3421 if ten_bit {
3422 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
3423 }
3424 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
3425 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3426 assert!(
3427 out.status.success(),
3428 "{NAME}: aomenc refused the arm {tag} fixture: {}",
3429 String::from_utf8_lossy(&out.stderr)
3430 );
3431 let stream = out.stdout;
3432 let before = crate::decode::intrabc_128rect_hits();
3433 let (frames, hidden) = decode_all_frames_vs_oracle(
3434 &stream,
3435 &format!("ibcrect-strip-{tag}-{width}x{height}"),
3436 );
3437 let hits = crate::decode::intrabc_128rect_hits() - before;
3438 eprintln!(
3439 "{NAME}: arm {tag} {width}x{height} cq={cq} {}bit: {frames} decode-order frames \
3440 pixel-exact ({hidden} hidden), intrabc_128rect_hits=+{hits}",
3441 if ten_bit { 10 } else { 8 },
3442 );
3443 if hits > 0 {
3444 engaged_arms += 1;
3445 // The VERT arm is tag 2; its engagement is what proves the
3446 // 64x128 orientation, not just 128x64.
3447 if tag == 2 {
3448 vert_arms += 1;
3449 }
3450 }
3451 }
3452 assert!(
3453 engaged_arms > 0,
3454 "{NAME}: {engaged_arms} arm(s) decoded pixel-exact but NOT ONE decoded a 128-root \
3455 rect-strip intrabc block -- the shape this gate exists for was never engaged"
3456 );
3457 assert!(
3458 vert_arms > 0,
3459 "{NAME}: the VERT (64x128) orientation was never engaged -- only 128x64 HORZ strips \
3460 proved the lift"
3461 );
3462 }
3463
3464 /// lane-av1intrapred r2, REGRESSION GATE for the two intrabc TX4-split
3465 /// chroma defects this lane fixed.
3466 ///
3467 /// An intrabc 8x8 leaf whose var-tx tree split to TX_4X4 must (a) arm
3468 /// `INTRABC_CHROMA_TX` from the co-located luma TU's coded type -- the
3469 /// chroma units then take that type's class-1 eob row, HORIZ scan and nz
3470 /// contexts (libaom `av1_get_tx_type`'s is_inter branch; intrabc is
3471 /// inter-classified) -- and (b) predict the chroma units from the FRAME
3472 /// COPY at the DV, not intra-from-UV-mode (intrabc's UV mode is DC, so a
3473 /// leaf that loses the override predicts flat DC where libaom copies a
3474 /// busy region).
3475 ///
3476 /// Pre-r2, decode_leaf8's TX4 arm did neither: R5's chroma U txb at
3477 /// mi (36,66) decoded `eob=11` off the 2D row where aomdec decoded
3478 /// `eob=13` off the class-1 row, and the first surviving pixel fork was
3479 /// U(184,4) of mi (2,92) (class `intrabc-chroma-tx-not-armed`, then
3480 /// `intrabc-chroma-predicts-intra`).
3481 ///
3482 /// The fixture is the report's R5 stream pinned into `fixtures/`
3483 /// (aomenc oracle, testsrc2 320x180 tiled 2x2 -> 640x360, sb64 maxp64
3484 /// square-only screen intrabc, cq20, 1 frame; 7173 bytes,
3485 /// sha256 bc699af4a6e7c1c5657f041e8cbdf2d3d899ddb80ec2a549a950b7cebb5b41bd).
3486 /// The gate needs no oracle at run time and cannot be skipped: a missing
3487 /// fixture, a decode error, a zero counter, a moved pixel patch or a
3488 /// changed full-frame fingerprint each fail by name. The fingerprint is
3489 /// FNV-1a (dependency-free, same rationale as the cdf-forwarding gate's).
3490 #[test]
3491 fn an_intrabc_tx4_leaf_chroma_inherits_the_luma_type_and_predicts_from_the_frame_copy() {
3492 const NAME: &str =
3493 "an_intrabc_tx4_leaf_chroma_inherits_the_luma_type_and_predicts_from_the_frame_copy";
3494 const FIXTURE_LEN: usize = 7173;
3495 const FIXTURE_FNV: u64 = 0x3a57_d075_5e4c_fe5b;
3496 const RAW_LEN: usize = 640 * 360 * 3 / 2;
3497 const RAW_FNV: u64 = 0xf271_df27_ce4d_ba66;
3498 // The 4x4 chroma patches at (184,4) -- the first surviving pixel fork
3499 // -- as the oracles (aomdec and ffmpeg agree) reconstruct them.
3500 const U_PATCH: [u16; 16] = [
3501 86, 116, 55, 110, 114, 114, 51, 83, 99, 121, 48, 114, 103, 117, 102, 67,
3502 ];
3503 const V_PATCH: [u16; 16] = [
3504 179, 158, 199, 105, 155, 158, 195, 147, 163, 153, 194, 108, 170, 148, 168, 172,
3505 ];
3506
3507 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3508 .join("fixtures/intrabc_tx4_chroma_kf.obu");
3509 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
3510 panic!(
3511 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
3512 which is a failure, not a skip",
3513 obu.display()
3514 )
3515 });
3516 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
3517 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
3518
3519 let _guard = lock_gate_counters();
3520 crate::decode::reset_leaf8_intrabc_hits();
3521 crate::decode::reset_intrabc_tx4_chroma_copy_hits();
3522 let frames = decode_stream(&stream)
3523 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
3524 assert_eq!(frames.len(), 1, "{NAME}: frame count");
3525 let frame = &frames[0];
3526 assert_eq!(
3527 (frame.width, frame.height),
3528 (640, 360),
3529 "{NAME}: dimensions"
3530 );
3531
3532 // Non-vacuity, both halves: the leaf shape must be reached at all,
3533 // and its chroma route must have consulted the ARMED slot (pre-r2
3534 // this counter is 0 -- the arm never armed the slot).
3535 assert!(
3536 crate::decode::leaf8_intrabc_hits() > 0,
3537 "{NAME}: gate is vacuous -- no intrabc 8x8 leaf was decoded"
3538 );
3539 assert!(
3540 crate::decode::intrabc_tx4_chroma_copy_hits() > 0,
3541 "{NAME}: gate is vacuous -- no intrabc TX4-split leaf's chroma read consulted \
3542 the armed slot (class intrabc-chroma-tx-not-armed)"
3543 );
3544
3545 // The first surviving pixel fork: chroma 4x4 at (184,4). The wrong
3546 // wirings put flat intra-DC predictions or the wrong eob class here.
3547 let cw = frame.width / 2;
3548 let u_patch: Vec<u16> = (0..4)
3549 .flat_map(|dy| (0..4).map(move |dx| frame.u[(4 + dy) * cw + 184 + dx]))
3550 .collect();
3551 let v_patch: Vec<u16> = (0..4)
3552 .flat_map(|dy| (0..4).map(move |dx| frame.v[(4 + dy) * cw + 184 + dx]))
3553 .collect();
3554 assert_eq!(u_patch, U_PATCH, "{NAME}: U(184,4) patch moved");
3555 assert_eq!(v_patch, V_PATCH, "{NAME}: V(184,4) patch moved");
3556 // The unit the FRAME-COPY override specifically pins: chroma 4x4 at
3557 // (168,0) is an intrabc TX4-split leaf's chroma whose copy source is
3558 // a busy ramp region; without the `palette_uv_bufs` intrabc wrap the
3559 // read predicts flat intra-DC here (78k chroma bytes drift from this
3560 // unit alone), with it the copy reproduces the oracle exactly.
3561 const U_COPY_PATCH: [u16; 16] = [
3562 91, 91, 91, 91, 120, 120, 120, 120, 120, 120, 120, 120, 73, 102, 116, 116,
3563 ];
3564 const V_COPY_PATCH: [u16; 16] = [
3565 241, 241, 241, 241, 156, 156, 156, 156, 158, 158, 158, 158, 181, 163, 154, 154,
3566 ];
3567 let u_copy: Vec<u16> = (0..4)
3568 .flat_map(|dy| (0..4).map(move |dx| frame.u[dy * cw + 168 + dx]))
3569 .collect();
3570 let v_copy: Vec<u16> = (0..4)
3571 .flat_map(|dy| (0..4).map(move |dx| frame.v[dy * cw + 168 + dx]))
3572 .collect();
3573 assert_eq!(
3574 u_copy, U_COPY_PATCH,
3575 "{NAME}: U(168,0) patch moved -- the intrabc TX4 chroma read no longer \
3576 predicts from the frame copy (class intrabc-chroma-predicts-intra)"
3577 );
3578 assert_eq!(v_copy, V_COPY_PATCH, "{NAME}: V(168,0) patch moved");
3579
3580 // The whole frame, packed as the rawvideo byte stream the oracles
3581 // produce: any remaining byte anywhere in Y/U/V fails the gate.
3582 let mut raw = Vec::with_capacity(RAW_LEN);
3583 for plane in [&frame.y, &frame.u, &frame.v] {
3584 raw.extend(plane.iter().map(|&s| s as u8));
3585 }
3586 assert_eq!(raw.len(), RAW_LEN, "{NAME}: raw size");
3587 assert_eq!(
3588 fnv1a64(&raw),
3589 RAW_FNV,
3590 "{NAME}: full-frame fingerprint moved"
3591 );
3592 }
3593
3594 /// lane-t900 r33, CENSUS for "a sub-8x8 leaf that uses intrabc".
3595 ///
3596 /// The `use_intrabc` symbol IS read at that reader for every sub-8x8 leaf
3597 /// of an `allow_intrabc` frame, so arrival is provable rather than
3598 /// assumed: the arms below force 4x4 leaves (`--min-partition-size=4`) on
3599 /// the exact-repetition screen content that keeps `allow_intrabc`, and the
3600 /// gate requires both counters -- `allow_intrabc` frames and decoded sub-8
3601 /// leaves -- to be non-zero before it reads anything into the refusal
3602 /// firing 0 times (class `gate-blind-to-feature`).
3603 #[test]
3604 fn a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal() {
3605 const NAME: &str =
3606 "a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal";
3607 if !have_ffmpeg() || !have_aomenc() {
3608 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
3609 return;
3610 }
3611 let (width, height) = (256usize, 192usize);
3612 let _guard = lock_gate_counters();
3613 let (mut premise_arms, mut reached, mut sub8_total, mut frames_compared) =
3614 (0u32, 0u32, 0usize, 0u32);
3615 for cq in ["30", "45"] {
3616 let arm = format!("sub8 cq={cq}");
3617 let stream = screen_intrabc_stream_with(
3618 "smptebars=size=128x96:rate=25",
3619 cq,
3620 "0",
3621 true,
3622 true,
3623 &["--min-partition-size=4"],
3624 );
3625 let (_, intrabc_frames) = sb128_and_intrabc_frames(&stream);
3626 if intrabc_frames > 0 {
3627 premise_arms += 1;
3628 }
3629 // No reset for this counter, so measure the delta (the gate lock
3630 // above keeps another gate's decode out of it).
3631 let sub8_before = crate::decode::sub8_split_hits();
3632 match decode_stream(&stream) {
3633 Ok(frames) => {
3634 let sub8 = crate::decode::sub8_split_hits() - sub8_before;
3635 sub8_total += sub8;
3636 // The ENCODE's frame count: `screen_intrabc_stream_with` (12593)
3637 // renders `smptebars=size=128x96:rate=25` with `-t 0.2` and
3638 // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame
3639 // out -- and its aomenc runs with `--limit=1` (12101), so both
3640 // cq arms code exactly 1 frame. The census is report-only about
3641 // the COUNTS, but its Ok arm asserts pixel-exactness, so the
3642 // budget handed to ffmpeg is pinned here rather than derived
3643 // from the decode under test.
3644 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
3645 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
3646 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
3647 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
3648 assert!(
3649 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
3650 "{NAME}: {arm} frame {i} does not match ffmpeg"
3651 );
3652 frames_compared += 1;
3653 }
3654 eprintln!(
3655 "{NAME}: {arm} intrabc_frames={intrabc_frames} sub8_leaves={sub8} \
3656 DECODED {} frame(s) exact",
3657 frames.len()
3658 );
3659 }
3660 Err(e) => {
3661 let msg = e.to_string();
3662 assert!(
3663 msg.contains("unsupported"),
3664 "{NAME}: {arm} decode failed: {e}"
3665 );
3666 if msg.contains("a sub-8x8 leaf that uses intrabc") {
3667 reached += 1;
3668 }
3669 sub8_total += crate::decode::sub8_split_hits() - sub8_before;
3670 eprintln!("{NAME}: {arm} intrabc_frames={intrabc_frames} REFUSED: {e}");
3671 }
3672 }
3673 }
3674 eprintln!(
3675 "{NAME}: {premise_arms}/2 arm(s) keep allow_intrabc, {sub8_total} sub-8 leaf/leaves \
3676 decoded, {reached} reach the refusal, {frames_compared} frame(s) exact"
3677 );
3678 assert!(
3679 premise_arms > 0,
3680 "{NAME}: census is vacuous -- no arm kept allow_intrabc, so the refusal's own \
3681 premise was never within reach"
3682 );
3683 assert!(
3684 sub8_total > 0,
3685 "{NAME}: census is vacuous -- no sub-8 leaf was decoded at all, so the \
3686 `use_intrabc` symbol this refusal guards was never read"
3687 );
3688 }
3689
3690 /// lane-t900 r33, CENSUS for "an intrabc block whose var-tx tree resolved
3691 /// to mixed leaf transform sizes" -- the residue lane-t900 r32 left when
3692 /// it lifted the intrabc `TX_MODE_SELECT` refusal.
3693 ///
3694 /// The tree is read in full; lane-av1-ibcvtx taught the luma reconstruct
3695 /// to walk the tree's own leaf list, so mixed trees now decode. This
3696 /// census sweeps the quantiser across the exact-repetition recipe that
3697 /// reaches the tree at all and requires the tree to actually be read
3698 /// (`intrabc_vartx_hits`); it stays as the premise witness for the lifted
3699 /// refusal (`reached` is 0 by construction now).
3700 #[test]
3701 fn an_intrabc_vartx_census_measures_the_mixed_leaf_refusal() {
3702 const NAME: &str = "an_intrabc_vartx_census_measures_the_mixed_leaf_refusal";
3703 if !have_ffmpeg() || !have_aomenc() {
3704 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
3705 return;
3706 }
3707 let (width, height) = (256usize, 192usize);
3708 let _guard = lock_gate_counters();
3709 let (mut vartx_total, mut reached, mut frames_compared) = (0usize, 0u32, 0u32);
3710 for cq in ["20", "30", "45", "55"] {
3711 let arm = format!("vartx cq={cq}");
3712 let stream =
3713 screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
3714 let (select, premise) = tx_select_and_intrabc_frames(&stream);
3715 crate::decode::reset_intrabc_vartx_hits();
3716 match decode_stream(&stream) {
3717 Ok(frames) => {
3718 let vartx = crate::decode::intrabc_vartx_hits();
3719 vartx_total += vartx;
3720 // The ENCODE's frame count: `screen_intrabc_stream` (12679)
3721 // renders `smptebars=size=128x96:rate=25` with `-t 0.2` and
3722 // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame
3723 // out -- and its aomenc runs with `--limit=1` (12101), so all
3724 // four cq arms code exactly 1 frame. The census is
3725 // report-only about the COUNTS, but its Ok arm does assert
3726 // pixel-exactness, so the budget it hands ffmpeg is pinned
3727 // here rather than derived from the decode under test.
3728 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
3729 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
3730 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
3731 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
3732 assert!(
3733 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
3734 "{NAME}: {arm} frame {i} does not match ffmpeg"
3735 );
3736 frames_compared += 1;
3737 }
3738 eprintln!(
3739 "{NAME}: {arm} select={select} premise={premise} vartx_blocks={vartx} \
3740 DECODED {} frame(s) exact",
3741 frames.len()
3742 );
3743 }
3744 Err(e) => {
3745 let msg = e.to_string();
3746 assert!(
3747 msg.contains("unsupported"),
3748 "{NAME}: {arm} decode failed: {e}"
3749 );
3750 vartx_total += crate::decode::intrabc_vartx_hits();
3751 if msg.contains("mixed leaf transform sizes") {
3752 reached += 1;
3753 }
3754 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
3755 }
3756 }
3757 }
3758 eprintln!(
3759 "{NAME}: {vartx_total} intrabc block(s) read the var-tx tree, {reached} resolved to \
3760 mixed leaves, {frames_compared} frame(s) exact"
3761 );
3762 assert!(
3763 vartx_total > 0,
3764 "{NAME}: census is vacuous -- no intrabc block read the var-tx tree at all"
3765 );
3766 assert_eq!(
3767 reached, 0,
3768 "{NAME}: an intrabc var-tx tree was REFUSED -- the mixed-leaf refusal \
3769 is lifted (lane-av1-ibcvtx) and must stay gone"
3770 );
3771 }
3772
3773 /// lane-av1-ibcvtx, capability gate for the LIFTED refusal "an intrabc
3774 /// block whose var-tx tree resolved to mixed leaf transform sizes": the
3775 /// t900 r33 census recipe class (screen content, square partitions,
3776 /// tx-size search) reaches mixed trees the moment the canvas carries
3777 /// testsrc2's texture and blocks grow past 32 -- on the PRE-fix tree this
3778 /// exact stream refused by name on its first mixed tree (5 of the 12
3779 /// hunt recipes hit it, `lanes/av1ibcvtx.report.md`).
3780 ///
3781 /// The luma reconstruct walks the tree's own leaf list per leaf (libaom
3782 /// `decode_token_recon_block`), and the block's chroma inherits the
3783 /// co-located luma unit's coded tx type (`av1_get_tx_type`,
3784 /// `blockd.h:1278`) -- the inheritance the uniform multi-TU intrabc path
3785 /// was missing as well: symbol-aligned against an instrumented aomdec,
3786 /// the 640x360 cq20 witness desynced inside the FIRST chroma unit of its
3787 /// first mixed tree until the arm landed, then matched every subsequent
3788 /// read.
3789 ///
3790 /// NOT yet asserted: full pixel-exactness against ffmpeg. A second,
3791 /// PRE-EXISTING defect that is not this refusal -- a NON-intrabc intra
3792 /// block (R5 witness: mi (32,32), 64x64, uniform 4x TX_32X32 tree, every
3793 /// coefficient all_zero, reads symbol-identical to aomdec) mispredicts
3794 /// isolated samples on testsrc2 content (first divergence px (128,296)
3795 /// of the 640x360 cq20 recipe) and cascades over roughly a third of the
3796 /// frame. It is pinned in `lanes/av1ibcvtx.report.md`; when it lands,
3797 /// tighten this gate to a full pixel-exact assert.
3798 #[test]
3799 fn a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal() {
3800 const NAME: &str =
3801 "a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal";
3802 if !have_ffmpeg() || !have_aomenc() {
3803 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
3804 return;
3805 }
3806 let (width, height) = (640usize, 360usize);
3807 let _guard = lock_gate_counters();
3808 let stream = screen_intrabc_stream_with(
3809 "testsrc2=size=320x180:rate=25",
3810 "30",
3811 "1",
3812 true,
3813 true,
3814 &["--max-partition-size=64"],
3815 );
3816 let (select, premise) = tx_select_and_intrabc_frames(&stream);
3817 assert!(
3818 premise > 0,
3819 "{NAME}: vacuous -- no frame keeps allow_intrabc under TxMode::Select, \
3820 so the refusal's premise was never within reach (select={select})"
3821 );
3822 crate::decode::reset_intrabc_vartx_hits();
3823 crate::decode::reset_intrabc_vartx_mixed_leaves_hits();
3824 match decode_stream(&stream) {
3825 Ok(frames) => {
3826 let trees = crate::decode::intrabc_vartx_hits();
3827 let mixed = crate::decode::intrabc_vartx_mixed_leaves_hits();
3828 assert!(
3829 trees > 0 && mixed > 0,
3830 "{NAME}: vacuous -- {trees} var-tx tree(s), {mixed} mixed: the \
3831 capability this gate pins was never exercised"
3832 );
3833 // The ENCODE's frame count: `screen_intrabc_stream_with` (12766)
3834 // renders `testsrc2=size=320x180:rate=25` with `-t 0.2` and
3835 // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame out
3836 // at 640x360 -- and its aomenc runs with `--limit=1` (12101), so
3837 // the stream codes exactly 1 frame. Asserted ABOVE the call.
3838 assert_eq!(frames.len(), 1, "{NAME}: key frame");
3839 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
3840 assert_eq!(frames.len(), theirs.len(), "{NAME}: frame count");
3841 let mut mismatched = 0usize;
3842 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
3843 // A size mismatch makes every number this ladder prints
3844 // meaningless -- the `zip` walks below would truncate to the
3845 // shorter plane and report a clean ladder over what is
3846 // really a plane-shape defect -- so it is LOUD. A PIXEL
3847 // mismatch stays report-only: this gate deliberately
3848 // tolerates the pinned second defect (see the doc comment).
3849 for (plane, a, b) in [
3850 ("Y", &ours.y, &ref_frame.y),
3851 ("U", &ours.u, &ref_frame.u),
3852 ("V", &ours.v, &ref_frame.v),
3853 ] {
3854 assert_eq!(
3855 a.len(),
3856 b.len(),
3857 "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has \
3858 {} -- a size mismatch makes this whole diagnostic ladder \
3859 meaningless, so it is loud while a pixel mismatch stays \
3860 report-only",
3861 a.len(),
3862 b.len()
3863 );
3864 }
3865 mismatched += ours
3866 .y
3867 .iter()
3868 .zip(ref_frame.y.iter())
3869 .filter(|(x, y)| x != y)
3870 .count();
3871 mismatched += ours
3872 .u
3873 .iter()
3874 .zip(ref_frame.u.iter())
3875 .filter(|(x, y)| x != y)
3876 .count();
3877 mismatched += ours
3878 .v
3879 .iter()
3880 .zip(ref_frame.v.iter())
3881 .filter(|(x, y)| x != y)
3882 .count();
3883 }
3884 eprintln!(
3885 "{NAME}: select={select} premise={premise} vartx_blocks={trees} \
3886 mixed_trees={mixed}, {mismatched} sample(s) differ from ffmpeg \
3887 (the pinned non-intrabc second defect, see the doc comment)"
3888 );
3889 }
3890 Err(e) => panic!(
3891 "{NAME}: the mixed-leaf refusal is lifted (lane-av1-ibcvtx); the \
3892 witness stream must decode, not stop: {e}"
3893 ),
3894 }
3895 }
3896
3897 /// lane-t900 r31, CENSUS for the refusal "an intrabc block under
3898 /// TxMode::Select" -- which this gate DISPROVES as an "no encoder writes
3899 /// one" claim and pins as a real capability gap instead.
3900 ///
3901 /// The premise is reachable by the SPEC: `tx_mode` (5.9.21) is forced to
3902 /// `ONLY_4X4` only under `CodedLossless`, while `allow_intrabc` (5.9.2)
3903 /// needs `allow_screen_content_tools` at unscaled resolution -- two
3904 /// independent conditions. libaom leaves it open too: `select_tx_mode`
3905 /// (encodeframe.c:2355) never consults `allow_intrabc`, and the only
3906 /// downgrade to `TX_MODE_LARGEST` is `txb_split_count == 0`
3907 /// (encodeframe.c:2690).
3908 ///
3909 /// The measurement over 14 real `--tune-content=screen --enable-intrabc=1`
3910 /// recipes:
3911 ///
3912 /// * the 10 non-repeating arms never present the premise at all -- with
3913 /// `--enable-tx-size-search=1` the frame codes `TX_MODE_SELECT` but RD
3914 /// never picks intrabc, so libaom clears `allow_intrabc` again; with
3915 /// `=0` intrabc IS used and the frame is `TX_MODE_LARGEST`. That
3916 /// correlation, not any rule, is why earlier rounds never saw this;
3917 /// * the four EXACT-REPETITION arms (a 2x2 tiling of one 128x96 bar
3918 /// pattern) all code `allow_intrabc && tx_mode == Select`. Two of them
3919 /// stop on the older rect-strip intrabc refusal (the shape that fires
3920 /// first, class `refusal-hides-a-defect`), and the two with rect/1:4
3921 /// partitions off put intrabc on a SQUARE block: `cq=30` reaches THIS
3922 /// refusal by name, `cq=45`'s intrabc blocks are all `skip` and decode
3923 /// pixel-exact against ffmpeg.
3924 ///
3925 /// So the refusal is correct and load-bearing, exactly one arm reaches it,
3926 /// and the lift it names has a waiting witness:
3927 /// [`an_intrabc_block_under_tx_mode_select_decodes_pixel_exact`] (ignored
3928 /// until the intra path reads the inter var-tx tree for an intrabc block).
3929 #[test]
3930 fn an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal() {
3931 const NAME: &str =
3932 "an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal";
3933 if !have_ffmpeg() {
3934 eprintln!("SKIP {NAME}: no ffmpeg");
3935 return;
3936 }
3937 if !have_aomenc() {
3938 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3939 return;
3940 }
3941 const TS: &str = "testsrc2=s=256x192:r=25";
3942 const SB: &str = "smptebars=size=256x192:rate=25";
3943 const PB: &str = "pal75bars=size=256x192:rate=25";
3944 const TILE: &str = "smptebars=size=128x96:rate=25";
3945 let (width, height) = (256usize, 192usize);
3946 // (arm, source, cq, tx-size-search, tiled, square_only)
3947 let arms: [(&str, &str, &str, &str, bool, bool); 14] = [
3948 ("smptebars-cq40-txs1", SB, "40", "1", false, false),
3949 ("smptebars-cq45-txs1", SB, "45", "1", false, false),
3950 ("smptebars-cq55-txs1", SB, "55", "1", false, false),
3951 ("smptebars-cq63-txs1", SB, "63", "1", false, false),
3952 ("pal75bars-cq40-txs1", PB, "40", "1", false, false),
3953 ("pal75bars-cq55-txs1", PB, "55", "1", false, false),
3954 ("testsrc2-cq50-txs1", TS, "50", "1", false, false),
3955 ("testsrc2-cq63-txs1", TS, "63", "1", false, false),
3956 ("smptebars-cq45-txs0", SB, "45", "0", false, false),
3957 ("pal75bars-cq45-txs0", PB, "45", "0", false, false),
3958 ("tiled-cq30-txs1", TILE, "30", "1", true, false),
3959 ("tiled-cq45-txs1", TILE, "45", "1", true, false),
3960 ("tiled-square-cq30-txs1", TILE, "30", "1", true, true),
3961 // lane-t900 r32: both square arms are now ORDINARY census members
3962 // -- cq30 (unskipped intrabc, the inter var-tx tree) and cq45
3963 // (all-skip intrabc, `maxRectTxSize` with no symbol at all) decode
3964 // pixel-exact, so nothing here reaches the lifted refusal.
3965 ("tiled-square-cq45-txs1", TILE, "45", "1", true, true),
3966 ];
3967 let (mut select_arms, mut premise_arms, mut intrabc_arms, mut blocks_total) =
3968 (0u32, 0u32, 0u32, 0usize);
3969 let (mut refused_tx_select, mut frames_compared) = (0u32, 0usize);
3970 for (arm, src, cq, txs, tiled, square_only) in &arms {
3971 let stream = screen_intrabc_stream(src, cq, txs, *tiled, *square_only);
3972 let (select, premise) = tx_select_and_intrabc_frames(&stream);
3973 if select > 0 {
3974 select_arms += 1;
3975 }
3976 if premise > 0 {
3977 premise_arms += 1;
3978 }
3979 crate::decode::reset_intrabc_hits();
3980 let decoded = decode_stream(&stream);
3981 let blocks = crate::decode::intrabc_hits();
3982 blocks_total += blocks;
3983 if blocks > 0 {
3984 intrabc_arms += 1;
3985 }
3986 match decoded {
3987 Ok(frames) => {
3988 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
3989 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
3990 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
3991 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
3992 assert!(
3993 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
3994 "{NAME}: {arm} frame {i} does not match ffmpeg"
3995 );
3996 frames_compared += 1;
3997 }
3998 eprintln!(
3999 "{NAME}: {arm} select={select} premise={premise} {blocks} intrabc \
4000 block(s), {} frame(s) exact",
4001 frames.len()
4002 );
4003 }
4004 Err(e) => {
4005 let msg = e.to_string();
4006 assert!(
4007 msg.contains("unsupported"),
4008 "{NAME}: {arm} decode failed: {e}"
4009 );
4010 if msg.contains("an intrabc block under TxMode::Select") {
4011 refused_tx_select += 1;
4012 assert!(
4013 premise > 0,
4014 "{NAME}: {arm} reached the TxMode::Select intrabc refusal in a \
4015 frame that codes no such header"
4016 );
4017 } else {
4018 assert!(
4019 msg.contains("intra block copy"),
4020 "{NAME}: {arm} refused for an unrelated reason: {e}"
4021 );
4022 }
4023 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
4024 }
4025 }
4026 }
4027 eprintln!(
4028 "{NAME}: {select_arms}/{n} arm(s) code a TX_MODE_SELECT frame, {premise_arms} of \
4029 those keep allow_intrabc, {intrabc_arms} arm(s) decode an intrabc block \
4030 ({blocks_total} total), {refused_tx_select} reach the refusal, \
4031 {frames_compared} frame(s) compared exact",
4032 n = arms.len()
4033 );
4034 assert!(
4035 intrabc_arms > 0 && blocks_total > 0,
4036 "{NAME}: census is vacuous -- no arm decoded an intrabc block at all"
4037 );
4038 assert!(
4039 premise_arms > 0,
4040 "{NAME}: census is vacuous -- no arm coded a frame with both allow_intrabc and \
4041 tx_mode == Select, so the refusal's own premise was never within reach"
4042 );
4043 assert_eq!(
4044 refused_tx_select, 0,
4045 "{NAME}: lane-t900 r32 lifted this refusal -- an intrabc block now reads the \
4046 INTER tx-size syntax, so no arm may reach it again"
4047 );
4048 assert!(
4049 frames_compared > 0,
4050 "{NAME}: no frame was compared pixel-exact"
4051 );
4052 }
4053
4054 /// lane-t900 r31, the WAITING witness for the capability
4055 /// [`an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal`]
4056 /// pins: a real aomenc screen key frame whose intrabc block sits on a
4057 /// square block of a `TX_MODE_SELECT` frame, unskipped. libaom's
4058 /// `parse_decode_block` treats an intrabc block as `inter_block_tx`, so
4059 /// its transform size comes off the inter var-tx partition tree
4060 /// (`read_var_tx_size`), which this decoder reads nowhere on the intra
4061 /// path -- reading the intra `tx_depth` symbol instead desyncs.
4062 ///
4063 /// lane-t900 r32 closed both arms. A SKIPPED intrabc block reads no
4064 /// tx-size symbol at all (`allowSelect = !skip || !is_inter`, false for an
4065 /// intrabc block since libaom's `is_inter_block` counts one); reading the
4066 /// intra `tx_depth` for it consumed a symbol libaom never wrote and
4067 /// desynced the tile a whole block later, at the superblock corner
4068 /// (192,64) (class `equal-range-means-unread`). An UNSKIPPED one reads the
4069 /// inter var-tx tree (`read_var_tx_size`). r31's note that cq=45's blocks
4070 /// are all `skip` was read off that desynced decode: with the tx-size read
4071 /// corrected, cq=45 carries 3 unskipped intrabc blocks of 10 and cq=30
4072 /// carries 1 of 16, so both arms exercise both sides of the split.
4073 #[test]
4074 fn an_intrabc_block_under_tx_mode_select_decodes_pixel_exact() {
4075 const NAME: &str = "an_intrabc_block_under_tx_mode_select_decodes_pixel_exact";
4076 if !have_ffmpeg() || !have_aomenc() {
4077 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
4078 return;
4079 }
4080 let (width, height) = (256usize, 192usize);
4081 for cq in ["30", "45"] {
4082 let stream =
4083 screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
4084 let (select, premise) = tx_select_and_intrabc_frames(&stream);
4085 assert!(
4086 select > 0 && premise > 0,
4087 "{NAME}: cq={cq} no longer codes allow_intrabc under TX_MODE_SELECT \
4088 (select={select} premise={premise})"
4089 );
4090 crate::decode::reset_intrabc_hits();
4091 crate::decode::reset_intrabc_vartx_hits();
4092 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: cq={cq}: {e}"));
4093 let (blocks, vartx) = (
4094 crate::decode::intrabc_hits(),
4095 crate::decode::intrabc_vartx_hits(),
4096 );
4097 assert!(
4098 blocks > 0,
4099 "{NAME}: cq={cq} no longer decodes an intrabc block"
4100 );
4101 // r31 recorded cq=45's intrabc blocks as ALL skip; that was read
4102 // off the desynced decode. With the tx-size read corrected both
4103 // arms carry unskipped ones (cq30 1 of 16, cq45 3 of 10), so both
4104 // must reach the var-tx tree or the gate is blind to the lift
4105 // (class `gate-blind-to-feature`).
4106 assert!(
4107 vartx > 0,
4108 "{NAME}: cq={cq} no longer reads the inter var-tx tree for an intrabc block"
4109 );
4110 eprintln!("{NAME}: cq={cq} {blocks} intrabc block(s), {vartx} through var-tx");
4111 // The ENCODE's frame count: `screen_intrabc_stream` (12022) renders
4112 // `smptebars=size=128x96:rate=25` with `-t 0.2` and `-vf tile=2x2`
4113 // (12066, 12069) -- 5 frames in, 1 tiled frame out -- and its aomenc
4114 // runs with `--limit=1` (12101), so both cq arms code exactly 1
4115 // frame. Asserted ABOVE the oracle call.
4116 assert_eq!(frames.len(), 1, "{NAME}: cq={cq} key frame");
4117 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
4118 assert_eq!(frames.len(), theirs.len(), "{NAME}: cq={cq} frame count");
4119 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
4120 assert!(
4121 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
4122 "{NAME}: cq={cq} frame {i} does not match ffmpeg"
4123 );
4124 }
4125 }
4126 }
4127
4128 /// lane-av1txr: a real `aomenc --cdf-update-mode=0` stream (spec 5.9.2
4129 /// `disable_cdf_update`) decodes SAMPLE-EXACT. The read that was missing:
4130 /// `stream.rs` never threaded the header bit, so the tile readers adapted
4131 /// every symbol of a frame the encoder coded against fixed tables -- the
4132 /// stream desynced at its first multi-symbol block and the pixels differed
4133 /// from byte 6 (`EC_PROBE_OUT` vs `ffmpeg -pix_fmt yuv420p`, measured
4134 /// 2026-09-20). The msac unit gate
4135 /// (`a_reader_told_not_to_adapt_matches_a_non_adapting_writer`) pins the
4136 /// mechanism; this one pins the wiring end to end.
4137 #[test]
4138 fn a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact() {
4139 const NAME: &str = "a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact";
4140 if !have_ffmpeg() || !have_aomenc() {
4141 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
4142 return;
4143 }
4144 let (width, height) = (256usize, 192usize);
4145 let stream = screen_intrabc_stream_with(
4146 "testsrc2=size=256x192:rate=25",
4147 "45",
4148 "1",
4149 false,
4150 true,
4151 &["--cdf-update-mode=0", "--limit=3"],
4152 );
4153 // Non-vacuity: the fixture must really code the bit on every frame.
4154 let mut parser = Av1Parser::new();
4155 let mut pos = 0usize;
4156 let mut headers = 0usize;
4157 while pos < stream.len() {
4158 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
4159 break;
4160 };
4161 pos += obu.total_size.max(1);
4162 let header = match &obu.kind {
4163 ObuKind::Frame(h, _) | ObuKind::FrameHeader(h) => h,
4164 _ => continue,
4165 };
4166 assert!(
4167 header.disable_cdf_update,
4168 "{NAME}: frame {headers} does not carry disable_cdf_update -- aomenc ignored \
4169 --cdf-update-mode=0"
4170 );
4171 headers += 1;
4172 }
4173 assert!(
4174 headers >= 3,
4175 "{NAME}: only {headers} frame headers in the fixture"
4176 );
4177 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {e}"));
4178 // The frame count, and it comes from the WIRE, not from our decode: the
4179 // loop above parsed this stream's own OBU frame headers with
4180 // `Av1Parser` and counted `headers` of them (>= 3, from the arm's
4181 // `--limit=3` at 13127, which overrides the helper's `--limit=1` because
4182 // aomenc keeps the last occurrence of a repeated flag). Asserted ABOVE
4183 // the oracle call, so a decode that showed fewer frames than the bitstream
4184 // codes reds naming the wire instead of asking ffmpeg for the same short
4185 // count. Deriving it from `headers` rather than a literal keeps the pin
4186 // honest if aomenc's frame count ever drifts.
4187 assert_eq!(
4188 frames.len(),
4189 headers,
4190 "{NAME}: the stream codes {headers} frame(s), the decode showed {}",
4191 frames.len()
4192 );
4193 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
4194 assert_eq!(frames.len(), theirs.len(), "{NAME}: frame count");
4195 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
4196 assert!(
4197 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
4198 "{NAME}: frame {i} does not match ffmpeg"
4199 );
4200 }
4201 eprintln!("{NAME}: {headers} disable_cdf_update frame headers, all frames sample-exact");
4202 }
4203
4204 /// lane-kf900 r4, the gate for the two lifted palette refusals ("a 1:4
4205 /// rect strip that actually uses a palette (reconstruction is not ported
4206 /// at this shape)" and "a palette block on a HORZ/VERT intra strip below
4207 /// 16x16 (reconstruction not ported)"): real `aomenc` streams that put a
4208 /// palette on a RECT strip, decoded whole-frame pixel-exact against
4209 /// ffmpeg's own decode of the identical bytes, at 8 AND 10 bit.
4210 ///
4211 /// Arm 0 is the stream lane-kf900 r3 pinned and stopped on -- `testsrc2`
4212 /// 256x192, `--cq-level=59 --cpu-used=0 --min-partition-size=8
4213 /// --enable-rect-partitions=1 --enable-tx-size-search=1`, md5
4214 /// `e5f033d8fe34e4418d8cca3ac9d2b595` at 10 bit. Arms 1-2 force the shape
4215 /// on screen-like content with `--tune-content=screen --enable-palette=1
4216 /// --enable-1to4-partitions=1`.
4217 ///
4218 /// An attempt whose decode never hit a rect-strip palette block proves
4219 /// nothing about the lift, so it is counted OUT OF SCOPE rather than
4220 /// silently passing -- but a mismatch on one is still a failure
4221 /// (`out_of_scope_mismatch == 0`), and at least one attempt must fire the
4222 /// counter or the gate is vacuous.
4223 #[test]
4224 fn a_real_aomenc_rect_strip_palette_decodes_pixel_exact() {
4225 const NAME: &str = "a_real_aomenc_rect_strip_palette_decodes_pixel_exact";
4226 if !have_ffmpeg() {
4227 eprintln!("SKIP {NAME}: no ffmpeg");
4228 return;
4229 }
4230 if !have_aomenc() {
4231 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4232 return;
4233 }
4234 let (width, height) = (256usize, 192usize);
4235 let screen: &[&str] = &[
4236 "--tune-content=screen",
4237 "--enable-palette=1",
4238 "--enable-1to4-partitions=1",
4239 "--min-partition-size=8",
4240 ];
4241 // lane-kf900 r6: arms 3-4 are the palette + `--enable-tx-size-search=1`
4242 // shape whose neighbour palette lookup was SUB-granular -- a 16x8 strip
4243 // pair shares one 16px cell, so strip 1 read strip 0's palette size and
4244 // the colour cache came out short. Both were whole-frame wrong before
4245 // the mi-granular fix (`$HOME/.cache/kf900-r6/sweep.log`: smptebars
4246 // cq40/cq55 txs=1 pal=1 = DIFF).
4247 let screen_txs: &[&str] = &[
4248 "--tune-content=screen",
4249 "--enable-palette=1",
4250 "--enable-1to4-partitions=1",
4251 "--min-partition-size=8",
4252 "--max-partition-size=32",
4253 "--sb-size=64",
4254 "--enable-intrabc=1",
4255 "--enable-tx-size-search=1",
4256 ];
4257 let cq40: Vec<&str> = screen_txs
4258 .iter()
4259 .copied()
4260 .chain(["--cq-level=40"])
4261 .collect();
4262 let cq55: Vec<&str> = screen_txs
4263 .iter()
4264 .copied()
4265 .chain(["--cq-level=55"])
4266 .collect();
4267 let arms: [(&str, String, &[&str]); 5] = [
4268 (
4269 "testsrc2-pinned",
4270 "testsrc2=s=256x192:r=25".to_string(),
4271 &[],
4272 ),
4273 (
4274 "testsrc2-screen",
4275 "testsrc2=s=256x192:r=25".to_string(),
4276 screen,
4277 ),
4278 (
4279 "smptebars-screen",
4280 "smptebars=size=256x192:rate=25".to_string(),
4281 screen,
4282 ),
4283 (
4284 "smptebars-screen-txs-cq40",
4285 "smptebars=size=256x192:rate=25".to_string(),
4286 &cq40,
4287 ),
4288 (
4289 "smptebars-screen-txs-cq55",
4290 "smptebars=size=256x192:rate=25".to_string(),
4291 &cq55,
4292 ),
4293 ];
4294 let (mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32, 0u32);
4295 let mut refused = 0u32;
4296 let mut fired_at_depth = [0u32; 2];
4297 let mut frames_compared = 0usize;
4298 for (arm, src, extra) in &arms {
4299 for depth in [8usize, 10] {
4300 let pix_fmt = if depth == 10 {
4301 "yuv420p10le"
4302 } else {
4303 "yuv420p"
4304 };
4305 let render = || {
4306 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
4307 .args([
4308 "-v",
4309 "error",
4310 "-f",
4311 "lavfi",
4312 "-i",
4313 src.as_str(),
4314 "-t",
4315 "0.2",
4316 "-pix_fmt",
4317 pix_fmt,
4318 "-strict",
4319 "-1",
4320 "-f",
4321 "yuv4mpegpipe",
4322 "-",
4323 ])
4324 .stdin(Stdio::null())
4325 .stdout(Stdio::piped())
4326 .stderr(Stdio::piped()), None, |c| c.output())
4327 .expect("ffmpeg failed to run");
4328 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
4329 out.stdout
4330 };
4331 let y4m_a = render();
4332 let y4m_b = render();
4333 assert_eq!(
4334 y4m_a, y4m_b,
4335 "{NAME}: {arm} must render byte-identical across two runs at {depth}-bit"
4336 );
4337 let y4m = y4m_a;
4338 let depth_arg = format!("--bit-depth={depth}");
4339 let in_depth_arg = format!("--input-bit-depth={depth}");
4340 let out = run_with_stdin(
4341 Command::new(aomenc_path())
4342 .args(["--codec=av1"])
4343 .args([&depth_arg, &in_depth_arg])
4344 .args([
4345 "--passes=1",
4346 "--end-usage=q",
4347 "--cq-level=59",
4348 "--cpu-used=0",
4349 "--lag-in-frames=0",
4350 "--kf-max-dist=1",
4351 "--limit=1",
4352 "--threads=1",
4353 "--tile-columns=0",
4354 "--enable-tx-size-search=1",
4355 "--min-partition-size=8",
4356 "--enable-rect-partitions=1",
4357 ])
4358 // Per-arm overrides go AFTER the base recipe: aomenc keeps
4359 // the LAST occurrence of a repeated flag.
4360 .args(*extra)
4361 // The 8-bit twin of the pinned recipe picks a 128-root
4362 // HORZ partition, which this decoder still refuses by name
4363 // ("a 128x128 superblock HORZ/VERT or AB partition") --
4364 // an open refusal of another lane, unrelated to palette.
4365 // Pinning the superblock to 64 keeps the 8-bit arm on the
4366 // shape this gate is about; the 10-bit arms are the
4367 // untouched pinned recipe.
4368 .args(if depth == 8 {
4369 &["--sb-size=64"][..]
4370 } else {
4371 &[][..]
4372 })
4373 .args(["--obu", "-o", "-", "-"]),
4374 &y4m,
4375 );
4376 assert!(
4377 out.status.success(),
4378 "{NAME}: aomenc refused {arm} at {depth}-bit: {}",
4379 String::from_utf8_lossy(&out.stderr)
4380 );
4381 let stream = out.stdout;
4382 let before = decode::rect4_palette_hits();
4383 let frames = match decode_stream(&stream) {
4384 Ok(frames) => frames,
4385 // A NAMED refusal is another lane's open shape (here: a
4386 // palette on an 8x8 SQUARE leaf, still out of scope), never
4387 // a pass -- the attempt is counted out of scope and the
4388 // per-depth firing assert below keeps the gate honest.
4389 Err(e) if e.to_string().contains("unsupported") => {
4390 eprintln!("{NAME}: {arm} {depth}-bit REFUSED: {e}");
4391 refused += 1;
4392 continue;
4393 }
4394 Err(e) => panic!("{NAME}: decode failed on {arm} at {depth}-bit: {e}"),
4395 };
4396 let fired = decode::rect4_palette_hits() - before;
4397 // The ENCODE's frame count, asserted ABOVE the oracle call: the
4398 // y4m renders 5 frames (`-t 0.2` at every arm's `rate=25`,
4399 // 13275) but aomenc is given `--limit=1` (13313), so the stream
4400 // codes exactly 1 frame at both depths on every arm. Asserted
4401 // here it is NOT the tautology the old comment below claimed:
4402 // `frames.len() == 1` is a fact about the encode, checked before
4403 // `frames.len()` is spent as ffmpeg's frame budget.
4404 assert_eq!(frames.len(), 1, "{NAME}: {arm} at {depth}-bit key frame");
4405 let ffmpeg_frames = if depth == 10 {
4406 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
4407 } else {
4408 ffmpeg_decode_sequence(&stream, width, height, frames.len())
4409 };
4410 assert!(
4411 !frames.is_empty(),
4412 "{NAME}: {arm} at {depth}-bit decoded no frame"
4413 );
4414 // EVERY decode-order frame, all three planes.
4415 let mut exact = true;
4416 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
4417 if ours.y != theirs.y || ours.u != theirs.u || ours.v != theirs.v {
4418 exact = false;
4419 eprintln!("{NAME}: {arm} {depth}-bit frame {i} differs");
4420 }
4421 frames_compared += 1;
4422 }
4423 if fired > 0 {
4424 fired_arms += 1;
4425 fired_at_depth[usize::from(depth == 10)] += 1;
4426 assert!(
4427 exact,
4428 "{NAME}: {arm} at {depth}-bit has {fired} rect-strip palette block(s) \
4429 and does NOT decode pixel-exact"
4430 );
4431 } else {
4432 out_of_scope += 1;
4433 if !exact {
4434 out_of_scope_mismatch += 1;
4435 }
4436 }
4437 }
4438 }
4439 eprintln!(
4440 "{NAME}: {fired_arms} attempt(s) with a rect-strip palette block, \
4441 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
4442 {refused} refused, {frames_compared} frames compared, \
4443 fired 8-bit={} 10-bit={}",
4444 fired_at_depth[0], fired_at_depth[1]
4445 );
4446 // MEASURED 2026-09-02, every 8-bit attempt of these recipes: aomenc
4447 // puts its palettes on SQUARE blocks at 8 bit and every 8-bit stream
4448 // that reaches a rect strip with one lands on a palette shape still
4449 // out of scope (8x8 square leaf, or a 64x32/32x64 superblock strip
4450 // with a real transform). So the 8-bit arms here prove the DECODE
4451 // path, not the lift -- `fired_at_depth[0] == 0` is a known, reported
4452 // coverage gap and not a silent pass: the counter is printed.
4453 assert!(
4454 fired_at_depth[1] > 0,
4455 "{NAME}: no attempt put a palette on a rect strip \
4456 (8-bit={}, 10-bit={}) -- gate is vacuous",
4457 fired_at_depth[0],
4458 fired_at_depth[1]
4459 );
4460 assert!(fired_arms > 0, "{NAME}: gate is vacuous");
4461 assert_eq!(
4462 out_of_scope_mismatch, 0,
4463 "{NAME}: {out_of_scope_mismatch} attempt(s) without a rect-strip palette block \
4464 still mismatched -- an unrelated defect, not a SKIP"
4465 );
4466 }
4467
4468 /// The 12-bit KEY witness: CDEF and loop restoration ON, grain off.
4469 /// Byte-exact against ffmpeg, and the 12-bit-sensitive pixel paths hard-
4470 /// assert fired: a CDEF index literal read (bits > 0) and at least one
4471 /// Wiener or SGR restoration unit. Gauntlet for the parameterised
4472 /// rounding sites: MC/Wiener round pairs, `coeff_shift = bd - 8` CDEF,
4473 /// the 12-bit dequant tables, bd-scaled SGR box sums.
4474 #[test]
4475 fn a_real_aomenc_12bit_stream_decodes_pixel_exact() {
4476 const NAME: &str = "a_real_aomenc_12bit_stream_decodes_pixel_exact";
4477 let _gate_lock = lock_gate_counters();
4478 if !have_ffmpeg() {
4479 eprintln!("SKIP {NAME}: no ffmpeg");
4480 return;
4481 }
4482 if !have_aomenc() {
4483 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4484 return;
4485 }
4486 let y4m = y4m_12bit_subpel_source(1);
4487 let stream = encode_12bit(
4488 &y4m,
4489 1,
4490 &["--enable-warped-motion=0", "--enable-global-motion=0"],
4491 );
4492 assert_12bit_sequence_header(&stream, NAME);
4493 let before_cdef = decode::cdef_idx_hits();
4494 let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
4495 let frames = decode_stream(&stream).unwrap_or_else(|e| {
4496 panic!("{NAME}: decode_stream refused a real 12-bit key frame: {e}")
4497 });
4498 assert_eq!(frames.len(), 1);
4499 assert!(
4500 decode::cdef_idx_hits() > before_cdef,
4501 "{NAME}: no CDEF index literal was read -- CDEF is not exercised"
4502 );
4503 assert!(
4504 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
4505 "{NAME}: no loop restoration unit was decoded -- LR is not exercised"
4506 );
4507 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 1);
4508 assert_eq!(
4509 frames[0].y, ffmpeg_frames[0].y,
4510 "luma vs ffmpeg (12-bit key)"
4511 );
4512 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (12-bit key)");
4513 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (12-bit key)");
4514 }
4515
4516 /// The 12-bit INTER witness: a key frame plus one P frame over sub-pixel
4517 /// true motion. Byte-exact against ffmpeg; hard-asserts the two-pass
4518 /// SUBPEL prediction path ran (`MC_SUBPEL_HITS`), so the frame's own
4519 /// `round_0`/`round_1` -- 5/9 at 12 bits, the whole point of the mc.rs
4520 /// parameterisation -- really executed, and asserts
4521 /// `compound_mode_hits` UNCHANGED (this recipe offers no divergent
4522 /// second reference, so no compound mode symbol is read -- the lane's
4523 /// compound witness is the six-frame gate below).
4524 #[test]
4525 fn a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact() {
4526 const NAME: &str = "a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact";
4527 let _gate_lock = lock_gate_counters();
4528 if !have_ffmpeg() {
4529 eprintln!("SKIP {NAME}: no ffmpeg");
4530 return;
4531 }
4532 if !have_aomenc() {
4533 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4534 return;
4535 }
4536 let y4m = y4m_12bit_subpel_source(2);
4537 let stream = encode_12bit(
4538 &y4m,
4539 2,
4540 &["--enable-warped-motion=0", "--enable-global-motion=0"],
4541 );
4542 assert_12bit_sequence_header(&stream, NAME);
4543 let before_subpel = crate::mc::mc_subpel_hits();
4544 let before_compound = decode::compound_mode_hits();
4545 let frames = decode_stream(&stream).unwrap_or_else(|e| {
4546 panic!("{NAME}: decode_stream refused a real 12-bit inter stream: {e}")
4547 });
4548 assert_eq!(frames.len(), 2);
4549 assert!(
4550 crate::mc::mc_subpel_hits() > before_subpel,
4551 "{NAME}: no subpel inter prediction decoded -- the 12-bit round pair is unexercised"
4552 );
4553 assert_eq!(
4554 decode::compound_mode_hits(),
4555 before_compound,
4556 "{NAME}: a compound mode symbol was read -- the single-reference premise is gone"
4557 );
4558 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2);
4559 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4560 assert_eq!(
4561 ours.y, reference.y,
4562 "frame {i} luma vs ffmpeg (12-bit inter)"
4563 );
4564 assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit inter)");
4565 assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit inter)");
4566 }
4567 }