forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

t08.rs4540 lines, 206.3 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-tiles r10: non-uniform tile spacing (`uniform_spacing_flag == 0`,
9 /// spec 5.9.15). aomenc never sets this from `--tile-columns`/
10 /// `--tile-rows` (those always take the `uniform_spacing = 1` branch in
11 /// `set_tile_info`, libaom `encoder.c`), and `--auto-tiles` only takes
12 /// the non-uniform balancing path when `g_threads >= 2` -- this charter's
13 /// `--threads=1` rules that out. The only CLI surface that reaches
14 /// libaom's `else { tiles->uniform_spacing = 0; ... }` arm is the
15 /// explicit per-tile size lists `--tile-width=<sb-list>`/
16 /// `--tile-height=<sb-list>` (`av1_cx_iface.c` `set_tile_info`, argument
17 /// parsing at `arg_defs.c`'s `.tile_width`/`.tile_height` -- present in
18 /// the binary, just not printed by `--help`). Probed live with
19 /// `aomenc --tile-width=1,3 --tile-height=1 --sb-size=64` on a 256x64
20 /// source (4 SB columns, 1 SB row): confirmed by hand this round to
21 /// produce a real OBU stream aomdec/ffmpeg both decode.
22 ///
23 /// `decode.rs`'s tile loop was already generic over spacing before this
24 /// gate existed -- it walks `tile_info.mi_col_starts`/`mi_row_starts`
25 /// (populated identically by `read_tile_info` for both the uniform and
26 /// non-uniform branches, spec 5.9.15) and never recomputes tile bounds
27 /// from `cols_log2`/`rows_log2`. The only place in this crate that ever
28 /// refused non-uniform spacing is `frame.rs`'s OBU *writer*
29 /// (`"non-uniform tile spacing is not written"`), an unrelated encode
30 /// path this gate does not touch. So this is a staleness check, not new
31 /// machinery: prove the already-generic decode path live and pin it.
32 #[test]
33 fn a_real_aomenc_stream_with_non_uniform_tile_spacing_decodes_pixel_exact() {
34 const NAME: &str = "a_real_aomenc_stream_with_non_uniform_tile_spacing_decodes_pixel_exact";
35 if !have_ffmpeg() {
36 eprintln!("SKIP {NAME}: no ffmpeg");
37 return;
38 }
39 if !have_aomenc() {
40 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
41 return;
42 }
43 let (width, height) = (256usize, 64usize);
44 let mut matched = 0u32;
45 let mut named_refusals = 0u32;
46 let mut saw_non_uniform_spacing = false;
47 for attempt in 0..20u32 {
48 let seed = 42 + attempt;
49 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
50 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
51 .args([
52 "-v",
53 "error",
54 "-f",
55 "lavfi",
56 "-i",
57 &source,
58 "-pix_fmt",
59 "yuv420p",
60 "-f",
61 "yuv4mpegpipe",
62 "-",
63 ])
64 .stdin(Stdio::null())
65 .stdout(Stdio::piped())
66 .stderr(Stdio::piped()), None, |c| c.output())
67 .expect("ffmpeg failed to run");
68 assert!(
69 y4m.status.success(),
70 "ffmpeg fixture: {}",
71 String::from_utf8_lossy(&y4m.stderr)
72 );
73 let out = run_with_stdin(
74 Command::new(aomenc_path()).args([
75 "--codec=av1",
76 "--passes=1",
77 "--end-usage=q",
78 "--cq-level=45",
79 "--cpu-used=0",
80 "--limit=1",
81 "--kf-max-dist=1000",
82 "--threads=1",
83 "--row-mt=0",
84 "--sb-size=64",
85 "--tile-width=1,3",
86 "--tile-height=1",
87 "--loopfilter-control=0",
88 "--enable-rect-partitions=0",
89 "--enable-ab-partitions=0",
90 "--enable-1to4-partitions=0",
91 "--enable-filter-intra=0",
92 "--enable-smooth-intra=0",
93 "--enable-paeth-intra=0",
94 "--enable-directional-intra=0",
95 "--enable-angle-delta=0",
96 "--enable-tx-size-search=0",
97 "--enable-cdef=0",
98 "--enable-restoration=0",
99 "--max-partition-size=32",
100 "--min-partition-size=32",
101 "--enable-palette=0",
102 "--enable-intrabc=0",
103 "--enable-cfl-intra=0",
104 "--obu",
105 "-o",
106 "-",
107 "-",
108 ]),
109 &y4m.stdout,
110 );
111 assert!(
112 out.status.success(),
113 "aomenc refused the fixture: {}",
114 String::from_utf8_lossy(&out.stderr)
115 );
116 let stream = out.stdout;
117
118 let mut probe = Av1Parser::new();
119 let mut pos = 0usize;
120 while pos < stream.len() {
121 let obu = probe.parse_obu(&stream[pos..]).unwrap();
122 pos += obu.total_size;
123 let tile_info = match &obu.kind {
124 ObuKind::Frame(header, _) => Some(&header.tile_info),
125 ObuKind::FrameHeader(header) if !header.show_existing_frame => {
126 Some(&header.tile_info)
127 }
128 _ => None,
129 };
130 if let Some(info) = tile_info {
131 if !info.uniform_spacing {
132 saw_non_uniform_spacing = true;
133 }
134 assert!(
135 info.cols > 1 || info.rows > 1,
136 "{NAME}: --tile-width=1,3 --tile-height=1 produced only 1 tile \
137 (cols={} rows={}, seed {seed}) -- fixture stopped exercising the case",
138 info.cols,
139 info.rows
140 );
141 }
142 }
143
144 let before = crate::decode::tile_hits();
145 let pictures = match decode_stream(&stream) {
146 Err(e) => {
147 let msg = e.to_string();
148 assert!(
149 msg.contains("unsupported"),
150 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
151 );
152 named_refusals += 1;
153 eprintln!("seed {seed} refusal: {msg}");
154 continue;
155 }
156 Ok(pictures) => pictures,
157 };
158 let hits = crate::decode::tile_hits() - before;
159 assert!(
160 hits > 0,
161 "{NAME}: tile_hits delta was {hits}, expected >0 (seed {seed})"
162 );
163 assert_eq!(
164 pictures.len(),
165 1,
166 "{NAME}: expected exactly 1 picture (seed {seed})"
167 );
168
169 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
170 assert_eq!(
171 pictures[0].y, ffmpeg_frames[0].y,
172 "{NAME}: luma vs ffmpeg (seed {seed})"
173 );
174 assert_eq!(
175 pictures[0].u, ffmpeg_frames[0].u,
176 "{NAME}: U vs ffmpeg (seed {seed})"
177 );
178 assert_eq!(
179 pictures[0].v, ffmpeg_frames[0].v,
180 "{NAME}: V vs ffmpeg (seed {seed})"
181 );
182 matched += 1;
183 }
184 assert!(
185 matched > 0,
186 "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
187 decoded a non-uniform-tile-spacing stream"
188 );
189 assert!(
190 saw_non_uniform_spacing,
191 "{NAME}: no attempt actually set uniform_spacing_flag == 0 -- this sweep proves \
192 nothing about the non-uniform case"
193 );
194 eprintln!(
195 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
196 );
197 }
198
199 /// lane-sb128 r1 gate: a real `aomenc --sb-size=128` stream (the size his
200 /// ReelC encode uses -- `EC_TRACE=1 aomdec reelc-head.obu` prints
201 /// `EC_PART mi_row=0 mi_col=0 bsize=15` = `BLOCK_128X128`) must decode
202 /// pixel-exact. `--max-partition-size=64` keeps the RD search from ever
203 /// choosing a 128-level NONE/HORZ/VERT/AB arm, so every 128 root here is
204 /// genuinely `PARTITION_SPLIT` -- the one arm
205 /// `decode_key_frame_tile_with_cdfs` codes; the other seven refuse by
206 /// name (`PART128_NON_SPLIT_REFUSAL`) and stay refused after this round.
207 ///
208 /// What the 128 root actually changes, and what this gate therefore
209 /// proves: the 8-symbol `partition_w128` CDF and its forced-split gather
210 /// at the frame edge, the quadrant VISIT ORDER (TL, TR, BL, BR inside one
211 /// superblock, not raster over 64x64 superblocks), one loop-restoration
212 /// read per 128x128 instead of per 64x64, `delta_q`/`delta_lf` once per
213 /// 128x128, and the per-64x64 `cdef_idx` read inside the 128 superblock.
214 /// 256x192 gives a 2x2 grid of 128 superblocks whose bottom row is a
215 /// partial superblock (the gathered forced-split read); 384x384 gives a
216 /// 3x3 grid of whole ones. 8-bit sweep plus one 10-bit stream (his films
217 /// are `yuv420p10le`). Only a missing tool SKIPs.
218 #[test]
219 fn a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact() {
220 const NAME: &str = "a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact";
221 let _gate_lock = lock_gate_counters();
222 if !have_ffmpeg() {
223 eprintln!("SKIP {NAME}: no ffmpeg");
224 return;
225 }
226 if !have_aomenc() {
227 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
228 return;
229 }
230 let base: Vec<&str> = vec![
231 "--codec=av1",
232 "--passes=1",
233 "--end-usage=q",
234 "--cq-level=40",
235 "--cpu-used=0",
236 "--threads=1",
237 "--row-mt=0",
238 "--sb-size=128",
239 "--max-partition-size=64",
240 "--enable-rect-partitions=1",
241 "--enable-ab-partitions=0",
242 "--enable-1to4-partitions=0",
243 // aomenc emits PARTITION_HORZ_4/VERT_4 below 16x16 even with the
244 // flag off (ledger, lane-modectx r1), so bound the search instead.
245 "--min-partition-size=16",
246 "--enable-restoration=1",
247 "--enable-palette=0",
248 "--deltaq-mode=0",
249 "--enable-intrabc=0",
250 "--enable-tx-size-search=0",
251 "--limit=1",
252 ];
253 let encode = |y4m: &[u8], extra: &[&str]| -> Vec<u8> {
254 let mut args = base.clone();
255 args.extend_from_slice(extra);
256 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
257 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m);
258 assert!(
259 out.status.success(),
260 "aomenc refused the fixture: {}",
261 String::from_utf8_lossy(&out.stderr)
262 );
263 out.stdout
264 };
265 let render = |seed: u32, width: usize, height: usize, ten_bit: bool| -> Vec<u8> {
266 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
267 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
268 .args([
269 "-v",
270 "error",
271 "-f",
272 "lavfi",
273 "-i",
274 &gradients_source(seed, width, height, "duration=0.04:rate=25"),
275 "-pix_fmt",
276 pix,
277 "-strict",
278 "-1",
279 "-t",
280 "0.04",
281 "-f",
282 "yuv4mpegpipe",
283 "-",
284 ])
285 .stdin(Stdio::null())
286 .stdout(Stdio::piped())
287 .stderr(Stdio::piped()), None, |c| c.output())
288 .expect("ffmpeg failed to run");
289 assert!(
290 out.status.success(),
291 "ffmpeg fixture: {}",
292 String::from_utf8_lossy(&out.stderr)
293 );
294 out.stdout
295 };
296 let mut matched = 0u32;
297 let mut named_refusals = 0u32;
298 // (seed, width, height, 10-bit): 256x192 = 2x2 superblocks with a
299 // partial bottom row; 384x384 = 3x3 whole ones.
300 let arms: Vec<(u32, usize, usize, bool)> = vec![
301 (42, 256, 192, false),
302 (43, 256, 192, false),
303 (44, 256, 192, false),
304 (45, 384, 384, false),
305 (46, 256, 192, true),
306 (47, 384, 384, true),
307 ];
308 for (seed, width, height, ten_bit) in arms {
309 let y4m = render(seed, width, height, ten_bit);
310 let extra: Vec<&str> = if ten_bit {
311 vec!["--input-bit-depth=10", "--bit-depth=10"]
312 } else {
313 vec![]
314 };
315 let stream = encode(&y4m, &extra);
316 let parsed = {
317 let mut parser = ec_av1_syntax::Av1Parser::new();
318 let mut pos = 0usize;
319 while let Ok(obu) = parser.parse_obu(&stream[pos..]) {
320 pos += obu.total_size;
321 if pos >= stream.len() {
322 break;
323 }
324 }
325 parser
326 .sequence_header()
327 .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth))
328 };
329 assert_eq!(
330 parsed,
331 Some((true, if ten_bit { 10 } else { 8 })),
332 "{NAME} (seed {seed}): the encoder did not write a 128x128-superblock \
333 sequence header at the requested bit depth -- the flag never arrived"
334 );
335 let frames = match decode_stream(&stream) {
336 Err(e) => {
337 let msg = e.to_string();
338 assert!(
339 msg.contains("unsupported"),
340 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
341 );
342 named_refusals += 1;
343 eprintln!("seed {seed} refusal: {msg}");
344 continue;
345 }
346 Ok(frames) => frames,
347 };
348 let want = if ten_bit {
349 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
350 } else {
351 ffmpeg_decode_sequence(&stream, width, height, 1)
352 };
353 assert_eq!(frames.len(), 1);
354 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
355 assert_eq!(
356 got.y, want.y,
357 "{NAME} frame {i} luma vs ffmpeg (seed {seed})"
358 );
359 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
360 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
361 }
362 matched += 1;
363 }
364 assert!(
365 matched > 0,
366 "{NAME}: every attempt refused; the gate never decoded a stream"
367 );
368 // 256x192 codes 3 whole + 1 partial superblock, 384x384 codes 9 whole
369 // ones, so a run that decoded anything at all must have read real 128
370 // partition symbols and split every one of them.
371 assert!(
372 crate::decode::part128_symbols() >= 3 * matched as usize,
373 "{NAME}: only {} 128-level partition symbols over {matched} decoded streams -- \
374 the 128 root never fired",
375 crate::decode::part128_symbols()
376 );
377 assert!(
378 crate::decode::part128_split_hits() >= 4 * matched as usize,
379 "{NAME}: only {} 128 superblocks split",
380 crate::decode::part128_split_hits()
381 );
382 eprintln!(
383 "{NAME}: {matched} pixel-exact, {named_refusals} named refusals, \
384 part128_symbols={} part128_split_hits={}",
385 crate::decode::part128_symbols(),
386 crate::decode::part128_split_hits()
387 );
388 }
389
390 /// lane-sb128b r1 gate: a real `aomenc --sb-size=128` KEY frame whose 128
391 /// roots resolve to `PARTITION_NONE` -- one whole 128x128 intra block,
392 /// four TX_64X64 luma transform units and FOUR TX_32X32 chroma units per
393 /// plane (`av1_get_max_uv_txsize(BLOCK_128X128)` is
394 /// `av1_get_adjusted_tx_size` of its 64x64 uv plane block's TX_64X64, so
395 /// TX_32X32) -- lane-sb128b r2's `chroma_split_tx_hits` asserts them. The r1 gate above pins `--max-partition-size=64`, which
396 /// makes every 128 root a forced SPLIT and leaves this arm unexercised.
397 /// Smooth gradients at a high `--cq-level` are what make the RD search
398 /// keep a whole 128x128 block; `part128_none_hits` HARD-asserts it did.
399 #[test]
400 fn a_real_aomenc_key_frame_with_a_128x128_none_partition_decodes_pixel_exact() {
401 const NAME: &str =
402 "a_real_aomenc_key_frame_with_a_128x128_none_partition_decodes_pixel_exact";
403 let _gate_lock = lock_gate_counters();
404 if !have_ffmpeg() {
405 eprintln!("SKIP {NAME}: no ffmpeg");
406 return;
407 }
408 if !have_aomenc() {
409 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
410 return;
411 }
412 let render = |seed: u32, width: usize, height: usize, ten_bit: bool| -> Vec<u8> {
413 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
414 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
415 .args([
416 "-v",
417 "error",
418 "-f",
419 "lavfi",
420 "-i",
421 &gradients_source(seed, width, height, "duration=0.04:rate=25"),
422 "-pix_fmt",
423 pix,
424 "-strict",
425 "-1",
426 "-t",
427 "0.04",
428 "-f",
429 "yuv4mpegpipe",
430 "-",
431 ])
432 .stdin(Stdio::null())
433 .stdout(Stdio::piped())
434 .stderr(Stdio::piped()), None, |c| c.output())
435 .expect("ffmpeg failed to run");
436 assert!(
437 out.status.success(),
438 "ffmpeg fixture: {}",
439 String::from_utf8_lossy(&out.stderr)
440 );
441 out.stdout
442 };
443 let mut matched = 0u32;
444 let mut named_refusals = 0u32;
445 let mut none_arms = 0u32;
446 // (seed, cq, width, height, 10-bit). 384x384 is a 3x3 grid of whole
447 // 128 superblocks; 256x256 a 2x2.
448 let arms: Vec<(u32, &str, usize, usize, bool)> = vec![
449 (42, "--cq-level=63", 384, 384, false),
450 (43, "--cq-level=55", 384, 384, false),
451 (44, "--cq-level=63", 256, 256, false),
452 (45, "--cq-level=63", 384, 384, true),
453 ];
454 for (seed, cq, width, height, ten_bit) in arms {
455 let y4m = render(seed, width, height, ten_bit);
456 let mut args: Vec<&str> = vec![
457 "--codec=av1",
458 "--passes=1",
459 "--end-usage=q",
460 cq,
461 "--cpu-used=0",
462 "--threads=1",
463 "--row-mt=0",
464 "--sb-size=128",
465 "--enable-rect-partitions=0",
466 "--enable-ab-partitions=0",
467 "--enable-1to4-partitions=0",
468 "--min-partition-size=16",
469 "--enable-restoration=1",
470 "--enable-palette=0",
471 "--deltaq-mode=0",
472 "--enable-intrabc=0",
473 "--enable-tx-size-search=0",
474 "--limit=1",
475 ];
476 if ten_bit {
477 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
478 }
479 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
480 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m);
481 assert!(
482 out.status.success(),
483 "aomenc refused the fixture: {}",
484 String::from_utf8_lossy(&out.stderr)
485 );
486 let stream = out.stdout;
487 let before = crate::decode::part128_none_hits();
488 let frames = match decode_stream(&stream) {
489 Err(e) => {
490 let msg = e.to_string();
491 assert!(
492 msg.contains("unsupported"),
493 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
494 );
495 named_refusals += 1;
496 eprintln!("seed {seed} refusal: {msg}");
497 continue;
498 }
499 Ok(frames) => frames,
500 };
501 let want = if ten_bit {
502 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
503 } else {
504 ffmpeg_decode_sequence(&stream, width, height, 1)
505 };
506 assert_eq!(frames.len(), 1);
507 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
508 for (name, a, b, w) in [
509 ("Y", &got.y, &want.y, width),
510 ("U", &got.u, &want.u, width / 2),
511 ("V", &got.v, &want.v, width / 2),
512 ] {
513 let n = a.iter().zip(b.iter()).filter(|(x, y)| x != y).count();
514 let first = a.iter().zip(b.iter()).position(|(x, y)| x != y);
515 assert_eq!(
516 n,
517 0,
518 "{NAME} frame {i} {name} vs ffmpeg (seed {seed}): {n} differ, first row {} col {} ours {:?} ffmpeg {:?}",
519 first.unwrap_or(0) / w,
520 first.unwrap_or(0) % w,
521 first.map(|k| a[k]),
522 first.map(|k| b[k]),
523 );
524 assert_eq!(
525 a.len(),
526 b.len(),
527 "{NAME} frame {i} {name} vs ffmpeg (seed {seed}): ours has {} samples, \
528 ffmpeg's has {} -- a short plane would zip-truncate the walk above \
529 and hide a chroma-span defect",
530 a.len(),
531 b.len()
532 );
533 }
534 }
535 let hits = crate::decode::part128_none_hits() - before;
536 eprintln!("seed {seed} cq {cq} {width}x{height}: part128_none_hits +{hits}");
537 if hits > 0 {
538 none_arms += 1;
539 }
540 matched += 1;
541 }
542 assert!(
543 matched > 0,
544 "{NAME}: every attempt refused; the gate never decoded a stream"
545 );
546 assert!(
547 none_arms > 0,
548 "{NAME}: {matched} stream(s) decoded pixel-exact but NOT ONE 128 root was \
549 PARTITION_NONE -- the arm this gate exists for never fired"
550 );
551 eprintln!(
552 "{NAME}: {matched} pixel-exact ({none_arms} with a 128 NONE root), \
553 {named_refusals} named refusals, part128_none_hits={}",
554 crate::decode::part128_none_hits()
555 );
556 }
557
558 /// lane-sb128c r7 GATE: the 128 root's GATHERED bottom/right-edge arm --
559 /// the only 128-partition shape the user's 1080p AV1 film reaches
560 /// (`mi_rows = 270`, so every bottom 128 row has `has_rows128 == false`,
561 /// one gathered bit, and the film codes `PARTITION_HORZ`: a 128x64 block
562 /// whose bottom half is outside the frame and never decoded). Frame sizes
563 /// here are chosen so the LAST superblock row (or column, for the VERT
564 /// twin at 192x256) is partial, which is what forces the gathered symbol.
565 /// Both the key frame and the inter frames of each stream carry the arm;
566 /// `part128_edge_*_hits` and `inter_sb128_*_hits` HARD-assert it fired,
567 /// and `decode_all_frames_vs_oracle` compares EVERY decode-order frame
568 /// (hidden alt-refs included) against the instrumented aomdec.
569 #[test]
570 fn a_real_aomenc_sb128_gathered_edge_horz_partition_decodes_pixel_exact() {
571 const NAME: &str = "a_real_aomenc_sb128_gathered_edge_horz_partition_decodes_pixel_exact";
572 let _gate_lock = lock_gate_counters();
573 if !have_ffmpeg() {
574 eprintln!("SKIP {NAME}: no ffmpeg");
575 return;
576 }
577 if !have_aomenc() {
578 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
579 return;
580 }
581 // (seed, cq, width, height, 10-bit, vertical twin). Every size has a
582 // PARTIAL last superblock row (or column, for the VERT twin): 320 px
583 // = 80 mi rows, two full 128 rows and a 64-px remainder; 256 px = 64
584 // mi = two full rows and none, so the VERT arm uses 192 px = 48 mi on
585 // the column axis. A smooth `gradients` source makes the KEY frame
586 // take the arm too, which is still refused by name (square-block
587 // intra), so this gate's source is `mandelbrot`: its key frames split
588 // and its inter frames keep the 128x64/64x128 edge block.
589 // lane-vert46 r1: the last field picks a SMOOTH deterministic source
590 // (`geq` sinusoids, the sb128c r8 intra arm's own fixture) instead of
591 // `mandelbrot`. Arm 46 is the stream that exposed this round's two
592 // defects: mandelbrot's inter frames never put a 64x128 edge block
593 // next to a neighbour whose partition context or per-mu-chunk chroma
594 // DC sign decides a symbol, so both were invisible to arms 42-45.
595 let arms: Vec<(u32, &str, usize, usize, bool, bool, bool)> = vec![
596 (42, "--cq-level=55", 384, 320, false, false, false),
597 (43, "--cq-level=55", 384, 320, true, false, false),
598 (44, "--cq-level=32", 192, 256, false, true, false),
599 (45, "--cq-level=45", 192, 256, true, true, false),
600 (46, "--cq-level=55", 192, 256, false, true, true),
601 ];
602 let (mut matched, mut named_refusals) = (0u32, 0u32);
603 let (mut edge_arms, mut inter_arms) = (0u32, 0u32);
604 for (seed, cq, width, height, ten_bit, vert, smooth) in arms {
605 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
606 let source = if smooth {
607 format!(
608 "nullsrc=size={width}x{height}:rate=25,format=yuv420p,\
609 geq=lum='128+90*sin((X+2*N)/37)+30*sin(Y/29)':\
610 cb='128+30*sin(X/23)':cr='128+30*sin((Y+N)/19)'"
611 )
612 } else {
613 format!("mandelbrot=size={width}x{height}:rate=25:start_x=-0.6:start_y=-0.4")
614 };
615 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
616 .args([
617 "-v",
618 "error",
619 "-f",
620 "lavfi",
621 "-i",
622 &source,
623 "-pix_fmt",
624 pix,
625 "-strict",
626 "-1",
627 "-t",
628 "0.2",
629 "-f",
630 "yuv4mpegpipe",
631 "-",
632 ])
633 .stdin(Stdio::null())
634 .stdout(Stdio::piped())
635 .stderr(Stdio::piped()), None, |c| c.output())
636 .expect("ffmpeg failed to run");
637 assert!(
638 y4m.status.success(),
639 "{NAME}: ffmpeg fixture: {}",
640 String::from_utf8_lossy(&y4m.stderr)
641 );
642 let mut args: Vec<&str> = vec![
643 "--codec=av1",
644 "--passes=1",
645 "--end-usage=q",
646 cq,
647 "--cpu-used=0",
648 "--threads=1",
649 "--row-mt=0",
650 "--sb-size=128",
651 "--min-partition-size=64",
652 "--enable-rect-partitions=1",
653 "--enable-ab-partitions=0",
654 "--enable-1to4-partitions=0",
655 "--enable-palette=0",
656 "--enable-intrabc=0",
657 "--enable-tx-size-search=0",
658 "--deltaq-mode=0",
659 "--limit=5",
660 ];
661 if ten_bit {
662 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
663 }
664 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
665 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
666 assert!(
667 out.status.success(),
668 "{NAME}: aomenc refused the fixture: {}",
669 String::from_utf8_lossy(&out.stderr)
670 );
671 let stream = out.stdout;
672 let (before_edge, before_inter) = if vert {
673 (
674 crate::decode::part128_edge_vert_hits(),
675 crate::decode::inter_sb128_vert_hits(),
676 )
677 } else {
678 (
679 crate::decode::part128_edge_horz_hits(),
680 crate::decode::inter_sb128_horz_hits(),
681 )
682 };
683 // A refusal is still a legal outcome for an arm whose stream hits
684 // some OTHER lane's gap, but never for all of them (asserted
685 // below), and never as a silent skip.
686 if let Err(e) = decode_stream(&stream) {
687 let msg = e.to_string();
688 assert!(
689 msg.contains("unsupported"),
690 "{NAME} failed outright, not a named refusal \
691 (seed {seed} {width}x{height}): {msg}"
692 );
693 named_refusals += 1;
694 eprintln!("{NAME}: seed {seed} {width}x{height} refusal: {msg}");
695 continue;
696 }
697 let (frames, hidden) = decode_all_frames_vs_oracle(
698 &stream,
699 &format!("sb128c-edge-{seed}-{width}x{height}"),
700 );
701 assert!(frames > 0, "{NAME}: no frames decoded at {width}x{height}");
702 let (edge, inter) = if vert {
703 (
704 crate::decode::part128_edge_vert_hits() - before_edge,
705 crate::decode::inter_sb128_vert_hits() - before_inter,
706 )
707 } else {
708 (
709 crate::decode::part128_edge_horz_hits() - before_edge,
710 crate::decode::inter_sb128_horz_hits() - before_inter,
711 )
712 };
713 eprintln!(
714 "{NAME}: seed {seed} cq {cq} {width}x{height} {}bit {}: \
715 {frames} frames pixel-exact ({hidden} hidden), \
716 edge_hits +{edge} inter_128rect_blocks +{inter}",
717 if ten_bit { 10 } else { 8 },
718 if vert { "VERT" } else { "HORZ" },
719 );
720 if edge > 0 {
721 edge_arms += 1;
722 }
723 if inter > 0 {
724 inter_arms += 1;
725 }
726 matched += 1;
727 }
728 assert!(
729 matched > 0,
730 "{NAME}: every attempt refused ({named_refusals}); the gate never \
731 decoded a stream"
732 );
733 assert!(
734 edge_arms > 0,
735 "{NAME}: {matched} stream(s) decoded pixel-exact but NOT ONE 128 root \
736 took the gathered frame-edge HORZ/VERT arm this gate exists for"
737 );
738 assert!(
739 inter_arms > 0,
740 "{NAME}: the gathered arm fired only on key frames -- no INTER \
741 128x64/64x128 block was decoded, which is the film's own shape"
742 );
743 }
744
745 /// lane-sb128c r8: the 128 root's HORZ/VERT arm on a KEY frame -- one
746 /// 128x64 (or 64x128) INTRA block, the shape r7 still refused by name.
747 /// A smooth `gradients` source makes the key frame itself take the arm
748 /// (`mandelbrot`'s key frames always split), at sizes whose last
749 /// superblock row/column is a partial 64 so the gathered frame-edge bit
750 /// decides the root. `--enable-tx-size-search=1` on half the arms is what
751 /// makes the intra `tx_depth` symbol real (depth 1 = 32x32 units,
752 /// depth 2 = 16x16). Every decode-order frame (hidden alt-refs included)
753 /// is compared against the instrumented aomdec, and the per-depth
754 /// counters are printed for every compared attempt.
755 #[test]
756 fn a_real_aomenc_sb128_intra_rect_block_decodes_pixel_exact() {
757 const NAME: &str = "a_real_aomenc_sb128_intra_rect_block_decodes_pixel_exact";
758 let _gate_lock = lock_gate_counters();
759 if !have_ffmpeg() {
760 eprintln!("SKIP {NAME}: no ffmpeg");
761 return;
762 }
763 if !have_aomenc() {
764 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
765 return;
766 }
767 // (tag, cq, width, height, 10-bit, vertical twin, tx-size-search)
768 let arms: Vec<(u32, &str, usize, usize, bool, bool, bool)> = vec![
769 (42, "--cq-level=55", 384, 320, false, false, false),
770 (43, "--cq-level=32", 384, 320, true, false, true),
771 (44, "--cq-level=8", 256, 192, false, false, true),
772 (46, "--cq-level=55", 192, 256, false, true, false),
773 (45, "--cq-level=45", 192, 256, true, true, true),
774 // lane-sb128c r10: a SECOND 128 superblock column is what the
775 // arms above never had -- the right 64x128 half of a 128-root
776 // VERT at mi_col 80 read its tx-depth symbol off the wrong CDF
777 // row and every unit column of a 128x64 chunk predicted from the
778 // not-yet-decoded chunk to its right.
779 (47, "--cq-level=45", 512, 512, false, false, true),
780 ];
781 let (mut matched, mut named_refusals, mut out_of_scope) = (0u32, 0u32, 0u32);
782 let (mut horz_arms, mut vert_arms) = (0u32, 0u32);
783 let mut depth_seen = [0usize; 3];
784 for (tag, cq, width, height, ten_bit, vert, tx_search) in arms {
785 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
786 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
787 .args([
788 "-v", "error", "-f", "lavfi", "-i",
789 // DETERMINISTIC smooth source: lavfi `gradients` ignores
790 // its seed and gives a different picture every run (a
791 // whole round was spent on a "flake" that was really this),
792 // so the smoothness comes from long-period sinusoids
793 // through `geq` instead -- same effect on the encoder's
794 // partition choice, byte-identical across runs.
795 &format!(
796 "nullsrc=size={width}x{height}:rate=25,format=yuv420p, geq=lum='{lum}': cb='128+30*sin(X/23)':cr='128+30*sin((Y+N)/19)'",
797 // The 512x512 arm carries the r9 witness's own
798 // higher-frequency luma: the smooth two-term source
799 // gives every 128-rect block a whole-block TX_64X64
800 // and no VERT root at all, which is exactly the
801 // combination that hid the tx-depth CDF row defect.
802 lum = if width == 512 {
803 "128+80*sin((X+3*N)/17)+50*sin(Y/29)+30*sin((X+Y)/13)"
804 } else {
805 "128+90*sin((X+2*N)/37)+30*sin(Y/29)"
806 }
807 ),
808 "-pix_fmt", pix, "-strict", "-1", "-t", "0.2",
809 "-f", "yuv4mpegpipe", "-",
810 ])
811 .stdin(Stdio::null())
812 .stdout(Stdio::piped())
813 .stderr(Stdio::piped()), None, |c| c.output())
814 .expect("ffmpeg failed to run");
815 assert!(
816 y4m.status.success(),
817 "{NAME}: ffmpeg fixture: {}",
818 String::from_utf8_lossy(&y4m.stderr)
819 );
820 let mut args: Vec<&str> = vec![
821 "--codec=av1",
822 "--passes=1",
823 "--end-usage=q",
824 cq,
825 "--cpu-used=0",
826 "--threads=1",
827 "--row-mt=0",
828 "--sb-size=128",
829 "--min-partition-size=64",
830 "--enable-rect-partitions=1",
831 "--enable-ab-partitions=0",
832 "--enable-1to4-partitions=0",
833 "--enable-palette=0",
834 "--enable-intrabc=0",
835 "--deltaq-mode=0",
836 "--limit=5",
837 // EVERY frame a key frame: this gate exists for the INTRA
838 // 128x64/64x128 block, and a mixed stream lands on other
839 // lanes' inter gaps (sub-8 leaves, rect inter residual)
840 // before it ever gets there. The inter twin of this same
841 // 128-root arm has its own gate
842 // (`..._sb128_gathered_edge_horz_partition_decodes_pixel_exact`).
843 "--kf-max-dist=1",
844 ];
845 // AOMENC FLAG PRECEDENCE: the LAST occurrence wins, so this
846 // per-arm override goes after the base recipe.
847 args.push(if tx_search {
848 "--enable-tx-size-search=1"
849 } else {
850 "--enable-tx-size-search=0"
851 });
852 if ten_bit {
853 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
854 }
855 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
856 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
857 assert!(
858 out.status.success(),
859 "{NAME}: aomenc refused the fixture: {}",
860 String::from_utf8_lossy(&out.stderr)
861 );
862 let stream = out.stdout;
863 let before = intra_sb128_counters();
864 if let Err(e) = decode_stream(&stream) {
865 let msg = e.to_string();
866 assert!(
867 msg.contains("unsupported"),
868 "{NAME} failed outright, not a named refusal \
869 (arm {tag} {width}x{height}): {msg}"
870 );
871 named_refusals += 1;
872 eprintln!("{NAME}: arm {tag} {width}x{height} refusal: {msg}");
873 continue;
874 }
875 let (frames, hidden) = decode_all_frames_vs_oracle(
876 &stream,
877 &format!("sb128c-intra-{tag}-{width}x{height}"),
878 );
879 assert!(frames > 0, "{NAME}: no frames decoded at {width}x{height}");
880 let after = intra_sb128_counters();
881 let (horz, vert_hits) = (after.0 - before.0, after.1 - before.1);
882 let depth: Vec<usize> = (0..3).map(|i| after.2[i] - before.2[i]).collect();
883 eprintln!(
884 "{NAME}: arm {tag} cq {cq} {width}x{height} {}bit {} txsearch={}: \
885 {frames} frames pixel-exact ({hidden} hidden), \
886 intra_128x64 +{horz} intra_64x128 +{vert_hits} \
887 depth[64/32/16] {depth:?}",
888 if ten_bit { 10 } else { 8 },
889 if vert { "VERT" } else { "HORZ" },
890 u8::from(tx_search),
891 );
892 if horz == 0 && vert_hits == 0 {
893 out_of_scope += 1;
894 }
895 if horz > 0 {
896 horz_arms += 1;
897 }
898 if vert_hits > 0 {
899 vert_arms += 1;
900 }
901 for i in 0..3 {
902 depth_seen[i] += depth[i];
903 }
904 matched += 1;
905 }
906 assert!(
907 matched > 0,
908 "{NAME}: every attempt refused ({named_refusals}); the gate never \
909 decoded a stream"
910 );
911 assert!(
912 horz_arms > 0,
913 "{NAME}: {matched} stream(s) decoded pixel-exact ({out_of_scope} carried \
914 no 128-root rect intra block at all) but NOT ONE key-frame 128x64 \
915 block fired -- the shape this gate exists for"
916 );
917 assert!(
918 vert_arms > 0,
919 "{NAME}: the VERT twin never produced a key-frame 64x128 block"
920 );
921 assert!(
922 depth_seen[0] > 0,
923 "{NAME}: no depth-0 (TX_64X64) intra 128-rect block: {depth_seen:?}"
924 );
925 }
926
927 /// lane-sb128c r9 GATE: the four AB shapes at the 128 root
928 /// (`PARTITION_HORZ_A`/`_HORZ_B`/`_VERT_A`/`_VERT_B`), each one
929 /// 128x64/64x128 half plus two 64x64 quadrants in libaom
930 /// `decode_partition`'s visit order. The recipe is r8's measured one
931 /// (`--sb-size=128 --min-partition-size=64 --enable-ab-partitions=1` over
932 /// a 512x512 `geq` sinusoid), which is what made aomenc pick the shapes at
933 /// all; arms cover cq 18/45, 8 and 10 bit, and one INTER arm
934 /// (`--kf-max-dist=100`) so the shapes are exercised on both tile paths.
935 /// Continue-and-sweep: an arm that stops on ANOTHER lane's named refusal
936 /// is counted and skipped, a decode failure or a pixel mismatch is a hard
937 /// failure, and the end-of-sweep assert names which of the four fired.
938 #[test]
939 fn a_real_aomenc_sb128_ab_partition_at_the_128_root_decodes_pixel_exact() {
940 const NAME: &str = "a_real_aomenc_sb128_ab_partition_at_the_128_root_decodes_pixel_exact";
941 let _gate_lock = lock_gate_counters();
942 if !have_ffmpeg() {
943 eprintln!("SKIP {NAME}: no ffmpeg");
944 return;
945 }
946 if !have_aomenc() {
947 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
948 return;
949 }
950 // (tag, cq, width, height, 10-bit, inter)
951 let arms: Vec<(u32, &str, usize, usize, bool, bool)> = vec![
952 (18, "--cq-level=18", 512, 512, false, false),
953 (45, "--cq-level=45", 512, 512, false, false),
954 (32, "--cq-level=32", 512, 512, true, false),
955 (55, "--cq-level=55", 384, 320, false, false),
956 (91, "--cq-level=45", 512, 512, false, true),
957 (92, "--cq-level=18", 512, 512, false, true),
958 ];
959 let (mut matched, mut named_refusals, mut out_of_scope) = (0u32, 0u32, 0u32);
960 let mut ab_seen = [0usize; 4];
961 let mut ab_inter = [0usize; 4];
962 for (tag, cq, width, height, ten_bit, inter) in arms {
963 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
964 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
965 .args([
966 "-v",
967 "error",
968 "-f",
969 "lavfi",
970 "-i",
971 // Same DETERMINISTIC sinusoid source that made aomenc pick
972 // the AB shapes in the r8 sweep (lavfi `gradients` ignores
973 // its seed and is not reproducible -- never use it here).
974 &format!(
975 "nullsrc=size={width}x{height}:rate=25,format=yuv420p,\
976 geq=lum='128+80*sin((X+3*N)/17)+50*sin(Y/29)+30*sin((X+Y)/13)':\
977 cb='128+30*sin(X/23)':cr='128+30*sin((Y+N)/19)'"
978 ),
979 "-pix_fmt",
980 pix,
981 "-strict",
982 "-1",
983 "-t",
984 "0.2",
985 "-f",
986 "yuv4mpegpipe",
987 "-",
988 ])
989 .stdin(Stdio::null())
990 .stdout(Stdio::piped())
991 .stderr(Stdio::piped()), None, |c| c.output())
992 .expect("ffmpeg failed to run");
993 assert!(
994 y4m.status.success(),
995 "{NAME}: ffmpeg fixture: {}",
996 String::from_utf8_lossy(&y4m.stderr)
997 );
998 let mut args: Vec<&str> = vec![
999 "--codec=av1",
1000 "--passes=1",
1001 "--end-usage=q",
1002 cq,
1003 "--cpu-used=0",
1004 "--threads=1",
1005 "--row-mt=0",
1006 "--sb-size=128",
1007 "--min-partition-size=64",
1008 "--enable-rect-partitions=1",
1009 "--enable-ab-partitions=1",
1010 "--enable-1to4-partitions=0",
1011 "--enable-palette=0",
1012 "--enable-intrabc=0",
1013 "--deltaq-mode=0",
1014 "--limit=5",
1015 ];
1016 // AOMENC FLAG PRECEDENCE: last occurrence wins, so the per-arm
1017 // key-frame cadence goes AFTER the base recipe.
1018 args.push(if inter {
1019 "--kf-max-dist=100"
1020 } else {
1021 "--kf-max-dist=1"
1022 });
1023 if ten_bit {
1024 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
1025 }
1026 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
1027 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1028 assert!(
1029 out.status.success(),
1030 "{NAME}: aomenc refused the fixture: {}",
1031 String::from_utf8_lossy(&out.stderr)
1032 );
1033 let stream = out.stdout;
1034 let before = sb128_ab_counters();
1035 if let Err(e) = decode_stream(&stream) {
1036 let msg = e.to_string();
1037 assert!(
1038 msg.contains("unsupported"),
1039 "{NAME} failed outright, not a named refusal \
1040 (arm {tag} {width}x{height}): {msg}"
1041 );
1042 named_refusals += 1;
1043 eprintln!("{NAME}: arm {tag} {width}x{height} refusal: {msg}");
1044 continue;
1045 }
1046 let (frames, hidden) =
1047 decode_all_frames_vs_oracle(&stream, &format!("sb128c-ab-{tag}-{width}x{height}"));
1048 assert!(frames > 0, "{NAME}: no frames decoded at {width}x{height}");
1049 let after = sb128_ab_counters();
1050 let ab: Vec<usize> = (0..4).map(|i| after[i] - before[i]).collect();
1051 eprintln!(
1052 "{NAME}: arm {tag} cq {cq} {width}x{height} {}bit {}: {frames} frames \
1053 pixel-exact ({hidden} hidden), AB[HORZ_A,HORZ_B,VERT_A,VERT_B] {ab:?}",
1054 if ten_bit { 10 } else { 8 },
1055 if inter { "INTER" } else { "KEY" },
1056 );
1057 if ab.iter().sum::<usize>() == 0 {
1058 out_of_scope += 1;
1059 }
1060 for i in 0..4 {
1061 ab_seen[i] += ab[i];
1062 if inter {
1063 ab_inter[i] += ab[i];
1064 }
1065 }
1066 matched += 1;
1067 }
1068 assert!(
1069 matched > 0,
1070 "{NAME}: every attempt refused ({named_refusals}); the gate never \
1071 decoded a stream"
1072 );
1073 assert!(
1074 ab_seen.iter().sum::<usize>() > 0,
1075 "{NAME}: {matched} stream(s) decoded pixel-exact ({out_of_scope} carried \
1076 no 128-root AB partition at all) but NOT ONE AB shape fired -- the \
1077 shapes this gate exists for"
1078 );
1079 // Which of the four this sweep actually reaches, hard-asserted so a
1080 // later change that stops reaching one of them fails here instead of
1081 // silently narrowing the gate (class `gate-blind-to-feature`).
1082 for (i, name) in ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"].iter().enumerate() {
1083 if AB_ARMS_REACHED[i] {
1084 assert!(
1085 ab_seen[i] > 0,
1086 "{NAME}: PARTITION_{name} at the 128 root fired in the round that \
1087 pinned this gate but not now: {ab_seen:?}"
1088 );
1089 } else {
1090 eprintln!(
1091 "{NAME}: PARTITION_{name} NOT reached by this sweep (aomenc never \
1092 picked it): {ab_seen:?}"
1093 );
1094 }
1095 }
1096 assert!(
1097 ab_inter.iter().sum::<usize>() > 0,
1098 "{NAME}: the AB shapes fired only on KEY frames -- the inter tile path's \
1099 own AB arm was never exercised: key {ab_seen:?} inter {ab_inter:?}"
1100 );
1101 }
1102
1103 #[test]
1104 #[ignore = "lane-sb128 r2 diagnostic: is the frame-6 mismatch sb128-specific?"]
1105 fn sb128_r2_control_sb64() {
1106 // lane-av1cmpaudit2: this control reaches the oracle, so it takes
1107 // the gate mutex like every other one.
1108 let _gate_lock = lock_gate_counters();
1109 let (width, height) = (256usize, 192usize);
1110 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1111 .args([
1112 "-v",
1113 "error",
1114 "-f",
1115 "lavfi",
1116 "-i",
1117 &format!(
1118 "{},noise=all_seed=53:alls=12:allf=t",
1119 gradients_source(53, width, height, "duration=0.32:rate=25")
1120 ),
1121 "-pix_fmt",
1122 "yuv420p",
1123 "-t",
1124 "0.32",
1125 "-f",
1126 "yuv4mpegpipe",
1127 "-",
1128 ])
1129 .stdin(Stdio::null())
1130 .stdout(Stdio::piped()), None, |c| c.output())
1131 .expect("ffmpeg");
1132 let out = run_with_stdin(
1133 Command::new(aomenc_path()).args([
1134 "--codec=av1",
1135 "--passes=1",
1136 "--end-usage=q",
1137 "--cq-level=40",
1138 "--cpu-used=2",
1139 "--threads=1",
1140 "--row-mt=0",
1141 "--sb-size=64",
1142 "--max-partition-size=64",
1143 "--min-partition-size=32",
1144 "--enable-rect-partitions=0",
1145 "--enable-ab-partitions=0",
1146 "--enable-1to4-partitions=0",
1147 "--enable-palette=0",
1148 "--enable-intrabc=0",
1149 "--enable-tx-size-search=0",
1150 "--deltaq-mode=0",
1151 "--limit=8",
1152 "--obu",
1153 "-o",
1154 "-",
1155 "-",
1156 ]),
1157 &y4m.stdout,
1158 );
1159 assert!(out.status.success());
1160 let (frames, hidden) = decode_all_frames_vs_oracle(&out.stdout, "sb128-control-64");
1161 eprintln!("control sb64: {frames} frames exact ({hidden} hidden)");
1162 }
1163
1164 /// lane-sb128 r2: an INTER SEQUENCE under a 128x128 superblock -- the
1165 /// half ReelC is made of. r1 refused it by name (the inter tile loop
1166 /// recursed a 64x64 root only); r2 ported `sb_visit_order` and the 128
1167 /// root (per-superblock `read_lr`, the 8-symbol `partition_w128` read with
1168 /// its edge gather, `delta_q`/`delta_lf` at 128 granularity) into that
1169 /// loop, so this gate replaces the refusal test.
1170 ///
1171 /// Every frame in DECODE order, hidden alt-refs included
1172 /// ([`decode_all_frames_vs_oracle`], class gate-blind-to-hidden-frames):
1173 /// `--lag-in-frames` is left at aomenc's default so the encoder really
1174 /// emits them. Per-ATTEMPT counter deltas are hard asserts (class
1175 /// counter-from-refused-stream: the helper panics on any refusal, so every
1176 /// counted attempt is a compared one): 128 partition roots read on this
1177 /// stream, `cdef_idx` reads (one per 64x64 quadrant inside the 128
1178 /// superblock), and temporal MV candidates (the inter-only path). Both bit
1179 /// depths -- his films are `yuv420p10le`. Only a missing tool SKIPs.
1180 #[test]
1181 fn a_real_aomenc_inter_sequence_with_128x128_superblocks_decodes_pixel_exact() {
1182 const NAME: &str =
1183 "a_real_aomenc_inter_sequence_with_128x128_superblocks_decodes_pixel_exact";
1184 let _gate_lock = lock_gate_counters();
1185 if !have_ffmpeg() || !have_aomenc() {
1186 eprintln!("SKIP {NAME}: no ffmpeg/aomenc/aomdec");
1187 return;
1188 }
1189 let (width, height) = (256usize, 192usize);
1190 for ten_bit in [false, true] {
1191 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
1192 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1193 .args([
1194 "-v",
1195 "error",
1196 "-f",
1197 "lavfi",
1198 "-i",
1199 &format!(
1200 // Noise on top of the gradient is what makes aomenc
1201 // signal a nonzero `cdef_bits` (a clean gradient codes
1202 // with CDEF off, and the cdef_idx counter stays 0).
1203 "{},noise=all_seed=53:alls=12:allf=t",
1204 gradients_source(53, width, height, "duration=0.32:rate=25")
1205 ),
1206 "-pix_fmt",
1207 pix,
1208 "-strict",
1209 "-1",
1210 "-t",
1211 "0.32",
1212 "-f",
1213 "yuv4mpegpipe",
1214 "-",
1215 ])
1216 .stdin(Stdio::null())
1217 .stdout(Stdio::piped())
1218 .stderr(Stdio::piped()), None, |c| c.output())
1219 .expect("ffmpeg failed to run");
1220 assert!(
1221 y4m.status.success(),
1222 "{NAME}: ffmpeg fixture: {}",
1223 String::from_utf8_lossy(&y4m.stderr)
1224 );
1225 let mut args: Vec<&str> = vec![
1226 "--codec=av1",
1227 "--passes=1",
1228 "--end-usage=q",
1229 "--cq-level=40",
1230 "--cpu-used=2",
1231 "--threads=1",
1232 "--row-mt=0",
1233 "--sb-size=128",
1234 "--max-partition-size=64",
1235 // aomenc emits PARTITION_HORZ_4/VERT_4 below 16x16 even with
1236 // the flag off (ledger, lane-modectx r1), so bound the search.
1237 "--min-partition-size=32",
1238 // The inter path still refuses rectangular strips ("a non-skip
1239 // rectangular (HORZ/VERT/HORZ_B) strip needs rectangular
1240 // residual coding") -- another lane's gap, off here so this
1241 // gate measures the 128 root and nothing else.
1242 "--enable-rect-partitions=0",
1243 "--enable-ab-partitions=0",
1244 "--enable-1to4-partitions=0",
1245 "--enable-palette=0",
1246 "--enable-intrabc=0",
1247 "--enable-tx-size-search=0",
1248 "--deltaq-mode=0",
1249 "--limit=8",
1250 ];
1251 if ten_bit {
1252 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
1253 }
1254 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
1255 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1256 assert!(
1257 out.status.success(),
1258 "{NAME}: aomenc refused the fixture: {}",
1259 String::from_utf8_lossy(&out.stderr)
1260 );
1261 let stream = out.stdout;
1262 let header = {
1263 let mut parser = ec_av1_syntax::Av1Parser::new();
1264 let mut pos = 0usize;
1265 while let Ok(obu) = parser.parse_obu(&stream[pos..]) {
1266 pos += obu.total_size;
1267 if pos >= stream.len() {
1268 break;
1269 }
1270 }
1271 parser
1272 .sequence_header()
1273 .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth))
1274 };
1275 assert_eq!(
1276 header,
1277 Some((true, if ten_bit { 10 } else { 8 })),
1278 "{NAME}: the encoder did not write a 128x128-superblock sequence header at \
1279 the requested bit depth -- the flag never arrived"
1280 );
1281 let before = (
1282 crate::decode::part128_symbols(),
1283 crate::decode::cdef_idx_hits(),
1284 crate::decode::tmv_hits(),
1285 );
1286 let (frames, hidden) = decode_all_frames_vs_oracle(
1287 &stream,
1288 &format!("sb128-inter-{}", if ten_bit { 10 } else { 8 }),
1289 );
1290 let (part128, cdef_idx, tmv) = (
1291 crate::decode::part128_symbols() - before.0,
1292 crate::decode::cdef_idx_hits() - before.1,
1293 crate::decode::tmv_hits() - before.2,
1294 );
1295 assert!(
1296 frames >= 6,
1297 "{NAME} ({pix}): only {frames} frames in decode order, the recipe asks for 8"
1298 );
1299 assert!(
1300 part128 >= 3,
1301 "{NAME} ({pix}): only {part128} 128-level partition symbols on this stream -- \
1302 the 128 root never fired on the inter frames"
1303 );
1304 assert!(
1305 cdef_idx >= 1,
1306 "{NAME} ({pix}): no cdef_idx read -- the per-64x64-quadrant cdef read inside \
1307 the 128 superblock never fired"
1308 );
1309 assert!(
1310 tmv >= 1,
1311 "{NAME} ({pix}): no temporal MV candidate -- the inter path never ran"
1312 );
1313 eprintln!(
1314 "{NAME} ({pix}): {frames} decode-order frames pixel-exact ({hidden} hidden), \
1315 part128_symbols={part128} cdef_idx_hits={cdef_idx} tmv_hits={tmv}"
1316 );
1317 }
1318 }
1319
1320 /// lane-sb128c r1: an INTER frame whose 128x128 superblock root really
1321 /// resolves `PARTITION_NONE` -- one whole 128x128 inter block, the shape
1322 /// ReelC's first inter frame stops this decoder on. r1 wired it: four
1323 /// TX_64X64 luma units (`max_txsize_rect_lookup[BLOCK_128X128]`), four
1324 /// TX_32X32 chroma units (`av1_get_max_uv_txsize`), interleaved Y,U,V per
1325 /// 64x64 "mu" chunk (libaom `decode_token_recon_block`) with the chroma
1326 /// `txb_skip_ctx` offset-10 rows, and OBMC's overlap capped at a 64x64
1327 /// block's half (`reconinter.c` 860/899).
1328 ///
1329 /// `--max-partition-size=128` is what lets the root be NONE at all (the
1330 /// sibling gate above pins 64, so its roots always SPLIT). Every arm hard
1331 /// asserts its own `inter_sb128_none_hits` delta, so a recipe that stops
1332 /// choosing the shape fails instead of passing vacuously; every decode
1333 /// order frame is compared by [`decode_all_frames_vs_oracle`], which
1334 /// panics on a refusal or any differing byte. Arms: 8-bit and 10-bit (his
1335 /// films are 10-bit) with `tx-size-search=0` (TX_MODE_LARGEST, the block's
1336 /// four TX_64X64 units come straight from `max_txsize_rect_lookup`) and an
1337 /// 8-bit `tx-size-search=1` arm (the var-tx tree at 128).
1338 // lane-sb128c r3: green. `--min-partition-size=32` let the RD search reach
1339 // 16x16-level AB / SB-level AB shapes that other lanes still refuse (two of
1340 // the three arms stopped there, measured); at 64 every arm decodes and the
1341 // 128 root still resolves NONE.
1342 #[test]
1343 fn a_real_aomenc_inter_128x128_none_root_decodes_pixel_exact() {
1344 const NAME: &str = "a_real_aomenc_inter_128x128_none_root_decodes_pixel_exact";
1345 let _gate_lock = lock_gate_counters();
1346 if !have_ffmpeg() || !have_aomenc() {
1347 eprintln!("SKIP {NAME}: no ffmpeg/aomenc/aomdec");
1348 return;
1349 }
1350 let (width, height) = (256usize, 256usize);
1351 let mut intra128_total = 0usize;
1352 for (ten_bit, tx_search, seed) in
1353 [(false, false, 61u32), (true, false, 61), (false, true, 62)]
1354 {
1355 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
1356 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1357 .args([
1358 "-v",
1359 "error",
1360 "-f",
1361 "lavfi",
1362 "-i",
1363 &format!(
1364 "{},noise=all_seed={seed}:alls=6:allf=t",
1365 gradients_source(seed, width, height, "duration=0.32:rate=25")
1366 ),
1367 "-pix_fmt",
1368 pix,
1369 "-strict",
1370 "-1",
1371 "-t",
1372 "0.32",
1373 "-f",
1374 "yuv4mpegpipe",
1375 "-",
1376 ])
1377 .stdin(Stdio::null())
1378 .stdout(Stdio::piped())
1379 .stderr(Stdio::piped()), None, |c| c.output())
1380 .expect("ffmpeg failed to run");
1381 assert!(
1382 y4m.status.success(),
1383 "{NAME}: ffmpeg fixture: {}",
1384 String::from_utf8_lossy(&y4m.stderr)
1385 );
1386 let mut args: Vec<&str> = vec![
1387 "--codec=av1",
1388 "--passes=1",
1389 "--end-usage=q",
1390 "--cq-level=62",
1391 "--cpu-used=0",
1392 "--threads=1",
1393 "--row-mt=0",
1394 "--sb-size=128",
1395 "--max-partition-size=128",
1396 "--min-partition-size=64",
1397 "--enable-rect-partitions=0",
1398 "--enable-ab-partitions=0",
1399 "--enable-1to4-partitions=0",
1400 "--enable-palette=0",
1401 "--enable-intrabc=0",
1402 "--deltaq-mode=0",
1403 "--limit=8",
1404 ];
1405 // Spelled ONCE per invocation (a repeated `--enable-*` keeps its
1406 // LAST occurrence, measured 2026-09-02).
1407 args.push(if tx_search {
1408 "--enable-tx-size-search=1"
1409 } else {
1410 "--enable-tx-size-search=0"
1411 });
1412 if ten_bit {
1413 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
1414 }
1415 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
1416 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1417 assert!(
1418 out.status.success(),
1419 "{NAME}: aomenc refused the fixture: {}",
1420 String::from_utf8_lossy(&out.stderr)
1421 );
1422 let stream = out.stdout;
1423 let header = {
1424 let mut parser = ec_av1_syntax::Av1Parser::new();
1425 let mut pos = 0usize;
1426 while let Ok(obu) = parser.parse_obu(&stream[pos..]) {
1427 pos += obu.total_size;
1428 if pos >= stream.len() {
1429 break;
1430 }
1431 }
1432 parser
1433 .sequence_header()
1434 .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth))
1435 };
1436 assert_eq!(
1437 header,
1438 Some((true, if ten_bit { 10 } else { 8 })),
1439 "{NAME}: the encoder did not write a 128x128-superblock sequence header at \
1440 the requested bit depth -- the flag never arrived"
1441 );
1442 let before = (
1443 crate::decode::inter_sb128_none_hits(),
1444 crate::decode::chroma_split_tx_hits(),
1445 crate::decode::intra_128_in_inter_hits(),
1446 );
1447 let (frames, hidden) = decode_all_frames_vs_oracle(
1448 &stream,
1449 &format!(
1450 "sb128c-inter-none-{}-{}",
1451 if ten_bit { 10 } else { 8 },
1452 tx_search
1453 ),
1454 );
1455 let (none128, chroma_units, intra128) = (
1456 crate::decode::inter_sb128_none_hits() - before.0,
1457 crate::decode::chroma_split_tx_hits() - before.1,
1458 crate::decode::intra_128_in_inter_hits() - before.2,
1459 );
1460 intra128_total += intra128;
1461 assert!(
1462 frames >= 6,
1463 "{NAME} ({pix} tx_search={tx_search}): only {frames} decode-order frames"
1464 );
1465 assert!(
1466 none128 >= 1,
1467 "{NAME} ({pix} tx_search={tx_search}): no 128x128 PARTITION_NONE root on an \
1468 inter frame -- the recipe stopped exercising the shape this gate names"
1469 );
1470 eprintln!(
1471 "{NAME} ({pix} tx_search={tx_search}): {frames} decode-order frames pixel-exact \
1472 ({hidden} hidden), inter_sb128_none_hits={none128} chroma_units={chroma_units} \
1473 intra_128_in_inter={intra128}"
1474 );
1475 }
1476 assert!(
1477 intra128_total >= 1,
1478 "{NAME}: no INTRA-coded 128x128 block inside an inter frame across the three arms -- \
1479 the refusal this round lifted is no longer exercised"
1480 );
1481 }
1482
1483 /// lane-av1-444-128: a real `aomenc` stream whose inter frames are ONE
1484 /// 128x128 PARTITION_NONE block each, non-skip, must walk that block's
1485 /// chroma through the mu-chunk loop -- one TX_32X32 unit per 64x64 mu
1486 /// chunk per plane at 4:2:0 (`decode_token_recon_block`'s mu walk with
1487 /// `av1_get_max_uv_txsize(BLOCK_128X128)` = `TX_32X32`), each unit read
1488 /// at its own origin against its own entropy-cell span and stamped
1489 /// immediately (`av1_set_entropy_contexts`). The census asserts the walk
1490 /// actually ran (four units per plane per coded 128-none block); the key
1491 /// frame splits to 64x64 (detailed testsrc2 content), so the whole
1492 /// stream stays inside the 4:2:0 paths this tree decodes. The 4:4:4 twin
1493 /// of this shape (FOUR TX_32X32 units per chunk per plane) is witnessed
1494 /// in `lanes/av1444128.report.md` and committed here as
1495 /// `a_real_aomenc_444_intra_in_inter_128_root_codes_chroma_per_mu_chunk_unit_pixel_exact`.
1496 /// lane-av1422lift: the sequence-header refusal is gone, so this tree no
1497 /// longer refuses non-4:2:0 sequences by name.
1498 #[test]
1499 fn a_real_aomenc_128x128_none_inter_blocks_coded_chroma_per_mu_chunk_decodes_pixel_exact() {
1500 const NAME: &str =
1501 "a_real_aomenc_128x128_none_inter_blocks_coded_chroma_per_mu_chunk_decodes_pixel_exact";
1502 let _gate_lock = lock_gate_counters();
1503 if !have_ffmpeg() || !have_aomenc() {
1504 eprintln!("SKIP {NAME}: no ffmpeg/aomenc/aomdec");
1505 return;
1506 }
1507 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1508 .args([
1509 "-v",
1510 "error",
1511 "-f",
1512 "lavfi",
1513 "-i",
1514 "testsrc2=size=128x128:rate=30",
1515 "-frames:v",
1516 "12",
1517 "-pix_fmt",
1518 "yuv420p",
1519 "-strict",
1520 "-1",
1521 "-f",
1522 "yuv4mpegpipe",
1523 "-",
1524 ])
1525 .stdin(Stdio::null())
1526 .stdout(Stdio::piped())
1527 .stderr(Stdio::piped()), None, |c| c.output())
1528 .expect("ffmpeg failed to run");
1529 assert!(
1530 y4m.status.success(),
1531 "{NAME}: ffmpeg fixture: {}",
1532 String::from_utf8_lossy(&y4m.stderr)
1533 );
1534 let args: Vec<&str> = vec![
1535 "--codec=av1",
1536 "--passes=1",
1537 "--end-usage=q",
1538 "--cq-level=8",
1539 "--cpu-used=2",
1540 "--threads=1",
1541 "--row-mt=0",
1542 "--lag-in-frames=0",
1543 "--kf-max-dist=100",
1544 "--enable-fwd-kf=0",
1545 "--sb-size=128",
1546 "--max-partition-size=128",
1547 "--min-partition-size=64",
1548 "--enable-palette=0",
1549 "--enable-intrabc=0",
1550 "--enable-cdef=0",
1551 "--enable-restoration=0",
1552 "--loopfilter-control=0",
1553 "--enable-obmc=0",
1554 "--enable-warped-motion=0",
1555 "--enable-interintra-comp=0",
1556 "--enable-interintra-wedge=0",
1557 "--enable-smooth-interintra=0",
1558 "--enable-ref-frame-mvs=0",
1559 "--deltaq-mode=0",
1560 "--tile-columns=0",
1561 "--limit=12",
1562 "--obu",
1563 "-o",
1564 "-",
1565 "-",
1566 ];
1567 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1568 assert!(
1569 out.status.success(),
1570 "{NAME}: aomenc refused the fixture: {}",
1571 String::from_utf8_lossy(&out.stderr)
1572 );
1573 let stream = out.stdout;
1574 let header = {
1575 let mut parser = ec_av1_syntax::Av1Parser::new();
1576 let mut pos = 0usize;
1577 while let Ok(obu) = parser.parse_obu(&stream[pos..]) {
1578 pos += obu.total_size;
1579 if pos >= stream.len() {
1580 break;
1581 }
1582 }
1583 parser
1584 .sequence_header()
1585 .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth))
1586 };
1587 assert_eq!(
1588 header,
1589 Some((true, 8)),
1590 "{NAME}: the encoder did not write a 128x128-superblock 8-bit sequence header -- \
1591 the flags never arrived"
1592 );
1593 let before = (
1594 crate::decode::inter_sb128_none_hits(),
1595 crate::decode::chroma_split_tx_hits(),
1596 );
1597 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, "av1444128-128none-mu-chroma");
1598 let (none128, chroma_units) = (
1599 crate::decode::inter_sb128_none_hits() - before.0,
1600 crate::decode::chroma_split_tx_hits() - before.1,
1601 );
1602 assert!(frames >= 11, "{NAME}: only {frames} decode-order frames");
1603 assert!(
1604 none128 >= 8,
1605 "{NAME}: only {none128} inter 128x128 PARTITION_NONE roots -- the recipe stopped \
1606 exercising the shape this gate names"
1607 );
1608 assert!(
1609 chroma_units >= 8 * 8,
1610 "{NAME}: only {chroma_units} mu-chunk chroma units read -- the per-unit walk this \
1611 gate names never fired (four units per plane per coded 128-none inter block)"
1612 );
1613 eprintln!(
1614 "{NAME}: {frames} decode-order frames pixel-exact ({hidden} hidden), \
1615 inter_sb128_none_hits={none128} chroma_units={chroma_units}"
1616 );
1617 }
1618
1619 /// lane-av1ibc128arm: the INTRA-in-inter 128x128 root's mu-chunk chroma
1620 /// arm (`decode_inter_block`'s `side > 64` arm, the intra half of the
1621 /// inter pair the sibling gate above names) must code the mu chunk's
1622 /// chroma as a PER-UNIT walk at every subsampling, and at 4:4:4 each
1623 /// 64x64 mu chunk is FOUR TX_32X32 units per plane, not one.
1624 ///
1625 /// **The defect.** The arm hardcoded `cu_tx = 32`, `luma_span = cu_tx *
1626 /// 2` and the chroma origin `cc * cu_tx` -- the 4:2:0 arithmetic, where a
1627 /// mu chunk's chroma plane block is `64 >> 1 == 32` square and the whole
1628 /// chunk IS one TX_32X32 unit. At 4:4:4 the chunk's chroma is 64x64, so
1629 /// the arm (a) read one 32x32 unit where libaom codes four, (b) stamped
1630 /// the unit's entropy context over the 4:2:0 64x64 luma span rather than
1631 /// the unit's own 32x32, and (c) placed chunk 1's unit at `cpx + 32`
1632 /// instead of `cpx + 64`, i.e. back inside chunk 0's samples.
1633 ///
1634 /// **`av1_get_max_uv_txsize` is NOT the source of a 64x64 chroma unit.**
1635 /// `blockd.h:1371` is `av1_get_adjusted_tx_size(max_txsize_rect_lookup[
1636 /// get_plane_block_size(bsize, ss_x, ss_y)])`, and `av1_get_adjusted_tx_size`
1637 /// (`blockd.h:1361`) takes NO subsampling argument -- it maps TX_64X64 /
1638 /// TX_64X32 / TX_32X64 to TX_32X32 UNCONDITIONALLY, so even at ss (0,0)
1639 /// (where `get_plane_block_size` returns BLOCK_128X128 and the lookup
1640 /// entry is TX_64X64) the answer is TX_32X32. Measured on this gate's own
1641 /// stream against the oracle's `EC_TRACE_COEFF`: every chroma read of the
1642 /// 128x128 intra-in-inter root is `tx_size=3` (TX_32X32), four per plane
1643 /// per mu chunk at (row,col) (0,0) (0,8) (8,0) (8,8).
1644 ///
1645 /// **The recipe** (128x256, 3 frames). `--sb-size=128` with
1646 /// `--min-partition-size=64 --max-partition-size=128` keeps the
1647 /// superblock root resolvable to `PARTITION_NONE`, and the noise-on-
1648 /// gradient content is what makes the encoder's RD pick INTRA over inter
1649 /// for a whole 128 root on an inter frame (a clean `testsrc2` stream
1650 /// never does -- measured over 24 recipe/cell combinations, three of
1651 /// which fired and none of them `testsrc2`):
1652 /// ```text
1653 /// ffmpeg -f lavfi -i "gradients=size=128x256:c0=..:c1=..:c2=..:c3=..:\
1654 /// seed=63:duration=0.12:rate=25,noise=all_seed=63:alls=6:allf=t" \
1655 /// -pix_fmt yuv444p -t 0.12 -f yuv4mpegpipe - | \
1656 /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=62 \
1657 /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=128 --limit=3 \
1658 /// --max-partition-size=128 --min-partition-size=64 \
1659 /// --enable-rect-partitions=0 --enable-ab-partitions=0 \
1660 /// --enable-1to4-partitions=0 --enable-palette=0 \
1661 /// --enable-intrabc=0 --deltaq-mode=0 --enable-tx-size-search=0 \
1662 /// --obu -o out.obu -
1663 /// ```
1664 /// Both `rate=25` and the frame limit are load-bearing: `gradients`' and
1665 /// `noise`' patterns are time-parameterised, so a different rate or a
1666 /// different `--limit` emits a different stream (and at `--limit=2` this
1667 /// recipe stops choosing the shape at all -- measured, 0 fires).
1668 ///
1669 /// Non-vacuity, three ways: the sequence header is asserted really to be
1670 /// 4:4:4 (`subsampling_x == subsampling_y == 0`) and 128-superblock;
1671 /// `intra_128_in_inter_mu_chroma_hits()` must be non-zero, so the arm
1672 /// really ran; and every decode-order frame is compared byte-for-byte
1673 /// against the oracle by [`decode_all_frames_vs_oracle`], which panics on
1674 /// a refusal or any differing byte. Red before the fix (the ss-aware
1675 /// arithmetic and the per-unit walk reverted, the counter kept): decode-
1676 /// order frame 2 differs in 44649 of 98304 bytes while the counter still
1677 /// reads 4 -- the red is on PIXELS, not on the counter.
1678 #[test]
1679 fn a_real_aomenc_444_intra_in_inter_128_root_codes_chroma_per_mu_chunk_unit_pixel_exact() {
1680 const NAME: &str =
1681 "a_real_aomenc_444_intra_in_inter_128_root_codes_chroma_per_mu_chunk_unit_pixel_exact";
1682 let _gate_lock = lock_gate_counters();
1683 if !have_ffmpeg() || !have_aomenc() {
1684 eprintln!("SKIP {NAME}: no ffmpeg/aomenc/aomdec");
1685 return;
1686 }
1687 let (width, height) = (128usize, 256usize);
1688 let source = format!(
1689 "{},noise=all_seed=63:alls=6:allf=t",
1690 gradients_source(63, width, height, "duration=0.12:rate=25")
1691 );
1692 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1693 .args([
1694 "-v",
1695 "error",
1696 "-f",
1697 "lavfi",
1698 "-i",
1699 &source,
1700 "-pix_fmt",
1701 "yuv444p",
1702 "-t",
1703 "0.12",
1704 "-f",
1705 "yuv4mpegpipe",
1706 "-",
1707 ])
1708 .stdin(Stdio::null())
1709 .stdout(Stdio::piped())
1710 .stderr(Stdio::piped()), None, |c| c.output())
1711 .expect("ffmpeg failed to run");
1712 assert!(
1713 y4m.status.success(),
1714 "{NAME}: ffmpeg fixture: {}",
1715 String::from_utf8_lossy(&y4m.stderr)
1716 );
1717 let args: Vec<&str> = vec![
1718 "--codec=av1",
1719 "--profile=1",
1720 "--passes=1",
1721 "--end-usage=q",
1722 "--cq-level=62",
1723 "--cpu-used=0",
1724 "--threads=1",
1725 "--row-mt=0",
1726 "--sb-size=128",
1727 "--limit=3",
1728 "--max-partition-size=128",
1729 "--min-partition-size=64",
1730 "--enable-rect-partitions=0",
1731 "--enable-ab-partitions=0",
1732 "--enable-1to4-partitions=0",
1733 "--enable-palette=0",
1734 "--enable-intrabc=0",
1735 "--deltaq-mode=0",
1736 "--enable-tx-size-search=0",
1737 "--obu",
1738 "-o",
1739 "-",
1740 "-",
1741 ];
1742 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1743 assert!(
1744 out.status.success(),
1745 "{NAME}: aomenc refused the fixture: {}",
1746 String::from_utf8_lossy(&out.stderr)
1747 );
1748 let stream = out.stdout;
1749 // The gate is only about 4:4:4 at a 128 superblock, so assert the
1750 // parsed sequence header really is that before anything else: a
1751 // stream that silently came back 4:2:0 would leave this arm
1752 // unexercised while every other assert below still passed.
1753 let header = {
1754 let mut parser = ec_av1_syntax::Av1Parser::new();
1755 let mut pos = 0usize;
1756 while let Ok(obu) = parser.parse_obu(&stream[pos..]) {
1757 pos += obu.total_size;
1758 if pos >= stream.len() {
1759 break;
1760 }
1761 }
1762 parser.sequence_header().map(|q| {
1763 (
1764 q.use_128x128_superblock,
1765 q.color_config.subsampling_x,
1766 q.color_config.subsampling_y,
1767 q.color_config.mono_chrome,
1768 )
1769 })
1770 };
1771 assert_eq!(
1772 header,
1773 Some((true, 0, 0, false)),
1774 "{NAME}: the encoder did not write a 4:4:4 (ss 0/0, non-mono) 128x128-superblock \
1775 sequence header -- the flags never arrived, so the arm this gate names is not \
1776 the one under test"
1777 );
1778 let before = (
1779 crate::decode::intra_128_in_inter_hits(),
1780 crate::decode::intra_128_in_inter_mu_chroma_hits(),
1781 );
1782 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
1783 let (roots, units) = (
1784 crate::decode::intra_128_in_inter_hits() - before.0,
1785 crate::decode::intra_128_in_inter_mu_chroma_hits() - before.1,
1786 );
1787 assert!(
1788 frames >= 3,
1789 "{NAME}: only {frames} decode-order frames ({hidden} hidden), the recipe asks for 3"
1790 );
1791 assert!(
1792 roots >= 1,
1793 "{NAME}: no INTRA-coded 128x128 root inside an inter frame -- the recipe stopped \
1794 exercising the shape this gate names"
1795 );
1796 // One mu chunk per arm firing, and at 4:4:4 FOUR units per plane per
1797 // chunk (two 64x64 mu chunks per 128 root, two planes each).
1798 assert!(
1799 units >= 4,
1800 "{NAME}: only {units} mu-chunk chroma reads across {roots} intra-in-inter 128 \
1801 root(s) -- the per-unit walk this gate names never fired (a 4:4:4 64x64 mu chunk \
1802 is FOUR TX_32X32 units per plane, not one)"
1803 );
1804 eprintln!(
1805 "{NAME}: {frames} decode-order frames pixel-exact ({hidden} hidden), \
1806 intra_128_in_inter={roots} mu_chunk_chroma_reads={units}"
1807 );
1808 }
1809
1810 /// lane-av1sb128chroma: the PINNED half of
1811 /// [`a_real_aomenc_444_intra_in_inter_128_root_codes_chroma_per_mu_chunk_unit_pixel_exact`].
1812 /// That gate re-encodes its fixture on every run, so the arm it names had
1813 /// NO committed 4:4:4 bytes at all: a host without ffmpeg/aomenc silently
1814 /// skips it, and the whole committed 4:4:4 base is lossless 8-bit, so
1815 /// nothing else in the crate decoded one of these streams. This gate is
1816 /// the pin, and it also carries the COUNTER-PROOF arm: the recipe a
1817 /// proposed 4:4:4 `--sb-size=128` chroma repair was argued from reads
1818 /// ZERO on both the arm's own counters, so its green is vacuous.
1819 ///
1820 /// **Witness** `fixtures/444_intra_in_inter_128root_mu_chroma.obu`,
1821 /// sha256 `f5999bd996fef820472dc7846e42cad3e62bd1f816fafd7f218e34b77786394a`,
1822 /// 3570 bytes, 3 decode-order frames. Recipe (verified byte-reproducible):
1823 /// ```text
1824 /// ffmpeg -v error -f lavfi -i "gradients=size=128x256:c0=0xa1128f:c1=0xd98c48:\
1825 /// c2=0x120601:c3=0x4abfba:seed=63:duration=0.12:rate=25,\
1826 /// noise=all_seed=63:alls=6:allf=t" -pix_fmt yuv444p -t 0.12 -f yuv4mpegpipe - > in.y4m
1827 /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=62 \
1828 /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=128 --limit=3 \
1829 /// --max-partition-size=128 --min-partition-size=64 \
1830 /// --enable-rect-partitions=0 --enable-ab-partitions=0 \
1831 /// --enable-1to4-partitions=0 --enable-palette=0 --enable-intrabc=0 \
1832 /// --deltaq-mode=0 --enable-tx-size-search=0 --obu -o out.obu in.y4m
1833 /// ```
1834 /// `duration=0.12:rate=25` and `--limit=3` are load-bearing (the
1835 /// `gradients`/`noise` patterns are time-parameterised, and at `--limit=2`
1836 /// the encoder stops choosing INTRA over inter for a whole 128 root).
1837 ///
1838 /// **Measured on this witness** (unpatched `main` `57834ee2`): the arm
1839 /// fires `intra_128_in_inter_hits = 1` root and
1840 /// `intra_128_in_inter_mu_chroma_hits = 4` mu-chunk chroma reads (a 4:4:4
1841 /// 64x64 mu chunk is FOUR TX_32X32 units per plane, two chunks, one
1842 /// plane reached before the other), and all 3 frames are byte-exact
1843 /// against the oracle. The claimed `cu_tx = 64` repair is refuted by two
1844 /// independent measurements: (a) with `cu_tx` at 64 this arm PANICS --
1845 /// `no default scan for a 64-point transform` at `decode.rs:7197`, because
1846 /// libaom's `av1_get_adjusted_tx_size` (blockd.h:1361) maps TX_64X64 to
1847 /// TX_32X32 unconditionally, so a 4:4:4 chroma unit is never 64 and
1848 /// `av1_scan_orders` has no 64-point chroma table; (b) with only the
1849 /// luma-span and per-chunk-origin halves of that repair applied (`cu_tx`
1850 /// left at 32 so the mutation reaches the pixels), this same witness goes
1851 /// RED: Y 12537, U 16696, V 16667 wrong samples of 98304 per plane,
1852 /// first at Y(90,120) ours 142 vs oracle 141, U(65,120) 153 vs 152,
1853 /// V(64,120) 145 vs 146 -- all of it on decode-order frame 2, and the
1854 /// counters still read 1/4, so the damage is on PIXELS.
1855 #[test]
1856 fn a_444_intra_in_inter_128root_muchroma_pinned_stream_decodes_pixel_exact() {
1857 const NAME: &str =
1858 "a_444_intra_in_inter_128root_muchroma_pinned_stream_decodes_pixel_exact";
1859 const WITNESS_LEN: usize = 3570;
1860 const WITNESS_FNV: u64 = 0xe455_060d_f685_86dd;
1861 const CONTROL_LEN: usize = 31602;
1862 const CONTROL_FNV: u64 = 0xc542_f45f_f3a5_d494;
1863 const W: usize = 128;
1864 const H: usize = 256;
1865 const FRAMES: usize = 3;
1866 let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures");
1867 let read_pinned = |name: &str, len: usize, fnv: u64| -> Vec<u8> {
1868 let path = dir.join(name);
1869 let bytes = std::fs::read(&path).unwrap_or_else(|e| {
1870 panic!(
1871 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
1872 which is a failure, not a skip",
1873 path.display()
1874 )
1875 });
1876 assert_eq!(bytes.len(), len, "{NAME}: {name} length moved");
1877 assert_eq!(fnv1a64(&bytes), fnv, "{NAME}: {name} bytes moved");
1878 bytes
1879 };
1880 let stream = read_pinned(
1881 "444_intra_in_inter_128root_mu_chroma.obu",
1882 WITNESS_LEN,
1883 WITNESS_FNV,
1884 );
1885
1886 let _gate_lock = lock_gate_counters();
1887 // The shape claim first: a stream that silently came back 4:2:0 would
1888 // leave the arm unexercised while every other assert still passed.
1889 let header = {
1890 let mut parser = ec_av1_syntax::Av1Parser::new();
1891 let mut pos = 0usize;
1892 while let Ok(obu) = parser.parse_obu(&stream[pos..]) {
1893 pos += obu.total_size;
1894 if pos >= stream.len() {
1895 break;
1896 }
1897 }
1898 parser.sequence_header().map(|q| {
1899 (
1900 q.use_128x128_superblock,
1901 q.color_config.subsampling_x,
1902 q.color_config.subsampling_y,
1903 q.color_config.mono_chrome,
1904 )
1905 })
1906 };
1907 assert_eq!(
1908 header,
1909 Some((true, 0, 0, false)),
1910 "{NAME}: the witness is not a 4:4:4 (ss 0/0, non-mono) 128x128-superblock stream \
1911 -- {header:?}, so the arm under test is not the one that ran"
1912 );
1913 let before = (
1914 crate::decode::intra_128_in_inter_hits(),
1915 crate::decode::intra_128_in_inter_mu_chroma_hits(),
1916 );
1917 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
1918 let (roots, units) = (
1919 crate::decode::intra_128_in_inter_hits() - before.0,
1920 crate::decode::intra_128_in_inter_mu_chroma_hits() - before.1,
1921 );
1922 assert_eq!(decoded, FRAMES, "{NAME}: decode-order frame count");
1923 // At 4:4:4 the chroma planes are full resolution; a decoder that kept
1924 // the 4:2:0 extent would hand quarter-size chroma to the byte compare,
1925 // which cannot pass. Say it here rather than let the compare stand in
1926 // for the shape claim.
1927 for f in crate::stream::decode_stream(&stream)
1928 .unwrap_or_else(|e| panic!("{NAME}: the witness no longer decodes cleanly: {e}"))
1929 {
1930 assert_eq!((f.width, f.height), (W, H), "{NAME}: frame dimensions");
1931 assert_eq!(
1932 f.u.len(),
1933 W * H,
1934 "{NAME}: chroma plane is {} samples",
1935 f.u.len()
1936 );
1937 }
1938 assert!(
1939 roots >= 1,
1940 "{NAME}: no INTRA-coded 128x128 root inside an inter frame -- the arm under \
1941 test never ran"
1942 );
1943 assert!(
1944 units >= 4,
1945 "{NAME}: only {units} mu-chunk chroma reads across {roots} intra-in-inter 128 \
1946 root(s) -- a 4:4:4 64x64 mu chunk is FOUR TX_32X32 units per plane, so fewer \
1947 than four means the per-unit walk this gate names did not run"
1948 );
1949 eprintln!(
1950 "{NAME}: {decoded} decode-order frame(s) pixel-exact ({hidden} hidden), \
1951 intra_128_in_inter={roots} mu_chunk_chroma_reads={units}"
1952 );
1953
1954 // The COUNTER-PROOF arm. The 4:4:4 `--sb-size=128 --cq-level=20`
1955 // `testsrc2` recipe a 64-point-chroma repair was argued from is
1956 // byte-exact on all 24 frames AND reads ZERO on both of the arm's
1957 // counters: on clean `testsrc2` the encoder's RD never picks INTRA
1958 // over inter for a whole 128 root, so that stream cannot witness this
1959 // arm at all. Pinning it keeps the refutation reproducible in-crate
1960 // with no encoder on the host.
1961 let control = read_pinned("444_sb128cq20_tsrc2_control.obu", CONTROL_LEN, CONTROL_FNV);
1962 let ctl_header = {
1963 let mut parser = ec_av1_syntax::Av1Parser::new();
1964 let mut pos = 0usize;
1965 while let Ok(obu) = parser.parse_obu(&control[pos..]) {
1966 pos += obu.total_size;
1967 if pos >= control.len() {
1968 break;
1969 }
1970 }
1971 parser.sequence_header().map(|q| {
1972 (
1973 q.use_128x128_superblock,
1974 q.color_config.subsampling_x,
1975 q.color_config.subsampling_y,
1976 )
1977 })
1978 };
1979 assert_eq!(
1980 ctl_header,
1981 Some((true, 0, 0)),
1982 "{NAME}: the control stream is not the 4:4:4 128-superblock stream its recipe \
1983 names -- {ctl_header:?}"
1984 );
1985 let ctl_before = (
1986 crate::decode::intra_128_in_inter_hits(),
1987 crate::decode::intra_128_in_inter_mu_chroma_hits(),
1988 );
1989 let ctl_frames = crate::stream::decode_stream(&control)
1990 .unwrap_or_else(|e| panic!("{NAME}: the control stream no longer decodes: {e}"))
1991 .len();
1992 let ctl = (
1993 crate::decode::intra_128_in_inter_hits() - ctl_before.0,
1994 crate::decode::intra_128_in_inter_mu_chroma_hits() - ctl_before.1,
1995 );
1996 assert_eq!(ctl_frames, 24, "{NAME}: control frame count");
1997 assert_eq!(
1998 ctl,
1999 (0, 0),
2000 "{NAME}: the control stream now reaches the arm ({ctl:?}) -- the witness's \
2001 non-vacuity argument rested on `testsrc2` never choosing an \
2002 intra-coded 128 root, and that is no longer true, so the two \
2003 fixtures no longer separate the cells"
2004 );
2005 if aomdec_available(NAME) {
2006 let (ctl_decoded, ctl_hidden) = decode_all_frames_vs_oracle(&control, NAME);
2007 assert_eq!(ctl_decoded, 24, "{NAME}: control decode-order frame count");
2008 eprintln!("{NAME}: control {ctl_decoded} frame(s) pixel-exact ({ctl_hidden} hidden)");
2009 }
2010 }
2011
2012 /// lane-av1muchunk422b: the **compound** `side > 64` mu-chunk walk --
2013 /// per-unit chroma allocation of `decode_inter_block`'s compound arm, site
2014 /// 2 of `lanes/av1muchunk422.report.md`, which that lane's recipes all
2015 /// missed (`part128 none=0` on a 384x256 frame).
2016 ///
2017 /// Reachability, shared with the intra-in-inter twin below: the streams
2018 /// that reach this walk are 128-as-the-whole-frame (`--sb-size=128
2019 /// --min-partition-size=128 --max-partition-size=128`, PARTITION_NONE
2020 /// forced; here `part128 none=7`) and LOSSY, which is load-bearing: each arm
2021 /// has a lossless branch that returns before the unit loop, and
2022 /// `W_intrabc.obu` reaches both guards at ss (1,0) allocating nothing. That
2023 /// is why [`crate::decode::mu_chunk_compound_units`] counts at the
2024 /// ALLOCATION and not at the guard; the counter-proof at the end of the
2025 /// intra test pins that gap. The single-reference twin of site 2 (site 5)
2026 /// shares this exact source text and is routed out of the counter by
2027 /// `is_compound`.
2028 ///
2029 /// **7 of the 8 streams this lane generated DIVERGED from ffmpeg; only
2030 /// `i6_grad128_iis` (the intra-in-inter fixture, pinned in the twin test
2031 /// below) was byte-exact.** lane-av1muchunk422sym has since fixed this
2032 /// pin's stream: the compound mu-chunk walk gathered its CHROMA
2033 /// coefficient context with the plain rect rule, which at ss (1, 0) counts
2034 /// one chroma column twice in the above vote (see the walk's own comment).
2035 /// **The stream is now byte-exact against the instrumented aomdec over all
2036 /// 7 decode-order frames (6 shown + 1 hidden alt-ref)**, so this test
2037 /// carries both halves: the counter witness that the walk ran AND the
2038 /// exactness witness. The pinned V-plane hashes run without an oracle;
2039 /// `decode_all_frames_vs_oracle` adds the decode-order compare when one is
2040 /// present. The counter half still stops this fixture silently ceasing to
2041 /// reach the walk it was pinned for.
2042 ///
2043 /// Recipe (byte-reproducible; whole aomenc argv):
2044 /// ```text
2045 /// ffmpeg -v error -f lavfi -i "testsrc2=size=128x128:rate=25" -t 0.24 \
2046 /// -pix_fmt yuv422p -f yuv4mpegpipe - > tsrc128.y4m
2047 /// aomenc --codec=av1 --profile=2 --input-chroma-subsampling-x=1 \
2048 /// --input-chroma-subsampling-y=0 --passes=1 --end-usage=q --cq-level=62 \
2049 /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=128 \
2050 /// --min-partition-size=128 --max-partition-size=128 \
2051 /// --enable-rect-partitions=0 --enable-ab-partitions=0 \
2052 /// --enable-1to4-partitions=0 --enable-palette=0 --enable-intrabc=0 \
2053 /// --deltaq-mode=0 --enable-tx-size-search=0 --enable-interintra-comp=1 \
2054 /// --enable-interintra-wedge=1 --enable-smooth-interintra=1 --obu -o X
2055 /// ```
2056 #[test]
2057 fn a_422_muchunk_compound_128root_pinned_stream_reaches_its_unit_walk() {
2058 const NAME: &str = "a_422_muchunk_compound_128root_pinned_stream_reaches_its_unit_walk";
2059 const FILE: &str = "422_muchunk_compound_128root.obu";
2060 const LEN: usize = 895;
2061 const FNV: u64 = 0xfb28_f9a7_cf23_9897;
2062 const MIN_UNITS: usize = 32;
2063 // lane-av1muchunk422sym: shown frame 2's V plane byte-for-byte (it is
2064 // the first intrinsically wrong frame; the pre-fix square gather put
2065 // 2138 of these 8192 samples off by up to 4), and shown frame 0's as
2066 // the unaffected control. 0xa0e5_8bf4_207b_29ba is the ffmpeg/aomdec
2067 // exact plane.
2068 const SHOWN_F2_V_FNV: u64 = 0xa0e5_8bf4_207b_29ba;
2069 const SHOWN_F0_V_FNV: u64 = 0xcc5e_3291_1915_9024;
2070 /// Chroma (36, 60) of shown frame 2 -- the FIRST sample that moved,
2071 /// `60 * 64 + 36`. The pre-fix square gather read 113, the oracle 112.
2072 const FIRST_WRONG_V: usize = 3876;
2073 const SHOWN_F2_V_AT_FIRST_WRONG: u16 = 112;
2074 let _gate_lock = lock_gate_counters();
2075 let stream = read_pinned_muchunk_fixture(FILE, LEN, FNV, NAME);
2076 assert_eq!(
2077 obu_stream_shape(&stream),
2078 Some((true, 1, 0, false)),
2079 "{NAME}: {FILE} is not a 4:2:2 (ss 1/0, non-mono) 128x128-superblock stream"
2080 );
2081 let before = (
2082 crate::decode::mu_chunk_compound_units(),
2083 crate::decode::mu_chunk_intra_in_inter_units(),
2084 );
2085 let shown = crate::stream::decode_stream(&stream)
2086 .unwrap_or_else(|e| panic!("{NAME}: {FILE} no longer decodes cleanly: {e}"));
2087 let frames = shown.len();
2088 let (compound, intra) = (
2089 crate::decode::mu_chunk_compound_units() - before.0,
2090 crate::decode::mu_chunk_intra_in_inter_units() - before.1,
2091 );
2092 assert_eq!(frames, 6, "{NAME}: {FILE} shown-frame count");
2093 assert!(
2094 compound >= MIN_UNITS,
2095 "{NAME}: {FILE} allocated only {compound} compound `side > 64` mu-chunk units \
2096 (expected >= {MIN_UNITS}) -- the walk this gate names did not run"
2097 );
2098 assert_eq!(
2099 intra, 0,
2100 "{NAME}: {FILE} also ran the intra-in-inter walk ({intra} units) -- the two fixtures \
2101 no longer separate the cells"
2102 );
2103 // lane-av1muchunk422sym: the EXACTNESS half the diagnostic lane handed
2104 // over ("when a fix lane lands, add the oracle compare to this test").
2105 // The fix routes this walk's CHROMA context gather through the 4:2:2
2106 // pair rule (`around_mi_422_chroma`): at ss (1, 0) one chroma column
2107 // spans two luma mi columns, so the plain rect gather summed the unit's
2108 // above dc sign twice and `dc_sign_ctx`'s signum flipped whenever above
2109 // and left cancelled. The first wrong symbol was the DC SIGN of the V
2110 // unit at chunk (1, 1) of decode frame 2 -- ours read
2111 // `dc_sign_cdf[1]`, the oracle row 0.
2112 //
2113 // The pinned half below needs NO oracle and is therefore the one that
2114 // cannot silently skip: shown frame 2 (the first intrinsically wrong
2115 // frame) is asserted sample-for-sample on its V plane. Frame 0's is
2116 // asserted too, as the unaffected control that fails if the gather is
2117 // "fixed" past its own cell.
2118 assert_eq!(
2119 shown[0].v.len(),
2120 64 * 128,
2121 "{NAME}: {FILE} is no longer 4:2:2 -- the V plane shape moved"
2122 );
2123 assert_eq!(
2124 fnv1a64(&shown[2].v.iter().map(|&s| s as u8).collect::<Vec<u8>>()),
2125 SHOWN_F2_V_FNV,
2126 "{NAME}: {FILE} shown frame 2's V plane moved -- the compound mu-chunk walk's 4:2:2 \
2127 chroma context gather is wrong again (first sample to move is chroma (36, 60), index \
2128 3876, expected {})",
2129 SHOWN_F2_V_AT_FIRST_WRONG
2130 );
2131 assert_eq!(
2132 shown[2].v[FIRST_WRONG_V], SHOWN_F2_V_AT_FIRST_WRONG,
2133 "{NAME}: {FILE} shown frame 2 V[3876] (chroma (36, 60)) is {} -- the pre-fix square \
2134 gather read 113 here",
2135 shown[2].v[FIRST_WRONG_V]
2136 );
2137 assert_eq!(
2138 fnv1a64(&shown[0].v.iter().map(|&s| s as u8).collect::<Vec<u8>>()),
2139 SHOWN_F0_V_FNV,
2140 "{NAME}: {FILE} shown frame 0's V plane moved -- the 4:2:2 routing changed a frame it \
2141 must not touch"
2142 );
2143 if aomdec_available(NAME) {
2144 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2145 assert_eq!(decoded, 7, "{NAME}: {FILE} decode-order frame count");
2146 eprintln!(
2147 "{NAME}: {FILE} byte-exact over {decoded} decode-order frame(s) ({hidden} hidden), \
2148 compound_units={compound} intra_in_inter_units={intra}"
2149 );
2150 } else {
2151 eprintln!(
2152 "{NAME}: {FILE} compound_units={compound} intra_in_inter_units={intra} -- the \
2153 decode-order oracle compare above did NOT run (no aomdec)"
2154 );
2155 }
2156 }
2157
2158 /// lane-av1muchunk422b: the **intra-in-inter** `side > 64` mu-chunk walk --
2159 /// per-unit chroma allocation of the intra-in-inter arm (site 8 of
2160 /// `lanes/av1muchunk422.report.md`). This is the ONE stream of the eight
2161 /// this lane generated that is BYTE-EXACT against the ffmpeg/aom oracle
2162 /// (`i6_grad128_iis`), so unlike its compound twin this gate asserts
2163 /// pixel-exactness over every decode-order frame AND that the site counter
2164 /// moved. See the compound test above for the shared reachability and
2165 /// count-at-the-ALLOCATION argument.
2166 ///
2167 /// Recipe (byte-reproducible; same aomenc argv as the compound test except
2168 /// for the source):
2169 /// ```text
2170 /// ffmpeg -v error -f lavfi -i "gradients=size=128x256:c0=0xa1128f:\
2171 /// c1=0xd98c48:c2=0x120601:c3=0x4abfba:seed=63:duration=0.24:rate=25,\
2172 /// noise=all_seed=63:alls=6:allf=t" -t 0.24 -pix_fmt yuv422p \
2173 /// -f yuv4mpegpipe - > grad256.y4m
2174 /// aomenc --codec=av1 --profile=2 --input-chroma-subsampling-x=1 \
2175 /// --input-chroma-subsampling-y=0 --passes=1 --end-usage=q --cq-level=62 \
2176 /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=128 \
2177 /// --min-partition-size=128 --max-partition-size=128 \
2178 /// --enable-rect-partitions=0 --enable-ab-partitions=0 \
2179 /// --enable-1to4-partitions=0 --enable-palette=0 --enable-intrabc=0 \
2180 /// --deltaq-mode=0 --enable-tx-size-search=0 --enable-interintra-comp=1 \
2181 /// --enable-interintra-wedge=1 --enable-smooth-interintra=1 --obu -o X
2182 /// ```
2183 #[test]
2184 fn a_422_muchunk_intra_in_inter_128root_pinned_stream_is_exact_and_reaches_its_unit_walk() {
2185 const NAME: &str =
2186 "a_422_muchunk_intra_in_inter_128root_pinned_stream_is_exact_and_reaches_its_unit_walk";
2187 const FILE: &str = "422_muchunk_intra_in_inter_128root.obu";
2188 const LEN: usize = 391;
2189 const FNV: u64 = 0xe4d7_2c19_5a11_1f4f;
2190 const MIN_UNITS: usize = 16;
2191 // 6 shown frames + the 1 hidden alt-ref frame the oracle also emits.
2192 const DECODED: usize = 7;
2193 let _gate_lock = lock_gate_counters();
2194 let stream = read_pinned_muchunk_fixture(FILE, LEN, FNV, NAME);
2195 assert_eq!(
2196 obu_stream_shape(&stream),
2197 Some((true, 1, 0, false)),
2198 "{NAME}: {FILE} is not a 4:2:2 (ss 1/0, non-mono) 128x128-superblock stream"
2199 );
2200 let before = (
2201 crate::decode::mu_chunk_compound_units(),
2202 crate::decode::mu_chunk_intra_in_inter_units(),
2203 );
2204 let frames = crate::stream::decode_stream(&stream)
2205 .unwrap_or_else(|e| panic!("{NAME}: {FILE} no longer decodes cleanly: {e}"))
2206 .len();
2207 let (compound, intra) = (
2208 crate::decode::mu_chunk_compound_units() - before.0,
2209 crate::decode::mu_chunk_intra_in_inter_units() - before.1,
2210 );
2211 assert_eq!(frames, 6, "{NAME}: {FILE} shown-frame count");
2212 assert!(
2213 intra >= MIN_UNITS,
2214 "{NAME}: {FILE} allocated only {intra} intra-in-inter `side > 64` mu-chunk units \
2215 (expected >= {MIN_UNITS}) -- the site counter this gate names did not move"
2216 );
2217 assert_eq!(
2218 compound, 0,
2219 "{NAME}: {FILE} also ran the compound walk ({compound} units) -- the two fixtures no \
2220 longer separate the cells"
2221 );
2222 if aomdec_available(NAME) {
2223 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2224 assert_eq!(decoded, DECODED, "{NAME}: {FILE} decode-order frame count");
2225 eprintln!(
2226 "{NAME}: {FILE} byte-exact over {decoded} decode-order frame(s) ({hidden} \
2227 hidden), intra_in_inter_units={intra}"
2228 );
2229 }
2230
2231 // The counter-proof: the LOSSLESS 4:2:2 stream that reaches both
2232 // `side > 64` guards at ss (1,0) and allocates nothing. `W_intrabc`
2233 // is the fixture the prior lane measured `site 2 = 0` on, and this
2234 // pins why that zero was real -- the arm's lossless branch returns
2235 // before the unit loop.
2236 let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures");
2237 let intrabc = std::fs::read(dir.join("W_intrabc.obu"))
2238 .expect("W_intrabc.obu is missing -- the counter-proof cannot run");
2239 let proof_before = (
2240 crate::decode::mu_chunk_compound_units(),
2241 crate::decode::mu_chunk_intra_in_inter_units(),
2242 crate::decode::intra_128_in_inter_mu_chroma_hits(),
2243 );
2244 let proof_frames = crate::stream::decode_stream(&intrabc)
2245 .expect("W_intrabc.obu no longer decodes")
2246 .len();
2247 let proof = (
2248 crate::decode::mu_chunk_compound_units() - proof_before.0,
2249 crate::decode::mu_chunk_intra_in_inter_units() - proof_before.1,
2250 crate::decode::intra_128_in_inter_mu_chroma_hits() - proof_before.2,
2251 );
2252 assert_eq!(proof_frames, 16, "{NAME}: W_intrabc shown-frame count");
2253 assert_eq!(
2254 (proof.0, proof.1),
2255 (0, 0),
2256 "{NAME}: W_intrabc now allocates mu-chunk units ({}, {}) -- it cannot be the \
2257 counter-proof any more",
2258 proof.0,
2259 proof.1
2260 );
2261 assert!(
2262 proof.2 > 0,
2263 "{NAME}: W_intrabc no longer reaches the intra-in-inter guard at all \
2264 (INTRA_128_IN_INTER_MU_CHROMA_HITS delta 0), so its zero allocations prove \
2265 nothing about the guard-to-allocation gap this gate rests on"
2266 );
2267 eprintln!(
2268 "{NAME}: counter-proof W_intrabc allocations=({}, {}) with the intra-in-inter guard \
2269 fired {} time(s)",
2270 proof.0, proof.1, proof.2
2271 );
2272 }
2273
2274 /// lane-av1muchunk422iis: the **intra-in-inter** `side > 64` mu-chunk
2275 /// walk at 128x256 (TWO 128-superblock rows), site 8's second stream.
2276 /// lane-av1muchunk422class measured this stream diverging with the class
2277 /// signature -- V-plane-only diffs, first wrong sample V (row 190, col 36)
2278 /// of shown frame 2 (V index `190 * 64 + 36 = 12196`, ours 147 vs
2279 /// ffmpeg's 146), a byte-identical decode before and after the compound
2280 /// fix, and the SAME `dc_sign_ctx` fork the compound fix targeted, on the
2281 /// TX_32X32 chroma unit of THIS walk. The walk gathered its chroma
2282 /// context with the plain luma `around_mi` (decode.rs:46820), which at
2283 /// ss (1, 0) sums `unit_luma_w / MI` above cells where libaom sums
2284 /// `txb_w_unit` -- twice as many -- flipping the signum whenever the
2285 /// doubled above vote cancels the left one (see the walk's own comment).
2286 ///
2287 /// The fixture is the hunt's `i5_grad256_iis.obu` (sha256
2288 /// `64794f278eee738dcc59d90dc0c7c4ef2828c5b7c13724760a33be11f224908e`),
2289 /// pinned byte-for-byte. Recipe: same aomenc argv as the 128x128 twin
2290 /// below, source `gradients=size=128x256:...:seed=63:duration=0.24:rate=25,
2291 /// noise=all_seed=63:alls=6:allf=t` (NOT re-encoded by this lane; the
2292 /// bytes are the hunted bytes).
2293 ///
2294 /// Three halves, in order: (a) the site counter moved AND this stream
2295 /// never enters the compound walk; (b) an ORACLE-FREE V-plane pin of
2296 /// shown frame 2 plus the one sample that moved, so the exactness half
2297 /// cannot silently skip; (c) the required ffmpeg compare -- every plane
2298 /// of every shown frame byte-exact -- and the decode-order oracle compare
2299 /// when one is available.
2300 #[test]
2301 fn a_422_muchunk_intra_in_inter_128x256_stream_is_exact_and_reaches_its_unit_walk() {
2302 const NAME: &str =
2303 "a_422_muchunk_intra_in_inter_128x256_stream_is_exact_and_reaches_its_unit_walk";
2304 const FILE: &str = "422_muchunk_intra_in_inter_128x256.obu";
2305 const LEN: usize = 667;
2306 const FNV: u64 = 0x2bee_eba3_052b_f9a3;
2307 const MIN_UNITS: usize = 96;
2308 // 6 shown frames; the oracle also emits 1 hidden alt-ref frame.
2309 const SHOWN: usize = 6;
2310 // Shown frame 2's V plane, 4:2:2 at 128x256 -> 64 x 256 chroma.
2311 const F2_V_FNV: u64 = 0xa7ba_8711_9d13_8fe5;
2312 // V (row 190, col 36): the first sample that moved. The pre-fix
2313 // square gather read 147 here, ffmpeg 146.
2314 const FIRST_WRONG_V: usize = 190 * 64 + 36;
2315 const F2_V_AT_FIRST_WRONG: u16 = 146;
2316 let _gate_lock = lock_gate_counters();
2317 let stream = read_pinned_muchunk_fixture(FILE, LEN, FNV, NAME);
2318 assert_eq!(
2319 obu_stream_shape(&stream),
2320 Some((true, 1, 0, false)),
2321 "{NAME}: {FILE} is not a 4:2:2 (ss 1/0, non-mono) 128-superblock stream"
2322 );
2323 let before = (
2324 crate::decode::mu_chunk_compound_units(),
2325 crate::decode::mu_chunk_intra_in_inter_units(),
2326 );
2327 let shown = crate::stream::decode_stream(&stream)
2328 .unwrap_or_else(|e| panic!("{NAME}: {FILE} no longer decodes cleanly: {e}"));
2329 let frames = shown.len();
2330 let (compound, intra) = (
2331 crate::decode::mu_chunk_compound_units() - before.0,
2332 crate::decode::mu_chunk_intra_in_inter_units() - before.1,
2333 );
2334 assert_eq!(frames, SHOWN, "{NAME}: {FILE} shown-frame count");
2335 assert!(
2336 intra >= MIN_UNITS,
2337 "{NAME}: {FILE} allocated only {intra} intra-in-inter `side > 64` mu-chunk units \
2338 (expected >= {MIN_UNITS}) -- the site counter this gate names did not move"
2339 );
2340 assert_eq!(
2341 compound, 0,
2342 "{NAME}: {FILE} also ran the compound walk ({compound} units) -- the two cells are \
2343 no longer separated"
2344 );
2345 // (b) the oracle-free half: the V plane of the first intrinsically
2346 // wrong frame, sample-for-sample, plus the one sample the pre-fix
2347 // gather got wrong.
2348 assert_eq!(
2349 shown[2].v.len(),
2350 64 * 256,
2351 "{NAME}: {FILE} is no longer 4:2:2 at 128x256 -- the V plane shape moved"
2352 );
2353 assert_eq!(
2354 shown[2].v[FIRST_WRONG_V], F2_V_AT_FIRST_WRONG,
2355 "{NAME}: {FILE} shown frame 2 V[{FIRST_WRONG_V}] (chroma (190, 36)) is {} -- the \
2356 pre-fix square gather read 147 here",
2357 shown[2].v[FIRST_WRONG_V]
2358 );
2359 assert_eq!(
2360 fnv1a64(&shown[2].v.iter().map(|&s| s as u8).collect::<Vec<u8>>()),
2361 F2_V_FNV,
2362 "{NAME}: {FILE} shown frame 2's V plane moved -- the intra-in-inter mu-chunk walk's \
2363 4:2:2 chroma context gather is wrong again (first sample to move is chroma (190, \
2364 36), index {FIRST_WRONG_V})"
2365 );
2366 // (c) the required ffmpeg compare: every plane of every shown frame.
2367 if !have_ffmpeg() {
2368 eprintln!(
2369 "SKIP {NAME}: no ffmpeg -- the 4:2:2 pixel compare this gate exists for did NOT \
2370 run (set EC_AV1_REQUIRE_FFMPEG=1 to make this a failure)"
2371 );
2372 return;
2373 }
2374 let ff = ffmpeg_decode_sequence_422(&stream, 128, 256, SHOWN);
2375 assert_eq!(ff.len(), SHOWN, "{NAME}: {FILE} ffmpeg shown-frame count");
2376 for (i, (got, want)) in shown.iter().zip(&ff).enumerate() {
2377 assert_eq!(
2378 got.y, want.y,
2379 "{NAME}: {FILE} shown frame {i} luma vs ffmpeg"
2380 );
2381 assert_eq!(got.u, want.u, "{NAME}: {FILE} shown frame {i} U vs ffmpeg");
2382 assert_eq!(got.v, want.v, "{NAME}: {FILE} shown frame {i} V vs ffmpeg");
2383 }
2384 if aomdec_available(NAME) {
2385 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2386 assert_eq!(
2387 decoded,
2388 SHOWN + 1,
2389 "{NAME}: {FILE} decode-order frame count"
2390 );
2391 eprintln!(
2392 "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames and vs the \
2393 decode-order oracle over {decoded} frame(s) ({hidden} hidden), \
2394 intra_in_inter_units={intra}"
2395 );
2396 } else {
2397 eprintln!(
2398 "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames, \
2399 intra_in_inter_units={intra} -- the decode-order oracle compare above did NOT \
2400 run (no aomdec)"
2401 );
2402 }
2403 }
2404
2405 /// lane-av1muchunkluma: the **compound-arm CONTENT** stream that reaches
2406 /// only the intra-in-inter `side > 64` mu-chunk walk. `aomenc` was driven
2407 /// with the compound arm's own flags (`--enable-masked-comp=1
2408 /// --enable-onesided-comp=1 --auto-alt-ref=1`), so it *is* the compound
2409 /// hunt's `c3_grad128_comp` -- but its partition search never enters the
2410 /// compound mu-chunk walk (0 `compound/singleref` probe lines, 16
2411 /// `intra_in_inter` ones), so its ONLY mu-chunk walk is site 8.
2412 ///
2413 /// lane-av1muchunk422class measured this stream diverging on the
2414 /// then-current tree: first wrong sample **Y (62, 6) of shown frame 1**
2415 /// (`62 * 128 + 6 = 7942`, ours 74, ffmpeg 75) and a byte-identical decode
2416 /// before and after the compound DC-sign fix. lane-av1muchunk422iis's
2417 /// intra-in-inter gather fix closed it: the pinned halves below are the
2418 /// exact plane and the exact sample the pre-fix square gather moved.
2419 ///
2420 /// Recipe (byte-reproducible; re-encoded by this lane from the frozen
2421 /// `grad128.y4m`, sha256 `ab8b23137c4efc818884efcf0bb6ccda363bae4b8360f2ca10ca68506cbb777d`,
2422 /// which itself regenerates byte-for-byte):
2423 /// ```text
2424 /// ffmpeg -v error -f lavfi -i "gradients=size=128x128:c0=0xa1128f:\
2425 /// c1=0xd98c48:c2=0x120601:c3=0x4abfba:seed=63:duration=0.24:rate=25,\
2426 /// noise=all_seed=63:alls=6:allf=t" -t 0.24 -pix_fmt yuv422p \
2427 /// -f yuv4mpegpipe - > grad128.y4m
2428 /// aomenc --codec=av1 --profile=2 --input-chroma-subsampling-x=1 \
2429 /// --input-chroma-subsampling-y=0 --passes=1 --end-usage=q --cq-level=40 \
2430 /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=128 \
2431 /// --min-partition-size=128 --max-partition-size=128 \
2432 /// --enable-rect-partitions=0 --enable-ab-partitions=0 \
2433 /// --enable-1to4-partitions=0 --enable-palette=0 --enable-intrabc=0 \
2434 /// --deltaq-mode=0 --enable-tx-size-search=0 --limit=6 --lag-in-frames=25 \
2435 /// --auto-alt-ref=1 --enable-global-motion=1 --enable-warped-motion=1 \
2436 /// --enable-masked-comp=1 --enable-diff-wtd-comp=1 --enable-onesided-comp=1 \
2437 /// --obu -o c3_grad128_comp.obu grad128.y4m
2438 /// ```
2439 #[test]
2440 fn a_422_muchunk_iis_128root_grad128_comp_stream_is_exact_and_reaches_its_unit_walk() {
2441 const NAME: &str =
2442 "a_422_muchunk_iis_128root_grad128_comp_stream_is_exact_and_reaches_its_unit_walk";
2443 const FILE: &str = "422_muchunk_iis_128root_grad128.obu";
2444 const LEN: usize = 34449;
2445 const FNV: u64 = 0xfc59_a295_38db_577e;
2446 const MIN_UNITS: usize = 16;
2447 const SHOWN: usize = 6;
2448 // The stream carried in frame 1, the first frame the pre-fix gather
2449 // moved; frame 0 is the unaffected control.
2450 const F1_Y_FNV: u64 = 0x1b17_b4c2_4bd3_58d9;
2451 const F0_Y_FNV: u64 = 0x7666_cd9b_dc47_be3f;
2452 // Y (62, 6) of shown frame 1: the first sample that moved. The
2453 // pre-fix square gather read 74 here, ffmpeg 75.
2454 const FIRST_WRONG_Y: usize = 62 * 128 + 6;
2455 const F1_Y_AT_FIRST_WRONG: u16 = 75;
2456 let _gate_lock = lock_gate_counters();
2457 let stream = read_pinned_muchunk_fixture(FILE, LEN, FNV, NAME);
2458 assert_eq!(
2459 obu_stream_shape(&stream),
2460 Some((true, 1, 0, false)),
2461 "{NAME}: {FILE} is not a 4:2:2 (ss 1/0, non-mono) 128x128-superblock stream"
2462 );
2463 let before = (
2464 crate::decode::mu_chunk_compound_units(),
2465 crate::decode::mu_chunk_intra_in_inter_units(),
2466 );
2467 let shown = crate::stream::decode_stream(&stream)
2468 .unwrap_or_else(|e| panic!("{NAME}: {FILE} no longer decodes cleanly: {e}"));
2469 let frames = shown.len();
2470 let (compound, intra) = (
2471 crate::decode::mu_chunk_compound_units() - before.0,
2472 crate::decode::mu_chunk_intra_in_inter_units() - before.1,
2473 );
2474 assert_eq!(frames, SHOWN, "{NAME}: {FILE} shown-frame count");
2475 assert!(
2476 intra >= MIN_UNITS,
2477 "{NAME}: {FILE} allocated only {intra} intra-in-inter `side > 64` mu-chunk units \
2478 (expected >= {MIN_UNITS}) -- the site counter this gate names did not move"
2479 );
2480 assert_eq!(
2481 compound, 0,
2482 "{NAME}: {FILE} moved the compound-named counter ({compound} units) -- this stream's \
2483 only mu-chunk walk is the intra-in-inter one and the cells are no longer separated"
2484 );
2485 // (b) the oracle-free half: shown frame 1 (the first frame the pre-fix
2486 // gather moved) is asserted sample-for-sample on its luma plane, plus
2487 // the single sample that moved first; shown frame 0's luma is the
2488 // unaffected control that fails if the gather is "fixed" past its own
2489 // cell.
2490 assert_eq!(
2491 shown[1].y.len(),
2492 128 * 128,
2493 "{NAME}: {FILE} is no longer 4:2:2 at 128x128 -- the luma plane shape moved"
2494 );
2495 assert_eq!(
2496 fnv1a64(&shown[1].y.iter().map(|&s| s as u8).collect::<Vec<u8>>()),
2497 F1_Y_FNV,
2498 "{NAME}: {FILE} shown frame 1's luma moved -- the intra-in-inter mu-chunk walk's 4:2:2 \
2499 chroma context gather is wrong again (first sample to move is Y (62, 6), index \
2500 {FIRST_WRONG_Y})"
2501 );
2502 assert_eq!(
2503 shown[1].y[FIRST_WRONG_Y], F1_Y_AT_FIRST_WRONG,
2504 "{NAME}: {FILE} shown frame 1 Y[{FIRST_WRONG_Y}] (luma (62, 6)) is {} -- the pre-fix \
2505 square gather read 74 here",
2506 shown[1].y[FIRST_WRONG_Y]
2507 );
2508 assert_eq!(
2509 fnv1a64(&shown[0].y.iter().map(|&s| s as u8).collect::<Vec<u8>>()),
2510 F0_Y_FNV,
2511 "{NAME}: {FILE} shown frame 0's luma moved -- the 4:2:2 routing changed a frame it \
2512 must not touch"
2513 );
2514 // (c) the required ffmpeg compare: every plane of every shown frame.
2515 if !have_ffmpeg() {
2516 eprintln!(
2517 "SKIP {NAME}: no ffmpeg -- the 4:2:2 pixel compare this gate exists for did NOT \
2518 run (set EC_AV1_REQUIRE_FFMPEG=1 to make this a failure)"
2519 );
2520 return;
2521 }
2522 let ff = ffmpeg_decode_sequence_422(&stream, 128, 128, SHOWN);
2523 assert_eq!(ff.len(), SHOWN, "{NAME}: {FILE} ffmpeg shown-frame count");
2524 for (i, (got, want)) in shown.iter().zip(&ff).enumerate() {
2525 assert_eq!(
2526 got.y, want.y,
2527 "{NAME}: {FILE} shown frame {i} luma vs ffmpeg"
2528 );
2529 assert_eq!(got.u, want.u, "{NAME}: {FILE} shown frame {i} U vs ffmpeg");
2530 assert_eq!(got.v, want.v, "{NAME}: {FILE} shown frame {i} V vs ffmpeg");
2531 }
2532 if aomdec_available(NAME) {
2533 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2534 assert_eq!(
2535 decoded,
2536 SHOWN + 1,
2537 "{NAME}: {FILE} decode-order frame count (6 shown + the hidden alt-ref)"
2538 );
2539 eprintln!(
2540 "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames and vs the \
2541 decode-order oracle over {decoded} frame(s) ({hidden} hidden), \
2542 compound_units={compound} intra_in_inter_units={intra}"
2543 );
2544 } else {
2545 eprintln!(
2546 "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames, \
2547 compound_units={compound} intra_in_inter_units={intra} -- the decode-order \
2548 oracle compare above did NOT run (no aomdec)"
2549 );
2550 }
2551 }
2552
2553 /// lane-av1muchunkluma: the 128x256 twin of the gate above -- the compound
2554 /// hunt's `c4_grad256_comp`. Unlike c3 this stream reaches BOTH `side > 64`
2555 /// mu-chunk walks (16 `intra_in_inter` probe lines, 24 `compound/singleref`
2556 /// ones with `compound=false`, i.e. the single-reference twin), yet
2557 /// lane-av1muchunk422class measured it diverging luma-first (first wrong
2558 /// sample **Y (126, 3) of shown frame 1**, `126 * 128 + 3 = 16131`, ours
2559 /// 94, ffmpeg 93). This lane re-measured it: still diverging on the
2560 /// pre-iis-gather tree, byte-exact on current `main`, so the
2561 /// intra-in-inter gather is what closed it -- its `MU_CHUNK_COMPOUND_UNITS`
2562 /// delta stays 0 (the counter names the compound arm only), which is why
2563 /// the gate's site half asserts the intra-in-inter counter.
2564 ///
2565 /// Recipe: same `aomenc` argv as the 128x128 gate above with the 128x256
2566 /// source (`gradients=size=128x256`, the frozen `grad256.y4m`, sha256
2567 /// `03c7fab7a6abc4e6764836cd2d35e76489438ecdba4ca1167fcd868250c0464c`,
2568 /// which regenerates byte-for-byte).
2569 #[test]
2570 fn a_422_muchunk_iis_128x256_grad256_comp_stream_is_exact_and_reaches_its_unit_walk() {
2571 const NAME: &str =
2572 "a_422_muchunk_iis_128x256_grad256_comp_stream_is_exact_and_reaches_its_unit_walk";
2573 const FILE: &str = "422_muchunk_iis_128x256_grad256.obu";
2574 const LEN: usize = 68925;
2575 const FNV: u64 = 0x65b8_d4dd_3806_7e09;
2576 const MIN_UNITS: usize = 16;
2577 const SHOWN: usize = 6;
2578 const F1_Y_FNV: u64 = 0x75e6_e790_47a8_9882;
2579 const F0_Y_FNV: u64 = 0x1265_8460_c00e_a10f;
2580 // Y (126, 3) of shown frame 1: the first sample that moved. The
2581 // pre-fix square gather read 94 here, ffmpeg 93.
2582 const FIRST_WRONG_Y: usize = 126 * 128 + 3;
2583 const F1_Y_AT_FIRST_WRONG: u16 = 93;
2584 let _gate_lock = lock_gate_counters();
2585 let stream = read_pinned_muchunk_fixture(FILE, LEN, FNV, NAME);
2586 assert_eq!(
2587 obu_stream_shape(&stream),
2588 Some((true, 1, 0, false)),
2589 "{NAME}: {FILE} is not a 4:2:2 (ss 1/0, non-mono) 128x128-superblock stream"
2590 );
2591 let before = (
2592 crate::decode::mu_chunk_compound_units(),
2593 crate::decode::mu_chunk_intra_in_inter_units(),
2594 );
2595 let shown = crate::stream::decode_stream(&stream)
2596 .unwrap_or_else(|e| panic!("{NAME}: {FILE} no longer decodes cleanly: {e}"));
2597 let frames = shown.len();
2598 let (compound, intra) = (
2599 crate::decode::mu_chunk_compound_units() - before.0,
2600 crate::decode::mu_chunk_intra_in_inter_units() - before.1,
2601 );
2602 assert_eq!(frames, SHOWN, "{NAME}: {FILE} shown-frame count");
2603 assert!(
2604 intra >= MIN_UNITS,
2605 "{NAME}: {FILE} allocated only {intra} intra-in-inter `side > 64` mu-chunk units \
2606 (expected >= {MIN_UNITS}) -- the site counter this gate names did not move"
2607 );
2608 assert_eq!(
2609 compound, 0,
2610 "{NAME}: {FILE} moved the compound-named counter ({compound} units) -- the fixture's \
2611 `compound/singleref` hits are its single-reference twin, which must not be counted \
2612 here"
2613 );
2614 assert_eq!(
2615 shown[1].y.len(),
2616 128 * 256,
2617 "{NAME}: {FILE} is no longer 4:2:2 at 128x256 -- the luma plane shape moved"
2618 );
2619 assert_eq!(
2620 fnv1a64(&shown[1].y.iter().map(|&s| s as u8).collect::<Vec<u8>>()),
2621 F1_Y_FNV,
2622 "{NAME}: {FILE} shown frame 1's luma moved -- the intra-in-inter mu-chunk walk's 4:2:2 \
2623 chroma context gather is wrong again (first sample to move is Y (126, 3), index \
2624 {FIRST_WRONG_Y})"
2625 );
2626 assert_eq!(
2627 shown[1].y[FIRST_WRONG_Y], F1_Y_AT_FIRST_WRONG,
2628 "{NAME}: {FILE} shown frame 1 Y[{FIRST_WRONG_Y}] (luma (126, 3)) is {} -- the pre-fix \
2629 square gather read 94 here",
2630 shown[1].y[FIRST_WRONG_Y]
2631 );
2632 assert_eq!(
2633 fnv1a64(&shown[0].y.iter().map(|&s| s as u8).collect::<Vec<u8>>()),
2634 F0_Y_FNV,
2635 "{NAME}: {FILE} shown frame 0's luma moved -- the 4:2:2 routing changed a frame it \
2636 must not touch"
2637 );
2638 if !have_ffmpeg() {
2639 eprintln!(
2640 "SKIP {NAME}: no ffmpeg -- the 4:2:2 pixel compare this gate exists for did NOT \
2641 run (set EC_AV1_REQUIRE_FFMPEG=1 to make this a failure)"
2642 );
2643 return;
2644 }
2645 let ff = ffmpeg_decode_sequence_422(&stream, 128, 256, SHOWN);
2646 assert_eq!(ff.len(), SHOWN, "{NAME}: {FILE} ffmpeg shown-frame count");
2647 for (i, (got, want)) in shown.iter().zip(&ff).enumerate() {
2648 assert_eq!(
2649 got.y, want.y,
2650 "{NAME}: {FILE} shown frame {i} luma vs ffmpeg"
2651 );
2652 assert_eq!(got.u, want.u, "{NAME}: {FILE} shown frame {i} U vs ffmpeg");
2653 assert_eq!(got.v, want.v, "{NAME}: {FILE} shown frame {i} V vs ffmpeg");
2654 }
2655 if aomdec_available(NAME) {
2656 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2657 assert_eq!(
2658 decoded,
2659 SHOWN + 1,
2660 "{NAME}: {FILE} decode-order frame count (6 shown + the hidden alt-ref)"
2661 );
2662 eprintln!(
2663 "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames and vs the \
2664 decode-order oracle over {decoded} frame(s) ({hidden} hidden), \
2665 compound_units={compound} intra_in_inter_units={intra}"
2666 );
2667 } else {
2668 eprintln!(
2669 "{NAME}: {FILE} byte-exact vs ffmpeg over {SHOWN} shown frames, \
2670 compound_units={compound} intra_in_inter_units={intra} -- the decode-order \
2671 oracle compare above did NOT run (no aomdec)"
2672 );
2673 }
2674 }
2675
2676 /// lane-sbpart r2: a real `aomenc` stream whose superblock-level
2677 /// partition decision is genuinely HORZ/VERT (not NONE/SPLIT) must
2678 /// decode pixel-exact through [`crate::decode::decode_block_rect64`] --
2679 /// `sb_rect_hits() > 0` is a HARD assert (this round's rule: a removed
2680 /// refusal needs a firing gate in the same commit, not a green suite
2681 /// that never took the new path). Recipe = the charter's own, verified
2682 /// live by r1: `--min/max-partition-size=32/64` keeps the RD search
2683 /// from ever recursing below 32x32, so every SB-level decision is
2684 /// genuinely NONE/SPLIT/HORZ/VERT; a `gradients` source blended with
2685 /// `testsrc2` (lavfi `blend=all_mode=average`) keeps the content from
2686 /// being flat enough that the search stops at NONE every time.
2687 #[test]
2688 fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact() {
2689 const NAME: &str =
2690 "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact";
2691 let _gate_lock = lock_gate_counters();
2692 if !have_ffmpeg() {
2693 eprintln!("SKIP {NAME}: no ffmpeg");
2694 return;
2695 }
2696 if !have_aomenc() {
2697 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2698 return;
2699 }
2700 let (width, height, frame_count) = (192usize, 128usize, 1usize);
2701 let mut named_refusals = 0u32;
2702 let mut matched = 0u32;
2703 let n_attempts: u32 = std::env::var("EC_SBPART_GATE_ATTEMPTS")
2704 .ok()
2705 .and_then(|s| s.parse().ok())
2706 .unwrap_or(40);
2707 for attempt in 0..n_attempts {
2708 let seed = 42 + attempt;
2709 let duration = frame_count as f64 / 25.0;
2710 let source =
2711 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
2712 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2713 .args([
2714 "-v",
2715 "error",
2716 "-f",
2717 "lavfi",
2718 "-i",
2719 &source,
2720 "-pix_fmt",
2721 "yuv420p",
2722 "-f",
2723 "yuv4mpegpipe",
2724 "-",
2725 ])
2726 .stdin(Stdio::null())
2727 .stdout(Stdio::piped())
2728 .stderr(Stdio::piped()), None, |c| c.output())
2729 .expect("ffmpeg failed to run");
2730 assert!(
2731 y4m.status.success(),
2732 "ffmpeg fixture: {}",
2733 String::from_utf8_lossy(&y4m.stderr)
2734 );
2735 let args: Vec<&str> = vec![
2736 "--codec=av1",
2737 "--passes=1",
2738 "--end-usage=q",
2739 "--cq-level=45",
2740 "--cpu-used=0",
2741 "--threads=1",
2742 "--row-mt=0",
2743 "--sb-size=64",
2744 "--enable-rect-partitions=1",
2745 "--enable-ab-partitions=0",
2746 "--enable-1to4-partitions=0",
2747 "--min-partition-size=32",
2748 "--max-partition-size=64",
2749 "--enable-restoration=0",
2750 "--enable-palette=0",
2751 "--deltaq-mode=0",
2752 "--enable-cdef=0",
2753 "--enable-filter-intra=0",
2754 "--enable-cfl-intra=0",
2755 "--enable-intrabc=0",
2756 "--enable-tx-size-search=0",
2757 "--obu",
2758 "-o",
2759 "-",
2760 "-",
2761 ];
2762 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2763 assert!(
2764 out.status.success(),
2765 "aomenc refused the fixture: {}",
2766 String::from_utf8_lossy(&out.stderr)
2767 );
2768 let stream = out.stdout;
2769 let frames = match decode_stream(&stream) {
2770 Err(e) => {
2771 let msg = e.to_string();
2772 assert!(
2773 msg.contains("unsupported"),
2774 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
2775 );
2776 // r5: the four SB-level AB arms (`partition_w64` 4-7)
2777 // decode since this round, so the only partition refusal
2778 // left at 64x64 is the 1:4 pair (values 8/9, four
2779 // 64x16/16x64 strips, whose luma TX_64X16 this decoder
2780 // has no transform for); the refusals this loop actually
2781 // counts on these fixtures are the pre-existing
2782 // screen-content-palette strip one. Every refusal is
2783 // named, so a genuine decode failure still fails the
2784 // assert above rather than skipping.
2785 named_refusals += 1;
2786 eprintln!("seed {seed} refusal: {msg}");
2787 continue;
2788 }
2789 Ok(frames) => frames,
2790 };
2791 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2792 assert_eq!(frames.len(), frame_count);
2793 let mismatched = frames
2794 .iter()
2795 .zip(&ffmpeg_frames)
2796 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2797 if mismatched
2798 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
2799 std::fs::write(&path, &stream).expect("writing pinned stream");
2800 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
2801 }
2802 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2803 assert_eq!(
2804 got.y, want.y,
2805 "{NAME} frame {i} luma vs ffmpeg (seed {seed})"
2806 );
2807 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
2808 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
2809 }
2810 matched += 1;
2811 }
2812 assert!(
2813 matched > 0,
2814 "{NAME}: every attempt refused; the gate never decoded a stream"
2815 );
2816 assert!(
2817 crate::decode::sb_rect_hits() > 0,
2818 "{NAME}: zero superblock-level HORZ/VERT blocks fired ({matched} matches, \
2819 {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run"
2820 );
2821 eprintln!(
2822 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
2823 {n_attempts}, sb_rect_hits={}",
2824 crate::decode::sb_rect_hits()
2825 );
2826 }
2827
2828 /// lane-golomb r2 gate: a 32x32-level block that STRADDLES the frame edge
2829 /// and whose partition is the gathered edge bit's `PARTITION_HORZ` (bottom
2830 /// edge) / `PARTITION_VERT` (right edge). Since r1 that bit can name
2831 /// HORZ/VERT instead of always inferring SPLIT, so the second 32x16/16x32
2832 /// half is out of frame and must NOT be decoded (libaom `decode_partition`:
2833 /// `case PARTITION_HORZ: decode_block(top); if (has_rows) decode_block(bottom)`).
2834 /// The AB and 1:4 arms need no such guard: at an edge libaom's
2835 /// `ec_read_partition_impl` can only yield HORZ/VERT/SPLIT, so those arms
2836 /// are unreachable there.
2837 ///
2838 /// Geometry: 192x80 (mi_rows=20 -- the second SB row is 16 px tall, so its
2839 /// 32-level blocks at y=64 have `has_rows32 == false`) and 80x192 for the
2840 /// right edge. Natural content (`testsrc2`); `smptebars`-style screen
2841 /// content trips the palette/screen-content refusal before the edge is
2842 /// reached. cq sweep, 8-bit and 10-bit, plus a 5-frame inter arm.
2843 /// Counters are sampled per attempt and summed only over attempts that
2844 /// decoded AND pixel-compared (class `counter-from-refused-stream`).
2845 #[test]
2846 fn a_real_aomenc_stream_with_a_32x32_frame_edge_rect_partition_decodes_pixel_exact() {
2847 edge32_gate(
2848 "a_real_aomenc_stream_with_a_32x32_frame_edge_rect_partition_decodes_pixel_exact",
2849 false,
2850 );
2851 }
2852
2853 /// lane-golomb r2 OPEN DEFECT, pinned as a runnable test: with the 16-px
2854 /// straddling band left FLAT the encoder answers the 32-level edge bit
2855 /// with HORZ (`edge32=[2, 0, 2, 0]` on 192x80 cq40 8-bit), the guard added
2856 /// this round keeps the stream in entropy sync -- every pixel outside the
2857 /// two edge strips matches ffmpeg -- but the strips themselves
2858 /// reconstruct wrong: `plane Y: 1081 pixels differ, first at row 62 col
2859 /// 128`, diffs confined to rows 62..79 over ~64 columns (exactly the two
2860 /// 32x16 strips plus the deblock bleed above them). That is a
2861 /// reconstruction defect inside the strip (prediction/availability), not
2862 /// the partition guard. Un-ignored 2026-09-04: that reconstruction defect is gone and the two edge strips decode exactly.
2863 #[test]
2864 fn a_32x32_frame_edge_rect_partition_with_a_flat_band_decodes_pixel_exact() {
2865 edge32_gate(
2866 "a_32x32_frame_edge_rect_partition_with_a_flat_band_decodes_pixel_exact",
2867 true,
2868 );
2869 }
2870
2871 /// lane-golomb r9 OPEN DEFECT, pinned as a runnable test: a frame whose
2872 /// height (192x68) or width (68x192) is not a multiple of 8 leaves a 4-px
2873 /// straddling band inside the mi-rounded plane, and every INTER frame's
2874 /// output is +-1 wrong across that band and the columns/rows next to it
2875 /// (`68x192 cq35 8-bit: frame 1 plane Y: 145 pixels differ, first at row 0
2876 /// col 64`, mass in columns 64..67). r9 bisected it stage by stage against
2877 /// the instrumented aomdec on that exact stream:
2878 /// * `EC_AV1_PREFILT_DUMP` frame 1 is BYTE-IDENTICAL over the cropped
2879 /// 68 columns -- reconstruction and inter prediction are exact, so the
2880 /// charter's "MC reads past the crop" hypothesis is refuted a second time.
2881 /// * `EC_AV1_POSTDEBLOCK_DUMP` with `EC_AV1_DEBUG_SKIP_CDEF=1` also matches
2882 /// aomdec's own post-deblock dump (which is 72 columns wide, i.e. it
2883 /// exposes the straddling band) -- the deblock, including its
2884 /// `frame_width` clip, is correct.
2885 /// * The divergence therefore enters in CDEF, at the last 8x8 CDEF block
2886 /// column/row, which is the one that straddles the crop edge.
2887 /// lane-cdef r2: CLOSED, and un-ignored. r1 rooted the luma half in
2888 /// `apply_cdef`'s direction search, which clamped at the CROPPED frame
2889 /// edge while libaom runs `cdef_find_dir` over `cdef_prepare_fb`'s buffer
2890 /// -- whose columns/rows past the MI-ROUNDED extent (`hsize = nhb <<
2891 /// mi_wide_l2`, `cdef.c:164-167`, and the `frame_boundary[RIGHT]`
2892 /// CDEF_VERY_LARGE fill at `cdef.c:249-256`) are CDEF_VERY_LARGE, not the
2893 /// last real sample. The chroma half was lane-golomb r8's loop-restoration
2894 /// plane size (LR is the one post-decode filter sized by the CROP, not the
2895 /// mi grid) plus its reference-size fix; merging both branches takes all
2896 /// four arms to 0 differing pixels on Y, U and V.
2897 ///
2898 /// Arms: 192x68 and 68x192 (a 4-px straddling band on one axis), 5 frames,
2899 /// 8-bit and 10-bit, plus a `--tile-columns=1` twin of each (COMMON's
2900 /// neighbour-map rule -- the skip band CDEF reads is a per-mi side band).
2901 /// RE-MEASURED lane-t900 r15 on the merged tip: all 64 attempts (8 arms x
2902 /// 8 cq levels, single- and multi-tile alike) decode pixel-exact with ZERO
2903 /// named refusals -- on 2026-09-02 all 32 multi-tile attempts still refused
2904 /// by name, so that half compared nothing (class
2905 /// `counter-from-refused-stream`). `compared_multi_tile` is asserted below
2906 /// so the multi-tile twins can never silently go back to comparing
2907 /// nothing.
2908 /// Hard-asserts `decode::cdef_straddle_units()` grew: a FILTERED 8x8 CDEF
2909 /// unit whose extent crosses the crop edge is the only shape for which
2910 /// clamping and padding differ, so a zero delta would make these arms
2911 /// vacuous for this defect.
2912 #[test]
2913 fn a_frame_edge_straddling_band_decodes_pixel_exact() {
2914 edge32_gate("a_frame_edge_straddling_band_decodes_pixel_exact", false);
2915 }
2916
2917 /// lane-sqchroma r1 gate: a plain SQUARE-partition intra key frame with
2918 /// REAL chroma (no `hue=s=0` guard) and aomenc's tx-size search left at
2919 /// its own DEFAULT (on) -- the combination the user's films hit
2920 /// everywhere and that no gate in this file covered: every older recipe
2921 /// pins `--enable-tx-size-search=0`, and the one that does not
2922 /// (`a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact`)
2923 /// desaturates its fixture. With the search on, RD gives a square block a
2924 /// luma transform smaller than its own side while chroma keeps the
2925 /// block's single `side/2` transform and its own `uv_mode`-derived
2926 /// `tx_type` -- the pair [`crate::decode::sq_chroma_tx_hits`] counts and
2927 /// this gate hard-asserts, so a stream whose split-transform blocks all
2928 /// landed on `DC_PRED` chroma cannot pass for free.
2929 ///
2930 /// Sweeps seeds 8-bit and finishes with one 10-bit stream of the same
2931 /// recipe (his films are `yuv420p10le`), whose sequence header's
2932 /// `bit_depth` is asserted before any pixel is compared. Only a missing
2933 /// tool SKIPs: a decode error that is not a named refusal, and every
2934 /// pixel mismatch, FAIL.
2935 #[test]
2936 fn a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact() {
2937 const NAME: &str =
2938 "a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact";
2939 let _gate_lock = lock_gate_counters();
2940 if !have_ffmpeg() {
2941 eprintln!("SKIP {NAME}: no ffmpeg");
2942 return;
2943 }
2944 if !have_aomenc() {
2945 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2946 return;
2947 }
2948 let (width, height) = (192usize, 128usize);
2949 // NOTE: no `--enable-tx-size-search=0` (the point of this gate), and
2950 // no chroma filter on the fixture (the other point). Square
2951 // partitions only: rect/AB/1to4 all off.
2952 let base_args: Vec<&str> = vec![
2953 "--codec=av1",
2954 "--passes=1",
2955 "--end-usage=q",
2956 "--cpu-used=0",
2957 "--threads=1",
2958 "--row-mt=0",
2959 "--sb-size=64",
2960 "--enable-rect-partitions=0",
2961 "--enable-ab-partitions=0",
2962 "--enable-1to4-partitions=0",
2963 "--min-partition-size=16",
2964 "--max-partition-size=32",
2965 "--enable-restoration=0",
2966 "--enable-palette=0",
2967 "--deltaq-mode=0",
2968 "--enable-intrabc=0",
2969 "--limit=1",
2970 ];
2971 let encode = |y4m: &[u8], extra: &[&str]| -> Vec<u8> {
2972 let mut args = base_args.clone();
2973 args.extend_from_slice(extra);
2974 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
2975 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m);
2976 assert!(
2977 out.status.success(),
2978 "aomenc refused the fixture: {}",
2979 String::from_utf8_lossy(&out.stderr)
2980 );
2981 assert!(
2982 !out.stdout.is_empty(),
2983 "{NAME}: aomenc wrote an empty stream"
2984 );
2985 out.stdout
2986 };
2987 let render = |source: &str, pix_fmt: &str| -> Vec<u8> {
2988 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2989 .args([
2990 "-v",
2991 "error",
2992 "-f",
2993 "lavfi",
2994 "-i",
2995 source,
2996 "-t",
2997 "0.04",
2998 "-pix_fmt",
2999 pix_fmt,
3000 "-strict",
3001 "-1",
3002 "-f",
3003 "yuv4mpegpipe",
3004 "-",
3005 ])
3006 .stdin(Stdio::null())
3007 .stdout(Stdio::piped())
3008 .stderr(Stdio::piped()), None, |c| c.output())
3009 .expect("ffmpeg failed to run");
3010 assert!(
3011 y4m.status.success(),
3012 "ffmpeg fixture: {}",
3013 String::from_utf8_lossy(&y4m.stderr)
3014 );
3015 y4m.stdout
3016 };
3017 let mut named_refusals = 0u32;
3018 let mut matched = 0u32;
3019 // Hits counted ONLY over attempts that decoded AND pixel-compared:
3020 // a stream that later refuses must not lend its firings to the
3021 // assertion below (class refusal-hides-a-defect).
3022 let mut firing = 0usize;
3023 let n_attempts: u32 = std::env::var("EC_SQCHROMA_GATE_ATTEMPTS")
3024 .ok()
3025 .and_then(|s| s.parse().ok())
3026 .unwrap_or(10);
3027 for attempt in 0..n_attempts {
3028 let seed = 42 + attempt;
3029 // Two quantisers per seed: the coarse one keeps most blocks on
3030 // one transform, the fine one is what actually splits them.
3031 let cq = if attempt % 2 == 0 {
3032 "--cq-level=20"
3033 } else {
3034 "--cq-level=40"
3035 };
3036 let y4m = render(
3037 &gradients_source(seed, width, height, "duration=0.04:rate=25"),
3038 "yuv420p",
3039 );
3040 let stream = encode(&y4m, &[cq]);
3041 let before = crate::decode::sq_chroma_tx_hits();
3042 let frames = match decode_stream(&stream) {
3043 Err(e) => {
3044 let msg = e.to_string();
3045 assert!(
3046 msg.contains("unsupported"),
3047 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
3048 );
3049 named_refusals += 1;
3050 continue;
3051 }
3052 Ok(frames) => frames,
3053 };
3054 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3055 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
3056 assert_eq!(
3057 frames[0].y, ffmpeg_frames[0].y,
3058 "{NAME} luma vs ffmpeg (seed {seed})"
3059 );
3060 assert_eq!(
3061 frames[0].u, ffmpeg_frames[0].u,
3062 "{NAME} U vs ffmpeg (seed {seed})"
3063 );
3064 assert_eq!(
3065 frames[0].v, ffmpeg_frames[0].v,
3066 "{NAME} V vs ffmpeg (seed {seed})"
3067 );
3068 firing += crate::decode::sq_chroma_tx_hits() - before;
3069 matched += 1;
3070 }
3071 // Same recipe, 10-bit: his two films are both yuv420p10le, so the
3072 // square+tx-search+chroma claim is only worth anything if it holds
3073 // at their bit depth too.
3074 let y4m10 = render(
3075 &gradients_source(42, width, height, "duration=0.04:rate=25"),
3076 "yuv420p10le",
3077 );
3078 let stream10 = encode(
3079 &y4m10,
3080 &["--cq-level=20", "--input-bit-depth=10", "--bit-depth=10"],
3081 );
3082 let mut probe = Av1Parser::new();
3083 let mut pos = 0usize;
3084 while pos < stream10.len() && probe.sequence_header().is_none() {
3085 let obu = probe.parse_obu(&stream10[pos..]).unwrap();
3086 pos += obu.total_size;
3087 }
3088 assert_eq!(
3089 probe
3090 .sequence_header()
3091 .expect("stream has a sequence header OBU")
3092 .color_config
3093 .bit_depth,
3094 10,
3095 "{NAME}: aomenc did not actually write a 10-bit sequence header"
3096 );
3097 let before10 = crate::decode::sq_chroma_tx_hits();
3098 let frames10 = match decode_stream(&stream10) {
3099 Ok(frames) => frames,
3100 Err(e) => panic!("{NAME}: decode_stream refused the 10-bit stream: {e}"),
3101 };
3102 let ffmpeg10 = ffmpeg_decode_sequence_10bit(&stream10, width, height, 1);
3103 assert_eq!(
3104 frames10[0].y, ffmpeg10[0].y,
3105 "{NAME} luma vs ffmpeg (10-bit)"
3106 );
3107 assert_eq!(frames10[0].u, ffmpeg10[0].u, "{NAME} U vs ffmpeg (10-bit)");
3108 assert_eq!(frames10[0].v, ffmpeg10[0].v, "{NAME} V vs ffmpeg (10-bit)");
3109 let firing10 = crate::decode::sq_chroma_tx_hits() - before10;
3110 firing += firing10;
3111 matched += 1;
3112 assert!(
3113 matched > 1,
3114 "{NAME}: every 8-bit attempt refused; the gate decoded only the 10-bit stream"
3115 );
3116 assert!(
3117 firing > 0,
3118 "{NAME}: zero square blocks split their luma transform under a non-DC chroma mode \
3119 ({matched} matches, {named_refusals} refusals) -- gate proved nothing this run"
3120 );
3121 eprintln!(
3122 "{NAME}: {matched} pixel-exact decodes ({named_refusals} named refusals out of \
3123 {n_attempts} 8-bit attempts), split-tx-with-chroma blocks: {firing} \
3124 (10-bit stream: {firing10})"
3125 );
3126 }
3127
3128 /// lane-rectsplit r1 gate (a): a real `aomenc` key frame whose 32x32
3129 /// quadrants split HORZ/VERT into true 32x16/16x32 strips, with the
3130 /// tx-size search left at aomenc's own default (ON) -- every sibling
3131 /// recipe in this file pins `--enable-tx-size-search=0`, which is exactly
3132 /// why the split-transform strip was never exercised. RD is then free to
3133 /// give a strip a transform smaller than its own size, the case
3134 /// [`crate::decode::decode_block_rect`] refused by name ("a HORZ/VERT
3135 /// intra strip with a split transform (per-unit rect prediction is not
3136 /// ported)") until this round ported the per-transform-unit predict-and-
3137 /// reconstruct loop. Hard-asserts a nonzero `rect_split_tx_hits()` delta:
3138 /// without it a stream that resolved every `tx_depth` to 0 would
3139 /// pixel-match by construction and prove nothing. A decode error that is
3140 /// not a named refusal, and any pixel mismatch, FAIL -- only a missing
3141 /// tool skips.
3142 #[test]
3143 fn a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact() {
3144 const NAME: &str =
3145 "a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact";
3146 let _gate_lock = lock_gate_counters();
3147 if !have_ffmpeg() {
3148 eprintln!("SKIP {NAME}: no ffmpeg");
3149 return;
3150 }
3151 if !have_aomenc() {
3152 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3153 return;
3154 }
3155 let (width, height) = (192usize, 128usize);
3156 let before = crate::decode::rect_split_tx_hits();
3157 let mut named_refusals = 0u32;
3158 let mut matched = 0u32;
3159 // lane-rectsplit r2 (verifier finding): the feature counter is
3160 // sampled PER ATTEMPT and folded in only after that attempt was
3161 // decoded AND pixel-compared. One delta across the whole sweep
3162 // counted strips decoded by attempts that went on to hit a named
3163 // refusal, so the gate could pass with every COMPARED stream
3164 // containing none of the feature at all.
3165 let mut compared_hits = 0usize;
3166 let mut split_so_far = 0usize;
3167 // Bounded sweep: see this gate's own doc for the seed-77 residue and
3168 // why extending it is a diagnosis knob, not a pass/fail one.
3169 let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
3170 .ok()
3171 .and_then(|s| s.parse().ok())
3172 .unwrap_or(20);
3173 for attempt in 0..n_attempts {
3174 let seed = 42 + attempt;
3175 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
3176 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3177 .args([
3178 "-v",
3179 "error",
3180 "-f",
3181 "lavfi",
3182 "-i",
3183 &source,
3184 // REAL chroma (lane-sqchroma r1 dropped the `hue=s=0`
3185 // guard this recipe carried): the "PRE-EXISTING square-path
3186 // chroma defect" that guard named does not reproduce at
3187 // HEAD -- seeds 42..61, cq 12/20/32/45, plus testsrc2 and
3188 // mandelbrot, all decode pixel-exact with
3189 // `--enable-rect-partitions=0`, and this gate is green with
3190 // the filter gone. Its own gate is
3191 // `a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact`.
3192 "-pix_fmt",
3193 "yuv420p",
3194 "-f",
3195 "yuv4mpegpipe",
3196 "-",
3197 ])
3198 .stdin(Stdio::null())
3199 .stdout(Stdio::piped())
3200 .stderr(Stdio::piped()), None, |c| c.output())
3201 .expect("ffmpeg failed to run");
3202 assert!(
3203 y4m.status.success(),
3204 "ffmpeg fixture: {}",
3205 String::from_utf8_lossy(&y4m.stderr)
3206 );
3207 // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's
3208 // own default (search ON) is the entire point of this gate.
3209 let args: Vec<&str> = vec![
3210 "--codec=av1",
3211 "--passes=1",
3212 "--end-usage=q",
3213 "--cq-level=45",
3214 "--cpu-used=0",
3215 "--threads=1",
3216 "--row-mt=0",
3217 "--sb-size=64",
3218 "--enable-rect-partitions=1",
3219 "--enable-ab-partitions=0",
3220 "--enable-1to4-partitions=0",
3221 "--min-partition-size=16",
3222 "--max-partition-size=32",
3223 "--enable-restoration=0",
3224 "--enable-palette=0",
3225 "--deltaq-mode=0",
3226 "--enable-cdef=0",
3227 "--enable-filter-intra=0",
3228 "--enable-cfl-intra=0",
3229 "--enable-intrabc=0",
3230 "--obu",
3231 "-o",
3232 "-",
3233 "-",
3234 ];
3235 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3236 assert!(
3237 out.status.success(),
3238 "aomenc refused the fixture: {}",
3239 String::from_utf8_lossy(&out.stderr)
3240 );
3241 let stream = out.stdout;
3242 assert!(
3243 !stream.is_empty(),
3244 "{NAME}: aomenc wrote an empty stream (seed {seed})"
3245 );
3246 let attempt_before = crate::decode::rect_split_tx_hits();
3247 let frames = match decode_stream(&stream) {
3248 Err(e) => {
3249 let msg = e.to_string();
3250 assert!(
3251 msg.contains("unsupported"),
3252 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
3253 );
3254 named_refusals += 1;
3255 continue;
3256 }
3257 Ok(frames) => frames,
3258 };
3259 let after = crate::decode::rect_split_tx_hits();
3260 eprintln!(
3261 "{NAME}: seed {seed} decoded, split-tx strips this stream: {}",
3262 after - before - split_so_far
3263 );
3264 split_so_far = after - before;
3265 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3266 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
3267 if let Some(i) = frames[0]
3268 .y
3269 .iter()
3270 .zip(&ffmpeg_frames[0].y)
3271 .position(|(a, b)| a != b)
3272 {
3273 let diffs: Vec<usize> = frames[0]
3274 .y
3275 .iter()
3276 .zip(&ffmpeg_frames[0].y)
3277 .enumerate()
3278 .filter(|(_, (a, b))| a != b)
3279 .map(|(j, _)| j)
3280 .collect();
3281 let (x0, x1) = (
3282 diffs.iter().map(|j| j % width).min().unwrap(),
3283 diffs.iter().map(|j| j % width).max().unwrap(),
3284 );
3285 let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width);
3286 eprintln!(
3287 "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \
3288 -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}",
3289 i % width,
3290 i / width,
3291 frames[0].y[i],
3292 ffmpeg_frames[0].y[i],
3293 diffs.len(),
3294 );
3295 }
3296 assert_eq!(
3297 frames[0].y, ffmpeg_frames[0].y,
3298 "{NAME}: luma vs ffmpeg (seed {seed})"
3299 );
3300 assert_eq!(
3301 frames[0].u, ffmpeg_frames[0].u,
3302 "{NAME}: U vs ffmpeg (seed {seed})"
3303 );
3304 assert_eq!(
3305 frames[0].v, ffmpeg_frames[0].v,
3306 "{NAME}: V vs ffmpeg (seed {seed})"
3307 );
3308 compared_hits += crate::decode::rect_split_tx_hits() - attempt_before;
3309 matched += 1;
3310 }
3311 let split_hits = compared_hits;
3312 assert!(
3313 matched > 0,
3314 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
3315 );
3316 assert!(
3317 split_hits > 0,
3318 "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \
3319 matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \
3320 this run"
3321 );
3322 eprintln!(
3323 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
3324 rect_split_tx_hits delta={split_hits} out of {n_attempts} attempts"
3325 );
3326 }
3327
3328 /// lane-rect1d r1 (copied from lane-rectclass r1): the class-correctness measurement for every
3329 /// RECTANGULAR transform unit this decoder reads. [`crate::decode::read_coeffs_rect`]
3330 /// handles `TxClass::TwoD` only -- it refuses by name both a coded
3331 /// `tx_type` symbol and a non-2D default -- so the open question a
3332 /// verifier raised was whether a real encoder ever puts a
3333 /// `V_DCT`/`H_DCT` (`TX_CLASS_HORIZ`/`VERT`) type on a rect TU that
3334 /// reaches this reader. The recipe deliberately maximises the chance:
3335 /// `--enable-flip-idtx=1` (the flip/identity/1D types are exactly what
3336 /// `EXT_TX_SET_DTT4_IDTX_1DDCT` and the wider inter sets add),
3337 /// `--enable-tx-size-search=1`, rect partitions on, small minimum
3338 /// partition size, both bit depths. Every successful decode is
3339 /// pixel-compared; the rect-TU counter is folded in PER ATTEMPT and only
3340 /// after that attempt compared (class `counter-from-refused-stream`), and
3341 /// the class-1 refusal counter is summed over EVERY attempt including the
3342 /// refused ones -- a refused attempt is exactly where a 1D class on a
3343 /// rect TU would show up.
3344 ///
3345 /// lane-rect1d: on THIS tree `read_coeffs_rect` no longer refuses a 1D
3346 /// class -- lane-tx4x8 gave it the mrow/mcol scan and the class-aware
3347 /// base/br contexts -- so the live pins are `compared_class1 > 0` (the
3348 /// flag arrived and 1D types were coded) plus the pixel compare itself.
3349 #[test]
3350 fn a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact() {
3351 const NAME: &str =
3352 "a_real_aomenc_stream_with_a_1d_tx_class_on_a_rect_transform_decodes_pixel_exact";
3353 let _gate_lock = lock_gate_counters();
3354 if !have_ffmpeg() {
3355 eprintln!("SKIP {NAME}: no ffmpeg");
3356 return;
3357 }
3358 if !have_aomenc() {
3359 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3360 return;
3361 }
3362 let (width, height) = (192usize, 128usize);
3363 let mut named_refusals = 0u32;
3364 let mut matched = 0u32;
3365 let mut matched_10bit = 0u32;
3366 let mut compared_rect_tus = 0usize;
3367 let mut compared_rect_parts = 0usize;
3368 let mut compared_tx_depths = 0usize;
3369 let mut compared_class1 = 0usize;
3370 let mut compared_rect_class1 = 0usize;
3371 let n_attempts: u32 = std::env::var("EC_RECTCLASS_GATE_ATTEMPTS")
3372 .ok()
3373 .and_then(|s| s.parse().ok())
3374 .unwrap_or(12);
3375 // Both bit depths in one sweep: his two films are yuv420p10le, and a
3376 // class claim that only holds at 8 bits is worth nothing to them.
3377 for attempt in 0..n_attempts {
3378 let seed = 42 + attempt / 2;
3379 let ten_bit = attempt % 2 == 1;
3380 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
3381 // Content + quantiser sweep: the 1D (`V_DCT`/`H_DCT`) types RD can
3382 // only pick on strongly one-directional detail, and only when the
3383 // quantiser leaves that detail in the residual -- smooth gradients
3384 // at cq 45 produced exactly zero of them (measured this round),
3385 // which would have made the `--enable-flip-idtx=1` arrival assert
3386 // fail rather than the gate pass vacuously.
3387 let period = [4u32, 6, 8, 12, 16][(attempt as usize / 2) % 5];
3388 let source = format!("testsrc2=size={width}x{height}:rate=25");
3389 let filter = format!(
3390 "geq=lum='128+80*sin(2*PI*Y/{period})':cb='128+60*sin(2*PI*X/{period})':cr=128,\
3391 noise=alls=6:allf=t"
3392 );
3393 let cq = if attempt % 4 < 2 {
3394 "--cq-level=20"
3395 } else {
3396 "--cq-level=40"
3397 };
3398 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3399 .args([
3400 // `-strict -1`: y4m calls 10-bit an unofficial pixel
3401 // format and refuses to write the header otherwise (no-op
3402 // at 8 bit).
3403 "-v",
3404 "error",
3405 "-f",
3406 "lavfi",
3407 "-i",
3408 &source,
3409 "-vf",
3410 &filter,
3411 "-t",
3412 "0.04",
3413 "-pix_fmt",
3414 pix_fmt,
3415 "-strict",
3416 "-1",
3417 "-f",
3418 "yuv4mpegpipe",
3419 "-",
3420 ])
3421 .stdin(Stdio::null())
3422 .stdout(Stdio::piped())
3423 .stderr(Stdio::piped()), None, |c| c.output())
3424 .expect("ffmpeg failed to run");
3425 assert!(
3426 y4m.status.success(),
3427 "ffmpeg fixture: {}",
3428 String::from_utf8_lossy(&y4m.stderr)
3429 );
3430 // aomenc keeps the LAST occurrence of a repeated `--enable-*`
3431 // flag (measured 2026-09-02 by md5 of four orderings), so this
3432 // lane's overrides come AFTER the base recipe. They are also
3433 // proven to have ARRIVED rather than assumed: the asserts below
3434 // pin a nonzero rect-partition, tx-depth and 1D-tx-class counter
3435 // on pixel-compared attempts, one per override.
3436 let mut args: Vec<&str> = vec![
3437 "--codec=av1",
3438 "--passes=1",
3439 "--end-usage=q",
3440 cq,
3441 "--cpu-used=0",
3442 "--threads=1",
3443 "--row-mt=0",
3444 "--sb-size=64",
3445 "--enable-ab-partitions=0",
3446 "--enable-1to4-partitions=0",
3447 "--enable-restoration=0",
3448 "--enable-palette=0",
3449 "--deltaq-mode=0",
3450 "--enable-cdef=0",
3451 "--enable-filter-intra=0",
3452 "--enable-cfl-intra=0",
3453 "--enable-intrabc=0",
3454 ];
3455 if ten_bit {
3456 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
3457 }
3458 args.extend_from_slice(&[
3459 "--enable-rect-partitions=1",
3460 "--enable-tx-size-search=1",
3461 "--enable-flip-idtx=1",
3462 // Without this aomenc's reduced tx set narrows every block to
3463 // DCT_DCT/IDTX and no 1D type can be coded at all -- the flag
3464 // that actually gates the class, as the arrival assert below
3465 // proved by staying at 0 without it.
3466 "--reduced-tx-type-set=0",
3467 "--min-partition-size=8",
3468 "--max-partition-size=32",
3469 "--obu",
3470 "-o",
3471 "-",
3472 "-",
3473 ]);
3474 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3475 assert!(
3476 out.status.success(),
3477 "aomenc refused the fixture: {}",
3478 String::from_utf8_lossy(&out.stderr)
3479 );
3480 let stream = out.stdout;
3481 assert!(
3482 !stream.is_empty(),
3483 "{NAME}: aomenc wrote an empty stream (seed {seed})"
3484 );
3485 if ten_bit {
3486 let mut probe = Av1Parser::new();
3487 let mut pos = 0usize;
3488 while pos < stream.len() && probe.sequence_header().is_none() {
3489 let obu = probe.parse_obu(&stream[pos..]).unwrap();
3490 pos += obu.total_size;
3491 }
3492 assert_eq!(
3493 probe
3494 .sequence_header()
3495 .expect("stream has a sequence header OBU")
3496 .color_config
3497 .bit_depth,
3498 10,
3499 "{NAME}: aomenc did not actually write a 10-bit sequence header"
3500 );
3501 }
3502 let attempt_before = crate::decode::rect_coeff_tu_hits();
3503 let rect_before = crate::decode::rect_partition_hits();
3504 let depth_before = crate::decode::tx_depth_hits();
3505 let class1_before = crate::decode::tx_class1_hits();
3506 let rect_class1_before = crate::decode::rect_class1_hits();
3507 let frames = match decode_stream(&stream) {
3508 Err(e) => {
3509 let msg = e.to_string();
3510 assert!(
3511 msg.contains("unsupported"),
3512 "{NAME} failed outright, not a named refusal (seed {seed}, 10bit \
3513 {ten_bit}): {msg}"
3514 );
3515 named_refusals += 1;
3516 continue;
3517 }
3518 Ok(frames) => frames,
3519 };
3520 let ffmpeg_frames = if ten_bit {
3521 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
3522 } else {
3523 ffmpeg_decode_sequence(&stream, width, height, 1)
3524 };
3525 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
3526 assert_eq!(
3527 frames[0].y, ffmpeg_frames[0].y,
3528 "{NAME}: luma vs ffmpeg (seed {seed}, 10bit {ten_bit})"
3529 );
3530 assert_eq!(
3531 frames[0].u, ffmpeg_frames[0].u,
3532 "{NAME}: U vs ffmpeg (seed {seed}, 10bit {ten_bit})"
3533 );
3534 assert_eq!(
3535 frames[0].v, ffmpeg_frames[0].v,
3536 "{NAME}: V vs ffmpeg (seed {seed}, 10bit {ten_bit})"
3537 );
3538 compared_rect_tus += crate::decode::rect_coeff_tu_hits() - attempt_before;
3539 compared_rect_parts += crate::decode::rect_partition_hits() - rect_before;
3540 compared_tx_depths += crate::decode::tx_depth_hits() - depth_before;
3541 compared_class1 += crate::decode::tx_class1_hits() - class1_before;
3542 compared_rect_class1 += crate::decode::rect_class1_hits() - rect_class1_before;
3543 matched += 1;
3544 matched_10bit += u32::from(ten_bit);
3545 }
3546 assert!(
3547 matched > 0,
3548 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded \
3549 nothing"
3550 );
3551 assert!(
3552 matched_10bit > 0,
3553 "{NAME}: every 10-bit attempt refused -- his films are yuv420p10le, so a gate that \
3554 only compared 8-bit streams proves nothing for them"
3555 );
3556 assert!(
3557 compared_rect_tus > 0,
3558 "{NAME}: no pixel-exact attempt coded a single rectangular transform unit \
3559 ({matched} matches, {named_refusals} refusals out of {n_attempts}) -- the gate \
3560 measured nothing about rect coefficient reading"
3561 );
3562 // FLAG ARRIVAL, one assert per override (a flag whose counter stays
3563 // at 0 is an inert flag, not a passing gate).
3564 assert!(
3565 compared_rect_parts > 0,
3566 "{NAME}: --enable-rect-partitions=1 never produced a rect partition on a compared \
3567 attempt ({matched} matches) -- the flag did not arrive"
3568 );
3569 assert!(
3570 compared_tx_depths > 0,
3571 "{NAME}: --enable-tx-size-search=1 never produced a nonzero tx depth on a compared \
3572 attempt ({matched} matches) -- the flag did not arrive"
3573 );
3574 assert!(
3575 compared_class1 > 0,
3576 "{NAME}: --enable-flip-idtx=1 never produced a V_DCT/H_DCT transform on a compared \
3577 attempt ({matched} matches) -- the 1D types live only in the extended ext-tx sets \
3578 this flag enables, so the flag did not arrive"
3579 );
3580 // lane-rect1d r1: the pin of the LANE's own capability -- a V_DCT/H_DCT
3581 // transform on a RECTANGULAR transform unit, read through
3582 // `read_coeffs_rect`'s own 1D scan and contexts. `compared_class1`
3583 // above counts square TUs too, so it can be nonzero while this path
3584 // never fires.
3585 assert!(
3586 compared_rect_class1 > 0,
3587 "{NAME}: no pixel-exact attempt put a 1D tx class on a RECTANGULAR transform \
3588 ({compared_class1} 1D transforms overall, {compared_rect_tus} rect coefficient \
3589 TUs) -- the gate proves nothing about the rect 1D path"
3590 );
3591 eprintln!(
3592 "{NAME}: {matched} pixel-exact decodes ({named_refusals} named refusals out of \
3593 {n_attempts} attempts, {matched_10bit} of the matches 10-bit), rect coefficient \
3594 TUs on compared attempts: {compared_rect_tus} ({compared_rect_class1} of them a \
3595 1D tx class); flag arrival: rect partitions {compared_rect_parts}, tx \
3596 depths {compared_tx_depths}, 1D-class (square) transforms {compared_class1}"
3597 );
3598 }
3599
3600 /// lane-rectsplit r1 gate (c): gate (a)'s recipe with
3601 /// `--enable-filter-intra=1` (every sibling gate here pins it to 0), so
3602 /// aomenc's RD is free to pick `use_filter_intra` on a 32x16/16x32 strip
3603 /// -- the case [`crate::decode::decode_block_rect`] refused by name
3604 /// ("filter intra on a HORZ/VERT strip (this decoder predicts
3605 /// square-only)") until this round gave `predict_filter_intra` its own
3606 /// `bw`x`bh`. Hard-asserts a nonzero `filter_intra_rect_hits()` delta:
3607 /// a stream where RD never picked filter intra on a strip would
3608 /// pixel-match by construction and prove nothing.
3609 #[test]
3610 fn a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact() {
3611 const NAME: &str =
3612 "a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact";
3613 let _gate_lock = lock_gate_counters();
3614 if !have_ffmpeg() {
3615 eprintln!("SKIP {NAME}: no ffmpeg");
3616 return;
3617 }
3618 if !have_aomenc() {
3619 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3620 return;
3621 }
3622 let (width, height) = (192usize, 128usize);
3623 let rect_before = crate::decode::rect_partition_hits();
3624 let fi_square_before = crate::decode::filter_intra_hits();
3625 let mut named_refusals = 0u32;
3626 let mut matched = 0u32;
3627 // lane-rectsplit r2 (verifier finding): the feature counter is
3628 // sampled PER ATTEMPT and folded in only after that attempt was
3629 // decoded AND pixel-compared. One delta across the whole sweep
3630 // counted strips decoded by attempts that went on to hit a named
3631 // refusal, so the gate could pass with every COMPARED stream
3632 // containing none of the feature at all.
3633 let mut compared_hits = 0usize;
3634 let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
3635 .ok()
3636 .and_then(|s| s.parse().ok())
3637 .unwrap_or(40);
3638 for attempt in 0..n_attempts {
3639 let seed = 42 + attempt;
3640 // Diagnosis knob: which content makes RD pick a HORZ/VERT strip
3641 // AND filter intra on it is a search (see this round's report).
3642 let source = match std::env::var("EC_RECTSPLIT_SRC")
3643 .unwrap_or_default()
3644 .as_str()
3645 {
3646 "bars" => format!("smptebars=size={width}x{height}:duration=0.04:rate=25"),
3647 "src2" => format!("testsrc2=size={width}x{height}:duration=0.04:rate=25"),
3648 _ => gradients_source(seed, width, height, "duration=0.04:rate=25"),
3649 };
3650 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3651 .args([
3652 "-v",
3653 "error",
3654 "-f",
3655 "lavfi",
3656 "-i",
3657 &source,
3658 // Real chroma: the `hue=s=0` guard gate (a) carried is
3659 // gone (lane-sqchroma r1 -- the square-path chroma defect
3660 // it named does not reproduce at HEAD).
3661 "-pix_fmt",
3662 "yuv420p",
3663 "-f",
3664 "yuv4mpegpipe",
3665 "-",
3666 ])
3667 .stdin(Stdio::null())
3668 .stdout(Stdio::piped())
3669 .stderr(Stdio::piped()), None, |c| c.output())
3670 .expect("ffmpeg failed to run");
3671 assert!(
3672 y4m.status.success(),
3673 "ffmpeg fixture: {}",
3674 String::from_utf8_lossy(&y4m.stderr)
3675 );
3676 // Diagnosis knob only (default is the gate's pinned recipe):
3677 // which `--cq-level` makes aomenc's RD reach for filter intra on
3678 // a strip is a search, and the sweep that found this one is in
3679 // lanes/rectsplit-r1.report.md.
3680 let cq = format!(
3681 "--cq-level={}",
3682 // Pinned by the sweep in lanes/rectsplit-r1.report.md: at
3683 // cq 45 aomenc's RD picks a strip 18 times in 100 seeds and
3684 // filter intra on none of them; at cq 25 strips are common
3685 // (130/100 seeds) and filter intra lands on one every ~13
3686 // seeds.
3687 std::env::var("EC_RECTSPLIT_CQ").unwrap_or_else(|_| "25".into())
3688 );
3689 let args: Vec<&str> = vec![
3690 "--codec=av1",
3691 "--passes=1",
3692 "--end-usage=q",
3693 &cq,
3694 "--cpu-used=0",
3695 "--threads=1",
3696 "--row-mt=0",
3697 "--sb-size=64",
3698 "--enable-rect-partitions=1",
3699 "--enable-ab-partitions=0",
3700 "--enable-1to4-partitions=0",
3701 "--min-partition-size=16",
3702 "--max-partition-size=32",
3703 "--enable-restoration=0",
3704 "--enable-palette=0",
3705 "--deltaq-mode=0",
3706 "--enable-cdef=0",
3707 // The point of this gate.
3708 "--enable-filter-intra=1",
3709 // NOTE (lane-rectsplit r2, verifier finding): every intra
3710 // mode stays ON here. The square filter-intra gate reaches
3711 // for filter intra by switching the directional/smooth/paeth
3712 // competitors off, and this gate CANNOT: with them off
3713 // aomenc stops picking rect partitions at all (rect
3714 // strips 0/20 seeds, r1's table). What fires filter intra on
3715 // a strip here is the quantiser (`--cq-level=25`), not the
3716 // mode set -- `EC_RECTSPLIT_OFF` below is the diagnosis knob
3717 // that re-runs the subset search.
3718 "--enable-cfl-intra=0",
3719 "--enable-intrabc=0",
3720 "--obu",
3721 "-o",
3722 "-",
3723 "-",
3724 ];
3725 // Diagnosis knob (default: every intra mode on): turning the
3726 // directional/smooth/paeth competitors off is how the square
3727 // filter-intra gate makes RD reach for filter intra, but with all
3728 // four off aomenc stops picking rect partitions here entirely
3729 // (rect strips=0, filter-intra blocks=28, measured this round),
3730 // so the firing recipe is a search over subsets.
3731 let mut args = args;
3732 let off = std::env::var("EC_RECTSPLIT_OFF").unwrap_or_default();
3733 for tool in off.split(',').filter(|t| !t.is_empty()) {
3734 args.push(match tool {
3735 "smooth" => "--enable-smooth-intra=0",
3736 "paeth" => "--enable-paeth-intra=0",
3737 "dir" => "--enable-directional-intra=0",
3738 "angle" => "--enable-angle-delta=0",
3739 other => panic!("unknown EC_RECTSPLIT_OFF entry {other}"),
3740 });
3741 }
3742 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3743 assert!(
3744 out.status.success(),
3745 "aomenc refused the fixture: {}",
3746 String::from_utf8_lossy(&out.stderr)
3747 );
3748 let stream = out.stdout;
3749 assert!(
3750 !stream.is_empty(),
3751 "{NAME}: aomenc wrote an empty stream (seed {seed})"
3752 );
3753 let attempt_before = crate::decode::filter_intra_rect_hits();
3754 let frames = match decode_stream(&stream) {
3755 Err(e) => {
3756 let msg = e.to_string();
3757 assert!(
3758 msg.contains("unsupported"),
3759 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
3760 );
3761 named_refusals += 1;
3762 continue;
3763 }
3764 Ok(frames) => frames,
3765 };
3766 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3767 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
3768 if let Some(i) = frames[0]
3769 .y
3770 .iter()
3771 .zip(&ffmpeg_frames[0].y)
3772 .position(|(a, b)| a != b)
3773 {
3774 let diffs: Vec<usize> = frames[0]
3775 .y
3776 .iter()
3777 .zip(&ffmpeg_frames[0].y)
3778 .enumerate()
3779 .filter(|(_, (a, b))| a != b)
3780 .map(|(j, _)| j)
3781 .collect();
3782 let (x0, x1) = (
3783 diffs.iter().map(|j| j % width).min().unwrap(),
3784 diffs.iter().map(|j| j % width).max().unwrap(),
3785 );
3786 let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width);
3787 eprintln!(
3788 "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \
3789 -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}",
3790 i % width,
3791 i / width,
3792 frames[0].y[i],
3793 ffmpeg_frames[0].y[i],
3794 diffs.len(),
3795 );
3796 }
3797 assert_eq!(
3798 frames[0].y, ffmpeg_frames[0].y,
3799 "{NAME}: luma vs ffmpeg (seed {seed})"
3800 );
3801 assert_eq!(
3802 frames[0].u, ffmpeg_frames[0].u,
3803 "{NAME}: U vs ffmpeg (seed {seed})"
3804 );
3805 assert_eq!(
3806 frames[0].v, ffmpeg_frames[0].v,
3807 "{NAME}: V vs ffmpeg (seed {seed})"
3808 );
3809 compared_hits += crate::decode::filter_intra_rect_hits() - attempt_before;
3810 matched += 1;
3811 }
3812 let fi_hits = compared_hits;
3813 eprintln!(
3814 "{NAME}: rect strips this run={}, filter-intra blocks (any shape)={}",
3815 crate::decode::rect_partition_hits() - rect_before,
3816 crate::decode::filter_intra_hits() - fi_square_before
3817 );
3818 assert!(
3819 matched > 0,
3820 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
3821 );
3822 assert!(
3823 fi_hits > 0,
3824 "{NAME}: no HORZ/VERT strip used filter intra ({matched} pixel-exact matches, \
3825 {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run"
3826 );
3827 eprintln!(
3828 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
3829 filter_intra_rect_hits delta={fi_hits} out of {n_attempts} attempts"
3830 );
3831 }
3832
3833 /// lane-fistrip r1, the 10-bit arm of the strip gate (his films are
3834 /// yuv420p10le). Same ceiling as its 8-bit twin, lifted in lane-rectsplitx
3835 /// r3 (the split arm's `smooth_neighbor_uv`); before that, MEASURED over seeds
3836 /// 42..61 the 8x16/16x8 strips aomenc writes filter intra on are
3837 /// `skip=0`, which `decode_leaf_rect` refuses, so
3838 /// `filter_intra_rect_sub16_hits` never reaches a pixel compare.
3839 /// lane-fistrip r2 adds seeds 49 and 213 to the window: those are the two
3840 /// seeds measured to fire the feature on the 8-BIT twin's recipe (this
3841 /// arm's 10-bit encode is a different stream, so they are a widening, not
3842 /// a measured firing set for this recipe). Green since r3.
3843 #[test]
3844 fn a_real_aomenc_10bit_filter_intra_on_a_sub16_strip_decodes_pixel_exact() {
3845 const NAME: &str = "a_real_aomenc_10bit_filter_intra_on_a_sub16_strip_decodes_pixel_exact";
3846 let _gate_lock = lock_gate_counters();
3847 if !have_ffmpeg() {
3848 eprintln!("SKIP {NAME}: no ffmpeg");
3849 return;
3850 }
3851 if !have_aomenc() {
3852 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3853 return;
3854 }
3855 let mut seeds: Vec<u32> = (42..62).collect();
3856 seeds.push(213);
3857 ten_bit_tool_gate(
3858 NAME,
3859 192,
3860 128,
3861 1,
3862 &[
3863 "--limit=1",
3864 "--cq-level=25",
3865 "--cpu-used=0",
3866 "--threads=1",
3867 "--row-mt=0",
3868 "--sb-size=64",
3869 "--enable-rect-partitions=1",
3870 "--enable-ab-partitions=0",
3871 "--enable-1to4-partitions=0",
3872 "--min-partition-size=8",
3873 "--max-partition-size=32",
3874 "--enable-restoration=0",
3875 "--enable-palette=0",
3876 "--deltaq-mode=0",
3877 "--enable-cdef=0",
3878 "--enable-filter-intra=1",
3879 "--enable-cfl-intra=0",
3880 "--enable-intrabc=0",
3881 ],
3882 &seeds,
3883 &[(
3884 "filter_intra_rect_sub16_hits",
3885 crate::decode::filter_intra_rect_sub16_hits as fn() -> usize,
3886 )],
3887 );
3888 }
3889
3890 /// lane-fistrip r1, the pinned half of this lane's proof: one real
3891 /// `aomenc` stream (recipe below, byte-reproducible -- md5
3892 /// ac3a64773e5454ee9b5d8650507063cd, hashed twice) whose key frame
3893 /// carries four `BLOCK_16X8` DC_PRED leaves, one of which sets
3894 /// `use_filter_intra`. `av1_filter_intra_allowed_bsize` allows 16x8, so
3895 /// aomenc writes that flag; before this round `filter_intra_size_class_rect`
3896 /// had no row for the shape, the symbol was never read, and the tile
3897 /// desynced ON THAT BLOCK -- observable as a DIFFERENT named refusal
3898 /// ("a HORZ/VERT intra strip below 16x16 with a split transform", a
3899 /// `tx_depth` read out of a desynced stream) instead of this one.
3900 ///
3901 /// The stream cannot be pixel-compared yet: the 16x8 strip that carries
3902 /// the flag is `skip=0`, and a coded rect strip below 16x16 has no
3903 /// residual path here (its own refusal, another lane's ceiling). What
3904 /// this test pins is the SYMBOL: the flag is read, the counter fires
3905 /// once, and the decode stops at the coded-strip ceiling rather than
3906 /// wandering off a desynced stream.
3907 ///
3908 /// Fixture recipe (`crates/ec-av1/fixtures/filter_intra_8x16_strip_seed49.obu`):
3909 /// `ffmpeg -f lavfi -i gradients=size=192x128:c0=0x986ae1:c1=0xd3e49a:
3910 /// c2=0x0b1e53:c3=0x42980c:seed=49:duration=0.04:rate=25 -pix_fmt yuv420p`
3911 /// into `aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=25
3912 /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=64
3913 /// --enable-rect-partitions=1 --enable-ab-partitions=0
3914 /// --enable-1to4-partitions=0 --min-partition-size=8
3915 /// --max-partition-size=32 --enable-restoration=0 --enable-palette=0
3916 /// --deltaq-mode=0 --enable-filter-intra=1 --enable-cfl-intra=0
3917 /// --enable-intrabc=0 --obu`.
3918 #[test]
3919 fn a_pinned_aomenc_16x8_strip_reads_its_use_filter_intra_flag() {
3920 const NAME: &str = "a_pinned_aomenc_16x8_strip_reads_its_use_filter_intra_flag";
3921 let _gate_lock = lock_gate_counters();
3922 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3923 .join("fixtures/filter_intra_8x16_strip_seed49.obu");
3924 let stream = std::fs::read(&path)
3925 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
3926 if !have_ffmpeg() {
3927 eprintln!("SKIP {NAME}: no ffmpeg");
3928 return;
3929 }
3930 let before = crate::decode::filter_intra_rect_sub16_hits();
3931 // lane-rectsplitx r1: the ceiling this fixture used to stop at (a
3932 // sub-16 strip with a SPLIT transform) is ported, so the pinned
3933 // stream is now a full pixel compare -- what the doc above said this
3934 // test should become the round that ceiling lifted.
3935 let frames =
3936 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: decode refused: {e}"));
3937 let hits = crate::decode::filter_intra_rect_sub16_hits() - before;
3938 // TWO now, not the one the truncated decode used to see: the frame
3939 // no longer stops at the first filter-intra strip, so the second one
3940 // later in the tile is reached as well (and the pixel compare below
3941 // proves both reconstructed right).
3942 assert_eq!(
3943 hits, 2,
3944 "{NAME}: expected both 16x8 strips to read use_filter_intra=1; got {hits}"
3945 );
3946 // This is also the GATE for the sub-16 split-transform lift: both
3947 // strips split their transform (`tx_depth != 0` on a BLOCK_16X8 ->
3948 // two TX_8X8 units), which is the refusal this round removed.
3949 let splits = crate::decode::sub16_split_hits();
3950 assert!(
3951 splits > 0,
3952 "{NAME}: no sub-16 strip split its transform -- the fixture no longer proves the \
3953 per-unit path this test gates"
3954 );
3955 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 192, 128, 1);
3956 assert_eq!(frames.len(), 1, "{NAME}: expected one frame");
3957 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
3958 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
3959 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
3960 }
3961
3962 /// lane-fistrip r1: the filter-intra strip gate above, one partition
3963 /// level DOWN (`--min-partition-size=8`, so a 16x16 HORZ/VERT splits
3964 /// into 8x16/16x8 leaves). `av1_filter_intra_allowed_bsize` is
3965 /// `wide <= 32 && high <= 32`, which both of those satisfy, so aomenc
3966 /// writes a `use_filter_intra` flag on every DC_PRED one of them --
3967 /// `filter_intra_size_class_rect` had no row for either shape and
3968 /// [`crate::decode::read_intra_mode_rect`] therefore never READ that
3969 /// symbol (class `symbol-consumption-gap`, a silent desync rather than
3970 /// a refusal). Hard-asserts
3971 /// [`crate::decode::filter_intra_rect_sub16_hits`], not the wider
3972 /// `filter_intra_rect_hits`: a 32x16 strip firing filter intra would
3973 /// satisfy that one and prove nothing about the new shapes.
3974 /// MEASURED (lane-fistrip r1, seeds 42..=241; r2 re-ran 50..=241), which
3975 /// is why the window carries the two firing seeds: over those 200 seeds at
3976 /// cq 25 aomenc put filter intra on an 8x16/16x8 strip exactly TWICE --
3977 /// **seed 49 and seed 213** -- and both times that strip was `skip=0`, so
3978 /// the attempt refused at the coded-rect-strip-below-16x16 ceiling before
3979 /// any pixel compare (r1: 177 pixel-exact matches, 23 refusals, compared
3980 /// sub16 delta 0, all-attempt delta 2; r2 seeds 50..=241: 172 matches, 20
3981 /// refusals, the one all-attempt hit at seed 213). BOTH firing seeds are
3982 /// appended to this gate's seed window below, so it compares two real
3983 /// hits. UN-IGNORED lane-rectsplitx r3: the ceiling lifted with the split
3984 /// refusal, and the residual chroma defect was the split arm of
3985 /// [`crate::decode::decode_leaf_rect`] passing `smooth_neighbor_uv: false`
3986 /// where the unsplit arm passes the neighbour's real answer. The symbol
3987 /// itself stays pinned by
3988 /// [`a_pinned_aomenc_16x8_strip_reads_its_use_filter_intra_flag`].
3989 #[test]
3990 fn a_real_aomenc_stream_with_filter_intra_on_a_sub16_horz_vert_strip_decodes_pixel_exact() {
3991 const NAME: &str =
3992 "a_real_aomenc_stream_with_filter_intra_on_a_sub16_horz_vert_strip_decodes_pixel_exact";
3993 let _gate_lock = lock_gate_counters();
3994 if !have_ffmpeg() {
3995 eprintln!("SKIP {NAME}: no ffmpeg");
3996 return;
3997 }
3998 if !have_aomenc() {
3999 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4000 return;
4001 }
4002 let (width, height) = (192usize, 128usize);
4003 let mut named_refusals = 0u32;
4004 let mut matched = 0u32;
4005 let mut compared_hits = 0usize;
4006 let n_attempts: u32 = std::env::var("EC_FISTRIP_GATE_ATTEMPTS")
4007 .ok()
4008 .and_then(|s| s.parse().ok())
4009 .unwrap_or(40);
4010 // lane-fistrip r2: the two seeds that MEASURABLY fire filter intra on
4011 // an 8x16/16x8 strip are 49 and 213 -- the only two in seeds 42..=241
4012 // (r1 measured 42..=241 and reported "all-attempt delta 2" with seed
4013 // 49; r2 re-ran seeds 50..=241 and found the second, log
4014 // `$HOME/.cache/fistrip-seedscan-r2.log`: "seed 213 refused with sub16
4015 // filter-intra delta 1"). Both are appended to whatever window
4016 // `EC_FISTRIP_GATE_ATTEMPTS` asks for, so the un-ignore after the
4017 // coded-rect-strip ceiling lifts compares TWO real hits instead of
4018 // depending on the default window happening to contain one.
4019 const FIRING_SEEDS: [u32; 2] = [49, 213];
4020 let mut seeds: Vec<u32> = (0..n_attempts).map(|a| 42 + a).collect();
4021 for s in FIRING_SEEDS {
4022 if !seeds.contains(&s) {
4023 seeds.push(s);
4024 }
4025 }
4026 let cq = format!(
4027 "--cq-level={}",
4028 std::env::var("EC_FISTRIP_CQ").unwrap_or_else(|_| "25".into())
4029 );
4030 // Diagnosis: the counter over EVERY attempt, refused ones included --
4031 // a filter-intra 8x16 strip inside an attempt that later refused
4032 // (non-skip, split transform) fires this but never reaches
4033 // `compared_hits`, and the two numbers differing is what says the
4034 // recipe reaches the feature but this decoder's other ceilings hide
4035 // it.
4036 let all_before = crate::decode::filter_intra_rect_sub16_hits();
4037 for &seed in &seeds {
4038 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
4039 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
4040 .args([
4041 "-v",
4042 "error",
4043 "-f",
4044 "lavfi",
4045 "-i",
4046 &source,
4047 "-pix_fmt",
4048 "yuv420p",
4049 "-f",
4050 "yuv4mpegpipe",
4051 "-",
4052 ])
4053 .stdin(Stdio::null())
4054 .stdout(Stdio::piped())
4055 .stderr(Stdio::piped()), None, |c| c.output())
4056 .expect("ffmpeg failed to run");
4057 assert!(
4058 y4m.status.success(),
4059 "ffmpeg fixture: {}",
4060 String::from_utf8_lossy(&y4m.stderr)
4061 );
4062 let args: Vec<&str> = vec![
4063 "--codec=av1",
4064 "--passes=1",
4065 "--end-usage=q",
4066 &cq,
4067 "--cpu-used=0",
4068 "--threads=1",
4069 "--row-mt=0",
4070 "--sb-size=64",
4071 "--enable-rect-partitions=1",
4072 "--enable-ab-partitions=0",
4073 "--enable-1to4-partitions=0",
4074 // The point of this gate: one level below the 32x16/16x32
4075 // strips the sibling gate covers.
4076 "--min-partition-size=8",
4077 "--max-partition-size=32",
4078 "--enable-restoration=0",
4079 "--enable-palette=0",
4080 "--deltaq-mode=0",
4081 "--enable-cdef=0",
4082 "--enable-filter-intra=1",
4083 "--enable-cfl-intra=0",
4084 "--enable-intrabc=0",
4085 "--obu",
4086 "-o",
4087 "-",
4088 "-",
4089 ];
4090 // Diagnosis knob only (default: every intra mode on) -- the same
4091 // subset search the 32x16/16x32 sibling gate carries.
4092 let mut args = args;
4093 let off = std::env::var("EC_FISTRIP_OFF").unwrap_or_default();
4094 for tool in off.split(',').filter(|t| !t.is_empty()) {
4095 args.push(match tool {
4096 "smooth" => "--enable-smooth-intra=0",
4097 "paeth" => "--enable-paeth-intra=0",
4098 "dir" => "--enable-directional-intra=0",
4099 "angle" => "--enable-angle-delta=0",
4100 other => panic!("unknown EC_FISTRIP_OFF entry {other}"),
4101 });
4102 }
4103 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
4104 assert!(
4105 out.status.success(),
4106 "aomenc refused the fixture: {}",
4107 String::from_utf8_lossy(&out.stderr)
4108 );
4109 let stream = out.stdout;
4110 assert!(
4111 !stream.is_empty(),
4112 "{NAME}: aomenc wrote an empty stream (seed {seed})"
4113 );
4114 let attempt_before = crate::decode::filter_intra_rect_sub16_hits();
4115 let frames = match decode_stream(&stream) {
4116 Err(e) => {
4117 let msg = e.to_string();
4118 assert!(
4119 msg.contains("unsupported"),
4120 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
4121 );
4122 // Diagnosis: a refused attempt that DID fire the feature
4123 // says which other ceiling of this decoder hides it.
4124 eprintln!(
4125 "{NAME}: seed {seed} refused with sub16 filter-intra delta {}: {msg}",
4126 crate::decode::filter_intra_rect_sub16_hits() - attempt_before
4127 );
4128 named_refusals += 1;
4129 continue;
4130 }
4131 Ok(frames) => frames,
4132 };
4133 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4134 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
4135 assert_eq!(
4136 frames[0].y, ffmpeg_frames[0].y,
4137 "{NAME}: luma vs ffmpeg (seed {seed})"
4138 );
4139 assert_eq!(
4140 frames[0].u, ffmpeg_frames[0].u,
4141 "{NAME}: U vs ffmpeg (seed {seed})"
4142 );
4143 assert_eq!(
4144 frames[0].v, ffmpeg_frames[0].v,
4145 "{NAME}: V vs ffmpeg (seed {seed})"
4146 );
4147 compared_hits += crate::decode::filter_intra_rect_sub16_hits() - attempt_before;
4148 matched += 1;
4149 }
4150 eprintln!(
4151 "{NAME}: filter_intra_rect_sub16_hits over ALL attempts (refused included) = {}",
4152 crate::decode::filter_intra_rect_sub16_hits() - all_before
4153 );
4154 assert!(
4155 matched > 0,
4156 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
4157 );
4158 assert!(
4159 compared_hits > 0,
4160 "{NAME}: no 8x16/16x8 strip used filter intra ({matched} pixel-exact matches, \
4161 {named_refusals} refusals out of {} attempts) -- gate proved nothing this run",
4162 seeds.len()
4163 );
4164 eprintln!(
4165 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
4166 filter_intra_rect_sub16_hits delta={compared_hits} (all attempts including \
4167 refused: {}) out of {} attempts",
4168 crate::decode::filter_intra_rect_sub16_hits() - all_before,
4169 seeds.len()
4170 );
4171 }
4172
4173 /// lane-rectsplit r1 gate (b): [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]'s
4174 /// own recipe (`--sb-size=64`, `--min/max-partition-size=32/64`, so every
4175 /// SB-level decision is genuinely NONE/SPLIT/HORZ/VERT) with its
4176 /// `--enable-tx-size-search=0` DROPPED: the 64x32/32x64 strips may then
4177 /// carry a split transform, which [`crate::decode::decode_block_rect64`]
4178 /// refused by name ("a superblock-level HORZ/VERT strip with a split
4179 /// transform") until lane-rectsplit r2 lifted it.
4180 ///
4181 /// The hard assert is on [`crate::decode::rect_split_sb_interior_tu_hits`],
4182 /// NOT the shared `rect_split_tx_hits()` gate (a) uses: that counter also
4183 /// counts 32x32-level and depth-1 strips, whose units are all in the
4184 /// first transform-unit row/column. Only a superblock-level strip split
4185 /// past depth 1 has an INTERIOR unit (`row_off > 0 && col_off > 0`),
4186 /// which is the per-unit availability rule this port exists for, and no
4187 /// gate fired one before this round.
4188 ///
4189 /// This gate was `#[ignore]`d RED through r3 (seed 50 luma (171,56)).
4190 /// Root cause, r4, TWO defects, neither of them availability -- the
4191 /// strip's own per-unit prediction was exact all along:
4192 /// 1. `av1_nz_map_ctx_offset` is indexed by libaom's COLUMN-major
4193 /// `coeff_idx = col * 32 + row`, so [`crate::decode::base_ctx`] read
4194 /// the `TX_32X64`/`TX_64X32` offset tables transposed (r2 saw this and
4195 /// r3 reverted it, because "fixing" it turned the merged SB HORZ/VERT
4196 /// gate RED at seed 43);
4197 /// 2. that seed-43 RED was a SECOND defect the first one had been hiding
4198 /// behind a refusal: `EOB_PT_512_CHROMA` was transcribed from
4199 /// `av1_default_eob_multi512_cdfs`'s `eob_multi_ctx = 1` row (the flat
4200 /// `V_DCT`/`H_DCT` distribution), so the first real 32x16 chroma
4201 /// transform read `eob_pt` 7 where aomdec read 2. With both fixed,
4202 /// seeds 43 and 50 are pixel-exact.
4203 #[test]
4204 fn a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact() {
4205 const NAME: &str =
4206 "a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact";
4207 let _gate_lock = lock_gate_counters();
4208 if !have_ffmpeg() {
4209 eprintln!("SKIP {NAME}: no ffmpeg");
4210 return;
4211 }
4212 if !have_aomenc() {
4213 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4214 return;
4215 }
4216 let (width, height) = (192usize, 128usize);
4217 let before = crate::decode::rect_split_tx_hits();
4218 let mut named_refusals = 0u32;
4219 let mut matched = 0u32;
4220 // lane-rectsplit r2 (verifier finding): the feature counter is
4221 // sampled PER ATTEMPT and folded in only after that attempt was
4222 // decoded AND pixel-compared. One delta across the whole sweep
4223 // counted strips decoded by attempts that went on to hit a named
4224 // refusal, so the gate could pass with every COMPARED stream
4225 // containing none of the feature at all.
4226 let mut compared_hits = 0usize;
4227 let mut split_so_far = 0usize;
4228 // Bounded sweep: see this gate's own doc for the seed-77 residue and
4229 // why extending it is a diagnosis knob, not a pass/fail one.
4230 let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
4231 .ok()
4232 .and_then(|s| s.parse().ok())
4233 .unwrap_or(20);
4234 for attempt in 0..n_attempts {
4235 let seed = 42 + attempt;
4236 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
4237 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
4238 .args([
4239 "-v",
4240 "error",
4241 "-f",
4242 "lavfi",
4243 "-i",
4244 &source,
4245 // REAL chroma (lane-sqchroma r1 dropped the `hue=s=0`
4246 // guard this recipe carried): the "PRE-EXISTING square-path
4247 // chroma defect" that guard named does not reproduce at
4248 // HEAD -- seeds 42..61, cq 12/20/32/45, plus testsrc2 and
4249 // mandelbrot, all decode pixel-exact with
4250 // `--enable-rect-partitions=0`, and this gate is green with
4251 // the filter gone. Its own gate is
4252 // `a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact`.
4253 "-pix_fmt",
4254 "yuv420p",
4255 "-f",
4256 "yuv4mpegpipe",
4257 "-",
4258 ])
4259 .stdin(Stdio::null())
4260 .stdout(Stdio::piped())
4261 .stderr(Stdio::piped()), None, |c| c.output())
4262 .expect("ffmpeg failed to run");
4263 assert!(
4264 y4m.status.success(),
4265 "ffmpeg fixture: {}",
4266 String::from_utf8_lossy(&y4m.stderr)
4267 );
4268 // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's
4269 // own default (search ON) is the entire point of this gate.
4270 let args: Vec<&str> = vec![
4271 "--codec=av1",
4272 "--passes=1",
4273 "--end-usage=q",
4274 "--cq-level=45",
4275 "--cpu-used=0",
4276 "--threads=1",
4277 "--row-mt=0",
4278 "--sb-size=64",
4279 "--enable-rect-partitions=1",
4280 "--enable-ab-partitions=0",
4281 "--enable-1to4-partitions=0",
4282 "--min-partition-size=32",
4283 "--max-partition-size=64",
4284 "--enable-restoration=0",
4285 "--enable-palette=0",
4286 "--deltaq-mode=0",
4287 "--enable-cdef=0",
4288 "--enable-filter-intra=0",
4289 "--enable-cfl-intra=0",
4290 "--enable-intrabc=0",
4291 "--obu",
4292 "-o",
4293 "-",
4294 "-",
4295 ];
4296 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
4297 assert!(
4298 out.status.success(),
4299 "aomenc refused the fixture: {}",
4300 String::from_utf8_lossy(&out.stderr)
4301 );
4302 let stream = out.stdout;
4303 assert!(
4304 !stream.is_empty(),
4305 "{NAME}: aomenc wrote an empty stream (seed {seed})"
4306 );
4307 let attempt_before = crate::decode::rect_split_sb_interior_tu_hits();
4308 let frames = match decode_stream(&stream) {
4309 Err(e) => {
4310 let msg = e.to_string();
4311 assert!(
4312 msg.contains("unsupported"),
4313 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
4314 );
4315 named_refusals += 1;
4316 continue;
4317 }
4318 Ok(frames) => frames,
4319 };
4320 let after = crate::decode::rect_split_tx_hits();
4321 eprintln!(
4322 "{NAME}: seed {seed} decoded, split-tx strips this stream: {}",
4323 after - before - split_so_far
4324 );
4325 split_so_far = after - before;
4326 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4327 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
4328 if let Some(i) = frames[0]
4329 .y
4330 .iter()
4331 .zip(&ffmpeg_frames[0].y)
4332 .position(|(a, b)| a != b)
4333 {
4334 let diffs: Vec<usize> = frames[0]
4335 .y
4336 .iter()
4337 .zip(&ffmpeg_frames[0].y)
4338 .enumerate()
4339 .filter(|(_, (a, b))| a != b)
4340 .map(|(j, _)| j)
4341 .collect();
4342 let (x0, x1) = (
4343 diffs.iter().map(|j| j % width).min().unwrap(),
4344 diffs.iter().map(|j| j % width).max().unwrap(),
4345 );
4346 let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width);
4347 eprintln!(
4348 "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \
4349 -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}",
4350 i % width,
4351 i / width,
4352 frames[0].y[i],
4353 ffmpeg_frames[0].y[i],
4354 diffs.len(),
4355 );
4356 }
4357 assert_eq!(
4358 frames[0].y, ffmpeg_frames[0].y,
4359 "{NAME}: luma vs ffmpeg (seed {seed})"
4360 );
4361 assert_eq!(
4362 frames[0].u, ffmpeg_frames[0].u,
4363 "{NAME}: U vs ffmpeg (seed {seed})"
4364 );
4365 assert_eq!(
4366 frames[0].v, ffmpeg_frames[0].v,
4367 "{NAME}: V vs ffmpeg (seed {seed})"
4368 );
4369 compared_hits += crate::decode::rect_split_sb_interior_tu_hits() - attempt_before;
4370 matched += 1;
4371 }
4372 let split_hits = compared_hits;
4373 assert!(
4374 matched > 0,
4375 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
4376 );
4377 assert!(
4378 split_hits > 0,
4379 "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \
4380 matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \
4381 this run"
4382 );
4383 eprintln!(
4384 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
4385 rect_split_sb_interior_tu_hits delta={split_hits} (over COMPARED streams only) \
4386 out of {n_attempts} attempts"
4387 );
4388 }
4389
4390 /// lane-part32 r4: a real `aomenc` stream whose superblock-level
4391 /// partition decision is one of the four AB arms (`PARTITION_HORZ_A`/
4392 /// `_B`/`VERT_A`/`_B` at 64x64: two 32x32 squares plus one 64x32/32x64
4393 /// strip) must decode pixel-exact. Same recipe as the HORZ/VERT sibling
4394 /// above with `--enable-ab-partitions=1`; `sb_ab_hits() > 0` is a HARD
4395 /// assert, so a run where aomenc's RD never picked an AB arm fails
4396 /// rather than passing vacuously.
4397 #[test]
4398 fn a_real_aomenc_stream_with_a_superblock_level_ab_partition_decodes_pixel_exact() {
4399 const NAME: &str =
4400 "a_real_aomenc_stream_with_a_superblock_level_ab_partition_decodes_pixel_exact";
4401 let _gate_lock = lock_gate_counters();
4402 if !have_ffmpeg() {
4403 eprintln!("SKIP {NAME}: no ffmpeg");
4404 return;
4405 }
4406 if !have_aomenc() {
4407 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4408 return;
4409 }
4410 let (width, height, frame_count) = (192usize, 128usize, 1usize);
4411 let mut named_refusals = 0u32;
4412 let mut matched = 0u32;
4413 let n_attempts: u32 = std::env::var("EC_SBAB_GATE_ATTEMPTS")
4414 .ok()
4415 .and_then(|s| s.parse().ok())
4416 .unwrap_or(40);
4417 for attempt in 0..n_attempts {
4418 let seed = 42 + attempt;
4419 let duration = frame_count as f64 / 25.0;
4420 let source =
4421 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
4422 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
4423 .args([
4424 "-v",
4425 "error",
4426 "-f",
4427 "lavfi",
4428 "-i",
4429 &source,
4430 "-pix_fmt",
4431 "yuv420p",
4432 "-f",
4433 "yuv4mpegpipe",
4434 "-",
4435 ])
4436 .stdin(Stdio::null())
4437 .stdout(Stdio::piped())
4438 .stderr(Stdio::piped()), None, |c| c.output())
4439 .expect("ffmpeg failed to run");
4440 assert!(
4441 y4m.status.success(),
4442 "ffmpeg fixture: {}",
4443 String::from_utf8_lossy(&y4m.stderr)
4444 );
4445 let args: Vec<&str> = vec![
4446 "--codec=av1",
4447 "--passes=1",
4448 "--end-usage=q",
4449 "--cq-level=45",
4450 "--cpu-used=0",
4451 "--threads=1",
4452 "--row-mt=0",
4453 "--sb-size=64",
4454 "--enable-rect-partitions=1",
4455 "--enable-ab-partitions=1",
4456 "--enable-1to4-partitions=0",
4457 "--min-partition-size=32",
4458 "--max-partition-size=64",
4459 "--enable-restoration=0",
4460 "--enable-palette=0",
4461 "--deltaq-mode=0",
4462 "--enable-cdef=0",
4463 "--enable-filter-intra=0",
4464 "--enable-cfl-intra=0",
4465 "--enable-intrabc=0",
4466 "--enable-tx-size-search=0",
4467 "--obu",
4468 "-o",
4469 "-",
4470 "-",
4471 ];
4472 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
4473 assert!(
4474 out.status.success(),
4475 "aomenc refused the fixture: {}",
4476 String::from_utf8_lossy(&out.stderr)
4477 );
4478 let stream = out.stdout;
4479 let frames = match decode_stream(&stream) {
4480 Err(e) => {
4481 let msg = e.to_string();
4482 assert!(
4483 msg.contains("unsupported"),
4484 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
4485 );
4486 // r5: the four SB-level AB arms (`partition_w64` 4-7)
4487 // decode since this round, so the only partition refusal
4488 // left at 64x64 is the 1:4 pair (values 8/9, four
4489 // 64x16/16x64 strips, whose luma TX_64X16 this decoder
4490 // has no transform for); the refusals this loop actually
4491 // counts on these fixtures are the pre-existing
4492 // screen-content-palette strip one. Every refusal is
4493 // named, so a genuine decode failure still fails the
4494 // assert above rather than skipping.
4495 named_refusals += 1;
4496 eprintln!("seed {seed} refusal: {msg}");
4497 continue;
4498 }
4499 Ok(frames) => frames,
4500 };
4501 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
4502 assert_eq!(frames.len(), frame_count);
4503 let mismatched = frames
4504 .iter()
4505 .zip(&ffmpeg_frames)
4506 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
4507 if mismatched
4508 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
4509 std::fs::write(&path, &stream).expect("writing pinned stream");
4510 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
4511 }
4512 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4513 assert_eq!(
4514 got.y, want.y,
4515 "{NAME} frame {i} luma vs ffmpeg (seed {seed})"
4516 );
4517 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
4518 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
4519 }
4520 matched += 1;
4521 }
4522 assert!(
4523 matched > 0,
4524 "{NAME}: every attempt refused; the gate never decoded a stream"
4525 );
4526 let arms = crate::decode::sb_ab_hits_by_arm();
4527 for (i, name) in ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"].iter().enumerate() {
4528 assert!(
4529 arms[i] > 0,
4530 "{NAME}: zero superblock-level PARTITION_{name} blocks fired (arms={arms:?}, \
4531 {matched} matches, {named_refusals} refusals out of {n_attempts}) -- that arm \
4532 proved nothing this run"
4533 );
4534 }
4535 eprintln!(
4536 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
4537 {n_attempts}, sb_ab_hits={} arms(HORZ_A,HORZ_B,VERT_A,VERT_B)={arms:?}",
4538 crate::decode::sb_ab_hits()
4539 );
4540 }