forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

t09.rs4486 lines, 224.2 KiBHistoryRawDownload
1use super::*;
2use super::support::*;
3use super::gates_a::*;
4use super::gates_b::*;
5use crate::probe::run_with_stdin;
6use std::process::{Command, Stdio};
7
8 /// lane-part32 r2: prints the exact mismatch geometry (block coords,
9 /// got/want pixels) of the pinned seed-42 stream captured off
10 /// `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
11 /// via `EC_AV1_GATE_DUMP`. Debug-only, `#[ignore]`d.
12 #[test]
13 // The geometry is HARD-CODED to the seed-42 pin (192x128, one frame):
14 // `ffmpeg_decode_sequence(&stream, 192, 128, 1)` plus the `width = 192` /
15 // `0..128` scan bounds below. Point it at any other pin and it does not
16 // say "wrong size" -- it dies inside the ffmpeg oracle with
17 // `expected 1 4:2:0 frames ... left 196162560 right 36864`. Measured
18 // against `fixtures/sbpart/seed42.obu` (the 192x128 pin it was written
19 // for): `total luma mismatches: 0`.
20 #[ignore = "debug harness: needs EC_AV1_GATE_DUMP_PIN at a 192x128 pin (the geometry is hard-coded; any other size dies in the ffmpeg oracle)"]
21 fn debug_part32_r2_sbpart_pin_mismatch_geometry() {
22 let path = std::env::var("EC_AV1_GATE_DUMP_PIN").expect("set EC_AV1_GATE_DUMP_PIN");
23 let stream = std::fs::read(&path).expect("read pinned stream");
24 let frames = decode_stream(&stream).expect("pinned stream must decode");
25 if let Ok(dump) = std::env::var("EC_DEBUG_DUMP_Y") {
26 let bytes: Vec<u8> = frames[0].y.iter().map(|&v| v as u8).collect();
27 std::fs::write(&dump, bytes).expect("write y dump");
28 }
29 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 192, 128, 1);
30 let got = &frames[0];
31 let want = &ffmpeg_frames[0];
32 let width = 192usize;
33 let mut n = 0;
34 let (mut min_x, mut max_x, mut min_y, mut max_y) = (width, 0, 128, 0);
35 for y in 0..128usize {
36 for x in 0..width {
37 let idx = y * width + x;
38 if got.y[idx] != want.y[idx] {
39 n += 1;
40 min_x = min_x.min(x);
41 max_x = max_x.max(x);
42 min_y = min_y.min(y);
43 max_y = max_y.max(y);
44 }
45 }
46 }
47 eprintln!(
48 "total luma mismatches: {n} bbox x=[{min_x},{max_x}] y=[{min_y},{max_y}] frame=192x128"
49 );
50 for y in 0..128usize {
51 let mut row_first = None;
52 let mut row_count = 0;
53 for x in 0..width {
54 let idx = y * width + x;
55 if got.y[idx] != want.y[idx] {
56 if row_first.is_none() {
57 row_first = Some(x);
58 }
59 row_count += 1;
60 }
61 }
62 if let Some(fx) = row_first {
63 eprintln!("row {y}: first mismatch x={fx} count={row_count}");
64 }
65 }
66 }
67
68 /// lane-rect64q r1, recipe rewritten by lane-av1recipehunt: the same
69 /// encoder-side situation as
70 /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]
71 /// -- a real superblock-level HORZ/VERT partition, so
72 /// [`crate::decode::decode_block_rect64`] runs -- but with `delta_q` left
73 /// ON, so that block's dequant sees a running `CURRENT_Q_IDX` that has
74 /// drifted away from the frame-constant `base_q_idx`. Real aomenc's
75 /// non-realtime default is `DELTA_Q_OBJECTIVE` (`av1_cx_iface.c:271`); the
76 /// `--deltaq-mode=0` sibling is the same command line with that one flag
77 /// added back, and this gate ASSERTS the pair differs (the control arm).
78 ///
79 /// **Why r1's recipe could not fire, measured (lane-av1recipehunt).** r1
80 /// swept 40 attempts of `gradients` at 192x128 with `frame_count = 1` -- a
81 /// single KEY frame, and that is the whole reason. A one-frame encode
82 /// carries no inter frame, and `delta_q_present` needs the temporal (TPL)
83 /// model to see a spatial complexity map at all. At `frame_count = 1` the
84 /// sweep read ZERO `delta_q` symbol groups on every attempt: 40/40 streams
85 /// had `delta_q_hits() == 0` AND `rect64_qidx_drift_hits() == 0` -- a
86 /// different failure from "the drift never reached a rect64 block", and the
87 /// reason r1 could not see the feature at all. The fix is a real inter
88 /// sequence: 4 frames at 512x384 (`8x6` superblocks, so there IS a spatial
89 /// map for the quantizer to vary over).
90 ///
91 /// **The recipe**, exactly (the recorded command line; `--deltaq-mode` is
92 /// ABSENT, i.e. aomenc's default):
93 /// ```text
94 /// ffmpeg -v error -y -f lavfi -i testsrc2=size=512x384:rate=25 \
95 /// -pix_fmt yuv420p -frames:v 4 -f yuv4mpegpipe src512.y4m
96 /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=45 --cpu-used=0 \
97 /// --threads=1 --row-mt=0 --sb-size=64 --enable-rect-partitions=1 \
98 /// --enable-ab-partitions=0 --enable-1to4-partitions=0 \
99 /// --min-partition-size=32 --max-partition-size=64 \
100 /// --enable-restoration=0 --enable-palette=0 --enable-cdef=0 \
101 /// --enable-filter-intra=0 --enable-cfl-intra=0 --enable-intrabc=0 \
102 /// --enable-tx-size-search=0 --obu -o out.obu src512.y4m
103 /// ```
104 /// Source `src512.y4m`: 1179730 bytes, sha256
105 /// `f430d581497e4f6f7db07d0fc92476e92194e1f96c321988ec0739d475cbbe0c`.
106 /// Output `crates/ec-av1/fixtures/rect64_dq_drift.obu`: 8384 bytes, sha256
107 /// `094e51bb21b6caccc905417e95a03f9131b448071567d0b14ec8850799ea2501`
108 /// (committed with `git add -f` past the `fixtures` gitignore, like every
109 /// sibling fixture). The gate re-encodes live and byte-compares against
110 /// that pin, so the pin is the expected output and not a second decode
111 /// path. MEASURED on the feature arm: 48 `delta_q` symbol groups read, 17
112 /// `rect64_qidx_drift_hits`, `sb_rect_hits` firing (the `inter_rect`
113 /// census reads `64x32=2 32x64=2`), all 4 frames pixel-exact vs ffmpeg.
114 /// On the `--deltaq-mode=0` control: 0 groups, 0 drift, also pixel-exact --
115 /// so the drift is the delta_q syntax, not some unrelated arm.
116 ///
117 /// `--cpu-used=0` is load-bearing, measured: the same source at
118 /// `--cpu-used=1` and `--cpu-used=3` reads the same 48 `delta_q` groups and
119 /// drifts ZERO times (the faster presets' RD never leaves a rect64 root in
120 /// a superblock whose quantizer moved). `--cq-level` is not: 45 and 55
121 /// give the identical stream and the same drift count.
122 #[test]
123 fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact()
124 {
125 const NAME: &str = "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact";
126 let _gate_lock = lock_gate_counters();
127 if !have_ffmpeg() {
128 eprintln!("SKIP {NAME}: no ffmpeg");
129 return;
130 }
131 if !have_aomenc() {
132 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
133 return;
134 }
135 const FIXTURE_LEN: usize = 8384;
136 const FIXTURE_FNV: u64 = 0x3d91_a216_8006_3ef6;
137 let (width, height, frame_count) = (512usize, 384usize, 4usize);
138 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
139 .args([
140 "-v",
141 "error",
142 "-y",
143 "-f",
144 "lavfi",
145 "-i",
146 "testsrc2=size=512x384:rate=25",
147 "-pix_fmt",
148 "yuv420p",
149 "-frames:v",
150 "4",
151 "-f",
152 "yuv4mpegpipe",
153 "-",
154 ])
155 .stdin(Stdio::null())
156 .stdout(Stdio::piped())
157 .stderr(Stdio::piped()), None, |c| c.output())
158 .expect("ffmpeg failed to run");
159 assert!(
160 y4m.status.success(),
161 "ffmpeg fixture: {}",
162 String::from_utf8_lossy(&y4m.stderr)
163 );
164 assert_eq!(
165 y4m.stdout.len(),
166 1_179_730,
167 "{NAME}: the testsrc2 source is not the pinned 4-frame 512x384 y4m -- `rate=` \
168 and `-frames:v` are both part of this recipe's identity"
169 );
170 // Every flag spelled exactly once (class [[aomenc-last-flag-wins]]).
171 // `delta_q` is absent ON PURPOSE: aomenc's non-realtime default is
172 // DELTA_Q_OBJECTIVE, and the control arm below re-checks that by
173 // ADDING `--deltaq-mode=0` back.
174 let args: Vec<&str> = vec![
175 "--codec=av1",
176 "--passes=1",
177 "--end-usage=q",
178 "--cq-level=45",
179 "--cpu-used=0",
180 "--threads=1",
181 "--row-mt=0",
182 "--sb-size=64",
183 "--enable-rect-partitions=1",
184 "--enable-ab-partitions=0",
185 "--enable-1to4-partitions=0",
186 "--min-partition-size=32",
187 "--max-partition-size=64",
188 "--enable-restoration=0",
189 "--enable-palette=0",
190 "--enable-cdef=0",
191 "--enable-filter-intra=0",
192 "--enable-cfl-intra=0",
193 "--enable-intrabc=0",
194 "--enable-tx-size-search=0",
195 "--obu",
196 "-o",
197 "-",
198 "-",
199 ];
200 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
201 assert!(
202 out.status.success(),
203 "aomenc refused the fixture: {}",
204 String::from_utf8_lossy(&out.stderr)
205 );
206 let stream = out.stdout;
207 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: encoded size moved");
208 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: encoded bytes moved");
209 let pin = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
210 .join("fixtures/rect64_dq_drift.obu");
211 assert_eq!(
212 std::fs::read(&pin).expect("fixtures/rect64_dq_drift.obu must be committed"),
213 stream,
214 "{NAME}: the live encode no longer matches the committed pin at {}",
215 pin.display()
216 );
217
218 let before = crate::decode::rect64_qidx_drift_hits();
219 let frames = decode_stream(&stream)
220 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream must decode: {e}"));
221 let drift = crate::decode::rect64_qidx_drift_hits() - before;
222 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
223 assert_eq!(frames.len(), frame_count);
224 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
225 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg");
226 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
227 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
228 }
229 assert!(
230 crate::decode::sb_rect_hits() > 0,
231 "{NAME}: zero superblock-level HORZ/VERT blocks fired -- the recipe stopped producing \
232 the shape the delta_q group is read inside"
233 );
234 assert!(
235 drift > 0,
236 "{NAME}: {frame_count} frames pixel-exact but zero rect64 dequant calls ever saw \
237 CURRENT_Q_IDX != base_q_idx -- delta_q was read and never moved the quantizer inside \
238 a rect64 block, so this run proved nothing (class gate-blind-to-feature)"
239 );
240
241 // The control arm: the ONE flag separating this gate from the
242 // always-vacuous `--deltaq-mode=0` sibling, reverted. If this ever
243 // drifts too, delta_q is no longer what carries the coverage and the
244 // feature arm above is not the witness it claims to be. It is also this
245 // gate's own red-proof: dropping that one flag is exactly what turns
246 // the drift assert above red on its own precondition.
247 let mut control = args.clone();
248 control.push("--deltaq-mode=0");
249 let ctl = run_with_stdin(Command::new(aomenc_path()).args(&control), &y4m.stdout);
250 assert!(
251 ctl.status.success(),
252 "aomenc refused the --deltaq-mode=0 control: {}",
253 String::from_utf8_lossy(&ctl.stderr)
254 );
255 let before = crate::decode::rect64_qidx_drift_hits();
256 decode_stream(&ctl.stdout)
257 .unwrap_or_else(|e| panic!("{NAME}: the control stream must decode too: {e}"));
258 let ctl_drift = crate::decode::rect64_qidx_drift_hits() - before;
259 assert_eq!(
260 ctl_drift, 0,
261 "{NAME}: the --deltaq-mode=0 control drifted {ctl_drift} times -- delta_q is no \
262 longer what moves CURRENT_Q_IDX inside a rect64 block, so the feature arm above is \
263 not witnessing what it names"
264 );
265 eprintln!(
266 "{NAME}: {frame_count} frames pixel-exact, sb_rect_hits={}, \
267 rect64_qidx_drift_hits={drift} (--deltaq-mode=0 control: {ctl_drift}), stream \
268 {FIXTURE_LEN} B fnv1a64={FIXTURE_FNV:016x}",
269 crate::decode::sb_rect_hits()
270 );
271 }
272
273 /// lane-sbpart r4: replays a pinned mismatch byte-for-byte off disk (no
274 /// aomenc/ffmpeg re-encode), same pattern as `pinned_golden3/4_stream_
275 /// decodes_pixel_exact` -- fast red/green loop for the bisect, and lets
276 /// `EC_AV1_TRACE=1` be set for one run without re-driving the encoder.
277 ///
278 /// LIVE since lane-av1pinslive (it was `#[ignore]`d from lane-sbpart r4
279 /// only because the bytes lived in a scratchpad). Bytes committed at
280 /// `crates/ec-av1/fixtures/sbpart-pin.obu` (238 bytes; sha256
281 /// `62238fc077f45d89745d4d254b9c0465464003529da3b42d0a65631fbb7e16e9`),
282 /// re-encoded 2026-09-29 from the source gate's own recipe
283 /// (`a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact`:
284 /// smptebars 192x128, single frame, `--sb-size=64 --enable-palette=1
285 /// --min-partition-size=16 --max-partition-size=64`, cq=55). The command
286 /// is in `lanes/av1pins.report.md`. That gate's source list has no
287 /// 192x128 cell, so this pin is a 192x128 re-run of its recipe, not a
288 /// replay of the original mismatch bytes.
289 #[test]
290 fn pinned_sbpart_stream_decodes_pixel_exact() {
291 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
292 .map(std::path::PathBuf::from)
293 .unwrap_or_else(|_| crate_pin("sbpart-pin.obu"));
294 let Ok(stream) = std::fs::read(&path) else {
295 eprintln!(
296 "SKIP pinned_sbpart_stream_decodes_pixel_exact: no pinned bytes at {} \
297 -- the committed copy is crates/ec-av1/fixtures/sbpart-pin.obu",
298 path.display()
299 );
300 return;
301 };
302 if !have_ffmpeg() {
303 eprintln!("SKIP pinned_sbpart_stream_decodes_pixel_exact: no ffmpeg");
304 return;
305 }
306 let frames = decode_stream(&stream).expect("pinned stream must decode");
307 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 192, 128, 1);
308 assert_eq!(
309 frames.len(),
310 ffmpeg_frames.len(),
311 "pinned stream decoded {} frames, ffmpeg {} -- a length mismatch would \
312 make the zip below compare a mis-paired set",
313 frames.len(),
314 ffmpeg_frames.len()
315 );
316 let (width, height) = (192usize, 128usize);
317 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
318 if std::env::var_os("EC_SBPART_DIAG").is_some() {
319 let (mut min_r, mut max_r, mut min_c, mut max_c, mut n) =
320 (usize::MAX, 0usize, usize::MAX, 0usize, 0usize);
321 for r in 0..height {
322 for c in 0..width {
323 let idx = r * width + c;
324 if got.y[idx] != want.y[idx] {
325 min_r = min_r.min(r);
326 max_r = max_r.max(r);
327 min_c = min_c.min(c);
328 max_c = max_c.max(c);
329 n += 1;
330 }
331 }
332 }
333 eprintln!(
334 "DIAG frame {i}: {n} luma mismatches, bbox rows [{min_r}..{max_r}] cols \
335 [{min_c}..{max_c}] of {width}x{height}"
336 );
337 // Per-64px-superblock-column mismatch counts, to see whether
338 // corruption starts exactly at the rect64 SB or bleeds into
339 // SBs decoded earlier (raster order).
340 for sb_col in 0..width.div_ceil(64) {
341 let c0 = sb_col * 64;
342 let c1 = (c0 + 64).min(width);
343 let mut cnt = 0usize;
344 let mut first = None;
345 for r in 0..height {
346 for c in c0..c1 {
347 let idx = r * width + c;
348 if got.y[idx] != want.y[idx] {
349 cnt += 1;
350 if first.is_none() {
351 first = Some((r, c));
352 }
353 }
354 }
355 }
356 eprintln!(
357 "DIAG frame {i} sb_col {sb_col} (cols {c0}..{c1}): {cnt} mismatches, \
358 first={first:?}"
359 );
360 }
361 }
362 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned sbpart)");
363 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned sbpart)");
364 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned sbpart)");
365 }
366 }
367
368 /// lane-tx64x16 r1: a real `aomenc` stream whose superblock-level
369 /// partition decision is `PARTITION_HORZ_4`/`PARTITION_VERT_4` (four
370 /// 64x16 / 16x64 strips) must decode pixel-exact. Both arms are HARD
371 /// asserted, and only hits earned inside an attempt that then compared
372 /// pixel-exact against ffmpeg are counted -- a strip decoded by an
373 /// attempt that later refused proves nothing (class
374 /// gate-skips-on-its-own-failure). `--enable-1to4-partitions=1` is the
375 /// tool switch; `--min-partition-size=16` keeps the RD search from
376 /// recursing below 16x16, where several other unlanded partition shapes
377 /// live.
378 #[test]
379 fn a_real_aomenc_stream_with_a_superblock_level_1to4_partition_decodes_pixel_exact() {
380 const NAME: &str =
381 "a_real_aomenc_stream_with_a_superblock_level_1to4_partition_decodes_pixel_exact";
382 let _gate_lock = lock_gate_counters();
383 if !have_ffmpeg() {
384 eprintln!("SKIP {NAME}: no ffmpeg");
385 return;
386 }
387 if !have_aomenc() {
388 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
389 return;
390 }
391 let (width, height, frame_count) = (192usize, 128usize, 1usize);
392 let mut named_refusals = 0u32;
393 let mut matched = 0u32;
394 let (mut horz_proved, mut vert_proved) = (0usize, 0usize);
395 let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32);
396 let n_attempts: u32 = std::env::var("EC_TX64X16_GATE_ATTEMPTS")
397 .ok()
398 .and_then(|s| s.parse().ok())
399 .unwrap_or(40);
400 for attempt in 0..n_attempts {
401 let seed = 42 + attempt;
402 let duration = frame_count as f64 / 25.0;
403 // Odd attempts render the SAME generator rotated 90 degrees
404 // (generated at height x width, then `transpose`), because
405 // aomenc's RD picks `PARTITION_VERT_4` on this content and
406 // essentially never `HORZ_4`: the two arms are a transposed
407 // pair, and a gate that only ever sees one of them cannot catch
408 // a transposed scan/context table (class scan-weights-cross-axis).
409 let source = if attempt % 2 == 0 {
410 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
411 } else {
412 format!(
413 "{},transpose=1",
414 gradients_source(seed, height, width, &format!("duration={duration}:rate=25"))
415 )
416 };
417 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
418 .args([
419 "-v",
420 "error",
421 "-f",
422 "lavfi",
423 "-i",
424 &source,
425 "-pix_fmt",
426 "yuv420p",
427 "-f",
428 "yuv4mpegpipe",
429 "-",
430 ])
431 .stdin(Stdio::null())
432 .stdout(Stdio::piped())
433 .stderr(Stdio::piped()), None, |c| c.output())
434 .expect("ffmpeg failed to run");
435 assert!(
436 y4m.status.success(),
437 "ffmpeg fixture: {}",
438 String::from_utf8_lossy(&y4m.stderr)
439 );
440 let args: Vec<&str> = vec![
441 "--codec=av1",
442 "--passes=1",
443 "--end-usage=q",
444 "--cq-level=45",
445 "--cpu-used=0",
446 "--threads=1",
447 "--row-mt=0",
448 "--sb-size=64",
449 "--enable-rect-partitions=1",
450 "--enable-ab-partitions=0",
451 "--enable-1to4-partitions=1",
452 "--min-partition-size=16",
453 "--max-partition-size=64",
454 "--enable-restoration=0",
455 "--enable-palette=0",
456 "--deltaq-mode=0",
457 "--enable-cdef=0",
458 "--enable-filter-intra=0",
459 "--enable-cfl-intra=0",
460 "--enable-intrabc=0",
461 "--enable-tx-size-search=0",
462 "--obu",
463 "-o",
464 "-",
465 "-",
466 ];
467 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
468 assert!(
469 out.status.success(),
470 "aomenc refused the fixture: {}",
471 String::from_utf8_lossy(&out.stderr)
472 );
473 let stream = out.stdout;
474 let before = (
475 crate::decode::sb_rect4_horz_hits(),
476 crate::decode::sb_rect4_vert_hits(),
477 );
478 let frames = match decode_stream(&stream) {
479 Err(e) => {
480 let msg = e.to_string();
481 assert!(
482 msg.contains("unsupported"),
483 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
484 );
485 named_refusals += 1;
486 eprintln!("seed {seed} refusal: {msg}");
487 continue;
488 }
489 Ok(frames) => frames,
490 };
491 let (horz, vert) = (
492 crate::decode::sb_rect4_horz_hits() - before.0,
493 crate::decode::sb_rect4_vert_hits() - before.1,
494 );
495 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
496 assert_eq!(frames.len(), frame_count);
497 let mismatched = frames
498 .iter()
499 .zip(&ffmpeg_frames)
500 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
501 if horz + vert == 0 {
502 // Out of this gate's territory: aomenc's RD picked no 1:4
503 // partition at all for this seed, so the attempt can neither
504 // prove nor disprove the arms under test. NOT silently
505 // dropped -- counted and printed, and a mismatch here is
506 // reported as a defect of another lane's shape (r1 found
507 // one: seed 55 of this very recipe decodes 3944 wrong luma
508 // samples with zero 1:4 blocks in the stream, first at
509 // (154, 59), inside the 64x32 `PARTITION_HORZ` superblock at
510 // (128, 64) -- see lanes/tx64x16-r1.report.md). Selecting on
511 // "the stream contains the feature", never on "the stream
512 // decoded correctly", is what keeps this from being survivor
513 // bias.
514 out_of_scope += 1;
515 if mismatched {
516 out_of_scope_mismatch += 1;
517 eprintln!(
518 "{NAME}: seed {seed} MISMATCHES with zero 1:4 blocks -- a pre-existing \
519 defect of another shape, not this gate's arms"
520 );
521 }
522 continue;
523 }
524 if mismatched
525 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
526 std::fs::write(&path, &stream).expect("writing pinned stream");
527 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
528 }
529 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
530 assert_eq!(
531 got.y, want.y,
532 "{NAME} frame {i} luma vs ffmpeg (seed {seed})"
533 );
534 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
535 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
536 }
537 horz_proved += horz;
538 vert_proved += vert;
539 matched += 1;
540 }
541 assert!(
542 matched > 0,
543 "{NAME}: every attempt refused; the gate never decoded a stream"
544 );
545 assert!(
546 horz_proved > 0 && vert_proved > 0,
547 "{NAME}: a 1:4 arm never fired inside a pixel-exact attempt \
548 (horz={horz_proved}, vert={vert_proved}, {matched} matches, {named_refusals} \
549 refusals out of {n_attempts}) -- gate proved nothing this run"
550 );
551 eprintln!(
552 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
553 {n_attempts}, horz_4 strips={horz_proved}, vert_4 strips={vert_proved}, \
554 {out_of_scope} attempts carried no 1:4 block ({out_of_scope_mismatch} of them \
555 mismatched -- other lanes' shapes)"
556 );
557 // Class gate-skips-on-its-own-failure: an attempt that decoded but
558 // does not carry this gate's shape is still a decode this crate got
559 // wrong. Counted separately so the message names the other shape,
560 // never tolerated.
561 assert_eq!(
562 out_of_scope_mismatch, 0,
563 "{NAME}: {out_of_scope_mismatch} attempt(s) with no 1:4 block decoded but \
564 mismatched ffmpeg -- a defect of another shape, not a pass"
565 );
566 }
567
568 /// lane-tx64x16 r3: the 32x32-LEVEL 1:4 pair -- `PARTITION_HORZ_4` /
569 /// `PARTITION_VERT_4` at 32x32, i.e. four 32x8 / 8x32 strips, the arm the
570 /// ReelB mid-film extract stops at ("a 32x32 partition type this
571 /// decoder does not code (value=8)"). `--min-partition-size=8` is what
572 /// lets aomenc's RD reach the 32-level 1:4 shapes; `--max-partition-size=32`
573 /// keeps the superblock-level pair (already gated by its own test above)
574 /// out of the counters. Both orientations HARD-asserted per bit depth --
575 /// the luma scans and the two new chroma scans (`SCAN_16X4`/`SCAN_4X16`)
576 /// are transposed pairs, so a one-sided gate cannot catch a transposition
577 /// (class scan-weights-cross-axis). `rect4_coeff_hits` is asserted too:
578 /// an all-skip stream would exercise none of the new coefficient tables
579 /// (class gate-blind-to-feature). Only hits earned inside an attempt that
580 /// then compared pixel-exact are counted (class
581 /// gate-skips-on-its-own-failure); the 10-bit arm is what retires
582 /// `enable-1to4-partitions` from `NEVER_EXERCISED_10BIT`.
583 /// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
584 /// 4x16 (`PARTITION_VERT_4`) strips, the shape the wall
585 /// "a 1:4 partition below 16x16" refused. Fixture: 4-PIXEL bands (the
586 /// 8-pixel ones of the 32-level gate above, one size down -- a 16x4 strip
587 /// is flat where a 16x8 one is not), transposed per attempt so a
588 /// transposed scan or nz-map table cannot pass (class
589 /// scan-weights-cross-axis), plus an explicit-seed noise layer that keeps
590 /// aomenc out of screen-content mode. `--enable-filter-intra=1` and
591 /// is ON: this shape reads `use_filter_intra` off its own CDF rows
592 /// (classes 12/13). The `--enable-tx-size-search=1` half of the window
593 /// splits the strip's transform (depth 1 = TX_8X4/TX_4X8, depth 2 =
594 /// TX_4X4).
595 ///
596 /// Counters: 16x4 strips, 4x16 strips, chroma-reference strips (the odd
597 /// strip of each 4:2:0 pair, the only one that codes chroma) and strips
598 /// with a coded residual must all be nonzero over the compared attempts,
599 /// and only attempts that DECODED and were compared pixel-exact count
600 /// (class gate-skips-on-its-own-failure).
601 #[test]
602 fn a_real_aomenc_stream_with_a_16_level_1to4_partition_decodes_pixel_exact() {
603 const NAME: &str =
604 "a_real_aomenc_stream_with_a_16_level_1to4_partition_decodes_pixel_exact";
605 let _gate_lock = lock_gate_counters();
606 if !have_ffmpeg() {
607 eprintln!("SKIP {NAME}: no ffmpeg");
608 return;
609 }
610 if !have_aomenc() {
611 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
612 return;
613 }
614 let (width, height, frame_count) = (192usize, 128usize, 1usize);
615 let n_attempts: u32 = std::env::var("EC_R14_GATE_ATTEMPTS")
616 .ok()
617 .and_then(|s| s.parse().ok())
618 .unwrap_or(8);
619 for bit_depth in [8u32, 10u32] {
620 let mut named_refusals = 0u32;
621 let mut matched = 0u32;
622 let (mut horz_proved, mut vert_proved) = (0usize, 0usize);
623 let (mut chroma_proved, mut coeff_proved) = (0usize, 0usize);
624 let mut split_proved = 0usize;
625 // lane-kf1200: chroma pairs whose intra-edge filter type comes out
626 // different when read from the PAIR's base mi (libaom's
627 // `chroma_above_mbmi`) rather than the odd strip mi -- the shape
628 // that was silently wrong by 1 on the ReelB key frames.
629 let mut pair_filt_proved = 0usize;
630 let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32);
631 // The second half of the window turns `--enable-tx-size-search` on:
632 // that is what makes a 16x4 strip SPLIT its transform (depth 1 =
633 // TX_8X4, depth 2 = TX_4X4), the arm the first half never reaches.
634 for attempt in 0..n_attempts * 2 {
635 let tx_search = attempt >= n_attempts;
636 let attempt = attempt % n_attempts;
637 let seed = 42 + attempt;
638 let duration = frame_count as f64 / 25.0;
639 let axis = if attempt.is_multiple_of(2) { "Y" } else { "X" };
640 let step = 67 + (attempt / 2) * 12;
641 let noise = 6 + (attempt % 4) * 3;
642 // lane-kf1200: the odd attempts carry CHROMA content. The
643 // original gray source leaves both chroma planes constant, so
644 // every `uv_mode` is DC and a pair's edge-filter type can never
645 // differ from its strip's -- the shape that shipped wrong for
646 // months. A smooth chroma gradient makes aomenc pick SMOOTH /
647 // directional `uv_mode`s next to each other.
648 let source = if attempt.is_multiple_of(2) {
649 format!(
650 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
651 geq=lum='mod(floor({axis}/4)*{step},256)',\
652 noise=alls={noise}:all_seed={seed},format=yuv420p"
653 )
654 } else {
655 format!(
656 "color=c=black:s={width}x{height}:d={duration}:r=25,format=yuv420p,\
657 geq=lum='mod(floor({axis}/4)*{step},256)'\
658 :cb='128+100*sin((X+Y)/23)':cr='128+100*cos(X/19)',\
659 noise=alls={noise}:all_seed={seed}"
660 )
661 };
662 let cq_level = format!("--cq-level={}", 24 + (attempt % 4) * 8);
663 let pix_fmt = if bit_depth == 10 {
664 "yuv420p10le"
665 } else {
666 "yuv420p"
667 };
668 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
669 .args([
670 "-v",
671 "error",
672 "-f",
673 "lavfi",
674 "-i",
675 &source,
676 "-t",
677 &duration.to_string(),
678 "-pix_fmt",
679 pix_fmt,
680 "-strict",
681 "-1",
682 "-f",
683 "yuv4mpegpipe",
684 "-",
685 ])
686 .stdin(Stdio::null())
687 .stdout(Stdio::piped())
688 .stderr(Stdio::piped()), None, |c| c.output())
689 .expect("ffmpeg failed to run");
690 assert!(
691 y4m.status.success(),
692 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
693 String::from_utf8_lossy(&y4m.stderr)
694 );
695 let depth_arg = format!("--bit-depth={bit_depth}");
696 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
697 let args: Vec<&str> = vec![
698 "--codec=av1",
699 "--passes=1",
700 "--end-usage=q",
701 &cq_level,
702 "--cpu-used=0",
703 "--threads=1",
704 "--row-mt=0",
705 "--sb-size=64",
706 &depth_arg,
707 &input_depth_arg,
708 "--enable-rect-partitions=1",
709 "--enable-ab-partitions=0",
710 "--enable-1to4-partitions=1",
711 "--min-partition-size=4",
712 "--max-partition-size=16",
713 "--enable-restoration=0",
714 "--enable-palette=0",
715 "--deltaq-mode=0",
716 "--enable-filter-intra=1",
717 // lane-r14: CfL stays OFF here. This shape's CfL averages
718 // the luma of the whole PAIR and is written, but no gate
719 // asserts a CfL hit counter (there is none), and passing
720 // `=1` would retire `enable-cfl-intra` from
721 // `gate_coverage::NEVER_EXERCISED_*` on a flag alone --
722 // exactly the false coverage that list exists to prevent.
723 "--enable-cfl-intra=0",
724 "--enable-intrabc=0",
725 if tx_search {
726 "--enable-tx-size-search=1"
727 } else {
728 "--enable-tx-size-search=0"
729 },
730 "--obu",
731 "-o",
732 "-",
733 "-",
734 ];
735 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
736 assert!(
737 out.status.success(),
738 "aomenc refused the fixture: {}",
739 String::from_utf8_lossy(&out.stderr)
740 );
741 let stream = out.stdout;
742 let before = crate::decode::rect4_16_counters();
743 let pair_filt_before = crate::decode::rect4_16_uv_pair_filt_hits();
744 let frames = match decode_stream(&stream) {
745 Err(e) => {
746 let msg = e.to_string();
747 assert!(
748 msg.contains("unsupported"),
749 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, seed \
750 {seed}): {msg}"
751 );
752 named_refusals += 1;
753 eprintln!("{bit_depth}-bit seed {seed} refusal: {msg}");
754 continue;
755 }
756 Ok(frames) => frames,
757 };
758 let now = crate::decode::rect4_16_counters();
759 let (horz, vert, chroma, coeff, split) = (
760 now.0 - before.0,
761 now.1 - before.1,
762 now.2 - before.2,
763 now.3 - before.3,
764 now.4 - before.4,
765 );
766 let ffmpeg_frames = if bit_depth == 10 {
767 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
768 } else {
769 ffmpeg_decode_sequence(&stream, width, height, frame_count)
770 };
771 assert_eq!(frames.len(), frame_count);
772 let mismatched = frames
773 .iter()
774 .zip(&ffmpeg_frames)
775 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
776 if horz + vert == 0 {
777 out_of_scope += 1;
778 if mismatched {
779 out_of_scope_mismatch += 1;
780 eprintln!(
781 "{NAME}: {bit_depth}-bit seed {seed} MISMATCHES with zero 16-level \
782 1:4 strips -- a pre-existing defect of another shape"
783 );
784 }
785 continue;
786 }
787 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
788 std::fs::write(&path, &stream).expect("writing pinned stream");
789 eprintln!(
790 "EC_AV1_GATE_DUMP: wrote mismatching stream ({bit_depth}-bit, seed \
791 {seed}) to {path}"
792 );
793 }
794 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
795 assert_eq!(
796 got.y, want.y,
797 "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit, seed {seed})"
798 );
799 assert_eq!(
800 got.u, want.u,
801 "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit, seed {seed})"
802 );
803 assert_eq!(
804 got.v, want.v,
805 "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit, seed {seed})"
806 );
807 }
808 horz_proved += horz;
809 vert_proved += vert;
810 chroma_proved += chroma;
811 coeff_proved += coeff;
812 pair_filt_proved += crate::decode::rect4_16_uv_pair_filt_hits() - pair_filt_before;
813 split_proved += split;
814 matched += 1;
815 }
816 assert!(
817 matched > 0,
818 "{NAME}: every {bit_depth}-bit attempt refused or fell out of scope ({named_refusals} \
819 refusals, {out_of_scope} out of scope); the gate proved nothing"
820 );
821 assert_eq!(
822 out_of_scope_mismatch, 0,
823 "{NAME}: {out_of_scope_mismatch} {bit_depth}-bit attempt(s) mismatch with no \
824 16-level 1:4 strip at all"
825 );
826 assert!(
827 horz_proved > 0 && vert_proved > 0,
828 "{NAME}: {bit_depth}-bit compared attempts decoded {horz_proved} 16x4 and \
829 {vert_proved} 4x16 strips -- both orientations must fire or a transposed table \
830 passes"
831 );
832 assert!(
833 chroma_proved > 0,
834 "{NAME}: {bit_depth}-bit compared attempts closed {chroma_proved} chroma pairs"
835 );
836 assert!(
837 coeff_proved > 0,
838 "{NAME}: {bit_depth}-bit compared attempts coded no residual on any strip"
839 );
840 assert!(
841 split_proved > 0,
842 "{NAME}: {bit_depth}-bit compared attempts never split a strip's transform -- \
843 the `--enable-tx-size-search=1` half of the window proved nothing"
844 );
845 assert!(
846 pair_filt_proved > 0,
847 "{NAME}: {bit_depth}-bit compared attempts never decoded a chroma pair whose \
848 edge-filter type differs between the pair's base mi and the strip's own mi -- \
849 the lane-kf1200 fix is unexercised, so this gate would pass with it reverted"
850 );
851 eprintln!(
852 "{NAME}: {bit_depth}-bit {matched} compared attempts, {horz_proved} 16x4 / \
853 {vert_proved} 4x16 strips, {chroma_proved} chroma pairs, {coeff_proved} coded \
854 units, {split_proved} split-transform strips, {pair_filt_proved} pair-base \
855 filt-type flips, {named_refusals} refusals, {out_of_scope} out of scope"
856 );
857 }
858 }
859
860 #[test]
861 // lane-tx64x16 r4: the fixture r3 could not find. `gradients` never wins
862 // a 32-level 1:4 shape; 8-pixel BANDS do -- each 32x8 strip is flat, so
863 // HORZ_4 beats both HORZ (two bands per 32x16) and SPLIT, while the noise
864 // layer keeps aomenc out of screen-content mode. Measured 16 HORZ_4 / 24
865 // VERT_4 strips per frame, both bit depths (lanes/tx64x16-r4.report.md).
866 fn a_real_aomenc_stream_with_a_32x32_level_1to4_partition_decodes_pixel_exact() {
867 const NAME: &str =
868 "a_real_aomenc_stream_with_a_32x32_level_1to4_partition_decodes_pixel_exact";
869 let _gate_lock = lock_gate_counters();
870 if !have_ffmpeg() {
871 eprintln!("SKIP {NAME}: no ffmpeg");
872 return;
873 }
874 if !have_aomenc() {
875 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
876 return;
877 }
878 let (width, height, frame_count) = (192usize, 128usize, 1usize);
879 let n_attempts: u32 = std::env::var("EC_TX64X16_GATE32_ATTEMPTS")
880 .ok()
881 .and_then(|s| s.parse().ok())
882 .unwrap_or(8);
883 for bit_depth in [8u32, 10u32] {
884 let mut named_refusals = 0u32;
885 let mut matched = 0u32;
886 let (mut horz_proved, mut vert_proved, mut coeff_proved) = (0usize, 0usize, 0usize);
887 let (mut depth1_proved, mut depth2_proved) = (0usize, 0usize);
888 let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32);
889 // lane-rectsplitx r1: the SECOND half of the attempt window turns
890 // `--enable-tx-size-search` ON at low cq, which is what makes a
891 // 32-level 1:4 strip SPLIT its transform -- depth 1 is the 2:1
892 // rect unit TX_16X8/TX_8X16 (`sub_tx_size_map[TX_32X8]`), depth 2
893 // the square TX_8X8, and the two interleave across attempts, so
894 // both are asserted (a depth-2-only run leaves the rect-unit path
895 // unproved).
896 for attempt in 0..n_attempts * 2 {
897 let tx_search = attempt >= n_attempts;
898 let attempt = attempt % n_attempts;
899 let seed = 42 + attempt;
900 let duration = frame_count as f64 / 25.0;
901 // 8-pixel bands: a 32x8 strip is flat, a 32x16 one is not, so
902 // aomenc's RD picks HORZ_4 (bands across Y) / VERT_4 (bands
903 // across X). Odd attempts are the transposed source -- the
904 // transposed-pair discipline the superblock-level 1:4 gate
905 // above documents, and the only way a transposed scan table is
906 // caught (class scan-weights-cross-axis). The noise layer is
907 // what keeps the flat bands out of screen-content mode; its
908 // seed is explicit, never lavfi's ignored default.
909 let axis = if attempt.is_multiple_of(2) { "Y" } else { "X" };
910 let step = 67 + (attempt / 2) * 12;
911 let noise = 6 + (attempt % 4) * 3;
912 let source = format!(
913 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
914 geq=lum='mod(floor({axis}/8)*{step},256)',\
915 noise=alls={noise}:all_seed={seed},format=yuv420p"
916 );
917 // lane-band63: the second cq is 63, not 45 -- a near-max
918 // quantiser is where deblock/CDEF do the most work and where a
919 // 1:4 strip is most often skip; all 16 streams of this family at
920 // cq 63 (8- and 10-bit) decode pixel-exact.
921 let cq_level = if tx_search {
922 // 12..28: the window measured to fire both split depths on
923 // this fixture (lanes/tx64x16-r4.handoff.md).
924 format!("--cq-level={}", 12 + (attempt % 4) * 5)
925 } else {
926 format!("--cq-level={}", if attempt % 4 < 2 { 32 } else { 63 })
927 };
928 let pix_fmt = if bit_depth == 10 {
929 "yuv420p10le"
930 } else {
931 "yuv420p"
932 };
933 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
934 .args([
935 "-v",
936 "error",
937 "-f",
938 "lavfi",
939 "-i",
940 &source,
941 "-t",
942 &duration.to_string(),
943 "-pix_fmt",
944 pix_fmt,
945 "-strict",
946 "-1",
947 "-f",
948 "yuv4mpegpipe",
949 "-",
950 ])
951 .stdin(Stdio::null())
952 .stdout(Stdio::piped())
953 .stderr(Stdio::piped()), None, |c| c.output())
954 .expect("ffmpeg failed to run");
955 assert!(
956 y4m.status.success(),
957 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
958 String::from_utf8_lossy(&y4m.stderr)
959 );
960 let depth_arg = format!("--bit-depth={bit_depth}");
961 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
962 let args: Vec<&str> = vec![
963 "--codec=av1",
964 "--passes=1",
965 "--end-usage=q",
966 &cq_level,
967 "--cpu-used=0",
968 "--threads=1",
969 "--row-mt=0",
970 "--sb-size=64",
971 &depth_arg,
972 &input_depth_arg,
973 "--enable-rect-partitions=1",
974 "--enable-ab-partitions=0",
975 "--enable-1to4-partitions=1",
976 "--min-partition-size=8",
977 "--max-partition-size=32",
978 "--enable-restoration=0",
979 "--enable-palette=0",
980 "--deltaq-mode=0",
981 "--enable-filter-intra=0",
982 "--enable-cfl-intra=0",
983 "--enable-intrabc=0",
984 if tx_search {
985 "--enable-tx-size-search=1"
986 } else {
987 "--enable-tx-size-search=0"
988 },
989 "--obu",
990 "-o",
991 "-",
992 "-",
993 ];
994 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
995 assert!(
996 out.status.success(),
997 "aomenc refused the fixture: {}",
998 String::from_utf8_lossy(&out.stderr)
999 );
1000 let stream = out.stdout;
1001 let before = (
1002 crate::decode::rect4_32_horz_hits(),
1003 crate::decode::rect4_32_vert_hits(),
1004 crate::decode::rect4_coeff_hits(),
1005 );
1006 let split_before = crate::decode::rect4_split_depth_hits();
1007 let frames = match decode_stream(&stream) {
1008 Err(e) => {
1009 let msg = e.to_string();
1010 assert!(
1011 msg.contains("unsupported"),
1012 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, seed \
1013 {seed}): {msg}"
1014 );
1015 named_refusals += 1;
1016 eprintln!("{bit_depth}-bit seed {seed} refusal: {msg}");
1017 continue;
1018 }
1019 Ok(frames) => frames,
1020 };
1021 let (horz, vert, coeff) = (
1022 crate::decode::rect4_32_horz_hits() - before.0,
1023 crate::decode::rect4_32_vert_hits() - before.1,
1024 crate::decode::rect4_coeff_hits() - before.2,
1025 );
1026 let split_now = crate::decode::rect4_split_depth_hits();
1027 let (d1, d2) = (split_now.0 - split_before.0, split_now.1 - split_before.1);
1028 let ffmpeg_frames = if bit_depth == 10 {
1029 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1030 } else {
1031 ffmpeg_decode_sequence(&stream, width, height, frame_count)
1032 };
1033 assert_eq!(frames.len(), frame_count);
1034 let mismatched = frames
1035 .iter()
1036 .zip(&ffmpeg_frames)
1037 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1038 if horz + vert == 0 {
1039 // Out of this gate's territory (no 32-level 1:4 block in
1040 // the stream): counted and printed, never silently
1041 // dropped, and a mismatch here is another shape's defect.
1042 out_of_scope += 1;
1043 if mismatched {
1044 out_of_scope_mismatch += 1;
1045 eprintln!(
1046 "{NAME}: {bit_depth}-bit seed {seed} MISMATCHES with zero 32-level \
1047 1:4 blocks -- a pre-existing defect of another shape"
1048 );
1049 }
1050 continue;
1051 }
1052 if mismatched
1053 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
1054 std::fs::write(&path, &stream).expect("writing pinned stream");
1055 eprintln!(
1056 "EC_AV1_GATE_DUMP: wrote mismatching stream ({bit_depth}-bit, seed \
1057 {seed}) to {path}"
1058 );
1059 }
1060 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1061 assert_eq!(
1062 got.y, want.y,
1063 "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit, seed {seed})"
1064 );
1065 assert_eq!(
1066 got.u, want.u,
1067 "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit, seed {seed})"
1068 );
1069 assert_eq!(
1070 got.v, want.v,
1071 "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit, seed {seed})"
1072 );
1073 }
1074 horz_proved += horz;
1075 vert_proved += vert;
1076 coeff_proved += coeff;
1077 depth1_proved += d1;
1078 depth2_proved += d2;
1079 matched += 1;
1080 }
1081 assert!(
1082 matched > 0,
1083 "{NAME}: every {bit_depth}-bit attempt refused; the gate never decoded a stream"
1084 );
1085 assert!(
1086 horz_proved > 0 && vert_proved > 0,
1087 "{NAME}: a 32-level 1:4 arm never fired inside a pixel-exact {bit_depth}-bit \
1088 attempt (horz={horz_proved}, vert={vert_proved}, {matched} matches, \
1089 {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run"
1090 );
1091 assert!(
1092 coeff_proved > 0,
1093 "{NAME}: every {bit_depth}-bit 32-level 1:4 strip was skip -- the 32x8/16x4 \
1094 coefficient tables were never read"
1095 );
1096 eprintln!(
1097 "{NAME}: {bit_depth}-bit: {named_refusals} named refusals, {matched} pixel-exact \
1098 matches out of {n_attempts}, horz_4 strips={horz_proved}, vert_4 \
1099 strips={vert_proved}, coded strips={coeff_proved}, {out_of_scope} attempts \
1100 carried no 32-level 1:4 block ({out_of_scope_mismatch} mismatched)"
1101 );
1102 // The split-transform halves of the window: both tx depths must
1103 // have fired inside an attempt that then compared pixel-exact
1104 // (class counter-from-refused-stream -- a global counter would
1105 // count strips of attempts that later refused).
1106 // lane-rectsplitx r2: BOTH depths are now decoded, so both are
1107 // HARD-asserted -- depth 1 is the 2:1 rect unit
1108 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square
1109 // TX_8X8, and they interleave across the window; a run that only
1110 // reached one of them proves half the walk.
1111 assert!(
1112 depth1_proved > 0 && depth2_proved > 0,
1113 "{NAME}: {bit_depth}-bit: a 1:4 split-transform depth never fired inside a \
1114 pixel-exact attempt (depth1={depth1_proved}, depth2={depth2_proved}) -- the \
1115 tx-size-search half of the window proved nothing"
1116 );
1117 eprintln!(
1118 "{NAME}: {bit_depth}-bit split-transform 1:4 strips: depth1={depth1_proved}, \
1119 depth2={depth2_proved}"
1120 );
1121 assert_eq!(
1122 out_of_scope_mismatch, 0,
1123 "{NAME}: {bit_depth}-bit: {out_of_scope_mismatch} attempt(s) with zero 32-level \
1124 1:4 blocks decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
1125 );
1126 }
1127 }
1128
1129 /// lane-fi32x8 r1 (class symbol-consumption-gap): the 32x32-level 1:4
1130 /// strips (32x8/8x32) are inside `av1_filter_intra_allowed_bsize`'s
1131 /// "both sides <= 32" bound, so libaom reads a `use_filter_intra` flag on
1132 /// every DC_PRED one of them -- and `--enable-filter-intra` is ON by
1133 /// aomenc default, so the sibling gate above (which spells it `=0`) could
1134 /// never see it. `filter_intra_size_class_rect` had no row for either
1135 /// shape, so the symbol was never read and the tile desynced silently
1136 /// from that strip on. Same band fixture as the sibling (8-px bands +
1137 /// seeded noise, both orientations), the ONLY recipe change being
1138 /// `--enable-filter-intra=1` appended AFTER the base recipe (aomenc keeps
1139 /// the LAST occurrence of a repeated `--enable-*` flag). The counter is
1140 /// this shape's OWN (`filter_intra_rect4_hits`), not the shared rect one,
1141 /// so a filter-intra 16x8 strip elsewhere in the frame cannot stand in
1142 /// for it; only hits earned inside an attempt that then compared
1143 /// pixel-exact are counted (class gate-skips-on-its-own-failure), and
1144 /// both bit depths are asserted independently.
1145 ///
1146 /// `--enable-tx-size-search=0` is kept from the sibling recipe: a 1:4
1147 /// strip with `tx_depth != 0` is still refused by name ("a 32x32-level
1148 /// 1:4 strip with a split transform"), so a search-on arm would only
1149 /// harvest refusals, not coverage -- filter intra is proven at depth 0
1150 /// here and the per-TU case belongs to the round that lifts that refusal.
1151 #[test]
1152 fn a_real_aomenc_stream_with_filter_intra_on_a_32_level_1to4_strip_decodes_pixel_exact() {
1153 const NAME: &str =
1154 "a_real_aomenc_stream_with_filter_intra_on_a_32_level_1to4_strip_decodes_pixel_exact";
1155 let _gate_lock = lock_gate_counters();
1156 if !have_ffmpeg() {
1157 eprintln!("SKIP {NAME}: no ffmpeg");
1158 return;
1159 }
1160 if !have_aomenc() {
1161 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1162 return;
1163 }
1164 let (width, height, frame_count) = (192usize, 128usize, 1usize);
1165 let n_attempts: u32 = std::env::var("EC_FI32X8_GATE_ATTEMPTS")
1166 .ok()
1167 .and_then(|s| s.parse().ok())
1168 // 16, not 12 (measured, r1): the first attempt whose VERT_4
1169 // (8x32) strips pick filter intra at 8 bit is attempt 13.
1170 .unwrap_or(16);
1171 for bit_depth in [8u32, 10u32] {
1172 let mut named_refusals = 0u32;
1173 let mut matched = 0u32;
1174 let (mut fi_horz_proved, mut fi_vert_proved, mut strips_proved) =
1175 (0usize, 0usize, 0usize);
1176 let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32);
1177 for attempt in 0..n_attempts {
1178 let seed = 42 + attempt;
1179 let duration = frame_count as f64 / 25.0;
1180 let axis = if attempt % 2 == 0 { "Y" } else { "X" };
1181 let step = 67 + (attempt / 2) * 12;
1182 // A HEAVIER noise layer than the sibling gate's 6..15 (lane-fi32x8 r1,
1183 // measured): filter intra is what aomenc reaches for when a flat
1184 // band is noisy, so at 6..15 the flag fired on a 1:4 strip in 3 of
1185 // 40 8-bit attempts and in NONE of 40 10-bit ones, while at 18..27
1186 // it fires in most attempts at BOTH depths.
1187 let noise = 18 + (attempt % 4) * 3;
1188 let source = format!(
1189 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
1190 geq=lum='mod(floor({axis}/8)*{step},256)',\
1191 noise=alls={noise}:all_seed={seed},format=yuv420p"
1192 );
1193 // lane-band63: 63 joins the rotation -- filter intra ON at a
1194 // near-max quantiser is exactly the configuration the stale
1195 // cq-63 premise blamed, and it decodes exact.
1196 let cq_level = format!(
1197 "--cq-level={}",
1198 [32, 45, 55, 63][(attempt / 2 % 4) as usize]
1199 );
1200 let pix_fmt = if bit_depth == 10 {
1201 "yuv420p10le"
1202 } else {
1203 "yuv420p"
1204 };
1205 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1206 .args([
1207 "-v",
1208 "error",
1209 "-f",
1210 "lavfi",
1211 "-i",
1212 &source,
1213 "-t",
1214 &duration.to_string(),
1215 "-pix_fmt",
1216 pix_fmt,
1217 "-strict",
1218 "-1",
1219 "-f",
1220 "yuv4mpegpipe",
1221 "-",
1222 ])
1223 .stdin(Stdio::null())
1224 .stdout(Stdio::piped())
1225 .stderr(Stdio::piped()), None, |c| c.output())
1226 .expect("ffmpeg failed to run");
1227 assert!(
1228 y4m.status.success(),
1229 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1230 String::from_utf8_lossy(&y4m.stderr)
1231 );
1232 let depth_arg = format!("--bit-depth={bit_depth}");
1233 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1234 let args: Vec<&str> = vec![
1235 "--codec=av1",
1236 "--passes=1",
1237 "--end-usage=q",
1238 &cq_level,
1239 "--cpu-used=0",
1240 "--threads=1",
1241 "--row-mt=0",
1242 "--sb-size=64",
1243 &depth_arg,
1244 &input_depth_arg,
1245 "--enable-rect-partitions=1",
1246 "--enable-ab-partitions=0",
1247 "--enable-1to4-partitions=1",
1248 "--min-partition-size=8",
1249 "--max-partition-size=32",
1250 "--enable-restoration=0",
1251 "--enable-palette=0",
1252 "--deltaq-mode=0",
1253 "--enable-cfl-intra=0",
1254 "--enable-intrabc=0",
1255 "--enable-tx-size-search=0",
1256 // The competing intra modes off (lane-fi32x8 r1): with
1257 // directional/paeth/smooth intra available, aomenc's RD
1258 // picks filter intra on a 32x8 strip in only ~3 of 40
1259 // attempts at 8 bit and NEVER at 10 bit (measured, see the
1260 // r1 report), so this shape's own symbol would go
1261 // unexercised at 10 bit. Leaving DC and filter intra as
1262 // the block's luma intra choices makes the flag fire
1263 // without weakening the gate: every decoded frame is
1264 // still compared to ffmpeg in full.
1265 "--enable-directional-intra=0",
1266 "--enable-paeth-intra=0",
1267 "--enable-smooth-intra=0",
1268 // THE override, last (aomenc keeps the last occurrence).
1269 "--enable-filter-intra=1",
1270 "--obu",
1271 "-o",
1272 "-",
1273 "-",
1274 ];
1275 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1276 assert!(
1277 out.status.success(),
1278 "aomenc refused the fixture: {}",
1279 String::from_utf8_lossy(&out.stderr)
1280 );
1281 let stream = out.stdout;
1282 let before = (
1283 crate::decode::filter_intra_rect4_horz_hits(),
1284 crate::decode::filter_intra_rect4_vert_hits(),
1285 crate::decode::rect4_32_horz_hits() + crate::decode::rect4_32_vert_hits(),
1286 );
1287 let frames = match decode_stream(&stream) {
1288 Err(e) => {
1289 let msg = e.to_string();
1290 assert!(
1291 msg.contains("unsupported"),
1292 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, seed \
1293 {seed}): {msg}"
1294 );
1295 named_refusals += 1;
1296 eprintln!("{bit_depth}-bit seed {seed} refusal: {msg}");
1297 continue;
1298 }
1299 Ok(frames) => frames,
1300 };
1301 let (fi_horz, fi_vert, strips) = (
1302 crate::decode::filter_intra_rect4_horz_hits() - before.0,
1303 crate::decode::filter_intra_rect4_vert_hits() - before.1,
1304 crate::decode::rect4_32_horz_hits() + crate::decode::rect4_32_vert_hits()
1305 - before.2,
1306 );
1307 let fi = fi_horz + fi_vert;
1308 let ffmpeg_frames = if bit_depth == 10 {
1309 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1310 } else {
1311 ffmpeg_decode_sequence(&stream, width, height, frame_count)
1312 };
1313 assert_eq!(frames.len(), frame_count);
1314 let mismatched = frames
1315 .iter()
1316 .zip(&ffmpeg_frames)
1317 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1318 // Per-attempt line (opt-in): which (seed, cq, axis, noise)
1319 // actually made aomenc pick filter intra ON a 1:4 strip is
1320 // exactly what a re-tune of this fixture needs, and it is not
1321 // recoverable from the summary.
1322 if std::env::var_os("EC_FI32X8_VERBOSE").is_some() {
1323 eprintln!(
1324 "{NAME}: {bit_depth}-bit seed {seed} {cq_level} axis={axis} noise={noise} \
1325 fi={fi_horz}+{fi_vert} strips={strips} mismatched={mismatched}"
1326 );
1327 }
1328 if fi == 0 {
1329 out_of_scope += 1;
1330 if mismatched {
1331 out_of_scope_mismatch += 1;
1332 eprintln!(
1333 "{NAME}: {bit_depth}-bit seed {seed} MISMATCHES with zero \
1334 filter-intra 1:4 strips ({strips} plain 1:4 strips) -- a defect of \
1335 another shape"
1336 );
1337 }
1338 continue;
1339 }
1340 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1341 assert_eq!(
1342 got.y, want.y,
1343 "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit, seed {seed})"
1344 );
1345 assert_eq!(
1346 got.u, want.u,
1347 "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit, seed {seed})"
1348 );
1349 assert_eq!(
1350 got.v, want.v,
1351 "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit, seed {seed})"
1352 );
1353 }
1354 fi_horz_proved += fi_horz;
1355 fi_vert_proved += fi_vert;
1356 strips_proved += strips;
1357 matched += 1;
1358 }
1359 // BOTH orientations, per bit depth: rows 8/9 of `cdf::FILTER_INTRA`
1360 // are asymmetric (18101 for 32x8, 20229 for 8x32), so a one-sided
1361 // assert would pass on a transposed pair.
1362 assert!(
1363 fi_horz_proved > 0 && fi_vert_proved > 0 && matched > 0,
1364 "{NAME}: a 32x8/8x32 strip orientation never read use_filter_intra=1 inside a \
1365 pixel-exact {bit_depth}-bit attempt (32x8={fi_horz_proved}, \
1366 8x32={fi_vert_proved}, {matched} matches, {named_refusals} refusals, \
1367 {out_of_scope} attempts with no filter-intra 1:4 strip, out of {n_attempts}) \
1368 -- gate proved nothing this run"
1369 );
1370 eprintln!(
1371 "{NAME}: {bit_depth}-bit: {named_refusals} named refusals, {matched} pixel-exact \
1372 matches out of {n_attempts}, filter-intra 1:4 strips={fi_horz_proved}x(32x8)+{fi_vert_proved}x(8x32) of \
1373 {strips_proved} 1:4 strips, {out_of_scope} attempts carried none \
1374 ({out_of_scope_mismatch} mismatched)"
1375 );
1376 assert_eq!(
1377 out_of_scope_mismatch, 0,
1378 "{NAME}: {bit_depth}-bit: {out_of_scope_mismatch} attempt(s) with zero \
1379 filter-intra 1:4 strips decoded but mismatched ffmpeg -- a defect of another \
1380 shape, not a pass"
1381 );
1382 }
1383 }
1384
1385 #[test]
1386 fn a_real_aomenc_multi_tile_intra_stream_decodes_pixel_exact() {
1387 const NAME: &str = "a_real_aomenc_multi_tile_intra_stream_decodes_pixel_exact";
1388 let before = crate::decode::uv_tile_edge_suppressed_hits();
1389 run_multi_tile_gate(NAME, 1, 1, 8, 1, &[], false, None);
1390 // lane-mtfix r1: this is the only arm with a tile ROW boundary, so it
1391 // is the one that exercises the tile-relative guard on the chroma
1392 // edge-filter neighbour. Without the guard, seed 46's first block of
1393 // the bottom-right tile read the tile ABOVE it and mis-filtered its
1394 // chroma edge (U/V off by 1..2 over chroma x[120..127] y[32..37]).
1395 if have_ffmpeg() && have_aomenc() {
1396 assert!(
1397 crate::decode::uv_tile_edge_suppressed_hits() > before,
1398 "{NAME}: no chroma edge-filter neighbour read was suppressed at a tile edge -- \
1399 the tile-relative guard is untested by this gate"
1400 );
1401 }
1402 }
1403
1404 /// lane-kf900 r1: a SKIPPED 8x8 intra leaf whose `tx_depth` symbol
1405 /// resolved to TX_4X4 must publish 4 -- not its 8-px block side -- to the
1406 /// next block's `get_tx_size_context` (libaom `set_txfm_ctxs(mbmi->tx_size,
1407 /// ..., skip_txfm && is_inter_block(mbmi), xd)`; that skip term is always 0
1408 /// for an intra block). `decode_leaf8`'s tail wrote the literal 8, so the
1409 /// rect strip below such a leaf read `tx_size_cat1` row 2 where libaom
1410 /// reads row 1 -- same alphabet, wrong CDF row, the msac range diverged
1411 /// mid-frame with NO refusal. `skip_split_tx_hits` was `pub` and asserted
1412 /// by no gate at all before this one (class `tool-disabled-in-every-gate`).
1413 #[test]
1414 fn a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_decodes_pixel_exact() {
1415 const NAME: &str =
1416 "a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_decodes_pixel_exact";
1417 crate::decode::reset_skip_split_tx_hits();
1418 run_multi_tile_gate(NAME, 0, 0, 8, 1, &[], false, None);
1419 // lane-kf900 r2: the counter assert that used to sit here is
1420 // UNREACHABLE from aomenc. 108 measured recipes (72 at 8-bit, 36 at
1421 // 10-bit: `geq` half-flat/half-noise, `mandelbrot`, `testsrc2`,
1422 // `noise=all_seed=49`, cq 55/59/63, `--cpu-used=0..2`,
1423 // `--enable-tx-size-search=1 --min-partition-size=8
1424 // --enable-rect-partitions=1`; log
1425 // `$HOME/.cache/kf900/sweep/results{,10}.tsv`) produced
1426 // `skip_split_tx_hits() == 0` on every stream that decoded, because
1427 // libaom's own encoder forces `tx_size` to the block maximum once it
1428 // decides `skip_txfm` -- so no aomenc stream carries a SKIPPED 8x8
1429 // intra leaf whose `tx_depth` resolved to `TX_4X4`. The film's
1430 // encoder does; the counter is hard-asserted on the real stream in
1431 // [`a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact`].
1432 // These two arms stay as the pixel-exact multi-tile control.
1433 }
1434
1435 /// [`a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_decodes_pixel_exact`]'s
1436 /// 10-bit arm -- the film that exposed the defect is yuv420p10le.
1437 #[test]
1438 fn a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_10bit_decodes_pixel_exact()
1439 {
1440 const NAME: &str = "a_real_aomenc_stream_with_a_skipped_8x8_intra_leaf_whose_tx_split_10bit_decodes_pixel_exact";
1441 crate::decode::reset_skip_split_tx_hits();
1442 run_multi_tile_gate(NAME, 0, 0, 10, 1, &[], false, None);
1443 // lane-kf900 r2: the counter assert that used to sit here is
1444 // UNREACHABLE from aomenc. 108 measured recipes (72 at 8-bit, 36 at
1445 // 10-bit: `geq` half-flat/half-noise, `mandelbrot`, `testsrc2`,
1446 // `noise=all_seed=49`, cq 55/59/63, `--cpu-used=0..2`,
1447 // `--enable-tx-size-search=1 --min-partition-size=8
1448 // --enable-rect-partitions=1`; log
1449 // `$HOME/.cache/kf900/sweep/results{,10}.tsv`) produced
1450 // `skip_split_tx_hits() == 0` on every stream that decoded, because
1451 // libaom's own encoder forces `tx_size` to the block maximum once it
1452 // decides `skip_txfm` -- so no aomenc stream carries a SKIPPED 8x8
1453 // intra leaf whose `tx_depth` resolved to `TX_4X4`. The film's
1454 // encoder does; the counter is hard-asserted on the real stream in
1455 // [`a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact`].
1456 // These two arms stay as the pixel-exact multi-tile control.
1457 }
1458
1459 #[test]
1460 fn a_real_aomenc_multi_tile_intra_10bit_stream_decodes_pixel_exact() {
1461 run_multi_tile_gate(
1462 "a_real_aomenc_multi_tile_intra_10bit_stream_decodes_pixel_exact",
1463 2,
1464 0,
1465 10,
1466 1,
1467 &[],
1468 false,
1469 None,
1470 );
1471 }
1472
1473 /// lane-t900 r19, the defect this arm exists for, now FIXED: spec 5.11.2
1474 /// `decode_tile` resets `RefLrWiener`/`RefSgrXqd` (the running
1475 /// loop-restoration coefficient reference) to the midpoint filter at the
1476 /// top of EVERY tile; `decode.rs` declared that state once per frame, so
1477 /// every tile after the first decoded its Wiener/Sgrproj coefficients off
1478 /// the previous tile's reference. The symbol COUNT is unchanged, so
1479 /// entropy and reconstruction stayed byte-exact and only the filtered
1480 /// pixels moved -- at seed 44 frame 0 (the key frame) the whole right tile
1481 /// column, luma x[128..255] y[0..91], 1330 samples off by at most 2, with
1482 /// chroma exact. Ladder that named it: `EC_AV1_PREFILT_DUMP` exact,
1483 /// `EC_AV1_POSTDEBLOCK_DUMP` exact, `EC_AV1_POSTCDEF_DUMP` exact (that
1484 /// last rung added to the oracle's `decodeframe.c` in this round), so the
1485 /// only remaining stage was loop restoration.
1486 #[test]
1487 fn a_real_aomenc_multi_tile_inter_stream_decodes_pixel_exact() {
1488 run_multi_tile_gate(
1489 "a_real_aomenc_multi_tile_inter_stream_decodes_pixel_exact",
1490 1,
1491 1,
1492 8,
1493 16,
1494 // Pre-existing, non-tile decoder limits this lane does not own:
1495 // the inter path only recurses a superblock as SPLIT (so the SB
1496 // level must be forced to split) and never reads a `tx_depth`
1497 // symbol under `TxMode::Select`. Both are named refusals in
1498 // `refusal_inventory.rs`; without these two flags every inter
1499 // attempt refuses before a single tile edge is compared.
1500 &["--max-partition-size=32", "--enable-tx-size-search=0"],
1501 false,
1502 None,
1503 );
1504 }
1505
1506 /// lane-tiles r11, the defect this arm exists for: `palette_ctx_and_cache`
1507 /// / `palette_uv_cache` (`decode.rs`) read the LEFT palette neighbour with
1508 /// no availability guard at all, where libaom's `av1_get_palette_cache`
1509 /// takes `xd->left_mbmi`, which is NULL at the block's own TILE left
1510 /// column. A second tile column therefore inherited the previous tile's
1511 /// palette colours and `palette_y_mode` ctx. Screen content is what makes
1512 /// aomenc pick palette at all, so this arm drives `--tune-content=screen
1513 /// --enable-palette=1` over a 2-column grid and asserts a real palette
1514 /// block actually fired.
1515 /// `#[ignore]`d at r11 and NOT yet proof of the fix: with the broad tool
1516 /// set every seed refuses before a palette block reconstructs
1517 /// ("a HORZ_A/HORZ_B/VERT_A partition below 16x16"), and the per-arm
1518 /// `extra` overrides do not switch the base recipe's tools off -- aomenc
1519 /// keeps the FIRST occurrence of a repeated `--enable-*` flag (measured:
1520 /// appending `--enable-rect-partitions=0` after the base `=1` changed the
1521 /// refusal not at all). Next round: put `extra` BEFORE the base list in
1522 /// `run_multi_tile_gate`'s args, then this arm should reach a palette
1523 /// block on smptebars with rect/ab off.
1524 #[test]
1525 fn a_real_aomenc_multi_tile_palette_stream_decodes_pixel_exact() {
1526 const NAME: &str = "a_real_aomenc_multi_tile_palette_stream_decodes_pixel_exact";
1527 let before = crate::decode::palette_hits();
1528 run_multi_tile_gate(
1529 NAME,
1530 1,
1531 0,
1532 8,
1533 1,
1534 &[
1535 "--enable-palette=1",
1536 "--tune-content=screen",
1537 "--cq-level=30",
1538 "--enable-tx-size-search=0",
1539 "--max-partition-size=32",
1540 // Screen content + rect strips is a separate, pre-existing
1541 // refusal ("palette syntax is consumed for square blocks
1542 // only"); this arm owns the palette CACHE at a tile edge, so
1543 // it takes the square-only path the other palette gates take.
1544 "--enable-rect-partitions=0",
1545 "--enable-ab-partitions=0",
1546 ],
1547 true,
1548 Some("smptebars"),
1549 );
1550 if have_ffmpeg() && have_aomenc() {
1551 assert!(
1552 crate::decode::palette_hits() > before,
1553 "{NAME}: no palette block fired -- the gate proves nothing about the palette \
1554 cache at a tile edge"
1555 );
1556 }
1557 }
1558
1559 #[test]
1560 fn a_real_aomenc_multi_tile_inter_10bit_stream_decodes_pixel_exact() {
1561 run_multi_tile_gate(
1562 "a_real_aomenc_multi_tile_inter_10bit_stream_decodes_pixel_exact",
1563 2,
1564 0,
1565 10,
1566 16,
1567 // Pre-existing, non-tile decoder limits this lane does not own:
1568 // the inter path only recurses a superblock as SPLIT (so the SB
1569 // level must be forced to split) and never reads a `tx_depth`
1570 // symbol under `TxMode::Select`. Both are named refusals in
1571 // `refusal_inventory.rs`; without these two flags every inter
1572 // attempt refuses before a single tile edge is compared.
1573 &["--max-partition-size=32", "--enable-tx-size-search=0"],
1574 false,
1575 None,
1576 );
1577 }
1578
1579 /// lane-rectchroma r1: a real `aomenc` stream in which a HORZ/VERT strip
1580 /// splits its transform (`--enable-tx-size-search` left ON) and whose
1581 /// chroma half is one of the four rect shapes that had NO coefficient
1582 /// tables in [`crate::decode`] before this round -- 32x8 / 8x32 (the 1:4
1583 /// superblock strips 64x16 / 16x64) and 8x4 / 4x8 (the 8x16 / 16x8 rect
1584 /// of a 16x16-level AB partition). Every such strip refused by name
1585 /// ("a coded HORZ/VERT strip whose chroma transform has no rect
1586 /// coefficient tables here"), which is where both ReelC extracts stopped.
1587 ///
1588 /// Per-shape counters, deltas taken only over attempts that then compared
1589 /// pixel-exact (class counter-from-refused-stream), on 8 AND 10 bit (his
1590 /// films are `yuv420p10le`). Odd seeds render the source transposed so
1591 /// the 32x8/8x32 and 8x4/4x8 pairs both fire -- a single-orientation
1592 /// sweep cannot catch a transposed scan table (class
1593 /// scan-weights-cross-axis).
1594 #[test]
1595 fn a_real_aomenc_stream_with_a_coded_strip_whose_chroma_is_a_4to1_or_sub8_rect_decodes_pixel_exact()
1596 {
1597 const NAME: &str = "a_real_aomenc_stream_with_a_coded_strip_whose_chroma_is_a_4to1_or_sub8_rect_decodes_pixel_exact";
1598 // No seed is excluded any more: seed 46's cq-32 mismatch was the
1599 // per-transform-unit reach (lane-band46 / palette2 r12), and the pin
1600 // below decodes it pixel-exact at both depths.
1601 const EXCLUDED_SEEDS: &[u32] = &[];
1602 let _gate_lock = lock_gate_counters();
1603 if !have_ffmpeg() {
1604 eprintln!("SKIP {NAME}: no ffmpeg");
1605 return;
1606 }
1607 if !have_aomenc() {
1608 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1609 return;
1610 }
1611 let (width, height) = (192usize, 128usize);
1612 let n_attempts: u32 = std::env::var("EC_RECTCHROMA_GATE_ATTEMPTS")
1613 .ok()
1614 .and_then(|s| s.parse().ok())
1615 .unwrap_or(20);
1616 // 32x8, 8x32, 8x4, 4x8, summed over both bit depths.
1617 let mut proved = [0usize; 4];
1618 let mut matched = 0u32;
1619 let mut refusals = 0u32;
1620 // Diagnostics: how much of the territory the COMPARED streams carried
1621 // at all, so a zero above reads as "recipe picked nothing" rather
1622 // than "the shape never split" without another run.
1623 let (mut split_strips, mut rect4_strips) = (0usize, 0usize);
1624 let mut all_rect4 = 0usize;
1625 // Asserted separately: this is the gate that takes `enable-1to4-
1626 // partitions` off `gate_coverage::NEVER_EXERCISED_10BIT`, so the
1627 // 10-bit half has to carry the shape on its own.
1628 let mut rect4_strips_10bit = 0usize;
1629 let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32);
1630 // 1:4 strips whose transform splits ONCE (the unit is still a 2:1
1631 // rect) that decoded and compared pixel-exact. Until the rectsplitx
1632 // merge this shape was refused by name and the gate counted the
1633 // REFUSALS; counting the decoded hits instead keeps the same
1634 // territory claim now that the capability landed (class
1635 // counter-from-refused-stream: only attempts that compared exact
1636 // count).
1637 let mut depth1_decoded = 0usize;
1638 for (bit_depth, cq) in [
1639 (8u32, 45u32),
1640 (8, 32),
1641 (8, 60),
1642 (10, 45),
1643 (10, 32),
1644 (10, 60),
1645 ] {
1646 for attempt in 0..n_attempts {
1647 let seed = 42 + attempt;
1648 if EXCLUDED_SEEDS.contains(&seed) {
1649 continue;
1650 }
1651 let stream = rectchroma_stream(bit_depth, cq, attempt, width, height);
1652 let before = crate::decode::rect_split_chroma_shape_hits();
1653 let split_before = crate::decode::rect_split_tx_hits();
1654 let depth1_before = crate::decode::rect4_split_depth_hits().0;
1655 let rect4_before = (
1656 crate::decode::sb_rect4_horz_hits(),
1657 crate::decode::sb_rect4_vert_hits(),
1658 );
1659 let frames = match decode_stream(&stream) {
1660 Err(e) => {
1661 let msg = e.to_string();
1662 assert!(
1663 msg.contains("unsupported"),
1664 "{NAME} failed outright, not a named refusal ({bit_depth}-bit seed \
1665 {seed}): {msg}"
1666 );
1667 refusals += 1;
1668 all_rect4 += (crate::decode::sb_rect4_horz_hits() - rect4_before.0)
1669 + (crate::decode::sb_rect4_vert_hits() - rect4_before.1);
1670 let r4 = (crate::decode::sb_rect4_horz_hits() - rect4_before.0)
1671 + (crate::decode::sb_rect4_vert_hits() - rect4_before.1);
1672 eprintln!(
1673 "{NAME}: {bit_depth}-bit cq {cq} seed {seed} refusal (1:4 strips so \
1674 far {r4}): {msg}"
1675 );
1676 continue;
1677 }
1678 Ok(frames) => frames,
1679 };
1680 let after = crate::decode::rect_split_chroma_shape_hits();
1681 if (0..4).any(|k| after[k] > before[k]) {
1682 eprintln!(
1683 "{NAME}: {bit_depth}-bit cq {cq} seed {seed} carries chroma shapes \
1684 32x8={} 8x32={} 8x4={} 4x8={}",
1685 after[0] - before[0],
1686 after[1] - before[1],
1687 after[2] - before[2],
1688 after[3] - before[3]
1689 );
1690 }
1691 let rect4_now = (crate::decode::sb_rect4_horz_hits() - rect4_before.0)
1692 + (crate::decode::sb_rect4_vert_hits() - rect4_before.1);
1693 // The ENCODE's frame count: `rectchroma_stream` (42059) renders
1694 // `duration=0.04:rate=25` (42082) with `-t 0.04` (42094) -- one
1695 // frame -- and its aomenc runs with no `--limit`, so every
1696 // attempt's stream codes exactly 1 frame at both depths.
1697 assert_eq!(
1698 frames.len(),
1699 1,
1700 "{NAME}: {bit_depth}-bit cq {cq} seed {seed} key frame"
1701 );
1702 let reference = if bit_depth == 10 {
1703 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
1704 } else {
1705 ffmpeg_decode_sequence(&stream, width, height, frames.len())
1706 };
1707 assert_eq!(frames.len(), reference.len(), "{NAME}: frame count");
1708 if rect4_now == 0 {
1709 // Out of this gate's territory (same rule the sibling
1710 // superblock-1:4 gate applies): aomenc picked no 1:4
1711 // strip at all, so the attempt can neither prove nor
1712 // disprove this round's shape. Counted and PRINTED, never
1713 // silently dropped -- selection is on "the stream carries
1714 // the feature", never on "the stream decoded correctly".
1715 out_of_scope += 1;
1716 if frames
1717 .iter()
1718 .zip(&reference)
1719 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
1720 {
1721 out_of_scope_mismatch += 1;
1722 eprintln!(
1723 "{NAME}: {bit_depth}-bit cq {cq} seed {seed} MISMATCHES with zero \
1724 1:4 strips -- a pre-existing defect of another shape, not this \
1725 gate's arms"
1726 );
1727 }
1728 continue;
1729 }
1730 for (i, (got, want)) in frames.iter().zip(&reference).enumerate() {
1731 assert_eq!(
1732 got.y, want.y,
1733 "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit cq {cq} seed {seed})"
1734 );
1735 assert_eq!(
1736 got.u, want.u,
1737 "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit cq {cq} seed {seed})"
1738 );
1739 assert_eq!(
1740 got.v, want.v,
1741 "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit cq {cq} seed {seed})"
1742 );
1743 }
1744 for k in 0..4 {
1745 proved[k] += after[k] - before[k];
1746 }
1747 split_strips += crate::decode::rect_split_tx_hits() - split_before;
1748 depth1_decoded += crate::decode::rect4_split_depth_hits().0 - depth1_before;
1749 let rect4 = (crate::decode::sb_rect4_horz_hits() - rect4_before.0)
1750 + (crate::decode::sb_rect4_vert_hits() - rect4_before.1);
1751 rect4_strips += rect4;
1752 if bit_depth == 10 {
1753 rect4_strips_10bit += rect4;
1754 }
1755 matched += 1;
1756 }
1757 }
1758 eprintln!(
1759 "{NAME}: {matched} pixel-exact matches, {refusals} named refusals out of \
1760 {} attempts; chroma shapes proved 32x8={} 8x32={} 8x4={} 4x8={}; compared \
1761 streams carried {split_strips} split-transform strips and {rect4_strips} \
1762 superblock 1:4 strips ({all_rect4} more in refused streams); {out_of_scope} \
1763 attempts carried no 1:4 strip ({out_of_scope_mismatch} of them mismatched -- \
1764 other shapes' defects)",
1765 6 * n_attempts,
1766 proved[0],
1767 proved[1],
1768 proved[2],
1769 proved[3]
1770 );
1771 assert_eq!(
1772 out_of_scope_mismatch, 0,
1773 "{NAME}: {out_of_scope_mismatch} attempts carrying no 1:4 strip mismatched \
1774 ffmpeg -- a defect of another shape, not out of scope for the suite (the one \
1775 known case, seed 46, was the per-TU reach and is fixed)"
1776 );
1777 assert!(
1778 matched > 0,
1779 "{NAME}: every attempt refused; the gate never decoded a stream"
1780 );
1781 assert!(
1782 rect4_strips_10bit > 0,
1783 "{NAME}: no superblock 1:4 strip in any pixel-exact 10-BIT stream -- this gate is \
1784 what claims 10-bit coverage for enable-1to4-partitions"
1785 );
1786 assert!(
1787 rect4_strips > 0,
1788 "{NAME}: no superblock 1:4 strip in any pixel-exact stream -- recipe lost its \
1789 territory, gate proved nothing this run"
1790 );
1791 // r1's actual capability delta. Before this round a 1:4 strip whose
1792 // transform depth is 1 was decoded as if its units were SQUARE
1793 // (`bw.min(bh) >> (depth - 1)`), because `sub_tx_size_map[TX_64X16]`
1794 // is TX_32X16, a 2:1 RECT, not TX_16X16 -- 8-bit cq 45 seed 42 of
1795 // this very recipe decoded 2 such strips and MISMATCHED ffmpeg on
1796 // frame 0 luma. It is now refused by name (rect luma transform units
1797 // inside a split strip are unported; the chroma half's 32x8/8x32
1798 // tables this round wired are in place for it). This assert is what
1799 // keeps that from silently regressing to a wrong-pixel decode.
1800 assert!(
1801 depth1_decoded > 0,
1802 "{NAME}: no attempt decoded a depth-1 1:4 split strip -- the recipe no longer \
1803 covers the shape this round fixed"
1804 );
1805 }
1806
1807 /// PIN for the stream the chroma-rect gate used to exclude: cq 32 seed 46
1808 /// mismatched ffmpeg at BOTH bit depths while carrying zero 1:4 strips.
1809 /// The defect was the per-transform-unit intra reach (lane-band46 /
1810 /// palette2 r12); un-ignored 2026-09-02 once it decoded pixel-exact.
1811 #[test]
1812 fn the_chroma_rect_gates_excluded_seed_46_decodes_pixel_exact() {
1813 const NAME: &str = "the_chroma_rect_gates_excluded_seed_46_decodes_pixel_exact";
1814 let _gate_lock = lock_gate_counters();
1815 if !have_ffmpeg() {
1816 eprintln!("SKIP {NAME}: no ffmpeg");
1817 return;
1818 }
1819 if !have_aomenc() {
1820 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1821 return;
1822 }
1823 let (width, height) = (192usize, 128usize);
1824 // seed 46 == attempt 4 of the gate's sweep, cq 32.
1825 for bit_depth in [8u32, 10] {
1826 let stream = rectchroma_stream(bit_depth, 32, 4, width, height);
1827 let frames = decode_stream(&stream)
1828 .unwrap_or_else(|e| panic!("{NAME}: {bit_depth}-bit seed 46 refused: {e}"));
1829 // The ENCODE's frame count: `rectchroma_stream` (42059) renders
1830 // `duration=0.04:rate=25` (42082) with `-t 0.04` (42094) -- one frame
1831 // -- and its aomenc runs with no `--limit`, so the stream codes
1832 // exactly 1 frame at both depths. Asserted ABOVE the oracle call.
1833 assert_eq!(frames.len(), 1, "{NAME}: {bit_depth}-bit seed 46 key frame");
1834 let reference = if bit_depth == 10 {
1835 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
1836 } else {
1837 ffmpeg_decode_sequence(&stream, width, height, frames.len())
1838 };
1839 assert_eq!(frames.len(), reference.len(), "{NAME}: frame count");
1840 for (i, (got, want)) in frames.iter().zip(&reference).enumerate() {
1841 assert_eq!(
1842 got.y, want.y,
1843 "{NAME} frame {i} luma ({bit_depth}-bit seed 46)"
1844 );
1845 assert_eq!(
1846 got.u, want.u,
1847 "{NAME} frame {i} U ({bit_depth}-bit seed 46)"
1848 );
1849 assert_eq!(
1850 got.v, want.v,
1851 "{NAME} frame {i} V ({bit_depth}-bit seed 46)"
1852 );
1853 }
1854 }
1855 }
1856
1857 /// lane-band46 r1: a real `aomenc` band stream whose 16x16 (and 8x8)
1858 /// intra blocks SPLIT their transform, so every unit but the first
1859 /// answers `has_top_right`/`has_bottom_left` from its `row_off`/`col_off`
1860 /// inside the parent block rather than from the standalone-block tables
1861 /// (libaom `reconintra.c`; class reach-is-per-transform-unit).
1862 ///
1863 /// Seed 46 of the sibling 1:4-strip recipe is the stream that found it:
1864 /// it carries ZERO 1:4 strips, so that gate skipped it as out of scope
1865 /// while frame 0 luma mismatched ffmpeg over 916 samples -- the first at
1866 /// (x 14, y 18), the second 8x8 transform unit of the D203_PRED block at
1867 /// mi (4, 0), whose bottom-left samples sit in a unit that is not
1868 /// reconstructed yet (`col_off > 0` => `has_bottom_left` is 0). The full
1869 /// mode-info range ladder matched aomdec element for element, so the
1870 /// defect was reconstruction, never entropy.
1871 ///
1872 /// The gate asserts the fix FIRED (`split_tu_reach_fix_hits`, transform
1873 /// units whose reach differs from the old standalone answer) on 8 AND 10
1874 /// bit, and that seed 46 itself decodes pixel-exact.
1875 #[test]
1876 fn a_real_aomenc_band_stream_seed46_decodes_pixel_exact() {
1877 const NAME: &str = "a_real_aomenc_band_stream_seed46_decodes_pixel_exact";
1878 let _gate_lock = lock_gate_counters();
1879 if !have_ffmpeg() {
1880 eprintln!("SKIP {NAME}: no ffmpeg");
1881 return;
1882 }
1883 if !have_aomenc() {
1884 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1885 return;
1886 }
1887 let (width, height) = (192usize, 128usize);
1888 let mut matched = 0u32;
1889 let mut refusals = 0u32;
1890 let mut fixed_tus = 0usize;
1891 let mut fixed_tus_10bit = 0usize;
1892 let mut seed46_compared = [false; 2];
1893 for (di, bit_depth) in [8u32, 10].into_iter().enumerate() {
1894 let pix_fmt = if bit_depth == 10 {
1895 "yuv420p10le"
1896 } else {
1897 "yuv420p"
1898 };
1899 for seed in 42u32..=51 {
1900 // Byte-identical recipe to the 1:4-strip sibling gate, whose
1901 // seed-46 attempt is what exposed this defect (that gate
1902 // classes a no-1:4 stream as out of scope; this one compares
1903 // it).
1904 let bands = format!(
1905 "geq=lum='mod(floor(Y/16),2)*160+48':cb=128:cr=128,noise=alls=10:all_seed={seed}"
1906 );
1907 let source = if seed % 2 == 0 {
1908 format!("color=c=black:size={width}x{height}:duration=0.04:rate=25,{bands}")
1909 } else {
1910 format!(
1911 "color=c=black:size={height}x{width}:duration=0.04:rate=25,{bands},transpose=1"
1912 )
1913 };
1914 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1915 .args([
1916 "-v",
1917 "error",
1918 "-f",
1919 "lavfi",
1920 "-i",
1921 &source,
1922 "-t",
1923 "0.04",
1924 "-pix_fmt",
1925 pix_fmt,
1926 "-strict",
1927 "-1",
1928 "-f",
1929 "yuv4mpegpipe",
1930 "-",
1931 ])
1932 .stdin(Stdio::null())
1933 .stdout(Stdio::piped())
1934 .stderr(Stdio::piped()), None, |c| c.output())
1935 .expect("ffmpeg failed to run");
1936 assert!(
1937 y4m.status.success(),
1938 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1939 String::from_utf8_lossy(&y4m.stderr)
1940 );
1941 let depth_arg = format!("--bit-depth={bit_depth}");
1942 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1943 let out = run_with_stdin(
1944 Command::new(aomenc_path()).args([
1945 "--codec=av1",
1946 "--passes=1",
1947 "--end-usage=q",
1948 "--cq-level=32",
1949 "--cpu-used=0",
1950 "--threads=1",
1951 "--row-mt=0",
1952 "--sb-size=64",
1953 &depth_arg,
1954 &input_depth_arg,
1955 "--enable-rect-partitions=1",
1956 "--enable-ab-partitions=0",
1957 "--enable-1to4-partitions=1",
1958 "--min-partition-size=16",
1959 "--max-partition-size=64",
1960 // Left ON: this is what makes a 16x16 block code four
1961 // 8x8 transform units, the shape the fix is about.
1962 "--enable-tx-size-search=1",
1963 "--enable-restoration=0",
1964 "--enable-palette=0",
1965 "--deltaq-mode=0",
1966 "--enable-filter-intra=0",
1967 "--enable-cfl-intra=0",
1968 "--enable-intrabc=0",
1969 "--obu",
1970 "-o",
1971 "-",
1972 "-",
1973 ]),
1974 &y4m.stdout,
1975 );
1976 assert!(
1977 out.status.success(),
1978 "{NAME}: aomenc refused the fixture: {}",
1979 String::from_utf8_lossy(&out.stderr)
1980 );
1981 let stream = out.stdout;
1982 let before = crate::decode::split_tu_reach_fix_hits();
1983 let frames = match decode_stream(&stream) {
1984 Err(e) => {
1985 let msg = e.to_string();
1986 assert!(
1987 msg.contains("unsupported"),
1988 "{NAME} failed outright, not a named refusal ({bit_depth}-bit seed \
1989 {seed}): {msg}"
1990 );
1991 assert!(
1992 seed != 46,
1993 "{NAME}: seed 46 ({bit_depth}-bit) must decode -- it is this gate's \
1994 pinned stream, and it refused: {msg}"
1995 );
1996 refusals += 1;
1997 eprintln!("{NAME}: {bit_depth}-bit seed {seed} refusal: {msg}");
1998 continue;
1999 }
2000 Ok(frames) => frames,
2001 };
2002 // The ENCODE's frame count: `duration=0.04:rate=25` (42263) is
2003 // one frame and `-t 0.04` (42277) caps the y4m there, and aomenc
2004 // runs with no `--limit` -- so every arm (both depths, all 10
2005 // seeds) codes exactly 1 frame. Asserted ABOVE the oracle call.
2006 assert_eq!(
2007 frames.len(),
2008 1,
2009 "{NAME}: {bit_depth}-bit seed {seed} key frame"
2010 );
2011 let reference = if bit_depth == 10 {
2012 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
2013 } else {
2014 ffmpeg_decode_sequence(&stream, width, height, frames.len())
2015 };
2016 assert_eq!(frames.len(), reference.len(), "{NAME}: frame count");
2017 for (i, (got, want)) in frames.iter().zip(&reference).enumerate() {
2018 assert_eq!(
2019 got.y, want.y,
2020 "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit seed {seed})"
2021 );
2022 assert_eq!(
2023 got.u, want.u,
2024 "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit seed {seed})"
2025 );
2026 assert_eq!(
2027 got.v, want.v,
2028 "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit seed {seed})"
2029 );
2030 }
2031 let fixed = crate::decode::split_tu_reach_fix_hits() - before;
2032 fixed_tus += fixed;
2033 if bit_depth == 10 {
2034 fixed_tus_10bit += fixed;
2035 }
2036 if seed == 46 {
2037 seed46_compared[di] = true;
2038 }
2039 matched += 1;
2040 }
2041 }
2042 eprintln!(
2043 "{NAME}: {matched} pixel-exact streams, {refusals} named refusals out of 20; \
2044 {fixed_tus} split transform units took the per-TU reach ({fixed_tus_10bit} of them \
2045 10-bit)"
2046 );
2047 assert!(
2048 seed46_compared[0] && seed46_compared[1],
2049 "{NAME}: seed 46 was not compared on both depths (8-bit {}, 10-bit {})",
2050 seed46_compared[0],
2051 seed46_compared[1]
2052 );
2053 assert!(
2054 fixed_tus > 0,
2055 "{NAME}: no split transform unit answered its reach from its offset inside the \
2056 parent block -- the recipe lost the shape this gate pins"
2057 );
2058 assert!(
2059 fixed_tus_10bit > 0,
2060 "{NAME}: the shape never appeared in a 10-BIT pixel-exact stream (his films are \
2061 yuv420p10le)"
2062 );
2063 }
2064
2065 /// lane-hgkf r1: a frame whose height (or width) is not a multiple of the
2066 /// block size makes the last superblock row (column) read a GATHERED
2067 /// partition bit instead of a full alphabet symbol -- and libaom's
2068 /// `ec_read_partition_impl` answers that bit with `PARTITION_HORZ`
2069 /// (resp. `VERT`) when it is 0, only `SPLIT` when it is 1. All three
2070 /// key-frame edge readers (64-, 32- and 16-level) read the bit and threw
2071 /// it away, forcing SPLIT; every such frame desynced at the first block
2072 /// of its partial row. 192x136 / 136x192 is the smallest shape that hits
2073 /// all three levels at once (136 = 2*64 + 8, so mi_rows = 34: the 64-,
2074 /// 32- and 16-level halves all fall outside), and it is the shape of a
2075 /// real 3840x1608 10-bit film key frame (1608 mod 64 == 8) that decoded
2076 /// 51768 samples wrong before this round.
2077 ///
2078 /// The counter is sampled per attempt and read only on an attempt that
2079 /// decoded AND is pixel-compared; slot 0/2 (the bit taken as HORZ/VERT)
2080 /// must be nonzero or the gate proves nothing -- before this round that
2081 /// arm was unreachable by construction.
2082 #[test]
2083 fn a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact() {
2084 const NAME: &str =
2085 "a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact";
2086 let _gate_lock = lock_gate_counters();
2087 if !have_ffmpeg() {
2088 eprintln!("SKIP {NAME}: no ffmpeg");
2089 return;
2090 }
2091 if !have_aomenc() {
2092 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2093 return;
2094 }
2095 let mut compared = 0usize;
2096 let mut edge_horz_total = 0usize;
2097 let mut edge_sub_total = 0usize;
2098 let mut skip_split_tx_total = 0usize;
2099 // The last two shapes are the ledger-measured 64-level pair: on a
2100 // flat band (192x80 / 80x192) real aomenc answers the bottom-edge
2101 // superblock with the 64-level HORZ/VERT, which the 136 shapes above
2102 // never produce (their SBs always split down to the 32/16 levels).
2103 // lane-kf1200 r3: the 2-/4-/6-mi partial bottom rows (h mod 64 == 8,
2104 // 16, 24) with partial RIGHT columns as well (w mod 64 == 8), the
2105 // geometry of the film key frames this lane chases.
2106 for (width, height, flat) in [
2107 (192usize, 136usize, false),
2108 (136usize, 192usize, false),
2109 (192usize, 80usize, true),
2110 (80usize, 192usize, true),
2111 (200usize, 72usize, false),
2112 (136usize, 88usize, false),
2113 (264usize, 104usize, false),
2114 ] {
2115 // lane-kf1200 r3 (class `tool-disabled-in-every-gate`): the whole
2116 // recipe ran with `--enable-tx-size-search=0`, so no block ever
2117 // carried a nonzero `tx_depth` and the SKIPPED 8x8 leaf that
2118 // resolves to TX_4X4 -- whose txfm context this round fixed --
2119 // was unreachable by construction. The second arm turns it on.
2120 for tx_search in [0usize, 1] {
2121 for depth in [8usize, 10] {
2122 let pix = if depth == 10 {
2123 "yuv420p10le"
2124 } else {
2125 "yuv420p"
2126 };
2127 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2128 .args([
2129 "-v",
2130 "error",
2131 "-f",
2132 "lavfi",
2133 "-i",
2134 &if flat {
2135 format!("color=c=gray:size={width}x{height}")
2136 } else {
2137 format!("mandelbrot=size={width}x{height}:start_x=-0.6")
2138 },
2139 "-pix_fmt",
2140 pix,
2141 "-strict",
2142 "-1",
2143 "-t",
2144 "1",
2145 "-vframes",
2146 "1",
2147 "-f",
2148 "yuv4mpegpipe",
2149 "-",
2150 ])
2151 .stdin(Stdio::null())
2152 .stdout(Stdio::piped())
2153 .stderr(Stdio::piped()), None, |c| c.output())
2154 .expect("ffmpeg failed to run");
2155 assert!(
2156 y4m.status.success(),
2157 "{NAME}: ffmpeg fixture ({width}x{height}, depth={depth}): {}",
2158 String::from_utf8_lossy(&y4m.stderr)
2159 );
2160 let encode = || {
2161 let out = run_with_stdin(
2162 Command::new(aomenc_path()).args([
2163 "--codec=av1",
2164 "--passes=1",
2165 "--end-usage=q",
2166 "--cq-level=32",
2167 "--cpu-used=3",
2168 "--threads=1",
2169 "--row-mt=0",
2170 "--sb-size=64",
2171 "--kf-max-dist=0",
2172 "--enable-rect-partitions=1",
2173 "--enable-ab-partitions=0",
2174 "--enable-1to4-partitions=0",
2175 &format!("--enable-tx-size-search={tx_search}"),
2176 "--reduced-tx-type-set=1",
2177 "--min-partition-size=8",
2178 "--max-partition-size=64",
2179 &format!("--input-bit-depth={depth}"),
2180 &format!("--bit-depth={depth}"),
2181 "--obu",
2182 "-o",
2183 "-",
2184 "-",
2185 ]),
2186 &y4m.stdout,
2187 );
2188 assert!(
2189 out.status.success(),
2190 "aomenc refused the fixture ({width}x{height}, depth={depth}): {}",
2191 String::from_utf8_lossy(&out.stderr)
2192 );
2193 out.stdout
2194 };
2195 let stream = encode();
2196 assert_eq!(
2197 stream,
2198 encode(),
2199 "{NAME}: aomenc output is not reproducible ({width}x{height}, depth={depth})"
2200 );
2201 crate::decode::reset_edge_part_hits();
2202 crate::decode::reset_skip_split_tx_hits();
2203 let frames = match decode_stream(&stream) {
2204 Ok(frames) => frames,
2205 Err(e) => {
2206 let msg = e.to_string();
2207 assert!(
2208 msg.contains("unsupported"),
2209 "{NAME}: decode failed ({width}x{height}, depth={depth}): {msg}"
2210 );
2211 eprintln!(
2212 "{NAME}: {width}x{height} depth={depth} arm refused (not compared): {msg}"
2213 );
2214 continue;
2215 }
2216 };
2217 let hits = crate::decode::edge_part_hits();
2218 let skip_split_tx = crate::decode::skip_split_tx_hits();
2219 // The ENCODE's frame count: `-t 1` AND `-vframes 1` (42490)
2220 // cap the y4m at one frame and aomenc is given that one frame
2221 // with no `--limit`, so every arm's stream holds exactly 1
2222 // coded frame. Asserted ABOVE the oracle call so a decode that
2223 // dropped it reds naming the encode.
2224 assert_eq!(
2225 frames.len(),
2226 1,
2227 "{NAME}: {width}x{height} depth={depth} key frame"
2228 );
2229 let ffmpeg_frames = if depth == 10 {
2230 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
2231 } else {
2232 ffmpeg_decode_sequence(&stream, width, height, frames.len())
2233 };
2234 assert_eq!(
2235 ffmpeg_frames.len(),
2236 frames.len(),
2237 "{NAME}: ffmpeg frame count"
2238 );
2239 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2240 assert_eq!(
2241 got.y, want.y,
2242 "{NAME} frame {i} luma vs ffmpeg ({width}x{height}, depth={depth}, \
2243 edge bits horz/split 64-level {}/{}, sub-level {}/{})",
2244 hits[0], hits[1], hits[2], hits[3]
2245 );
2246 assert_eq!(
2247 got.u, want.u,
2248 "{NAME} frame {i} U vs ffmpeg ({width}x{height}, depth={depth})"
2249 );
2250 assert_eq!(
2251 got.v, want.v,
2252 "{NAME} frame {i} V vs ffmpeg ({width}x{height}, depth={depth})"
2253 );
2254 }
2255 compared += 1;
2256 edge_horz_total += hits[0];
2257 edge_sub_total += hits[2];
2258 skip_split_tx_total += skip_split_tx;
2259 eprintln!(
2260 "{NAME}: pixel-exact {width}x{height} at {depth}-bit tx_search={tx_search}, \
2261 edge bits 64-level horz/vert={} split={} sub-level horz/vert={} split={}, \
2262 skipped 8x8 leaves with TX_4X4 {skip_split_tx}",
2263 hits[0], hits[1], hits[2], hits[3]
2264 );
2265 }
2266 }
2267 }
2268 assert!(
2269 compared > 0,
2270 "{NAME}: every arm refused -- the gate compared no pixels at all"
2271 );
2272 assert!(
2273 edge_horz_total > 0,
2274 "{NAME}: no 64-level frame-edge bit was ever answered HORZ/VERT -- the arm this \
2275 round fixed never fired"
2276 );
2277 assert!(
2278 edge_sub_total > 0,
2279 "{NAME}: no 32/16-level frame-edge bit was ever answered HORZ/VERT"
2280 );
2281 // lane-kf1200 r3: the `--enable-tx-size-search=1` half of the window
2282 // exists so a partial-row block can carry a nonzero `tx_depth` at all
2283 // (the whole recipe ran with it OFF before -- class
2284 // `tool-disabled-in-every-gate`). The SKIPPED 8x8 leaf that resolves
2285 // to TX_4X4 -- whose txfm context this round fixed -- is NOT reachable
2286 // from any synthetic source measured here (80 recipes, all zero), so
2287 // that arm is asserted by the pinned film fixture
2288 // `the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact`
2289 // instead; this counter is reported, not gated.
2290 eprintln!(
2291 "{NAME}: {skip_split_tx_total} skipped 8x8 TX_4X4 leaves across compared attempts"
2292 );
2293 }
2294
2295 /// lane-rectchroma2 r1, the defect this gate exists for: our inter path
2296 /// predicts a RECTANGULAR block over its enclosing SQUARE buffer
2297 /// (`side`x`side`, `chroma_side`x`chroma_side` -- see
2298 /// [`crate::decode`]'s `write_w`/`write_h` corner-cut), and
2299 /// [`crate::mc::predict_with_filters`] took libaom's narrow-block 4-tap
2300 /// decision from that buffer's dimensions. libaom
2301 /// (`av1_get_interp_filter_params_with_block_size`, called per axis from
2302 /// `inter_predictor` with `w` then `h`) takes it from the PREDICTION
2303 /// block's own dimensions, so an 8x16 / 16x8 inter block -- whose chroma
2304 /// is 4x8 / 8x4 -- must use the 4-tap kernel on the short axis. Luma is
2305 /// never <= 4 wide here, which is exactly why every such stream decoded
2306 /// LUMA EXACT and differed by +-1 on scattered chroma samples of those
2307 /// blocks (lane-interedge r1's 192x128 control, a size with no frame-edge
2308 /// node at all).
2309 ///
2310 /// Full-plane (Y+U+V) compare of EVERY decode-order frame
2311 /// (`--lag-in-frames=0`), both orientations (192x128 and its transposed
2312 /// twin, so the 4x8 and 8x4 chroma shapes both fire -- class
2313 /// `scan-weights-cross-axis`), 8 AND 10 bit (his films are yuv420p10le),
2314 /// cq 20/32/45, CDEF and loop restoration left ON. The counter is reset
2315 /// per attempt and read only on an attempt that decoded and compared
2316 /// (class `counter-from-refused-stream`); it counts predictions whose
2317 /// kernel choice DIFFERS from what the square buffer would have given, so
2318 /// a zero means the recipe lost the shape this gate pins.
2319 #[test]
2320 fn a_real_aomenc_rect_inter_block_predicts_chroma_with_the_narrow_kernel_pixel_exact() {
2321 const NAME: &str =
2322 "a_real_aomenc_rect_inter_block_predicts_chroma_with_the_narrow_kernel_pixel_exact";
2323 let _gate_lock = lock_gate_counters();
2324 if !have_ffmpeg() {
2325 eprintln!("SKIP {NAME}: no ffmpeg");
2326 return;
2327 }
2328 if !have_aomenc() {
2329 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2330 return;
2331 }
2332 const FRAMES: usize = 6;
2333 let mut compared = 0usize;
2334 let mut narrow_by_depth = [0usize; 2];
2335 let mut narrow_by_shape = [0usize; 2];
2336 for (si, (width, height)) in [(192usize, 128usize), (128usize, 192usize)]
2337 .into_iter()
2338 .enumerate()
2339 {
2340 for (di, depth) in [8usize, 10].into_iter().enumerate() {
2341 let pix = if depth == 10 {
2342 "yuv420p10le"
2343 } else {
2344 "yuv420p"
2345 };
2346 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2347 .args([
2348 "-v",
2349 "error",
2350 "-f",
2351 "lavfi",
2352 "-i",
2353 &format!("mandelbrot=size={width}x{height}:rate=25"),
2354 "-pix_fmt",
2355 pix,
2356 "-strict",
2357 "-1",
2358 "-vframes",
2359 &FRAMES.to_string(),
2360 "-f",
2361 "yuv4mpegpipe",
2362 "-",
2363 ])
2364 .stdin(Stdio::null())
2365 .stdout(Stdio::piped())
2366 .stderr(Stdio::piped()), None, |c| c.output())
2367 .expect("ffmpeg failed to run");
2368 assert!(
2369 y4m.status.success(),
2370 "{NAME}: ffmpeg fixture ({width}x{height}, depth={depth}): {}",
2371 String::from_utf8_lossy(&y4m.stderr)
2372 );
2373 for cq in [20usize, 32, 45] {
2374 let encode = || {
2375 let out = run_with_stdin(
2376 Command::new(aomenc_path()).args([
2377 "--codec=av1",
2378 "--passes=1",
2379 "--end-usage=q",
2380 &format!("--cq-level={cq}"),
2381 "--cpu-used=4",
2382 "--threads=1",
2383 "--row-mt=0",
2384 "--kf-max-dist=9999",
2385 &format!("--limit={FRAMES}"),
2386 "--lag-in-frames=0",
2387 &format!("--bit-depth={depth}"),
2388 &format!("--input-bit-depth={depth}"),
2389 // Rect partitions ON is the whole point; every
2390 // other tool below is another lane's open gap
2391 // that would refuse before a pixel compare.
2392 "--enable-rect-partitions=1",
2393 "--enable-ab-partitions=0",
2394 "--enable-1to4-partitions=0",
2395 "--min-partition-size=8",
2396 "--max-partition-size=64",
2397 "--enable-palette=0",
2398 "--enable-intrabc=0",
2399 "--enable-warped-motion=0",
2400 "--enable-obmc=0",
2401 "--enable-masked-comp=0",
2402 "--enable-interintra-comp=0",
2403 "--enable-onesided-comp=0",
2404 "--enable-interintra-wedge=0",
2405 "--enable-smooth-interintra=0",
2406 "--enable-ref-frame-mvs=0",
2407 "--enable-angle-delta=0",
2408 "--enable-cfl-intra=0",
2409 "--enable-directional-intra=0",
2410 "--enable-smooth-intra=0",
2411 "--enable-paeth-intra=0",
2412 "--enable-filter-intra=0",
2413 "--enable-tx-size-search=0",
2414 "--obu",
2415 "-o",
2416 "-",
2417 "-",
2418 ]),
2419 &y4m.stdout,
2420 );
2421 assert!(
2422 out.status.success(),
2423 "aomenc refused the fixture ({width}x{height}, depth={depth}, \
2424 cq={cq}): {}",
2425 String::from_utf8_lossy(&out.stderr)
2426 );
2427 out.stdout
2428 };
2429 let stream = encode();
2430 assert_eq!(
2431 stream,
2432 encode(),
2433 "{NAME}: aomenc output is not reproducible ({width}x{height}, \
2434 depth={depth}, cq={cq})"
2435 );
2436 crate::mc::reset_rect_narrow_kern_hits();
2437 let frames = match decode_stream(&stream) {
2438 Ok(frames) => frames,
2439 Err(e) => {
2440 let msg = e.to_string();
2441 assert!(
2442 msg.contains("unsupported"),
2443 "{NAME}: decode failed ({width}x{height}, depth={depth}, \
2444 cq={cq}): {msg}"
2445 );
2446 eprintln!(
2447 "{NAME}: {width}x{height} depth={depth} cq={cq} arm refused \
2448 (not compared): {msg}"
2449 );
2450 continue;
2451 }
2452 };
2453 let narrow = crate::mc::rect_narrow_kern_hits();
2454 // The ENCODE's frame count, asserted ABOVE the oracle call, not
2455 // our decode's length: `-vframes {FRAMES}` (42696) feeds aomenc
2456 // exactly FRAMES frames and `--limit={FRAMES}` (42724) caps its
2457 // output there. A decode that dropped a frame must red HERE,
2458 // naming the encode, rather than hand the same short count to
2459 // ffmpeg and let the helper's byte-length assert blame ffmpeg.
2460 assert_eq!(
2461 frames.len(),
2462 FRAMES,
2463 "{NAME}: not every coded frame was decoded ({width}x{height}, \
2464 depth={depth}, cq={cq})"
2465 );
2466 let ffmpeg_frames = if depth == 10 {
2467 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
2468 } else {
2469 ffmpeg_decode_sequence(&stream, width, height, frames.len())
2470 };
2471 assert_eq!(
2472 ffmpeg_frames.len(),
2473 frames.len(),
2474 "{NAME}: ffmpeg frame count ({width}x{height}, depth={depth}, cq={cq})"
2475 );
2476 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2477 assert_eq!(
2478 got.y, want.y,
2479 "{NAME} frame {i} luma vs ffmpeg ({width}x{height}, depth={depth}, \
2480 cq={cq}, narrow-kernel hits {narrow})"
2481 );
2482 assert_eq!(
2483 got.u, want.u,
2484 "{NAME} frame {i} U vs ffmpeg ({width}x{height}, depth={depth}, \
2485 cq={cq}, narrow-kernel hits {narrow})"
2486 );
2487 assert_eq!(
2488 got.v, want.v,
2489 "{NAME} frame {i} V vs ffmpeg ({width}x{height}, depth={depth}, \
2490 cq={cq}, narrow-kernel hits {narrow})"
2491 );
2492 }
2493 compared += 1;
2494 narrow_by_depth[di] += narrow;
2495 narrow_by_shape[si] += narrow;
2496 eprintln!(
2497 "{NAME}: {width}x{height} depth={depth} cq={cq} {} frames full-plane \
2498 exact, narrow-kernel hits {narrow}",
2499 frames.len()
2500 );
2501 }
2502 }
2503 }
2504 assert_eq!(
2505 compared, 12,
2506 "{NAME}: only {compared} of 12 arms were pixel-compared -- a refusal makes this \
2507 gate vacuous"
2508 );
2509 assert!(
2510 narrow_by_depth[0] > 0 && narrow_by_depth[1] > 0,
2511 "{NAME}: no rect-chroma narrow kernel fired at 8-bit ({}) or 10-bit ({}) -- the \
2512 recipe lost the shape this gate pins",
2513 narrow_by_depth[0],
2514 narrow_by_depth[1]
2515 );
2516 assert!(
2517 narrow_by_shape[0] > 0 && narrow_by_shape[1] > 0,
2518 "{NAME}: the shape fired in only one orientation (192x128 {}, 128x192 {})",
2519 narrow_by_shape[0],
2520 narrow_by_shape[1]
2521 );
2522 }
2523
2524 /// lane-intra14 r1's decisive gate: a real aomenc INTER sequence with
2525 /// `--enable-1to4-partitions=1`, whose fast-zooming content makes aomenc
2526 /// code INTRA blocks inside inter frames on 1:4 strip shapes (32x8/8x32 at
2527 /// the 32 level, 64x16/16x64 at the superblock level). Every such block
2528 /// was the named refusal "an intra-coded 1:4 (or other non-2:1) rect strip
2529 /// on the inter block path" until this round; they now decode through the
2530 /// same `decode_block_rect4` / `decode_block_rect64` readers the KEY FRAME
2531 /// 1:4 paths already prove, with only the mode-info read switched to
2532 /// `read_intra_block_mode_info` (libaom decodemv.c:1189).
2533 ///
2534 /// Hard-asserts `intra_rect4_strip_in_inter_hits` (0 = 64x16, 1 = 16x64,
2535 /// 2 = 32x8, 3 = 8x32) on the one pinned recipe below, and every
2536 /// decode-order frame is compared. A decode that succeeds is ALWAYS
2537 /// pixel-compared (class [[gate-skips-on-its-own-failure]]), and a recipe
2538 /// that decodes exact without a counted strip is a FAILURE, never a pass.
2539 /// The recipe, the pin and the `--enable-1to4-partitions=0` control arm
2540 /// are documented on [`intra_rect4_in_inter_gate`].
2541 #[test]
2542 // CLOSED by lane-av1recipehunt r1 (un-ignored). Two independent runs agree
2543 // on why this gate was blind, and they are worth keeping side by side.
2544 //
2545 // lane-av1pins RE-RAN this gate in RELEASE on a21f3680 (the seven-lane
2546 // merged tree) and found BOTH halves of the r2 record stale:
2547 // * THE PIXEL BLOCKER IS GONE -- `counted-exact=0 uncounted-exact=40
2548 // named-refusals=0 (attempts 40)` at both bit depths, and not one
2549 // mismatch line anywhere in the run log. 40/40 pixel-exact.
2550 // * THE RECIPE NEVER FIRES -- every counted attempt reads
2551 // `64x16=0 16x64=0 32x8=0 8x32=0`, so the assert trips on its
2552 // non-vacuity precondition, not on any pixel.
2553 //
2554 // lane-av1recipehunt then found WHY, and closed it. The blindness is not
2555 // the r2 "pre-existing INTER-frame pixel defect" (gone) and not the
2556 // mandelbrot source: the old recipe produced ZERO 1:4 strips of ANY shape
2557 // at ANY level, because `--min-partition-size=32` with an all-but-empty
2558 // intra mode set never puts a 1:4 partition on aomenc's RD menu.
2559 // MEASURED: the 32-level 1:4 counter is 0 in ALL 48 attempts at
2560 // `--min-partition-size=16` and fires in 40 of 48 at 8 with
2561 // `--enable-smooth-intra/paeth-intra/directional-intra/angle-delta=1`
2562 // (a 32x8/8x32 strip needs an intra mode WORTH CODING; with those four
2563 // off the only candidate is DC, and DC never wins a 1:4 strip against
2564 // inter). That also explains r2's "`--enable-1to4-partitions=0` is
2565 // byte-identical": with no 1:4 reachable at all, the flag had nothing to
2566 // turn off. The new recipe is 256x192x6, `--min-partition-size=8`, the
2567 // full intra mode set, `--cpu-used=2 --cq-level=63`; it fires 32x8=8
2568 // 8x32=11 and is pixel-exact on all 6 frames. See
2569 // [`intra_rect4_in_inter_gate`] for the pin and the flag control arm.
2570 fn a_real_aomenc_inter_sequence_with_an_intra_1to4_strip_decodes_pixel_exact() {
2571 intra_rect4_in_inter_gate(8);
2572 }
2573
2574 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
2575 #[test]
2576 // CLOSED by lane-av1recipehunt r1 (un-ignored), same recipe and same two
2577 // reasons as the 8-bit arm above: lane-av1pins' RELEASE re-run showed the
2578 // pixel blocker gone and the recipe never firing, and the root cause is
2579 // `--min-partition-size=32` plus the pruned intra mode set, not the
2580 // mandelbrot source. The 10-bit cell fires 32x8=12 8x32=7 and is
2581 // pixel-exact on all 6 frames.
2582 fn a_real_aomenc_inter_sequence_with_an_intra_1to4_strip_decodes_pixel_exact_10bit() {
2583 intra_rect4_in_inter_gate(10);
2584 }
2585
2586 /// lane-intrasplit r1's decisive gate: a real aomenc INTER sequence in
2587 /// which aomenc's RD picks an intra-coded HORZ/VERT *strip* (a 2:1
2588 /// rectangular partition) inside an inter frame AND splits its luma
2589 /// transform (`tx_depth >= 1`). Until this round that block was the named
2590 /// refusal "a split (nonzero tx_depth) transform on an intra HORZ/VERT
2591 /// strip in an inter frame"; it now walks the key frame's own per-TU path
2592 /// ([`decode::decode_rect_split`]). Hard-asserts
2593 /// [`decode::intra_rect_in_inter_split_tx_hits`] per depth: an attempt
2594 /// that never produced such a block proves nothing, and exhausting every
2595 /// attempt is a FAILURE, not a SKIP.
2596 #[test]
2597 fn a_real_aomenc_inter_sequence_with_a_split_transform_intra_strip_decodes_pixel_exact() {
2598 intra_rect_in_inter_split_tx_gate(8);
2599 }
2600
2601 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
2602 #[test]
2603 fn a_real_aomenc_10bit_inter_sequence_with_a_split_transform_intra_strip_decodes_pixel_exact() {
2604 intra_rect_in_inter_split_tx_gate(10);
2605 }
2606
2607 /// lane-t900 r21: the witness for the palette SYNTAX on a rect intra strip
2608 /// inside a screen-content INTER frame.
2609 ///
2610 /// `read_palette_mode_info` is gated by the frame's
2611 /// `allow_screen_content_tools` and by the block's own shape
2612 /// (`palette_bsize_ctx_wh`: `min(w,h) >= 8`, `max(w,h) <= 64`),
2613 /// with no square-only term -- so a `--tune-content=screen` inter frame
2614 /// writes `palette_y_mode` (and `palette_uv_mode`) for an 8x16 or 16x8
2615 /// intra strip exactly as for a square block. This decoder's inter-path
2616 /// intra arm skipped both symbols and refused the whole case by name ("a
2617 /// HORZ/VERT intra strip in a screen-content frame (palette syntax is
2618 /// consumed for square blocks only)"), which a real stream reached:
2619 /// measured with `decode_probe`, `testsrc2` 256x192 at
2620 /// `--tune-content=screen --enable-palette=0 --enable-intrabc=0` stops on
2621 /// that refusal at an 8x16 strip (8-bit) / a 16x8 one (10-bit).
2622 ///
2623 /// Both arms now decode all ten frames pixel-exact against ffmpeg, and
2624 /// [`decode::intra_rect_in_inter_screen_hits`] counts the strips that read
2625 /// the syntax -- hard-asserted, because an attempt with no such strip
2626 /// proves nothing about the case the refusal named.
2627 ///
2628 /// Note `--enable-palette=0`: the encoder's palette SEARCH is what this
2629 /// gate must switch off, not the syntax. With it on, the key frame codes
2630 /// a block that really uses a palette and stops on the separate,
2631 /// still-live "a block that actually uses a palette (Y)" refusal before
2632 /// any inter frame is reached (class `refusal-hides-a-defect`, measured on
2633 /// six such encodes).
2634 #[test]
2635 fn a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips() {
2636 screen_rect_intra_palette_syntax_gate(8);
2637 }
2638
2639 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
2640 #[test]
2641 fn a_real_aomenc_10bit_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips() {
2642 screen_rect_intra_palette_syntax_gate(10);
2643 }
2644
2645 /// lane-intra14 r4: the FILM witness for an intra block on a 1:4 partition
2646 /// inside an INTER frame -- `crates/ec-av1/fixtures/reelb_intra14_witness.obu`,
2647 /// 163057 bytes, sha256
2648 /// `0eff603bf1608e47faf5e6729670c4c77cf5c674dbad3a1533ac6660151fd90e`,
2649 /// two decode-order frames (key + first inter) cut from two INDEPENDENT
2650 /// `ffmpeg -ss 90 -t 2 -i <3840x1608 10-bit AV1 HDR10 mkv> -c:v copy -f obu`
2651 /// runs that hashed identically.
2652 ///
2653 /// MEASURED (r4, 27 two-second segments of that film at ss 0..6000, probe
2654 /// logs in the report): no aomenc recipe reaches this shape and only ONE
2655 /// class of stream does -- the film's own inter frames. Decode-order frame
2656 /// 1 of this fixture codes 3 intra 16x64 strips (`intra_rect4_in_inter`
2657 /// 16x64=3, zero when the fixture is truncated to the key frame alone), so
2658 /// the counter attribution is pinned to that frame.
2659 ///
2660 /// It is `#[ignore]`d for exactly ONE reason, and not this lane's shape:
2661 /// that same frame stops at a SIBLING refusal, "a split intra strip whose
2662 /// transform unit is 64x32 (no luma coefficient tables for that shape
2663 /// here)". The moment TX_64X32/TX_32X64 luma coefficient tables land, drop
2664 /// the `#[ignore]` -- everything else this gate needs (the reader, the
2665 /// counter, the two-frame pixel compare) is in place and runs.
2666 ///
2667 /// lane-sub8x4 r3: un-`#[ignore]`d. The sibling refusal it waited on (the
2668 /// un-split TX_64X32/TX_32X64 corner unit) is lifted in this round, so the
2669 /// frame this gate exists for now finishes.
2670 ///
2671 /// lane-wit16x4 r1, MEASURED: this gate is blind to the frame it counts
2672 /// (class `gate-blind-to-hidden-frames`). The fixture has two frame OBUs
2673 /// and ONE shown frame, and `decode_probe` on the fixture truncated to its
2674 /// first frame OBU reads `intra_rect4_in_inter 0/0/0/0` and
2675 /// `intra16x4_in_inter 0/0/0` while matching ffmpeg exactly -- so all of
2676 /// 4/23/28/72 (and the 4 intra 16x4 strips with them) live in the SECOND,
2677 /// NO-SHOW frame, whose pixels ffmpeg never emits and this gate never
2678 /// compares. Since that hidden frame also carries the intra 16x4/4x16
2679 /// strip whose refusal this round re-adds (no stream anywhere decodes
2680 /// pixel-exact while that arm fires -- lanes/wit16x4-r1.report.md), the
2681 /// decode now stops by name here. Un-ignored 2026-09-04: that re-added intra 16x4/4x16-in-inter refusal is gone and the gate passes.
2682 #[test]
2683 fn a_10bit_film_inter_frame_with_intra_1to4_strips_decodes_pixel_exact() {
2684 const NAME: &str = "a_10bit_film_inter_frame_with_intra_1to4_strips_decodes_pixel_exact";
2685 if !have_ffmpeg() {
2686 eprintln!("SKIP {NAME}: no ffmpeg");
2687 return;
2688 }
2689 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2690 .join("fixtures/reelb_intra14_witness.obu");
2691 let stream = std::fs::read(&path)
2692 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
2693 let (width, height) = (3840usize, 1608usize);
2694 let before = intra_rect4_in_inter_counters();
2695 let frames = match decode_stream(&stream) {
2696 Ok(frames) => frames,
2697 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2698 };
2699 let now = intra_rect4_in_inter_counters();
2700 let fired =
2701 (now.0 - before.0) + (now.1 - before.1) + (now.2 - before.2) + (now.3 - before.3);
2702 assert!(
2703 fired > 0,
2704 "{NAME}: zero intra 1:4 strips in an inter frame (64x16/16x64/32x8/8x32 = \
2705 {}/{}/{}/{}) -- the fixture stopped carrying the shape this gate exists for",
2706 now.0 - before.0,
2707 now.1 - before.1,
2708 now.2 - before.2,
2709 now.3 - before.3
2710 );
2711 // lane-sub8x4 r3, MEASURED when this gate first RAN: the fixture has
2712 // TWO frame OBUs but only ONE SHOWN frame -- a raw
2713 // `ffmpeg -i <fixture> -pix_fmt yuv420p10le -f rawvideo` writes exactly
2714 // 18524160 bytes, one 3840x1608 10-bit frame, so the second is a
2715 // no-show frame and `frames.len() == 2` was never true. The compare is
2716 // not vacuous: ffmpeg's own frame count is asserted equal to ours.
2717 assert_eq!(
2718 frames.len(),
2719 1,
2720 "{NAME}: one shown frame (the second frame OBU is a no-show)"
2721 );
2722 assert_eq!((frames[0].width, frames[0].height), (width, height));
2723 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len());
2724 assert_eq!(
2725 ffmpeg_frames.len(),
2726 frames.len(),
2727 "{NAME}: ffmpeg returned {} frames, we decoded {}",
2728 ffmpeg_frames.len(),
2729 frames.len()
2730 );
2731 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2732 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
2733 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
2734 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
2735 }
2736 eprintln!(
2737 "{NAME}: {fired} intra 1:4 strips in an inter frame, the shown frame pixel-exact"
2738 );
2739 }
2740
2741 /// lane-sub8x4 r3 / lane-wit16x4 r1: the FILM witness for the un-split
2742 /// TX_64X32/TX_32X64 corner unit of a split intra strip.
2743 ///
2744 /// r3 wrote this gate as a witness for TWO arms; its intra 16x4/4x16
2745 /// numbers were PHANTOMS (class `counter-from-refused-stream`), counted
2746 /// while decode-order frame 33 of this very prefix was desynced. On the
2747 /// merged tip (lane-frame36 r2 fixed that desync) the fixture decodes all
2748 /// 33 frames pixel-exact and `intra16x4_in_inter` reads 0/0/0, so the gate
2749 /// panicked "the intra 16x4/4x16 strip arm did not fire". lane-wit16x4 r1
2750 /// re-measured every counter, split the claim, and re-added the
2751 /// 16x4/4x16-in-inter refusal (no stream on this tree decodes exactly
2752 /// while that arm fires -- see the note at `decode.rs`'s `strip16`).
2753 ///
2754 /// `crates/ec-av1/fixtures/reelb_rect64_intra16x4_witness.obu`, 23472 bytes,
2755 /// sha256 `c9e721088766163b9dbeb9fa8dd8b257ff0ec7f9157fc350de4d3c33cd9ec4e4`:
2756 /// the first 50 frame-carrying OBUs of `ffmpeg -ss 0 -t 2 -i <3840x1608
2757 /// 10-bit AV1 HDR10 mkv> -c:v copy -f obu`, cut twice from independent
2758 /// ffmpeg runs that hashed identically. 33 decode-order frames.
2759 ///
2760 /// MEASURED on the merged tip (`decode_probe`, EC_PROBE_OUT16 vs
2761 /// `ffmpeg -pix_fmt yuv420p10le`): all 33 frames 0 differing bytes, and
2762 /// `rect64_corner_tu` fires 64x32=148 32x64=123 (r3's 90/5 came out of the
2763 /// desynced decode). `intra16x4_in_inter` reads 0/0/0 here and is asserted
2764 /// as such -- if a later change makes that arm fire on this stream, the
2765 /// refusal that now guards it moved and this gate says so.
2766 ///
2767 /// Refusal strings: "a split intra strip whose transform unit is
2768 /// {tx_w}x{tx_h}" stays NARROWED (every shape other than 64x32/32x64 --
2769 /// that is what this gate lifts), and "an intra 16x4/4x16 strip inside an
2770 /// inter 16x16-level 1:4 partition" is back to its FULL width.
2771 #[test]
2772 fn a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact() {
2773 const NAME: &str = "a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact";
2774 if !have_ffmpeg() {
2775 eprintln!("SKIP {NAME}: no ffmpeg");
2776 return;
2777 }
2778 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2779 .join("fixtures/reelb_rect64_intra16x4_witness.obu");
2780 let stream = std::fs::read(&path)
2781 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
2782 let (width, height) = (3840usize, 1608usize);
2783 let before16 = crate::decode::intra16x4_in_inter_hits();
2784 let before64 = (
2785 crate::decode::rect64_corner_tu_hits(0),
2786 crate::decode::rect64_corner_tu_hits(1),
2787 );
2788 let frames = match decode_stream(&stream) {
2789 Ok(frames) => frames,
2790 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2791 };
2792 let now16 = crate::decode::intra16x4_in_inter_hits();
2793 let fired16 = (
2794 now16.0 - before16.0,
2795 now16.1 - before16.1,
2796 now16.2 - before16.2,
2797 );
2798 let fired64 = (
2799 crate::decode::rect64_corner_tu_hits(0) - before64.0,
2800 crate::decode::rect64_corner_tu_hits(1) - before64.1,
2801 );
2802 // Hard counter asserts: the lift may not rest on a stream that stopped
2803 // carrying its shape (class `tool-disabled-in-every-gate`).
2804 assert_eq!(
2805 fired16,
2806 (0, 0, 0),
2807 "{NAME}: this stream carries NO intra 16x4/4x16 strip in an inter 1:4 \
2808 partition (r3's 31/17/23 were phantoms of the frame-33 desync); a \
2809 non-zero count here means the refusal guarding that arm moved"
2810 );
2811 assert!(
2812 fired64.0 > 0 && fired64.1 > 0,
2813 "{NAME}: the un-split TX_64X32/TX_32X64 corner arm did not fire (64x32={} 32x64={})",
2814 fired64.0,
2815 fired64.1
2816 );
2817 assert_eq!(frames.len(), 33, "{NAME}: 33 decode-order frames");
2818 assert_eq!((frames[0].width, frames[0].height), (width, height));
2819 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len());
2820 assert_eq!(
2821 ffmpeg_frames.len(),
2822 frames.len(),
2823 "{NAME}: ffmpeg returned {} frames, we decoded {}",
2824 ffmpeg_frames.len(),
2825 frames.len()
2826 );
2827 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2828 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
2829 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
2830 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
2831 }
2832 eprintln!(
2833 "{NAME}: 33 frames pixel-exact, rect64_corner_tu 64x32={} 32x64={} \
2834 (intra16x4_in_inter {} {} {}, refused shape)",
2835 fired64.0, fired64.1, fired16.0, fired16.1, fired16.2
2836 );
2837 }
2838
2839 /// lane-thread2 (iv): frame-parallel decoding changes nothing a caller
2840 /// can observe. Two real streams are decoded through
2841 /// [`decode_stream_with_threads`] at 1 and at 4 threads and every sink
2842 /// call is compared -- decode index, shown flag, and all three planes.
2843 ///
2844 /// `reelb_arf_witness.obu` is the one that proves the parallel path: it
2845 /// carries hidden alt-refs, which is exactly the case where "output in
2846 /// coded order" is not the same as "output in the order workers finish",
2847 /// and under lane-thread3's dependency-aware scheduling 39 of its 40
2848 /// coded frames (all but the key frame) are decoded off the main thread
2849 /// -- MORE than its 37 shown frames, which is the point: lane-thread2's
2850 /// leaf rule dispatched 18. `palette_screen_witness.obu` is the
2851 /// complement, an 8-bit screen stream whose every coded frame refreshes a
2852 /// slot: lane-thread2 dispatched NOTHING for it, lane-thread3 dispatches
2853 /// all 14 of its non-key frames. Both counts are asserted exactly, plus
2854 /// the "more than half the shown frames really ran on a worker" bound, so
2855 /// neither arm can pass vacuously.
2856 #[test]
2857 fn a_real_stream_decodes_identically_with_one_and_four_threads() {
2858 const NAME: &str = "a_real_stream_decodes_identically_with_one_and_four_threads";
2859 // (fixture, shown frames, frames a 4-thread run must dispatch)
2860 for (fixture, shown_frames, want_dispatched) in [
2861 ("fixtures/reelb_arf_witness.obu", 37usize, 39usize),
2862 ("fixtures/palette_screen_witness.obu", 15, 14),
2863 ] {
2864 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture);
2865 let stream = std::fs::read(&path)
2866 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
2867 let run = |threads: usize| -> Vec<(usize, bool, Picture)> {
2868 let mut out = Vec::new();
2869 decode_stream_with_threads(&stream, threads, |p, idx, shown| {
2870 out.push((idx, shown, p.clone()));
2871 Ok(())
2872 })
2873 .unwrap_or_else(|e| panic!("{NAME}: {fixture} at {threads} threads refused: {e}"));
2874 out
2875 };
2876 let serial = run(1);
2877 let before = frames_dispatched();
2878 let parallel = run(4);
2879 let dispatched = frames_dispatched() - before;
2880 assert_eq!(
2881 dispatched, want_dispatched,
2882 "{NAME}: {fixture} dispatched {dispatched} frames to workers, expected {want_dispatched}"
2883 );
2884 assert!(
2885 dispatched * 2 > shown_frames,
2886 "{NAME}: {fixture} dispatched {dispatched} frames, not even half of its {shown_frames} shown frames -- the parallel path is barely exercised"
2887 );
2888 assert_eq!(
2889 serial.iter().filter(|f| f.1).count(),
2890 shown_frames,
2891 "{NAME}: {fixture} shown frames"
2892 );
2893 assert_eq!(
2894 serial.len(),
2895 parallel.len(),
2896 "{NAME}: {fixture} sink call count differs"
2897 );
2898 for (i, (a, b)) in serial.iter().zip(&parallel).enumerate() {
2899 assert_eq!(a.0, b.0, "{NAME}: {fixture} sink {i} decode index");
2900 assert_eq!(a.1, b.1, "{NAME}: {fixture} sink {i} shown flag");
2901 assert_eq!(a.2.y, b.2.y, "{NAME}: {fixture} sink {i} luma");
2902 assert_eq!(a.2.u, b.2.u, "{NAME}: {fixture} sink {i} U");
2903 assert_eq!(a.2.v, b.2.v, "{NAME}: {fixture} sink {i} V");
2904 }
2905 eprintln!(
2906 "{NAME}: {fixture} {} sink calls identical, {dispatched} decoded on workers",
2907 serial.len()
2908 );
2909 }
2910 }
2911
2912 /// lane-frame36 r2: the hidden-ARF witness. `crates/ec-av1/fixtures/
2913 /// reelb_arf_witness.obu`, 32126 bytes, sha256
2914 /// `7f3b060da5aa9c537633e760c4af71316237db7692f6ae0d459bd2c2dd867d37`:
2915 /// the first 58 frame-carrying OBUs of a 2 s head cut of the 10-bit
2916 /// 3840x1608 AV1 HDR10 stream, 40 decode-order frames, 37 shown.
2917 ///
2918 /// What it covers that no earlier fixture did: decode-order frame 33 is a
2919 /// HIDDEN alt-ref (`show_frame=0`, order_hint 64, `cdef_bits=1`, loop
2920 /// restoration `[Switchable, Sgrproj, Switchable]`, `skip_mode_frame`
2921 /// [1,6]) -- the first frame of the stream carrying a SPLIT
2922 /// superblock-level intra strip in an inter frame. Its 16x64 strip at
2923 /// mi(192,140) reads `tx_depth=1` (TX_16X32), and until this round
2924 /// [`decode_block_rect64`]'s split arm returned past the tail that
2925 /// publishes the `TXFM_CONTEXT` bands, so the 32x64 block at mi(192,144)
2926 /// read the row's init value 64 as its left transform height and took
2927 /// `tx_size_cat3` row 2 where aomdec takes row 1 -- a desync no shown
2928 /// frame exposed until the ARF was displayed (class
2929 /// `gate-blind-to-hidden-frames`).
2930 ///
2931 /// The counter assert is on `rect64_split_txfm_publish_hits`, the split
2932 /// arm that was silent, so a stream that stopped carrying the shape fails
2933 /// the gate instead of passing it vacuously.
2934 #[test]
2935 fn a_10bit_film_hidden_arf_with_split_superblock_strips_decodes_pixel_exact() {
2936 const NAME: &str =
2937 "a_10bit_film_hidden_arf_with_split_superblock_strips_decodes_pixel_exact";
2938 if !have_ffmpeg() {
2939 eprintln!("SKIP {NAME}: no ffmpeg");
2940 return;
2941 }
2942 let path =
2943 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_arf_witness.obu");
2944 let stream = std::fs::read(&path)
2945 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
2946 let (width, height) = (3840usize, 1608usize);
2947 let before = crate::decode::rect64_split_txfm_publish_hits();
2948 let frames = match decode_stream(&stream) {
2949 Ok(frames) => frames,
2950 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2951 };
2952 let fired = crate::decode::rect64_split_txfm_publish_hits() - before;
2953 assert!(
2954 fired > 0,
2955 "{NAME}: no split superblock-level strip in the stream -- the gate would be vacuous"
2956 );
2957 assert_eq!(frames.len(), 37, "{NAME}: 37 shown frames");
2958 assert_eq!((frames[0].width, frames[0].height), (width, height));
2959 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len());
2960 assert_eq!(
2961 ffmpeg_frames.len(),
2962 frames.len(),
2963 "{NAME}: ffmpeg returned {} frames, we decoded {}",
2964 ffmpeg_frames.len(),
2965 frames.len()
2966 );
2967 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2968 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
2969 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
2970 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
2971 }
2972 eprintln!(
2973 "{NAME}: 37 shown frames pixel-exact on every plane, \
2974 rect64_split_txfm_publish={fired}"
2975 );
2976 }
2977
2978 /// lane-unwritten-dep: the UNWRITTEN-SAMPLE census at the point the output is
2979 /// taken, over the real film fixtures that carry hidden alt-refs.
2980 ///
2981 /// SCOPE, stated rather than implied: the census is taken where
2982 /// `EC_AV1_FINAL_DUMP` writes, which is BEFORE `apply_grain`. The claim is
2983 /// therefore over the PRE-GRAIN planes -- which are also the bytes the
2984 /// reference bank stores and every later frame predicts from, the dependency
2985 /// that matters. Every filter writes IN PLACE into the buffer this scans, so
2986 /// none of them can open a hole outside its extent. `apply_grain` is the one
2987 /// stage after this scan that ALLOCATES a new picture, and this census never
2988 /// sees it: the claim is NOT "the caller's final grained picture has no hole".
2989 ///
2990 /// lane-av1graincensus: that paragraph is still true of THIS gate and is not
2991 /// weakened by the pointer below -- what changed is that the gap it names is
2992 /// no longer UNMEASURED.
2993 /// [`the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample`]
2994 /// measures the grained picture `apply_grain` returns, over its own counters,
2995 /// and is the gate that carries the post-grain claim.
2996 ///
2997 /// NON-VACUITY, the part that makes this gate worth having: a census is only a
2998 /// measurement if it CAN report non-zero. The control is a SYNTHETIC positive
2999 /// -- the census is handed planes with a known number of sentinel samples and
3000 /// must report exactly that number. It deliberately does NOT use a fixture:
3001 /// the corpus's one witness with a real hole (`440_request_is_422`) is REFUSED
3002 /// by lane/av1unwritten, so a fixture-carried control goes red on merge for a
3003 /// reason unrelated to this gate. A synthetic control cannot be refused and
3004 /// cannot change behaviour when a lane lands. It is proven by mutation in the
3005 /// same run: neutering `census_unwritten_final` reds it (lane report §5).
3006 ///
3007 /// WHAT THIS IS NOT, corrected from an earlier revision of this comment: it
3008 /// does NOT rest on a claim that the pre-deblock census is blind. That claim
3009 /// was wrong. It came from `dump_stage16` cropping chroma as `(fw/2, fh/2)` --
3010 /// a 4:2:0 assumption -- so on a 64x64 4:2:2 frame 2048 chroma samples were in
3011 /// no stage dump at all, and an earlier revision read that blind spot as
3012 /// "identical pre-deblock, so deblock creates the dependence". With per-axis
3013 /// extents the corrected measurement is the opposite: the pre-deblock dump on
3014 /// `440_request_is_422` already DIFFERS by 2158 bytes and the exact u16 census
3015 /// finds 224 unwritten samples (U 112, V 112, rows 36..63, whole 4x4 groups) --
3016 /// the same count `lanes/av1unwritten.report.md` reports. The hole is present
3017 /// before any filter runs and the pre-deblock census SEES it. This census is
3018 /// here because it is the measurement taken where the OUTPUT is taken, which
3019 /// spans the whole route from the tile walk to the caller.
3020 ///
3021 /// The four film fixtures are the corpus's real 10-bit streams with hidden
3022 /// alt-refs -- the shapes where a hidden frame's unwritten region would feed
3023 /// a later DISPLAYED frame through the reference bank, which is the only way
3024 /// an unwritten sample could reach output on a stream that decodes correctly.
3025 /// All four measure 0 here AND 0 on the pre-deblock census.
3026 ///
3027 /// Measured on `8d6998d7` with a provenance-verified probe (`strings` on the
3028 /// binary names only this worktree; reelb_arf sha256 `7f3b060da5aa9c53`,
3029 /// reelb_rect64 `c9e721088766163b`):
3030 ///
3031 /// ```text
3032 /// pre-deblock census (u16, whole plane, 0xDEAD counted per frame)
3033 /// 440_request_is_422 224 <- also lane/av1unwritten's own number
3034 /// reelb_arf_witness 0
3035 /// reelb_rect64_intra16x4_witness 0
3036 /// this gate (pre-grain, at the output point)
3037 /// reelb_arf_witness 0
3038 /// reelb_rect64_intra16x4_witness 0
3039 /// gm_small_side_witness 0
3040 /// reelc_sb128_inter_witness 0
3041 /// ```
3042 #[test]
3043 fn the_frame_the_caller_receives_carries_no_unwritten_plane_sample() {
3044 const NAME: &str = "the_frame_the_caller_receives_carries_no_unwritten_plane_sample";
3045 let _gate_lock = lock_gate_counters();
3046
3047 // The census needs the sentinel FILL, which is env-gated (see
3048 // `fresh_plane`), and this crate forbids `set_var` (see `envflags`), so
3049 // the fill cannot be switched from inside a test process. The child
3050 // process below is therefore how the measurement is taken; what the
3051 // parent asserts is the CHILD's reported count.
3052 let census = |fixture: &str| -> (usize, usize) {
3053 let exe = std::env::current_exe().expect("test binary path");
3054 let out = std::process::Command::new(exe)
3055 .args([
3056 "--exact",
3057 "stream::tests::t09::uwdep_child_unwritten_census",
3058 "--nocapture",
3059 ])
3060 .env("UWDEP_CENSUS_FIXTURE", fixture)
3061 .env("EC_AV1_PLANE_SENTINEL", "1")
3062 .output()
3063 .expect("running the census child");
3064 // `--nocapture` puts the child's `println!` on its stderr, so both
3065 // streams are searched.
3066 let text = format!(
3067 "{}{}",
3068 String::from_utf8_lossy(&out.stdout),
3069 String::from_utf8_lossy(&out.stderr),
3070 );
3071 text.lines()
3072 .find_map(|l| l.strip_prefix("UWDEP_CENSUS "))
3073 .and_then(parse_census_line)
3074 .unwrap_or_else(|| {
3075 panic!(
3076 "{NAME}: the census child reported no count for {fixture} \
3077 (child said: {:?})",
3078 text.trim()
3079 )
3080 })
3081 };
3082
3083 // Non-vacuity FIRST, and SYNTHETIC on purpose (see the doc comment): the
3084 // census is handed planes with a known number of sentinel samples and must
3085 // report exactly that number. No fixture is involved, so this cannot be
3086 // affected by lane/av1unwritten refusing `440_request_is_422` on merge.
3087 // The fill is env-gated, so even this runs in the child.
3088 let (synthetic, synthetic_scanned) = census_synthetic();
3089 assert_eq!(
3090 synthetic_scanned, 40,
3091 "{NAME}: the synthetic control scanned {synthetic_scanned} samples, expected 40 \
3092 (16 + 16 + 8) -- the census did not look at what it was handed"
3093 );
3094 assert_eq!(
3095 synthetic, 7,
3096 "{NAME}: the census reported {synthetic} for planes carrying exactly 7 sentinel \
3097 samples -- the census is not measuring what it claims, so every zero below is \
3098 meaningless (class: census-silently-blind)"
3099 );
3100
3101 for fixture in [
3102 "reelb_arf_witness",
3103 "reelb_rect64_intra16x4_witness",
3104 "gm_small_side_witness",
3105 "reelc_sb128_inter_witness",
3106 ] {
3107 let (n, scanned) = census(fixture);
3108 assert!(
3109 scanned > 0,
3110 "{NAME}: the census scanned 0 samples on {fixture} -- the call at the output \
3111 point is not running, so the {n} below proves nothing (class: \
3112 census-never-ran). Deleting the call site reproduces this."
3113 );
3114 assert_eq!(
3115 n, 0,
3116 "{NAME}: {fixture} hands the caller {n} samples the tile walk never wrote"
3117 );
3118 }
3119 }
3120
3121 /// lane-av1graincensus: the picture the caller RECEIVES -- including film
3122 /// grain -- carries no unwritten plane sample.
3123 ///
3124 /// # WHAT THIS GATE IS FOR, and the blind spot it closes
3125 ///
3126 /// [`the_frame_the_caller_receives_carries_no_unwritten_plane_sample`] scans
3127 /// at `stream.rs`'s `EC_AV1_FINAL_DUMP` site, which is BEFORE `apply_grain`.
3128 /// Every filter (deblock/CDEF/LR/superres) writes IN PLACE into the buffer it
3129 /// scans, so none of them can open a hole outside its extent -- but
3130 /// `apply_grain` is the one stage after that scan that ALLOCATES a fresh
3131 /// picture: `film_grain::uninit_plane`, `Vec::with_capacity` + `set_len`, no
3132 /// fill, with correctness resting on a band row partition rather than on the
3133 /// type system. `lanes/unwritten-dep.report.md` §6 and §8 declined to claim
3134 /// anything about that destination. This gate measures it.
3135 ///
3136 /// # WHY THE COUNT CAN BE NON-ZERO (the part that makes it a census)
3137 ///
3138 /// Counting `== plane_poison()` over an uninitialised buffer is a census that
3139 /// reports ~0 either way: a hole survives with probability ~1/65536, not
3140 /// always. `uninit_plane` therefore fills with the poison under the SAME
3141 /// predicate `fresh_plane` honours. With the sentinel off -- every shipped
3142 /// build -- `uninit_plane` is still `with_capacity` + `set_len`, so the
3143 /// corner-cut it documents is untouched.
3144 ///
3145 /// # SCOPE, stated not implied
3146 ///
3147 /// The claim is over the picture the caller receives ON A GRAINED FRAME, in
3148 /// its final form, after the noise. It is NOT a claim that the pre-grain
3149 /// census already covered this -- that census never sees this buffer -- and it
3150 /// is NOT a claim about a frame whose grain step does not run.
3151 ///
3152 /// # NON-VACUITY, two arms, both required
3153 ///
3154 /// 1. **synthetic, first, and with a DIFFERENT known count (5, not the
3155 /// pre-grain arm's 7)** so a gate reading the wrong counter goes red. No
3156 /// fixture involved, so no lane's refusal can redden it.
3157 /// 2. **per-fixture `scanned > 0`** -- `unwritten == 0` is also what a build
3158 /// with the census call deleted reports. `scanned > 0` is reachable only by
3159 /// `apply_grain` actually running, so it is at once the
3160 /// proof-that-grain-fired and the deletion control.
3161 ///
3162 /// Both mutations are in `lanes/av1graincensus.report.md`: deleting the
3163 /// `census_unwritten_grained` call at `apply_grain`'s return reds arm 2, and
3164 /// forcing ONE poison sample into a grained picture reds arm 2's count.
3165 #[test]
3166 fn the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample() {
3167 const NAME: &str =
3168 "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample";
3169 let _gate_lock = lock_gate_counters();
3170
3171 let (syn, syn_scanned) = grain_census_synthetic();
3172 assert_eq!(
3173 syn_scanned, 40,
3174 "{NAME}: the synthetic control scanned {syn_scanned} samples, expected 40 \
3175 (16 + 16 + 8) -- the grained census did not look at what it was handed"
3176 );
3177 assert_eq!(
3178 syn, 5,
3179 "{NAME}: the grained census reported {syn} for planes carrying exactly 5 sentinel \
3180 samples -- it is not measuring what it claims, so every zero below is \
3181 meaningless (class: census-silently-blind). Note 5, not the pre-grain arm's 7: \
3182 reading the wrong counter is the failure this number catches."
3183 );
3184
3185 // Small and cheap: a 4:2:2 grain stream, a 4:2:0 one that also runs
3186 // CDEF+LR, and the real 10-bit 3840x1608 hidden-alt-ref film whose height
3187 // is not a multiple of the 32-pixel band row -- the shape where the band
3188 // row partition has a tail.
3189 for fixture in [
3190 "s422_grain_160x128",
3191 "grain_cdef_lr_128x128",
3192 "reelb_arf_witness",
3193 ] {
3194 let (n, scanned) = grain_census(fixture);
3195 assert!(
3196 scanned > 0,
3197 "{NAME}: the grained census scanned 0 samples on {fixture} -- the call at \
3198 `apply_grain`'s return is not running (or grain never fired), so the {n} \
3199 below proves nothing (class: census-never-ran). Deleting the call in \
3200 apply_grain reproduces this."
3201 );
3202 assert_eq!(
3203 n, 0,
3204 "{NAME}: {fixture} hands the caller a grained picture with {n} samples the \
3205 grain destination's band copy never wrote"
3206 );
3207 }
3208 }
3209
3210 /// The child half of
3211 /// [`the_frame_the_caller_receives_carries_no_unwritten_plane_sample`]: decodes
3212 /// the fixture named in `UWDEP_CENSUS_FIXTURE` with the sentinel fill live and
3213 /// prints `UWDEP_CENSUS <n> frames=<n>` plus a frame-count assertion.
3214 ///
3215 /// A `#[test]` rather than an example because it needs the crate's own
3216 /// in-process counter -- which no external binary could read.
3217 #[test]
3218 fn uwdep_child_unwritten_census() {
3219 // Reached with NEITHER variable set means a normal suite run: the parent
3220 // invokes this test BY NAME with the variable set, so there is nothing to
3221 // measure here. Asserting the fill instead made every full suite red
3222 // (`stream::tests::uwdep_child_unwritten_census` is in the default test
3223 // list), and the run it wanted to catch is already caught on the parent's
3224 // side, which panics when the child prints no census line. A standalone
3225 // run SAYS it skipped rather than passing silently.
3226 if std::env::var_os("UWDEP_CENSUS_SYNTHETIC").is_none()
3227 && std::env::var_os("UWDEP_CENSUS_FIXTURE").is_none()
3228 {
3229 println!("UWDEP_CENSUS skipped: not invoked as a census child");
3230 return;
3231 }
3232 assert!(
3233 std::env::var_os("EC_AV1_PLANE_SENTINEL").is_some(),
3234 "the census child ran without EC_AV1_PLANE_SENTINEL, so the fill was never live \
3235 and the count is meaningless"
3236 );
3237 // The non-vacuity control: no decode, no fixture, just the census over
3238 // planes with a KNOWN number of sentinel samples. 3 + 4 + 0 = 7.
3239 if std::env::var_os("UWDEP_CENSUS_SYNTHETIC").is_some() {
3240 const S: u16 = 0xDEAD;
3241 let mut a = vec![7u16; 16];
3242 let mut b = vec![7u16; 16];
3243 let c = vec![7u16; 8];
3244 for s in a.iter_mut().take(3) {
3245 *s = S;
3246 }
3247 for s in b.iter_mut().take(4) {
3248 *s = S;
3249 }
3250 let _ = decode::take_final_unwritten_samples();
3251 decode::census_unwritten_final(&a, &b, &c);
3252 let n = decode::take_final_unwritten_samples();
3253 let scanned = decode::take_final_census_scanned();
3254 println!("UWDEP_CENSUS {n} synthetic=1 scanned={scanned}");
3255 // lane-av1graincensus: the grained census over the SAME planes but a
3256 // DIFFERENT known count, 2 + 3 + 0 = 5. Deliberately not 7: a parent
3257 // that read the pre-grain counter for the grained arm would see 7 and
3258 // go red, so the two arms cannot be confused for one another.
3259 for s in a.iter_mut().take(3) {
3260 *s = 7;
3261 }
3262 for s in b.iter_mut().take(4) {
3263 *s = 7;
3264 }
3265 for s in a.iter_mut().take(2) {
3266 *s = S;
3267 }
3268 for s in b.iter_mut().take(3) {
3269 *s = S;
3270 }
3271 let _ = decode::take_grained_unwritten_samples();
3272 decode::census_unwritten_grained(&a, &b, &c);
3273 let gn = decode::take_grained_unwritten_samples();
3274 let gscanned = decode::take_grained_census_scanned();
3275 println!("GRAINCENSUS {gn} synthetic=1 scanned={gscanned}");
3276 return;
3277 }
3278 let Ok(fixture) = std::env::var("UWDEP_CENSUS_FIXTURE") else {
3279 // Not a census run: the parent invokes this test by name, so being
3280 // reached without the variable means a normal suite run.
3281 return;
3282 };
3283 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3284 .join(format!("fixtures/{fixture}.obu"));
3285 let stream =
3286 std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
3287 let _ = decode::take_final_unwritten_samples();
3288 // Both counters are drained BEFORE the decode: they are process-global
3289 // and this child may inherit nothing, but a partial run must not be able
3290 // to add its numbers to another test's.
3291 let _ = decode::take_grained_unwritten_samples();
3292 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{fixture} refused: {e}"));
3293 let n = decode::take_final_unwritten_samples();
3294 let scanned = decode::take_final_census_scanned();
3295 println!("UWDEP_CENSUS {n} frames={} scanned={scanned}", frames.len());
3296 // lane-av1graincensus: the post-grain census, over the picture
3297 // `apply_grain` returns. A different prefix from `UWDEP_CENSUS`, so
3298 // neither parent can pick up the other's line.
3299 let gn = decode::take_grained_unwritten_samples();
3300 let gscanned = decode::take_grained_census_scanned();
3301 println!(
3302 "GRAINCENSUS {gn} frames={} scanned={gscanned}",
3303 frames.len()
3304 );
3305 }
3306
3307 /// lane-av1uballoc: the frame the caller receives does not depend on what
3308 /// the plane buffer held before the decode wrote it.
3309 ///
3310 /// Four runs of the same fixtures, each in its own process (the fill and
3311 /// the alloc closure are both process-constant env reads -- see
3312 /// [`crate::envflags`] -- and this crate forbids `set_var`), must agree on
3313 /// one hash per fixture:
3314 ///
3315 /// * `EC_AV1_PLANE_SENTINEL=0xDEAD` and `=0xBEEF` -- two DIFFERENT
3316 /// impossible values for the same buffer. This is the arm that can
3317 /// actually FAIL: if any reader's value reaches the picture, changing the
3318 /// poison changes the output. Equal hashes are a statement about a READ,
3319 /// which is what the poisoned-read check in [`decode::fresh_plane`] needs and what no
3320 /// census in the crate measures.
3321 /// * the sentinel OFF (the shipped zeroed allocation), which must agree
3322 /// with the poisoned runs. This is the "same with the sentinel off"
3323 /// arm; on its own it is weak (the allocator may hand out the same
3324 /// ambient bytes twice) and is here as the join between the two worlds.
3325 ///
3326 /// NON-VACUITY, first and synthetic: [`allocdet_synthetic`] hashes two
3327 /// pictures that differ in ONE sample and asserts the hashes DIFFER. A hash
3328 /// that cannot see a one-sample difference would make every equality below
3329 /// vacuous, and it is the failure mode a "0 errors" style result has.
3330 /// Second: every arm must report `frames>0`, so a child that decoded
3331 /// nothing cannot agree with another child that decoded nothing.
3332 #[test]
3333 fn the_frame_does_not_depend_on_the_plane_buffers_initial_content() {
3334 const NAME: &str = "the_frame_does_not_depend_on_the_plane_buffers_initial_content";
3335 let _gate_lock = lock_gate_counters();
3336 // Kept SMALL on purpose: the whole gate is 4 child processes x this
3337 // list, and the suite runs it in a DEBUG build. A first revision used
3338 // the 1920x792 film fixtures here and took 252 s, which is not a gate
3339 // anyone keeps. These ten cover every shape the region list names --
3340 // 4:2:2 (12-bit key, inter, sb128 intrabc, 17-frame odd-size), 4:4:4
3341 // (lossless sb64, intrabc rect4, 128-root mu), a padded odd size, an
3342 // off-tile chroma walk, and superres+CDEF+LR -- for ~1.3 s per arm.
3343 //
3344 // lane-av1graincensus adds FILM GRAIN. `apply_grain`'s `uninit_plane` is
3345 // the crate's only OTHER `Vec::with_capacity` + `set_len` allocation, and
3346 // before this row the only gate that can catch a READ of it had no grain
3347 // fixture at all, so that path had no coverage here. It matters: with
3348 // the grain band's clean-row copy neutered, the noise kernels read the
3349 // destination to build `avgLuma` and the picture's values then depend on
3350 // whatever the buffer held -- a dependence the 0xDEAD-vs-0xBEEF arm
3351 // exists to catch and the unwritten-sample census cannot (the read value
3352 // is overwritten before the census runs). Measured in
3353 // `lanes/av1graincensus.report.md` §5. `s422_grain_160x128` is the
3354 // smallest grain fixture, so the arm grows by ~0.05 s.
3355 const FIXTURES: &[&str] = &[
3356 "s422_12bit_160x128",
3357 "422_inter_160x128_3f",
3358 "422_intrabc_sb128_strip",
3359 "s422_352x242_10b",
3360 "ll444_sb64_1to4_lossless",
3361 "444_intrabc_rect4_witness",
3362 "444_intra_in_inter_128root_mu_chroma",
3363 "svt1-split-tx-pin",
3364 "mix176_offtile_chroma_clip",
3365 "superres_kf_cdef_lr_64x64",
3366 "s422_grain_160x128",
3367 ];
3368
3369 let (a, b) = allocdet_synthetic();
3370 assert_ne!(
3371 a, b,
3372 "{NAME}: the content hash returned the same value for two pictures differing in one \
3373 sample, so every equality below is vacuous -- this gate would pass on any decoder, \
3374 including one that returns garbage (class: hash-cannot-see-content)"
3375 );
3376
3377 let arms: [(&str, Option<&str>, &str); 3] = [
3378 ("poison-dead", Some("0xDEAD"), "zeroed"),
3379 ("poison-beef", Some("0xBEEF"), "zeroed"),
3380 ("alloc-zeroed", None, "zeroed"),
3381 ];
3382 let mut baseline: Option<Vec<(String, usize, u64)>> = None;
3383 for (label, poison, alloc) in arms {
3384 let rows = allocdet_child(FIXTURES, poison, alloc);
3385 assert_eq!(
3386 rows.len(),
3387 FIXTURES.len(),
3388 "{NAME}: the {label} arm reported {} of {} fixtures -- a run that decoded \
3389 nothing can agree with another run that decoded nothing",
3390 rows.len(),
3391 FIXTURES.len()
3392 );
3393 for (f, frames, _) in &rows {
3394 assert!(
3395 *frames > 0,
3396 "{NAME}: the {label} arm decoded 0 frames of {f}; the hashes it compared are \
3397 over nothing"
3398 );
3399 }
3400 match &baseline {
3401 None => baseline = Some(rows),
3402 Some(first) => {
3403 for (i, (f, frames, h)) in rows.iter().enumerate() {
3404 let (bf, bframes, bh) = &first[i];
3405 assert_eq!(
3406 bf, f,
3407 "{NAME}: arm {label} reported fixture {f} where the \
3408 baseline reported {bf} -- the arms are not comparable"
3409 );
3410 assert_eq!(
3411 bframes, frames,
3412 "{NAME}: {f} decoded {frames} frames under \
3413 {label} and {bframes} under the baseline arm"
3414 );
3415 assert_eq!(
3416 bh, h,
3417 "{NAME}: {f} decoded to a DIFFERENT picture depending on what the \
3418 plane buffer held before the decode wrote it -- {label} gave {h:016x}, \
3419 the baseline arm gave {bh:016x}. A read of uninitialised memory \
3420 reaches the caller's frame (see decode::fresh_plane)."
3421 );
3422 }
3423 }
3424 }
3425 }
3426 }
3427
3428 /// The child half of
3429 /// [`the_frame_does_not_depend_on_the_plane_buffers_initial_content`]:
3430 /// decodes every fixture named in `ALLOCDET_FIXTURES` and prints one
3431 /// `ALLOCDET` line each.
3432 ///
3433 /// With `ALLOCDET_SYNTHETIC` set it instead prints the two hashes the
3434 /// non-vacuity control compares -- two pictures differing in ONE sample --
3435 /// and decodes nothing.
3436 #[test]
3437 fn allocdet_child_decode() {
3438 if std::env::var_os("ALLOCDET_SYNTHETIC").is_some() {
3439 let (a, b) = allocdet_synthetic();
3440 println!("ALLOCDET_SYNTHETIC {a:016x} {b:016x}");
3441 return;
3442 }
3443 let Ok(list) = std::env::var("ALLOCDET_FIXTURES") else {
3444 // Reached without either variable == a normal suite run: the parent
3445 // names this test with ALLOCDET_FIXTURES (or ALLOCDET_SYNTHETIC) set,
3446 // so there is nothing to measure here. Asserting the variable instead
3447 // made every full suite red (caught by the server suite at the merged
3448 // head); the parent already fails when the child prints no ALLOCDET
3449 // line, so a skip cannot hide a broken child. Print rather than
3450 // pass silently.
3451 println!("ALLOCDET skipped: not invoked as a census child");
3452 return;
3453 };
3454 let mut hash = 0xcbf2_9ce4_8422_2325u64;
3455 for fixture in list.split(',').filter(|s| !s.is_empty()) {
3456 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3457 .join(format!("fixtures/{fixture}.obu"));
3458 let stream =
3459 std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
3460 let mut frames = 0usize;
3461 decode_stream_with(&stream, |pic, _idx, shown| {
3462 if !shown {
3463 return Ok(());
3464 }
3465 frames += 1;
3466 for p in [&pic.y, &pic.u, &pic.v] {
3467 for &s in p.iter() {
3468 for b in s.to_le_bytes() {
3469 hash ^= u64::from(b);
3470 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
3471 }
3472 }
3473 }
3474 Ok(())
3475 })
3476 .unwrap_or_else(|e| panic!("{fixture} refused: {e}"));
3477 println!("ALLOCDET {fixture} frames={frames} hash={hash:016x}");
3478 }
3479 }
3480
3481 /// lane-t900 r6: the 128-superblock INTER witness.
3482 /// `crates/ec-av1/fixtures/reelc_sb128_inter_witness.obu`, 177773 bytes,
3483 /// sha256 `09d995946d27695ef4b7b1a24a4d7ad85f8e2c8176d58ee54e825efc061f9cbc`:
3484 /// the first 23 frame-carrying OBUs of a 2 s cut taken 900 s into a 10-bit
3485 /// 1920x792 AV1 stream with `use_128x128_superblock=1`, 16 decode-order
3486 /// frames, 15 shown. Cut twice independently from the source (`-ss 900 -t 2
3487 /// -c:v copy` then the OBU truncation) -- both cuts hash identically.
3488 /// lane-t900 r7 extended it from 19 OBUs / 14 frames: decode-order frame 14
3489 /// is the ONLY frame in this repository's fixtures whose sub-8x8 inter
3490 /// chroma inherits a `tx_type` from a chroma-reference sub-block that
3491 /// differs from its group's first sub-block AND codes coefficients
3492 /// (`sub8_chroma_tx_from_ref_hits`), i.e. the only frame that can tell
3493 /// `av1_get_tx_type`'s two candidate rules apart.
3494 ///
3495 /// It is the first stream in this repository that decodes exactly while
3496 /// five separately-found defects' paths all fire, which is why the asserts
3497 /// below are on all of them:
3498 ///
3499 /// * `warp_plane_suppress_hits` (r5) -- `av1_init_warp_params` bails out at
3500 /// `block_width < 8 || block_height < 8` on the PLANE's own block, so the
3501 /// 4x8 chroma of an 8x16 luma block is predicted translationally while its
3502 /// luma warps. Gated on the square side before r5.
3503 /// * `inter_sb128_vert_hits` + `cdef_idx_hits` (r5) -- the second half of a
3504 /// 128-root HORZ/VERT inter block must read its OWN `cdef_idx` literal
3505 /// (libaom `cdef_transmitted[4]`, one flag per 64x64 CDEF unit).
3506 /// * `interintra_rect_hits` (r4) -- interintra on a RECTANGULAR block built
3507 /// a square intra predictor before.
3508 /// * `non_chroma_ref_ctx_skip_hits` (r3) -- a block that is not the chroma
3509 /// reference of its 4:2:0 pair leaves its neighbours' chroma coefficient
3510 /// contexts untouched (`nplanes = 1 + (num_planes - 1) * is_chroma_ref`).
3511 /// * `intra_in_inter_txctx_hits` (r2) -- an intra strip in an INTER frame
3512 /// takes its `tx_depth` row from the real `TXFM_CONTEXT` bands, not the
3513 /// key frame's deblock grid.
3514 /// * `edge_filter_mi_fix_hits` (r4) -- both halves of a split intra block
3515 /// read their OWN mi-exact intra-edge-filter neighbours.
3516 ///
3517 /// It is ALSO the witness that lifted the intra-16x4-in-inter opt-in -- that path decodes by default now, gated here:
3518 /// `intra16x4_in_inter` fires 78x 16x4 + 149x 4x16 (108 chroma-paired)
3519 /// inside frames that are decoded AND compared exact -- not counted out of
3520 /// a refused or desynced stream the way lane-sub8x4 r3's phantom was
3521 /// (class `counter-from-refused-stream`). The 128x64/64x128 intra-in-inter
3522 /// arm fires 0 times here, so THAT refusal is untouched.
3523 ///
3524 /// All 14 decode-order frames (including the 2 no-show frames ffmpeg never
3525 /// hands back) were compared byte-exact against instrumented aomdec with
3526 /// `EC_AV1_FINAL_DUMP` -- see the lane report's EVIDENCE line; the gate
3527 /// itself compares the 12 shown frames on every plane.
3528 #[test]
3529 fn a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_decode_pixel_exact() {
3530 const NAME: &str =
3531 "a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_decode_pixel_exact";
3532 if !have_ffmpeg() {
3533 eprintln!("SKIP {NAME}: no ffmpeg");
3534 return;
3535 }
3536 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3537 .join("fixtures/reelc_sb128_inter_witness.obu");
3538 let stream = std::fs::read(&path)
3539 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
3540 let (width, height) = (1920usize, 792usize);
3541 let before = (
3542 crate::decode::warp_plane_suppress_hits(),
3543 crate::decode::cdef_idx_hits(),
3544 crate::decode::inter_sb128_vert_hits(),
3545 crate::decode::interintra_rect_hits(),
3546 crate::decode::non_chroma_ref_ctx_skip_hits(),
3547 crate::decode::intra_in_inter_txctx_hits(),
3548 crate::decode::edge_filter_mi_fix_hits(),
3549 );
3550 let sub8tx_before = crate::decode::sub8_chroma_tx_from_ref_hits();
3551 // lane-t900 r8: the intra edge-filter type an INTER neighbour keeps
3552 // non-smooth (the coarse SUB band still holds an older SMOOTH mode).
3553 let notsmooth_before = crate::decode::inter_neighbour_not_smooth_hits();
3554 // lane-t900 r10: the rect warp top-right reach (600 blocks here).
3555 let tr_before = crate::decode::tr_reach_longer_side_hits();
3556 let i16_before = crate::decode::intra16x4_in_inter_hits();
3557 // lane-t900 r14: OBMC neighbour strips that run past the frame edge
3558 // (792 luma rows = 198 mi rows, so every bottom-row 32x32 block
3559 // overhangs) -- the shape whose prediction size used to be clamped.
3560 let edge_before = crate::decode::obmc_edge_span_hits();
3561 let frames = match decode_stream(&stream) {
3562 Ok(frames) => frames,
3563 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
3564 };
3565 let obmc_edge_span = crate::decode::obmc_edge_span_hits() - edge_before;
3566 let fired = (
3567 crate::decode::warp_plane_suppress_hits() - before.0,
3568 crate::decode::cdef_idx_hits() - before.1,
3569 crate::decode::inter_sb128_vert_hits() - before.2,
3570 crate::decode::interintra_rect_hits() - before.3,
3571 crate::decode::non_chroma_ref_ctx_skip_hits() - before.4,
3572 crate::decode::intra_in_inter_txctx_hits() - before.5,
3573 crate::decode::edge_filter_mi_fix_hits() - before.6,
3574 );
3575 let sub8tx = crate::decode::sub8_chroma_tx_from_ref_hits() - sub8tx_before;
3576 let notsmooth = crate::decode::inter_neighbour_not_smooth_hits() - notsmooth_before;
3577 let tr = crate::decode::tr_reach_longer_side_hits() - tr_before;
3578 let i16_now = crate::decode::intra16x4_in_inter_hits();
3579 let i16 = (
3580 i16_now.0 - i16_before.0,
3581 i16_now.1 - i16_before.1,
3582 i16_now.2 - i16_before.2,
3583 );
3584 for (what, n) in [
3585 ("warp_plane_suppress", fired.0),
3586 ("cdef_idx", fired.1),
3587 ("inter_sb128_vert", fired.2),
3588 ("interintra_rect", fired.3),
3589 ("non_chroma_ref_ctx_skip", fired.4),
3590 ("intra_in_inter_txctx", fired.5),
3591 ("edge_filter_mi_fix", fired.6),
3592 ("intra16x4_in_inter 16x4", i16.0),
3593 ("intra16x4_in_inter 4x16", i16.1),
3594 ("intra16x4_in_inter chroma_ref", i16.2),
3595 ("sub8_chroma_tx_from_ref", sub8tx),
3596 ("inter_neighbour_not_smooth", notsmooth),
3597 ("tr_reach_longer_side", tr),
3598 ("obmc_edge_span", obmc_edge_span),
3599 ] {
3600 assert!(
3601 n > 0,
3602 "{NAME}: {what} never fired on this stream -- the gate would be vacuous for it"
3603 );
3604 }
3605 assert_eq!(frames.len(), 15, "{NAME}: 15 shown frames");
3606 assert_eq!((frames[0].width, frames[0].height), (width, height));
3607 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len());
3608 assert_eq!(
3609 ffmpeg_frames.len(),
3610 frames.len(),
3611 "{NAME}: ffmpeg returned {} frames, we decoded {}",
3612 ffmpeg_frames.len(),
3613 frames.len()
3614 );
3615 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3616 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
3617 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
3618 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
3619 }
3620 eprintln!(
3621 "{NAME}: 15 shown frames pixel-exact on every plane; warp_plane_suppress={} \
3622 cdef_idx={} inter_sb128_vert={} interintra_rect={} non_chroma_ref_ctx_skip={} \
3623 intra_in_inter_txctx={} edge_filter_mi_fix={} intra16x4_in_inter={:?} \
3624 sub8_chroma_tx_from_ref={sub8tx} inter_neighbour_not_smooth={notsmooth} \
3625 tr_reach_longer_side={tr} obmc_edge_span={obmc_edge_span}",
3626 fired.0, fired.1, fired.2, fired.3, fired.4, fired.5, fired.6, i16
3627 );
3628 }
3629
3630 /// lane-t900 r16/r17: a 10-bit 512x512 `--sb-size=128` stream in which
3631 /// every 128 root is a var-tx block, and the gate for the SKIPPED-128-block
3632 /// luma entropy reset (r17). It was BUILT as an intra-128-in-inter witness
3633 /// and r16 measured three hits of that arm in it -- every one of them an
3634 /// artifact of the desync fixed here (class `counter-from-refused-stream`).
3635 /// Decoding exactly, the arm fires ZERO times, so this stream does not
3636 /// carry that shape; the intra-128-in-inter path decodes by default now, gated by `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`. Renamed
3637 /// out of `an_intra_coded_128x64_block_inside_an_inter_frame_...` for that
3638 /// reason -- the fixture keeps the original intent in its own name.
3639 ///
3640 /// `crates/ec-av1/fixtures/intra128_in_inter_witness.obu`, 13066 bytes,
3641 /// sha256 `dd41fc39367a3d38bf8a8a8106dc30d91b716b2a9123fdfa4716930f4f98caf9`,
3642 /// produced by this repository's aomenc oracle:
3643 ///
3644 /// ```text
3645 /// aomenc --codec=av1 -w 512 -h 512 --input-bit-depth=10 --bit-depth=10 \
3646 /// --sb-size=128 --min-partition-size=64 --max-partition-size=128 \
3647 /// --enable-rect-partitions=1 --kf-max-dist=9999 --lag-in-frames=0 \
3648 /// --cpu-used=1 --end-usage=q --cq-level=24 --threads=1 --obu -o s.obu src.y4m
3649 /// ```
3650 ///
3651 /// The source is 10 frames of 10-bit 512x512 whose left two superblock
3652 /// columns carry 128-wide bands 64 rows apart (so the 128 root's cheapest
3653 /// split is `PARTITION_HORZ`) and whose right two carry 64-wide vertical
3654 /// bands (`PARTITION_VERT`), with two hard scene cuts at frames 4 and 7 and
3655 /// `--kf-max-dist=9999` so those cuts must be coded as INTER frames whose
3656 /// content no reference holds. It is the first stream found in this
3657 /// repository that makes the encoder code a 128-root HORZ/VERT half INTRA
3658 /// inside an inter frame at all: `intra128_in_inter` fires 1x 128x64 +
3659 /// 2x 64x128. Three recipes that do NOT fire it, so the shape matters: a
3660 /// small new patch on a static background (the frame costs 80 bytes, the
3661 /// encoder skips), unstructured texture (the 128 root always SPLITs), and
3662 /// cyclically repeating phases (GOLDEN holds an earlier phase, so the cut
3663 /// is predicted rather than coded intra).
3664 ///
3665 /// r16 could not lift the opt-in: the three hits landed in a frame this
3666 /// decoder did not decode exactly, and a counter read out of a desynced
3667 /// frame proves nothing (class `counter-from-refused-stream`). The blocker
3668 /// was a SEPARATE defect on the inter path, not this arm -- the same source
3669 /// re-encoded with every optional tool disabled fired the arm 0 times and
3670 /// desynced on exactly the same frames, and the same source at
3671 /// `--sb-size=64` decoded all 10 frames byte-exact.
3672 ///
3673 /// r17 root cause, and what this gate now pins (class
3674 /// `early-return-skips-tail`): a SKIPPED inter block
3675 /// whose `read_block_tx_size` still hands back var-tx leaves -- which every
3676 /// 128 root does under `TX_MODE_LARGEST` -- took `decode_inter_block`'s
3677 /// `if skip` arm, so the per-transform-unit luma publication loop never
3678 /// ran, and the block-level `record_split_luma_rect_mi` deliberately writes
3679 /// no plane 0. The skipped block therefore left the PREVIOUS block's luma
3680 /// coefficient levels standing where libaom's `av1_reset_entropy_context`
3681 /// zeroes all three planes over the block. First-bad before the fix
3682 /// (`EC_TRACE_COEFF` on both decoders, prefiltered to the
3683 /// `all_zero`/`eob`/`after_bases` tags, filtered index 426): frame 1, the
3684 /// 128x128 `is_inter=1 skip=0` block at mi(32,64), its first luma TU
3685 /// (`bc=0 br=0`, TX_64X64) -- aomdec `txb_skip` ctx 1 (`top == 0 &&
3686 /// left == 0`), ours ctx 2, entry range equal on both, because the skipped
3687 /// 128x128 block at mi(32,32) never cleared `left[32..48]` (ours 1,
3688 /// aomdec 0). With the publication restored the whole 10-frame filtered
3689 /// ladder matches 1397/1397 steps.
3690 ///
3691 #[test]
3692 fn a_128_superblock_stream_whose_skipped_blocks_are_var_tx_decodes_pixel_exact() {
3693 const NAME: &str =
3694 "a_128_superblock_stream_whose_skipped_blocks_are_var_tx_decodes_pixel_exact";
3695 if !have_ffmpeg() {
3696 eprintln!("SKIP {NAME}: no ffmpeg");
3697 return;
3698 }
3699 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3700 .join("fixtures/intra128_in_inter_witness.obu");
3701 let stream = std::fs::read(&path)
3702 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
3703 let (width, height) = (512usize, 512usize);
3704 let before = crate::decode::skip_vartx_luma_reset_hits();
3705 let intra128_before = intra128_in_inter_counters();
3706 let frames = match decode_stream(&stream) {
3707 Ok(frames) => frames,
3708 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
3709 };
3710 let fired = crate::decode::skip_vartx_luma_reset_hits() - before;
3711 assert!(
3712 fired > 0,
3713 "{NAME}: no skipped var-tx block cleared its own luma coefficient \
3714 contexts -- the gate would be vacuous for the defect it pins"
3715 );
3716 let intra128_now = intra128_in_inter_counters();
3717 assert_eq!(
3718 [
3719 intra128_now[0] - intra128_before[0],
3720 intra128_now[1] - intra128_before[1]
3721 ],
3722 [0, 0],
3723 "{NAME}: this stream does not carry a 128-root intra half -- the \
3724 witness for that arm is `intra128_in_inter_witness2.obu` (r18)"
3725 );
3726 assert_eq!(frames.len(), 10, "{NAME}: 10 shown frames");
3727 assert_eq!((frames[0].width, frames[0].height), (width, height));
3728 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len());
3729 assert_eq!(
3730 ffmpeg_frames.len(),
3731 frames.len(),
3732 "{NAME}: ffmpeg returned {} frames, we decoded {}",
3733 ffmpeg_frames.len(),
3734 frames.len()
3735 );
3736 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3737 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
3738 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
3739 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
3740 }
3741 eprintln!(
3742 "{NAME}: 10 shown frames pixel-exact on every plane; \
3743 skip_vartx_luma_reset={fired}"
3744 );
3745 }
3746
3747 /// lane-t900 r18 GATE: a 128-root `PARTITION_HORZ`/`PARTITION_VERT` half
3748 /// coded INTRA inside an INTER frame -- the shape an opt-in guarded from
3749 /// lane-inter128intra r1 until this round; it decodes by default now, gated by this stream.
3750 ///
3751 /// What r16 and r17 could not find, and what this recipe exploits: libaom
3752 /// does not PICK a 128-root HORZ/VERT in the frame interior -- r16's
3753 /// 512x512 witness codes its 128 roots as NONE (96) or SPLIT (64) and
3754 /// nothing else, and a textured 640x384 sweep the same. The shape appears
3755 /// where the frame EDGE forces it: with a partial last superblock ROW
3756 /// `has_rows128 == false`, so `PARTITION_HORZ` is implied and only the
3757 /// 128x64 top half is decoded; a partial last COLUMN implies the 64x128
3758 /// left half the same way (the arm the
3759 /// `..._sb128_gathered_edge_horz_partition_...` gate pins for INTER
3760 /// blocks). Put content no reference holds in exactly those two bands and
3761 /// the encoder codes those forced halves INTRA.
3762 ///
3763 /// `crates/ec-av1/fixtures/intra128_in_inter_witness2.obu`, 86516 bytes,
3764 /// sha256 `cace4cc3a5ba4dc5f8c7c219e87c9052351e832cad3d7f4c8ffe09288a6d7ccf`,
3765 /// produced by this repository's aomenc oracle:
3766 ///
3767 /// ```text
3768 /// aomenc --codec=av1 -w 704 -h 320 --input-bit-depth=10 --bit-depth=10 \
3769 /// --sb-size=128 --max-partition-size=128 --enable-rect-partitions=1 \
3770 /// --enable-ab-partitions=0 --enable-1to4-partitions=0 \
3771 /// --enable-intrabc=0 --enable-palette=0 --tune=psnr \
3772 /// --kf-max-dist=9999 --lag-in-frames=0 --cpu-used=1 --end-usage=q \
3773 /// --cq-level=20 --threads=1 --passes=1 --obu -o s.obu src.y4m
3774 /// ```
3775 ///
3776 /// The source is 15 frames of 10-bit 704x320 (704 = 5*128 + 64 and
3777 /// 320 = 2*128 + 64, so BOTH the last superblock column and the last
3778 /// superblock row are partial) whose interior is a low-passed noise
3779 /// texture panning 4 px per frame -- an exact integer translation, so
3780 /// inter predicts it and intra never would -- and whose bottom 64 rows and
3781 /// right 64 columns are replaced at frames 6, 9 and 12 by a fresh smooth
3782 /// diagonal ramp with a different angle and offset each time. No
3783 /// reference holds that content (`--lag-in-frames=0`, so there is no
3784 /// hidden alt-ref either), it is internally smooth, and it lands exactly
3785 /// in the edge-forced halves: `intra128_in_inter` fires 3x 128x64 and
3786 /// 6x 64x128, every one of them inside a frame this gate compares
3787 /// byte-exact against ffmpeg (class `counter-from-refused-stream`).
3788 #[test]
3789 fn an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact() {
3790 const NAME: &str = "an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact";
3791 if !have_ffmpeg() {
3792 eprintln!("SKIP {NAME}: no ffmpeg");
3793 return;
3794 }
3795 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3796 .join("fixtures/intra128_in_inter_witness2.obu");
3797 let stream = std::fs::read(&path)
3798 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
3799 let (width, height) = (704usize, 320usize);
3800 let before = intra128_in_inter_counters();
3801 let frames = match decode_stream(&stream) {
3802 Ok(frames) => frames,
3803 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
3804 };
3805 let after = intra128_in_inter_counters();
3806 let fired = [after[0] - before[0], after[1] - before[1]];
3807 assert!(
3808 fired[0] > 0 && fired[1] > 0,
3809 "{NAME}: intra-128-in-inter fired {fired:?} (128x64, 64x128) -- both \
3810 arms must fire or the gate is vacuous for the one that did not"
3811 );
3812 assert_eq!(frames.len(), 15, "{NAME}: 15 shown frames");
3813 assert_eq!((frames[0].width, frames[0].height), (width, height));
3814 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len());
3815 assert_eq!(
3816 ffmpeg_frames.len(),
3817 frames.len(),
3818 "{NAME}: ffmpeg returned {} frames, we decoded {}",
3819 ffmpeg_frames.len(),
3820 frames.len()
3821 );
3822 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3823 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
3824 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
3825 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
3826 }
3827 eprintln!(
3828 "{NAME}: 15 shown frames pixel-exact on every plane; \
3829 intra128_in_inter 128x64={} 64x128={}",
3830 fired[0], fired[1]
3831 );
3832 }
3833
3834 /// lane-t900 r32 GATE for the LIFTED refusal "a HORZ/VERT intra strip in
3835 /// a screen-content frame (palette syntax is consumed for square blocks
3836 /// only)": the r18 edge-forced recipe re-encoded with
3837 /// `--tune-content=screen`, i.e. the exact case that refusal guarded.
3838 ///
3839 /// `crates/ec-av1/fixtures/intra128_in_inter_screen_witness.obu`, 119048
3840 /// bytes, sha256
3841 /// `c84a493f90327f5d2bea038a42e87cbfe56762b5c6a856d76b4bff9797c5ea09`,
3842 /// from this repository's aomenc oracle over r18's own 10-bit 704x320
3843 /// source (`gen3.py`): the r18 flag set plus `--tune-content=screen
3844 /// --enable-palette=0 --enable-intrabc=0 --cq-level=20`. Three cq levels
3845 /// were swept (20/35/50); all three fire, and the `--enable-rect-\
3846 /// partitions=0` twin of each codes ZERO 128-root halves, which is what
3847 /// says the shape here is the coded HORZ/VERT arm and not an artefact.
3848 ///
3849 /// The lift's proof is r31's enumeration
3850 /// (`no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax`):
3851 /// `av1_allow_palette`'s `bw > 64 || bh > 64` bound means a 128x64/64x128
3852 /// half codes no palette syntax at all, so the screen flag changes nothing
3853 /// about its syntax. This is the WITNESS that the lifted arm is reachable
3854 /// and decodes, which r23's census could not produce.
3855 #[test]
3856 fn an_intra_coded_128_half_in_a_screen_content_inter_frame_decodes_pixel_exact() {
3857 const NAME: &str =
3858 "an_intra_coded_128_half_in_a_screen_content_inter_frame_decodes_pixel_exact";
3859 if !have_ffmpeg() {
3860 eprintln!("SKIP {NAME}: no ffmpeg");
3861 return;
3862 }
3863 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3864 .join("fixtures/intra128_in_inter_screen_witness.obu");
3865 let stream = std::fs::read(&path)
3866 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
3867 let (width, height) = (704usize, 320usize);
3868 // The refusal named `allow_screen_content_tools`, so the gate reads
3869 // that bit out of the frame headers rather than trusting the encoder
3870 // flag (class `gate-blind-to-feature`).
3871 let mut screen_frames = 0u32;
3872 {
3873 let mut p = Av1Parser::new();
3874 let mut pos = 0usize;
3875 while pos < stream.len() {
3876 let obu = p.parse_obu(&stream[pos..]).expect("parse");
3877 pos += obu.total_size;
3878 let header = match &obu.kind {
3879 ObuKind::Frame(h, _) => Some(&**h),
3880 ObuKind::FrameHeader(h) => Some(&**h),
3881 _ => None,
3882 };
3883 if header.is_some_and(|h| h.allow_screen_content_tools) {
3884 screen_frames += 1;
3885 }
3886 }
3887 }
3888 assert!(
3889 screen_frames > 0,
3890 "{NAME}: no frame sets allow_screen_content_tools -- the gate no longer \
3891 exercises the lifted refusal's own condition"
3892 );
3893 let before = intra128_in_inter_counters();
3894 let frames = match decode_stream(&stream) {
3895 Ok(frames) => frames,
3896 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
3897 };
3898 let after = intra128_in_inter_counters();
3899 let fired = [after[0] - before[0], after[1] - before[1]];
3900 assert!(
3901 fired[0] > 0 && fired[1] > 0,
3902 "{NAME}: intra-128-in-inter fired {fired:?} (128x64, 64x128) -- both arms \
3903 must fire or the lift is unwitnessed at the one that did not"
3904 );
3905 assert_eq!(frames.len(), 15, "{NAME}: 15 shown frames");
3906 assert_eq!((frames[0].width, frames[0].height), (width, height));
3907 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len());
3908 assert_eq!(
3909 ffmpeg_frames.len(),
3910 frames.len(),
3911 "{NAME}: frame count vs ffmpeg"
3912 );
3913 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3914 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
3915 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
3916 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
3917 }
3918 eprintln!(
3919 "{NAME}: {screen_frames} screen-content frame(s), 15 shown frames pixel-exact \
3920 on every plane; intra128_in_inter 128x64={} 64x128={}",
3921 fired[0], fired[1]
3922 );
3923 }
3924
3925 /// lane-t900 r22 GATE: a real `aomenc --tune-content=screen
3926 /// --enable-palette=1` stream whose INTER frames reconstruct palette
3927 /// blocks (Y and UV), at both bit depths.
3928 ///
3929 /// Recipe (both fixtures, 15 frames, key + 14 inter, 256x192, one tile):
3930 /// `aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20 --cpu-used=1
3931 /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=9999
3932 /// --sb-size=64 --tune-content=screen --enable-palette=1
3933 /// --enable-intrabc=0 --obu` (plus `--bit-depth=10 --profile=0` for the
3934 /// twin) over a synthetic screen-like source: two luma levels on a 16x16
3935 /// grid, four chroma levels on an 8x8 one, both re-keyed per frame so the
3936 /// encoder cannot predict the new blocks and codes them INTRA inside the
3937 /// inter frames. `--enable-palette=0` on the same source is 13% larger,
3938 /// which is what says the tool is really used.
3939 ///
3940 /// What this pins that no key-frame palette gate can: the palette
3941 /// colour-index CDFs are this decoder's only VARIABLE-ALPHABET tables (the
3942 /// reader takes `[..=n]` of a `[u16; 9]` row, so `update_cdf`'s counter
3943 /// lives at index `n`), and `Cdfs::reset_counts` zeroed slot 8 instead --
3944 /// so every colour-index row crossed a frame boundary with a SATURATED
3945 /// count and adapted at rate 6 where libaom, counting from 0, adapts at 4.
3946 /// The first inter-frame palette block's map desynced at its THIRD
3947 /// colour-index symbol (decode-order frame 3, mi(40,0), map cell (0,2):
3948 /// ours cdf0 = 32768-1071, aomdec's = 32768-971, same ctx, same value,
3949 /// different range).
3950 #[test]
3951 fn a_real_aomenc_screen_stream_with_palette_blocks_decodes_pixel_exact() {
3952 const NAME: &str = "a_real_aomenc_screen_stream_with_palette_blocks_decodes_pixel_exact";
3953 if !have_ffmpeg() {
3954 eprintln!("SKIP {NAME}: no ffmpeg");
3955 return;
3956 }
3957 for (fixture, ten_bit) in [
3958 ("fixtures/palette_screen_witness.obu", false),
3959 ("fixtures/palette_screen_witness_10bit.obu", true),
3960 ] {
3961 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture);
3962 let stream = std::fs::read(&path)
3963 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
3964 let (width, height) = (256usize, 192usize);
3965 let before = intra_in_inter_palette_hits();
3966 let frames = match decode_stream(&stream) {
3967 Ok(frames) => frames,
3968 Err(e) => panic!("{NAME} [{fixture}]: decode_stream refused: {e}"),
3969 };
3970 let after = intra_in_inter_palette_hits();
3971 let (fired_y, fired_uv) = (after.0 - before.0, after.1 - before.1);
3972 assert!(
3973 fired_y > 0 && fired_uv > 0,
3974 "{NAME} [{fixture}]: inter-frame palette fired y={fired_y} uv={fired_uv} \
3975 -- both planes must fire or the gate is vacuous for the one that did not"
3976 );
3977 assert_eq!(frames.len(), 15, "{NAME} [{fixture}]: 15 shown frames");
3978 let ffmpeg_frames = if ten_bit {
3979 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
3980 } else {
3981 ffmpeg_decode_sequence(&stream, width, height, frames.len())
3982 };
3983 assert_eq!(
3984 ffmpeg_frames.len(),
3985 frames.len(),
3986 "{NAME} [{fixture}]: frame count"
3987 );
3988 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3989 assert_eq!(
3990 ours.y, theirs.y,
3991 "{NAME} [{fixture}]: frame {i} luma vs ffmpeg"
3992 );
3993 assert_eq!(
3994 ours.u, theirs.u,
3995 "{NAME} [{fixture}]: frame {i} U vs ffmpeg"
3996 );
3997 assert_eq!(
3998 ours.v, theirs.v,
3999 "{NAME} [{fixture}]: frame {i} V vs ffmpeg"
4000 );
4001 }
4002 eprintln!(
4003 "{NAME} [{fixture}]: 15 frames pixel-exact on every plane; \
4004 inter-frame palette y={fired_y} uv={fired_uv}"
4005 );
4006 }
4007 }
4008
4009 /// lane-t900 r23 GATE for the two LIFTED refusals `"a block that actually
4010 /// uses a palette (Y)/(UV) -- reconstruction is out of scope"` at their
4011 /// 8x8-LEAF site ([`crate::decode`]'s `decode_inter_block8` intra arm):
4012 /// a palette block on an 8x8 intra leaf inside an inter frame.
4013 ///
4014 /// Recipe (`fixtures/palette_screen_leaf8_witness.obu`): 256x192, 15
4015 /// frames, a static two-level 16x16 screen background with a 96x96 patch
4016 /// of hashed 4x4 colour cells that moves non-periodically (so no
4017 /// reference holds it and the encoder codes it INTRA inside the inter
4018 /// frames), `aomenc --tune-content=screen --enable-palette=1
4019 /// --enable-intrabc=0 --sb-size=64 --cq-level=20 --cpu-used=1
4020 /// --lag-in-frames=0 --kf-max-dist=9999 --max-partition-size=8` -- the
4021 /// partition cap is what puts the palette on BLOCK_8X8 rather than on the
4022 /// 16x16/16x8 blocks r22's recipe produced. `EC_PALSYN=1` on aomdec
4023 /// counts 25 `bsize=BLOCK_8X8 palette_size>0` blocks past the key frame.
4024 ///
4025 /// What it caught beyond the refusal itself: a sub-8x8 group publishes no
4026 /// palette state, so it left the row's `left_palette_size` band holding an
4027 /// earlier 8x8 palette block's size and `av1_get_palette_mode_ctx` read 1
4028 /// where libaom gathers 0 (decode-order frame 1, mi(30,30), palette size
4029 /// decoded as 8 instead of 2) -- class `new-map-ignores-tile-edge`, fixed
4030 /// at all three sub-8x8 tails.
4031 #[test]
4032 fn a_screen_stream_with_palette_8x8_leaves_in_inter_frames_decodes_pixel_exact() {
4033 const NAME: &str =
4034 "a_screen_stream_with_palette_8x8_leaves_in_inter_frames_decodes_pixel_exact";
4035 if !have_ffmpeg() {
4036 eprintln!("SKIP {NAME}: no ffmpeg");
4037 return;
4038 }
4039 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
4040 .join("fixtures/palette_screen_leaf8_witness.obu");
4041 let stream = std::fs::read(&path)
4042 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
4043 let before = inter8_palette_hits();
4044 let frames = match decode_stream(&stream) {
4045 Ok(frames) => frames,
4046 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
4047 };
4048 let after = inter8_palette_hits();
4049 let (fired_y, fired_uv) = (after.0 - before.0, after.1 - before.1);
4050 assert!(
4051 fired_y > 0,
4052 "{NAME}: no palette block on an 8x8 leaf inside an inter frame \
4053 -- the gate is vacuous for the site whose refusal it pins"
4054 );
4055 assert_eq!(frames.len(), 15, "{NAME}: 15 shown frames");
4056 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 256, 192, frames.len());
4057 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: frame count");
4058 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4059 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
4060 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
4061 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
4062 }
4063 eprintln!("{NAME}: 15 frames pixel-exact; 8x8-leaf palette y={fired_y} uv={fired_uv}");
4064 }
4065
4066 /// lane-t900 r22 GATE for the LIFTED refusal `"a HORZ/VERT intra strip in
4067 /// a screen-content frame (palette syntax is consumed for square blocks
4068 /// only)"` on its 16x4/4x16 arm: that arm routes through
4069 /// `decode_rect4_16_strip`, which takes `allow_screen_content_tools` and
4070 /// reads the whole palette syntax itself, so the refusal was a stale
4071 /// premise (the key-frame path proves that body). This 10-bit
4072 /// `--tune-content=screen` stream reached that exact refusal before the
4073 /// lift and now decodes all 15 frames pixel-exact while 8 inter-frame
4074 /// palette blocks reconstruct.
4075 #[test]
4076 fn a_screen_stream_with_16x4_intra_strips_in_inter_frames_decodes_pixel_exact() {
4077 const NAME: &str =
4078 "a_screen_stream_with_16x4_intra_strips_in_inter_frames_decodes_pixel_exact";
4079 if !have_ffmpeg() {
4080 eprintln!("SKIP {NAME}: no ffmpeg");
4081 return;
4082 }
4083 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
4084 .join("fixtures/palette_screen_strip16_witness_10bit.obu");
4085 let stream = std::fs::read(&path)
4086 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
4087 let before = intra_in_inter_palette_hits();
4088 let frames = match decode_stream(&stream) {
4089 Ok(frames) => frames,
4090 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
4091 };
4092 let fired_y = intra_in_inter_palette_hits().0 - before.0;
4093 assert!(
4094 fired_y > 0,
4095 "{NAME}: no inter-frame palette block -- gate is vacuous"
4096 );
4097 assert_eq!(frames.len(), 15, "{NAME}: 15 shown frames");
4098 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, 256, 192, frames.len());
4099 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4100 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
4101 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
4102 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
4103 }
4104 eprintln!("{NAME}: 15 frames pixel-exact; inter-frame palette y={fired_y}");
4105 }
4106
4107 /// lane-t900 r20 GATE, refusal A -- `"a non-skip rectangular
4108 /// (HORZ/VERT/HORZ_B) strip needs rectangular residual coding"`.
4109 ///
4110 /// That string is a claim about a SHAPE, so what proves it is the set of
4111 /// shapes the inter block path presents. `inter_piece!` sets
4112 /// `reject_residual` to `$ww != $side || $wh != $side`, i.e. only for a
4113 /// block whose true footprint is not its square CDF context, and the
4114 /// refusal then needs `!rect_inter_residual_supported(write_w, write_h)`.
4115 /// So it can fire only for a footprint that is BOTH rectangular (or a
4116 /// square smaller than its own context) AND missing from that table.
4117 ///
4118 /// This gate measures the domain instead of asserting it:
4119 /// [`crate::decode::inter_block_shape_mask`] records every
4120 /// `(side, write_w, write_h)` triple decoded on this thread, with bit 31
4121 /// reserved for a triple [`crate::decode::INTER_BLOCK_SHAPES`] does not
4122 /// list. Three real streams -- a 10-bit 1920x792 128-superblock film cut,
4123 /// its 128-root intra witness and the 1920x792 small-side warp cut,
4124 /// together ~140k inter blocks -- decode without a refusal and present
4125 /// exactly 18 triples: the four square ones (`write == side`, where
4126 /// `reject_residual` is false) and the fourteen rectangular AV1 block
4127 /// shapes, every one of which `rect_inter_residual_supported` covers. No
4128 /// square-inside-a-larger-context triple appears at all.
4129 ///
4130 /// Measured 2026-09-04: mask covers 18/18 listed triples, bit 31 clear,
4131 /// 0 refusals.
4132 #[test]
4133 fn a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable() {
4134 const NAME: &str = "a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable";
4135 const REFUSAL: &str =
4136 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding";
4137 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures");
4138 let mut blocks = 0usize;
4139 for name in [
4140 "reelc_sb128_inter_witness.obu",
4141 "intra128_in_inter_witness2.obu",
4142 "gm_small_side_witness.obu",
4143 ] {
4144 let path = dir.join(name);
4145 let stream = std::fs::read(&path)
4146 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
4147 match decode_stream(&stream) {
4148 Ok(frames) => {
4149 assert!(!frames.is_empty(), "{NAME}: {name} decoded no frame");
4150 blocks += frames.len();
4151 }
4152 Err(e) => {
4153 assert!(
4154 !format!("{e}").contains(REFUSAL),
4155 "{NAME}: {name} hit the refusal this gate proves unreachable: {e}"
4156 );
4157 panic!("{NAME}: {name} refused: {e}");
4158 }
4159 }
4160 }
4161 assert!(blocks > 0, "{NAME}: no frames decoded");
4162 let mask = crate::decode::inter_block_shape_mask();
4163 assert_eq!(
4164 mask & crate::decode::INTER_BLOCK_SHAPE_UNLISTED,
4165 0,
4166 "{NAME}: a (side, write_w, write_h) triple outside INTER_BLOCK_SHAPES was decoded -- the census no longer describes the inter path's domain, so {REFUSAL:?} is not proven by it"
4167 );
4168 for (i, &(side, w, h)) in crate::decode::INTER_BLOCK_SHAPES.iter().enumerate() {
4169 assert!(
4170 mask & (1u32 << i) != 0,
4171 "{NAME}: {side}: {w}x{h} never decoded -- the census would prove nothing about it"
4172 );
4173 // `reject_residual` is false for a square footprint (`write ==
4174 // side`), so only the rectangular ones can reach the refusal.
4175 if (w, h) != (side, side) {
4176 assert!(
4177 crate::decode::rect_inter_residual_supported(w, h),
4178 "{NAME}: {w}x{h} is decoded by real streams with reject_residual set but has no rectangular residual path -- {REFUSAL:?} is reachable"
4179 );
4180 }
4181 }
4182 eprintln!(
4183 "{NAME}: 3 streams, 0 refusals, {} of {} listed (side, write) triples decoded, bit31 clear",
4184 crate::decode::INTER_BLOCK_SHAPES.len(),
4185 crate::decode::INTER_BLOCK_SHAPES.len()
4186 );
4187 }
4188
4189 /// lane-t900 r20 GATE, refusal C -- `"an intra 16x4/4x16 strip inside an
4190 /// inter 16x16-level 1:4 partition (its 4:2:0 chroma pair is coded once
4191 /// for two strips; only the inter path implements that pairing)"`.
4192 ///
4193 /// The arm fires for an INTRA footprint with a side below 8 that carries
4194 /// no chroma-pair record (`strip16`). Two measurements make that a claim
4195 /// rather than a hope:
4196 ///
4197 /// * the block-shape census: the ONLY sub-8 footprints three real streams
4198 /// present are 16x4 and 4x16 at a 16-px context, i.e. the strips of a
4199 /// 16x16-level 1:4 partition -- and that caller sets
4200 /// `INTER_STRIP_CHROMA` for every one of its four strips before the
4201 /// block is decoded, so the record is never missing there;
4202 /// * the sibling counter: the SUPPORTED path
4203 /// ([`crate::decode::intra16x4_in_inter_hits`]) fires on both
4204 /// orientations, chroma-paired, inside streams that decode with no
4205 /// refusal at all.
4206 ///
4207 /// Measured 2026-09-04: 3 streams, 0 refusals, 78 16x4 + 149 4x16 (108
4208 /// chroma-paired), and 2 of 2 sub-8 census triples are the 1:4 strips.
4209 #[test]
4210 fn a_sub8_footprint_census_over_real_streams_leaves_the_intra_16x4_pairing_refusal_unreachable()
4211 {
4212 const NAME: &str = "a_sub8_footprint_census_over_real_streams_leaves_the_intra_16x4_pairing_refusal_unreachable";
4213 const REFUSAL: &str = "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition";
4214 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures");
4215 let before = crate::decode::intra16x4_in_inter_hits();
4216 for name in [
4217 "reelc_sb128_inter_witness.obu",
4218 "intra128_in_inter_witness2.obu",
4219 "gm_small_side_witness.obu",
4220 ] {
4221 let path = dir.join(name);
4222 let stream = std::fs::read(&path)
4223 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
4224 if let Err(e) = decode_stream(&stream) {
4225 assert!(
4226 !format!("{e}").contains(REFUSAL),
4227 "{NAME}: {name} hit the refusal this gate proves unreachable: {e}"
4228 );
4229 panic!("{NAME}: {name} refused: {e}");
4230 }
4231 }
4232 let after = crate::decode::intra16x4_in_inter_hits();
4233 let fired = (after.0 - before.0, after.1 - before.1, after.2 - before.2);
4234 assert!(
4235 fired.0 > 0 && fired.1 > 0 && fired.2 > 0,
4236 "{NAME}: the SUPPORTED intra 16x4/4x16-in-inter path fired {fired:?} \
4237 (16x4, 4x16, chroma-paired) -- with a sibling at zero the refusal's claim is \
4238 untested from the other side"
4239 );
4240 let sub8: Vec<(usize, usize, usize)> = crate::decode::INTER_BLOCK_SHAPES
4241 .iter()
4242 .copied()
4243 .filter(|&(_, w, h)| w.min(h) < 8)
4244 .collect();
4245 assert_eq!(
4246 sub8,
4247 vec![(16, 4, 16), (16, 16, 4)],
4248 "{NAME}: the sub-8 footprints the inter path presents are no longer just the \
4249 16x16-level 1:4 strips, whose caller always records the chroma pair -- the \
4250 refusal's domain changed"
4251 );
4252 let mask = crate::decode::inter_block_shape_mask();
4253 for (i, &(side, w, h)) in crate::decode::INTER_BLOCK_SHAPES.iter().enumerate() {
4254 if w.min(h) < 8 {
4255 assert!(
4256 mask & (1u32 << i) != 0,
4257 "{NAME}: {side}: {w}x{h} never decoded -- the sub-8 census is vacuous"
4258 );
4259 }
4260 }
4261 eprintln!(
4262 "{NAME}: 3 streams, 0 refusals, intra16x4_in_inter 16x4={} 4x16={} chroma_ref={}, \
4263 sub-8 census triples {sub8:?}",
4264 fired.0, fired.1, fired.2
4265 );
4266 }
4267
4268 /// lane-t900 r10: the small-side GLOBALMV / rect warp-reach witness.
4269 /// `crates/ec-av1/fixtures/gm_small_side_witness.obu`, 1158066 bytes,
4270 /// sha256 `f1cdbcbb8d6d469c7957d70252ab42b24ab75f48a717600ffa25991458775dca`:
4271 /// the first 50 frame-carrying OBUs of a 2 s cut taken 5400 s into a 10-bit
4272 /// 1920x792 AV1 stream with `use_128x128_superblock=1` -- 34 decode-order
4273 /// frames, 33 shown, every ARF in it coded with `allow_warped_motion=1`.
4274 /// Truncated twice independently from the same source, both cuts hash
4275 /// identically. All 34 DECODE-order frames (the hidden ARF included) were
4276 /// compared byte-exact against instrumented aomdec with `EC_AV1_FINAL_DUMP`
4277 /// -- see the lane report's EVIDENCE line; the gate itself compares the 33
4278 /// shown frames on every plane, which is all ffmpeg hands back.
4279 ///
4280 /// It is the only stream in this repository that fires BOTH r9/r10 paths:
4281 ///
4282 /// * `gm_nontrans_small_side_hits` -- libaom `is_nontrans_global_motion`
4283 /// returns 0 at `AOMMIN(mi_size_wide, mi_size_high) < 2` BEFORE it looks
4284 /// at any warp model, so a GLOBALMV block with a 4-px side still reads
4285 /// its interp filter. We suppressed that symbol before r9.
4286 /// * `tr_reach_longer_side_hits` -- `av1_findSamples` probes the top-right
4287 /// warp sample at `AOMMAX(xd->width, xd->height)` (mvref_common.c:1235)
4288 /// with libaom's two rect shape refinements
4289 /// (`is_last_vertical_rect` / `is_first_horizontal_rect`,
4290 /// av1_common_int.h:1419-1428) applied; probing at the block's WIDTH
4291 /// instead picks the 3-symbol `motion_mode` alphabet where libaom reads
4292 /// the 2-symbol `obmc` one -- same value, different narrowing.
4293 #[test]
4294 fn a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_reach_decode_pixel_exact() {
4295 const NAME: &str =
4296 "a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_reach_decode_pixel_exact";
4297 if !have_ffmpeg() {
4298 eprintln!("SKIP {NAME}: no ffmpeg");
4299 return;
4300 }
4301 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
4302 .join("fixtures/gm_small_side_witness.obu");
4303 let stream = std::fs::read(&path)
4304 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
4305 let (width, height) = (1920usize, 792usize);
4306 let gm_before = crate::decode::gm_nontrans_small_side_hits();
4307 let tr_before = crate::decode::tr_reach_longer_side_hits();
4308 // lane-t900 r13: this stream is also the witness for r12's mi-granular
4309 // uv_mode grid -- the chroma edge-filter neighbour read that the coarse
4310 // one-slot-per-column map answered wrongly inside a sub-8x8 pair.
4311 let uv_before = crate::decode::uv_mode_grid_override_hits();
4312 let frames = match decode_stream(&stream) {
4313 Ok(frames) => frames,
4314 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
4315 };
4316 let gm = crate::decode::gm_nontrans_small_side_hits() - gm_before;
4317 let tr = crate::decode::tr_reach_longer_side_hits() - tr_before;
4318 let uvg = crate::decode::uv_mode_grid_override_hits() - uv_before;
4319 assert!(
4320 uvg > 0,
4321 "{NAME}: uv_mode_grid_override never fired -- the chroma edge-filter \
4322 grid read would be untested"
4323 );
4324 assert!(
4325 gm > 0,
4326 "{NAME}: gm_nontrans_small_side never fired -- the gate would be vacuous for it"
4327 );
4328 assert!(
4329 tr > 0,
4330 "{NAME}: tr_reach_longer_side never fired -- the gate would be vacuous for it"
4331 );
4332 assert_eq!(frames.len(), 33, "{NAME}: 33 shown frames");
4333 assert_eq!((frames[0].width, frames[0].height), (width, height));
4334 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len());
4335 assert_eq!(
4336 ffmpeg_frames.len(),
4337 frames.len(),
4338 "{NAME}: ffmpeg returned {} frames, we decoded {}",
4339 ffmpeg_frames.len(),
4340 frames.len()
4341 );
4342 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4343 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
4344 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
4345 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
4346 }
4347 eprintln!(
4348 "{NAME}: 33 shown frames pixel-exact on every plane; \
4349 gm_nontrans_small_side={gm} tr_reach_longer_side={tr} \
4350 uv_mode_grid_override={uvg}"
4351 );
4352 }
4353
4354 /// lane-film10fix: the DECODE-ORDER half of the two charter-named 10-bit
4355 /// film gates, against the instrumented `aomdec` rather than ffmpeg.
4356 ///
4357 /// `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...` (15 shown
4358 /// frames) and `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_...`
4359 /// (33 shown) each hold exactly ONE hidden alt-ref frame, and both
4360 /// compare through `ffmpeg_decode_sequence_10bit`, which emits SHOWN
4361 /// frames only. So one frame in 16 and one in 34 of each stream is
4362 /// outside both gates' reach -- class `gate-blind-to-hidden-frames`: a
4363 /// defect in a hidden frame surfaces only as drift on some later shown
4364 /// frame, if at all. Their doc comments claim the hidden frames were
4365 /// compared byte-exact against aomdec, but that measurement lived in a
4366 /// lane report, not in a test, so nothing re-ran it.
4367 ///
4368 /// This gate is that measurement, committed.
4369 /// [`decode_all_frames_vs_oracle`] writes `EC_AV1_FINAL_DUMP` on both
4370 /// sides (ours in `decode_stream`, the oracle's in rung 12 of
4371 /// `scripts/instrument-aom-oracle.sh`) and byte-compares EVERY decode-order
4372 /// frame, hidden included. Both fixtures are the same 1920x792 10-bit
4373 /// films their own gates pin, at the sha256 those gates record.
4374 ///
4375 /// The frame counts are asserted, not just reported: 16 = 15 shown + 1
4376 /// hidden, 34 = 33 shown + 1. A stream that quietly lost its hidden ARF
4377 /// would make this compare fewer frames and would otherwise read as a
4378 /// pass.
4379 #[test]
4380 fn the_two_10bit_film_pins_match_aomdec_on_every_decode_order_frame() {
4381 const NAME: &str = "the_two_10bit_film_pins_match_aomdec_on_every_decode_order_frame";
4382 let _gate_lock = lock_gate_counters();
4383 if !aomdec_available(NAME) {
4384 return;
4385 }
4386 // The pin paths are BOUND HERE, from literals, rather than built from
4387 // the loop variable: `crate_pin`'s argument has to be a literal the
4388 // fixture-library census can resolve, or invariant 4 reports this gate
4389 // as UNPROVEN ("name built at runtime -- this census cannot resolve
4390 // it") and a preflight that checks code shape goes RED.
4391 let pins: [(&str, std::path::PathBuf, usize, usize); 2] = [
4392 (
4393 "reelc_sb128_inter_witness.obu",
4394 crate_pin("reelc_sb128_inter_witness.obu"),
4395 16usize,
4396 15usize,
4397 ),
4398 (
4399 "gm_small_side_witness.obu",
4400 crate_pin("gm_small_side_witness.obu"),
4401 34usize,
4402 33usize,
4403 ),
4404 ];
4405 for (pin, path, frames, shown) in pins {
4406 let stream =
4407 std::fs::read(&path).unwrap_or_else(|e| panic!("{NAME}: reading {pin}: {e}"));
4408 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
4409 assert_eq!(
4410 (decoded, hidden),
4411 (frames, frames - shown),
4412 "{NAME}: {pin} must decode to {frames} decode-order frames of which {shown} are \
4413 shown -- a stream that lost its hidden alt-ref would make the byte compare below \
4414 cover less than it claims"
4415 );
4416 eprintln!(
4417 "{NAME}: {pin} {decoded} decode-order frames ({hidden} hidden) byte-exact vs \
4418 aomdec EC_AV1_FINAL_DUMP on every plane"
4419 );
4420 }
4421 }
4422
4423 /// lane-t900 r11: the frame-edge MV clamp witness.
4424 ///
4425 /// `crates/ec-av1/fixtures/reelb_head_mvclamp_witness.obu` (72158 bytes,
4426 /// sha256 451a9b138995e636f22308847a123b5c8621d4908cd93772cf5bbf2b37df39d7,
4427 /// truncated twice independently to identical hashes) is the first 80
4428 /// frame-carrying OBUs of a 10-bit 3840x1608 HDR film head -- the SMALLEST
4429 /// such prefix that fires the clamp (N=79 fires 0, N=80 fires 5). 55
4430 /// decode-order frames, 52 shown, every decode-order frame byte-identical
4431 /// to instrumented aomdec (`EC_AV1_FINAL_DUMP`, see the r11 report).
4432 ///
4433 /// The path it pins: libaom's `mb_to_right_edge` / `mb_to_bottom_edge`
4434 /// (`set_mi_row_col`, av1_common_int.h) are SIGNED, and a block that
4435 /// overhangs the frame's right/bottom edge keeps its full `bw4`/`bh4`, so
4436 /// `mi_cols - bw4 - mi_col` and `mi_rows - bh4 - mi_row` go NEGATIVE there
4437 /// and `clamp_mv_ref` (mvref_common.h) narrows the stack window by that
4438 /// much. This frame height is 1608 -> `mi_rows == 402`, so every 64x64
4439 /// block on the bottom row overhangs by 14 mi units. Computing that
4440 /// difference in `usize` saturated it to 0 and left the window 448 subpel
4441 /// too wide, so an edge block's predictor was never clamped -- one 64x64
4442 /// NEWMV block at mi(400,368) took `mv0=(224,568)` where libaom takes
4443 /// `(32,568)`, its MC then read the replicated bottom row instead of real
4444 /// reference rows, and the frame missed by 221 bytes.
4445 #[test]
4446 fn a_10bit_film_frames_with_frame_edge_mv_clamping_decode_pixel_exact() {
4447 const NAME: &str = "a_10bit_film_frames_with_frame_edge_mv_clamping_decode_pixel_exact";
4448 if !have_ffmpeg() {
4449 eprintln!("SKIP {NAME}: no ffmpeg");
4450 return;
4451 }
4452 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
4453 .join("fixtures/reelb_head_mvclamp_witness.obu");
4454 let stream = std::fs::read(&path)
4455 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
4456 let (width, height) = (3840usize, 1608usize);
4457 let clamp_before = crate::mvstack::mv_clamp_edge_overhang_hits();
4458 let frames = match decode_stream(&stream) {
4459 Ok(frames) => frames,
4460 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
4461 };
4462 let clamped = crate::mvstack::mv_clamp_edge_overhang_hits() - clamp_before;
4463 assert!(
4464 clamped > 0,
4465 "{NAME}: mv_clamp_edge_overhang never fired -- the gate would be vacuous for it"
4466 );
4467 assert_eq!(frames.len(), 52, "{NAME}: 52 shown frames");
4468 assert_eq!((frames[0].width, frames[0].height), (width, height));
4469 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len());
4470 assert_eq!(
4471 ffmpeg_frames.len(),
4472 frames.len(),
4473 "{NAME}: ffmpeg returned {} frames, we decoded {}",
4474 ffmpeg_frames.len(),
4475 frames.len()
4476 );
4477 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4478 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
4479 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
4480 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
4481 }
4482 eprintln!(
4483 "{NAME}: 52 shown frames pixel-exact on every plane; \
4484 mv_clamp_edge_overhang={clamped}"
4485 );
4486 }