forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

t10.rs4293 lines, 208.8 KiBHistoryRawDownload
1use super::*;
2use super::support::*;
3use super::gates_a::*;
4use crate::probe::run_with_stdin;
5use std::process::{Command, Stdio};
6
7 /// lane-sub8x4 r2, the gate that lifts BOTH sub-8x8 intra refusals ("an
8 /// intra 4x4 block inside an inter frame's sub-8x8 split" and "an intra
9 /// 8x4/4x8 block inside an inter frame's sub-8x8 HORZ/VERT partition").
10 ///
11 /// Recipe (measured, `~/.cache/sub8intra-tmp/sweep3.sh`): a 24-row band of
12 /// per-frame-moving noise over a smooth sinusoid, `--min-partition-size=4
13 /// --max-partition-size=8 --enable-1to4-partitions=0` -- at that maximum a
14 /// 16x4 shape cannot exist, so nothing here can be confused with the
15 /// still-refused intra 1:4 strip, and the noise band is what makes aomenc's
16 /// RD pick INTRA leaves inside an inter frame's 8x8 groups. 12 arms
17 /// (8/10-bit x cq 48/55/63 x 128x128/192x128) plus one `--tile-columns=1`
18 /// arm (COMMON's neighbour-map rule: these leaves publish per-mi side
19 /// bands), 6 frames each, every decode-order frame and all three planes
20 /// compared against ffmpeg. Continue-and-sweep: a NAMED refusal is
21 /// recorded and the arm skipped, any other decode error or any pixel
22 /// mismatch fails the gate on the spot.
23 ///
24 /// The end-of-sweep assert reads all five
25 /// [`decode::sub8_intra_rect_hits`] cells -- 8x4 leaves, 4x8 leaves, the
26 /// chroma-reference ones (which code the group's 4x4 chroma intra),
27 /// `is_sub8x8_inter`-false MIXED groups, and the `PARTITION_SPLIT` 4x4
28 /// leaves (the second refusal's own arm) -- so neither lifted refusal
29 /// rests on a stream that never carried its shape.
30 #[test]
31 fn a_real_aomenc_inter_sequence_with_intra_sub8x8_leaves_decodes_pixel_exact() {
32 const NAME: &str =
33 "a_real_aomenc_inter_sequence_with_intra_sub8x8_leaves_decodes_pixel_exact";
34 if !have_ffmpeg() {
35 eprintln!("SKIP {NAME}: no ffmpeg");
36 return;
37 }
38 if !have_aomenc() {
39 let msg = format!("no aomenc at {}", aomenc_path().display());
40 assert!(
41 std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
42 "EC_AV1_REQUIRE_AOMENC is set but {msg}"
43 );
44 eprintln!("SKIP {NAME}: {msg}");
45 return;
46 }
47 const FRAMES: usize = 6;
48 // One arm's stream, byte for byte: the lavfi source (a moving 24-row
49 // random band over `128+50*sin(x/7)`) feeds aomenc through a pipe.
50 let encode = |depth: u32, cq: u32, width: usize, height: usize, tiles: bool| -> Vec<u8> {
51 let pix = if depth == 10 {
52 "yuv420p10le"
53 } else {
54 "yuv420p"
55 };
56 let source = format!(
57 "color=c=gray:s={width}x{height}:d=0.24:r=25,format=gray,\
58 geq=lum='if(lt(mod(Y+N*37\\,{height})\\,24)\\,random(N*100+X+Y)*255\\,128+50*sin(X/7))',\
59 format={pix}"
60 );
61 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
62 .args([
63 "-v",
64 "error",
65 "-f",
66 "lavfi",
67 "-i",
68 &source,
69 "-t",
70 "0.24",
71 "-pix_fmt",
72 pix,
73 "-strict",
74 "-1",
75 "-f",
76 "yuv4mpegpipe",
77 "-",
78 ])
79 .stdin(Stdio::null())
80 .stdout(Stdio::piped())
81 .stderr(Stdio::piped()), None, |c| c.output())
82 .expect("ffmpeg failed to run");
83 assert!(
84 y4m.status.success(),
85 "{NAME}: ffmpeg fixture (depth={depth} cq={cq} {width}x{height}): {}",
86 String::from_utf8_lossy(&y4m.stderr)
87 );
88 let cq_arg = format!("--cq-level={cq}");
89 let mut args: Vec<&str> = vec![
90 "--codec=av1",
91 "--passes=1",
92 "--end-usage=q",
93 &cq_arg,
94 "--cpu-used=0",
95 "--threads=1",
96 "--row-mt=0",
97 "--sb-size=64",
98 "--enable-restoration=0",
99 "--enable-palette=0",
100 "--deltaq-mode=0",
101 "--enable-intrabc=0",
102 "--lag-in-frames=0",
103 "--kf-max-dist=9999",
104 "--enable-tx-size-search=1",
105 "--enable-rect-partitions=1",
106 // The 16x4/4x16 intra strip is a DIFFERENT (still refused)
107 // shape; keeping 1:4 off is what makes a refusal here mean
108 // this gate's own arm.
109 "--enable-1to4-partitions=0",
110 "--min-partition-size=4",
111 "--max-partition-size=8",
112 ];
113 if depth == 10 {
114 args.push("--bit-depth=10");
115 args.push("--input-bit-depth=10");
116 }
117 // AOMENC FLAG PRECEDENCE (COMMON): the per-arm override goes last.
118 args.push(if tiles {
119 "--tile-columns=1"
120 } else {
121 "--tile-columns=0"
122 });
123 args.extend(["--obu", "-o", "-", "-"]);
124 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
125 assert!(
126 out.status.success(),
127 "{NAME}: aomenc refused the fixture (depth={depth} cq={cq} {width}x{height}): {}",
128 String::from_utf8_lossy(&out.stderr)
129 );
130 out.stdout
131 };
132
133 let mut refusals: Vec<String> = Vec::new();
134 let mut exact_arms = 0u32;
135 let mut fired = [0usize; 5];
136 let mut checked_reproducible = false;
137 let mut arms: Vec<(u32, u32, usize, usize, bool)> = Vec::new();
138 for depth in [8u32, 10] {
139 for cq in [48u32, 55, 63] {
140 for (w, h) in [(128usize, 128usize), (192usize, 128usize)] {
141 arms.push((depth, cq, w, h, false));
142 }
143 }
144 }
145 // lane-sub8x4 r3: the `--tile-columns=1` arm COMMON's neighbour-map
146 // rule asks for. It was excluded in r2 because it desynced at
147 // decode-order frame 4 -- identically with `--min-partition-size=16
148 // --max-partition-size=16`, i.e. with no sub-8x8 block at all. That was
149 // main's `1d2259c` (the saved motion field kept only the LAST tile's
150 // columns), merged into this lane in r3; the arm is restored here.
151 arms.push((8, 63, 192, 128, true));
152 for (depth, cq, width, height, tiles) in arms {
153 let arm = format!("depth={depth} cq={cq} {width}x{height} tiles={tiles}");
154 let stream = encode(depth, cq, width, height, tiles);
155 if !checked_reproducible {
156 // seeded-fixture-not-reproducible: prove the recipe names ONE
157 // stream before any measurement rests on it.
158 let again = encode(depth, cq, width, height, tiles);
159 assert_eq!(
160 stream,
161 again,
162 "{NAME}: the fixture recipe is not reproducible ({arm}, {} vs {} bytes)",
163 stream.len(),
164 again.len()
165 );
166 checked_reproducible = true;
167 }
168 let before = decode::sub8_intra_rect_hits();
169 let tiles_before = decode::tile_hits();
170 let frames = match decode_stream(&stream) {
171 Ok(frames) => frames,
172 Err(e) => {
173 let msg = e.to_string();
174 assert!(
175 msg.starts_with("unsupported: "),
176 "{NAME}: decode error that is not a named refusal ({arm}): {msg}"
177 );
178 refusals.push(format!("{arm}: {msg}"));
179 continue;
180 }
181 };
182 assert_eq!(
183 frames.len(),
184 FRAMES,
185 "{NAME}: {arm} decoded {} frames",
186 frames.len()
187 );
188 assert!(
189 !tiles || decode::tile_hits() - tiles_before >= 2,
190 "{NAME}: {arm} decoded only {} tile(s)",
191 decode::tile_hits() - tiles_before
192 );
193 let theirs = if depth == 10 {
194 ffmpeg_decode_sequence_10bit(&stream, width, height, FRAMES)
195 } else {
196 ffmpeg_decode_sequence(&stream, width, height, FRAMES)
197 };
198 for (i, (ours, theirs)) in frames.iter().zip(&theirs).enumerate() {
199 assert_eq!(ours.y, theirs.y, "{NAME}: {arm} frame {i} luma vs ffmpeg");
200 assert_eq!(ours.u, theirs.u, "{NAME}: {arm} frame {i} U vs ffmpeg");
201 assert_eq!(ours.v, theirs.v, "{NAME}: {arm} frame {i} V vs ffmpeg");
202 }
203 let now = decode::sub8_intra_rect_hits();
204 let delta = [
205 now.0 - before.0,
206 now.1 - before.1,
207 now.2 - before.2,
208 now.3 - before.3,
209 now.4 - before.4,
210 ];
211 exact_arms += 1;
212 for (slot, d) in fired.iter_mut().zip(delta) {
213 *slot += d;
214 }
215 eprintln!(
216 "{NAME}: {arm} EXACT 8x4={} 4x8={} chroma_ref={} mixed={} split4x4={}",
217 delta[0], delta[1], delta[2], delta[3], delta[4]
218 );
219 }
220 assert!(
221 exact_arms >= 12,
222 "{NAME}: only {exact_arms} arm(s) decoded and compared exact; refusals:\n{}",
223 refusals.join("\n")
224 );
225 for (cell, what) in fired.iter().zip([
226 "intra 8x4 leaves",
227 "intra 4x8 leaves",
228 "chroma-reference intra leaves",
229 "is_sub8x8_inter-false MIXED groups",
230 "intra 4x4 leaves of a sub-8x8 PARTITION_SPLIT",
231 ]) {
232 assert!(
233 *cell > 0,
234 "{NAME}: zero {what} over {exact_arms} pixel-exact arms -- the lifted refusal \
235 rests on nothing (counters {fired:?})"
236 );
237 }
238 eprintln!(
239 "{NAME}: {exact_arms} arms pixel-exact over {FRAMES} frames each, counters {fired:?}"
240 );
241 }
242
243 /// lane-thread1: every per-frame/per-stream decode state now lives in
244 /// [`crate::decode::FrameCtx`], not in a `thread_local!`. A static that
245 /// comes back would silently re-break frame-parallel decoding (a worker
246 /// thread sees an empty copy) without failing any pixel gate, so pin the
247 /// 38 names by name against the sources themselves.
248 #[test]
249 fn no_per_frame_state_is_thread_local_any_more() {
250 const MOVED: [&str; 38] = [
251 "SB128",
252 "CDEF_BITS",
253 "BIT_DEPTH",
254 "SUPERRES",
255 "CDEF_TRANSMITTED",
256 "CDEF_SB_COLS",
257 "CDEF_IDX_GRID",
258 "DELTA_Q_PRESENT",
259 "DELTA_Q_RES",
260 "CURRENT_Q_IDX",
261 "QUANT_DELTAS",
262 "DELTA_LF_PRESENT",
263 "DELTA_LF_RES",
264 "DELTA_LF_MULTI",
265 "CURRENT_DELTA_LF",
266 "SEG",
267 "SEG_IDS",
268 "PREV_SEG_IDS",
269 "SEG_MI_DIMS",
270 "ABOVE_SEG_PRED",
271 "LEFT_SEG_PRED",
272 "CUR_SEGMENT_ID",
273 "SEG_TILE_ORIGIN",
274 "TX_SELECT_INTER",
275 "REDUCED_TX_SET_INTER",
276 "ENABLE_FILTER_INTRA_INTER",
277 "PALETTE_PRED",
278 "INTRABC_MI_GRID",
279 "INTRABC_DV",
280 "LUMA_TX_TYPE",
281 "INTRABC_CHROMA_TX",
282 "INTRA_IN_INTER_MODE",
283 "INTER_STRIP_CHROMA",
284 "INTER_LAST_MC",
285 "ENABLE_EDGE_FILTER",
286 "LAST_FRAME_WIDE_MARGIN",
287 "REACH_SB_PX",
288 "GRAIN_BIT_DEPTH",
289 ];
290 let sources = [
291 ("decode.rs", crate::test_source::module_source("decode")),
292 ("encode.rs", crate::test_source::module_source("encode")),
293 ("film_grain.rs", include_str!("../../film_grain.rs")),
294 ];
295 let mut back = Vec::new();
296 for (name, src) in sources {
297 for line in src.lines() {
298 let t = line.trim_start().trim_start_matches("pub(crate) ");
299 if let Some(rest) = t.strip_prefix("static ") {
300 let ident = rest.split(':').next().unwrap_or("").trim();
301 if MOVED.contains(&ident) {
302 back.push(format!("{name}: {ident}"));
303 }
304 }
305 }
306 }
307 assert!(
308 back.is_empty(),
309 "per-frame state is thread_local again (belongs in FrameCtx): {back:?}"
310 );
311 // ... and the scratch pools / gate counters DID stay thread-local:
312 // this file's own counter reads run on the test thread.
313 assert!(
314 crate::test_source::module_source("decode").contains("thread_local!"),
315 "the scratch pools and gate hit counters are still thread_local by design"
316 );
317 }
318
319 /// lane-d792: a frame whose height the superblock grid CUTS, decoded
320 /// against ffmpeg on every ladder point of BOTH reference encoders.
321 ///
322 /// WHY IT EXISTS: the reference encoders answer a straddling frame with
323 /// rectangular partitions in the cut superblock row -- the only place
324 /// these streams code a 16x8/8x4 transform unit at all -- and the rect
325 /// intra dequant path was reading the FRAME's quantizer index where every
326 /// square path reads the block's segment-adjusted one
327 /// (`SEG_LVL_ALT_Q`, class `parsed-then-discarded`). Every gate size
328 /// before this one was a whole number of superblocks, so no gate ever
329 /// decoded such a unit: the 1920x792 native BD arm's reference-decode
330 /// assertion was red on all four rav1e points and this is its small,
331 /// fast, encoder-independent form.
332 ///
333 /// 384x152 is 2 superblocks + 24 px (the 1920x792 straddle, film A's own
334 /// coded size) and 384x184 is 2 + 56 px (the 1920x1080 straddle), so both
335 /// the "less than half inside" and the "more than half inside" edge
336 /// superblock shapes are covered.
337 #[test]
338 fn a_straddling_frame_decodes_exactly_on_both_reference_encoders_ladders() {
339 const NAME: &str = "a_straddling_frame_decodes_exactly_on_both_reference_encoders_ladders";
340 if !have_ffmpeg() {
341 eprintln!("SKIP {NAME}: no ffmpeg");
342 return;
343 }
344 const FRAMES: usize = 4;
345 let mut checked = 0usize;
346 // The SEGMENTED half of this gate, built BY RECIPE.
347 //
348 // The defect this gate exists for only shows on a stream whose
349 // segments carry distinct `SEG_LVL_ALT_Q`, and neither `testsrc2` nor
350 // the repo's own clip turns activity segmentation on at all (ledger
351 // dead-end: 16 ladder points all pass with the defect still in). The
352 // contrast is therefore built here -- half flat grey, half heavy
353 // noise -- and libaom's `-aq-mode 1` answers it with segments whose
354 // quantizer indices differ; `block_q_span()` asserts exactly that, so
355 // the gate cannot go quietly blind (class `gate-blind-to-feature`).
356 // This replaces two crops of a real film that could never be
357 // committed and so SKIPped on every fresh clone.
358 for (w, h) in [(384usize, 152usize), (384, 184)] {
359 for crf in ["20", "35"] {
360 let half = (w / 2).to_string();
361 let flat = format!("color=c=gray:s={half}x{h}:r=25:d=1");
362 let busy = format!("{flat},noise=alls=80:all_seed=7:allf=t+u");
363 let args: Vec<String> = [
364 "-v",
365 "error",
366 "-f",
367 "lavfi",
368 "-i",
369 &flat,
370 "-f",
371 "lavfi",
372 "-i",
373 &busy,
374 "-filter_complex",
375 "[0:v][1:v]hstack=inputs=2,format=yuv420p",
376 "-frames:v",
377 &FRAMES.to_string(),
378 "-pix_fmt",
379 "yuv420p",
380 "-an",
381 "-threads",
382 "1",
383 "-g",
384 &FRAMES.to_string(),
385 "-c:v",
386 "libaom-av1",
387 "-cpu-used",
388 "6",
389 "-b:v",
390 "0",
391 "-crf",
392 crf,
393 // libaom's activity segmentation, i.e. `SEG_LVL_ALT_Q`.
394 "-aq-mode",
395 "1",
396 "-f",
397 "obu",
398 "-",
399 ]
400 .iter()
401 .map(|s| (*s).to_string())
402 .collect();
403 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
404 .args(&args)
405 .stdin(Stdio::null())
406 .stdout(Stdio::piped())
407 .stderr(Stdio::piped()), None, |c| c.output())
408 .expect("ffmpeg failed to run");
409 if !out.status.success() {
410 eprintln!(
411 "SKIP {NAME}: ffmpeg cannot encode the segmented {w}x{h} recipe ({})",
412 String::from_utf8_lossy(&out.stderr)
413 .lines()
414 .last()
415 .unwrap_or("")
416 );
417 continue;
418 }
419 let stream = out.stdout;
420 let want = ffmpeg_decode_sequence(&stream, w, h, FRAMES);
421 crate::decode::reset_segment_hits();
422 let got = decode_stream(&stream).unwrap_or_else(|e| {
423 panic!("{NAME}: the segmented {w}x{h} crf {crf} recipe refused: {e}")
424 });
425 let (lo, hi) = crate::decode::block_q_span();
426 assert!(
427 hi > lo,
428 "{NAME}: the segmented {w}x{h} crf {crf} recipe dequantized every block \
429 with q {lo} -- no segment carried a distinct SEG_LVL_ALT_Q, so this row \
430 would pass with the rect dequant defect back in ({} segment ids seen)",
431 crate::decode::segment_ids_seen()
432 );
433 assert_eq!(
434 got.len(),
435 want.len(),
436 "{NAME}: segmented {w}x{h} frame count"
437 );
438 for (f, (o, r)) in got.iter().zip(&want).enumerate() {
439 for (plane, a, b) in [("Y", &o.y, &r.y), ("U", &o.u, &r.u), ("V", &o.v, &r.v)] {
440 if let Some(i) = a.iter().zip(b.iter()).position(|(x, y)| x != y) {
441 let stride = if plane == "Y" { w } else { w / 2 };
442 panic!(
443 "{NAME}: segmented {w}x{h} crf {crf}, frame {f} plane {plane} \
444 sample ({}, {}): ours {} vs ffmpeg {} (block q span {lo}..{hi})",
445 i % stride,
446 i / stride,
447 a[i],
448 b[i],
449 );
450 }
451 assert_eq!(
452 a.len(),
453 b.len(),
454 "{NAME}: segmented {w}x{h} crf {crf}, frame {f} plane {plane}: ours \
455 has {} samples, ffmpeg's has {} -- a short plane would \
456 zip-truncate the walk above and hide a chroma-span defect",
457 a.len(),
458 b.len()
459 );
460 }
461 }
462 eprintln!("{NAME}: segmented {w}x{h} crf {crf} exact, block q span {lo}..{hi}");
463 checked += 1;
464 }
465 }
466 for (w, h) in [(384usize, 152usize), (384, 184)] {
467 // The ENCODER-LADDER half: both reference encoders, every
468 // ladder point, on real (non-bars) content. These rows code ONE
469 // segment, so they do not gate `SEG_LVL_ALT_Q` -- that is the
470 // recipe rows' job above -- but they are the rectangular
471 // partition coverage rav1e's straddle answer adds.
472 // lane-av1clipprobe: the one probe. This one is worse than a plain
473 // skip -- it `return`s from the middle of the gate, so everything
474 // asserted above it had already run and the encoder-ladder half
475 // silently never did, leaving a half-executed gate reported green.
476 let Some(clip) =
477 crate::library_fixture::require("video/h264-1080p-23.976-8bit.mp4", NAME)
478 else {
479 return;
480 };
481 for (encoder, points) in [
482 ("librav1e", ["50", "100", "150", "200"]),
483 ("libaom-av1", ["5", "20", "35", "45"]),
484 ] {
485 for point in points {
486 let mut args: Vec<String> =
487 ["-v", "error", "-i", clip.to_str().expect("fixture path")]
488 .iter()
489 .map(|s| (*s).to_string())
490 .collect();
491 args.extend(
492 [
493 "-frames:v",
494 &FRAMES.to_string(),
495 "-vf",
496 &format!("crop={w}:{h}:768:400"),
497 "-pix_fmt",
498 "yuv420p",
499 "-an",
500 ]
501 .iter()
502 .map(|s| (*s).to_string()),
503 );
504 args.extend(
505 ["-threads", "1", "-g", &FRAMES.to_string(), "-c:v", encoder]
506 .iter()
507 .map(|s| (*s).to_string()),
508 );
509 if encoder == "librav1e" {
510 args.push("-rav1e-params".into());
511 args.push(format!(
512 "speed=6:quantizer={point}:tile_cols=1:tile_rows=1:threads=1"
513 ));
514 } else {
515 args.extend(
516 // `-aq-mode 1`: libaom's activity segmentation,
517 // i.e. `SEG_LVL_ALT_Q` -- the feature the rect
518 // dequant path used to drop.
519 [
520 "-cpu-used",
521 "6",
522 "-b:v",
523 "0",
524 "-crf",
525 point,
526 "-aq-mode",
527 "1",
528 ]
529 .iter()
530 .map(|s| (*s).to_string()),
531 );
532 }
533 args.extend(["-f", "obu", "-"].iter().map(|s| (*s).to_string()));
534 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
535 .args(&args)
536 .stdin(Stdio::null())
537 .stdout(Stdio::piped())
538 .stderr(Stdio::piped()), None, |c| c.output())
539 .expect("ffmpeg failed to run");
540 if !out.status.success() {
541 eprintln!(
542 "SKIP {NAME}: ffmpeg cannot encode {w}x{h} with {encoder} ({})",
543 String::from_utf8_lossy(&out.stderr)
544 .lines()
545 .last()
546 .unwrap_or("")
547 );
548 continue;
549 }
550 let stream = out.stdout;
551 let want = ffmpeg_decode_sequence(&stream, w, h, FRAMES);
552 let got = decode_stream(&stream).unwrap_or_else(|e| {
553 panic!("{NAME}: {encoder} {point} at {w}x{h} refused: {e}")
554 });
555 assert_eq!(
556 got.len(),
557 want.len(),
558 "{NAME}: {encoder} {point} at {w}x{h} frame count"
559 );
560 for (f, (o, r)) in got.iter().zip(&want).enumerate() {
561 for (plane, a, b) in
562 [("Y", &o.y, &r.y), ("U", &o.u, &r.u), ("V", &o.v, &r.v)]
563 {
564 if let Some(i) = a.iter().zip(b.iter()).position(|(x, y)| x != y) {
565 let stride = if plane == "Y" { w } else { w / 2 };
566 panic!(
567 "{NAME}: {encoder} {point} at {w}x{h}, frame {f} plane \
568 {plane} sample ({}, {}): ours {} vs ffmpeg {}",
569 i % stride,
570 i / stride,
571 a[i],
572 b[i],
573 );
574 }
575 assert_eq!(
576 a.len(),
577 b.len(),
578 "{NAME}: {encoder} {point} at {w}x{h}, frame {f} plane {plane}: \
579 ours has {} samples, ffmpeg's has {} -- a short plane would \
580 zip-truncate the walk above and hide a chroma-span defect",
581 a.len(),
582 b.len()
583 );
584 }
585 }
586 checked += 1;
587 }
588 }
589 }
590 assert!(
591 checked > 0,
592 "{NAME}: neither reference encoder was available"
593 );
594 eprintln!("{NAME}: {checked} straddling reference points decoded sample-exact");
595 }
596
597 /// lane-seg2: a SEGMENTED key frame that also codes sub-8x8 INTRA leaves.
598 ///
599 /// WHY IT EXISTS: `read_intra_mode_sub8` -- the reader every `BLOCK_4X4`
600 /// split leaf and every 8x4/4x8 leaf goes through -- never called spec
601 /// 5.11.6's `intra_segment_id` at all. On a stream with segmentation on
602 /// it therefore (a) left the block's `segment_id` symbol unread, so the
603 /// tile desynced from the frame's first sub-8x8 partition on, and (b)
604 /// dequantized the leaf with the PREVIOUS block's `SEG_LVL_ALT_Q`.
605 /// Reading it with a hardcoded 1x1 mi footprint was the second half of
606 /// the same defect: an 8x4 leaf left its second mi cell at segment 0,
607 /// which the next block read back as its spatial prediction and CDF row.
608 ///
609 /// RECIPE: flat gray + heavy `noise` (the contrast is what turns libaom's
610 /// activity segmentation on -- a `testsrc2`/bars source codes ONE segment
611 /// and passes with the defect in, ledger dead-end `gate film rows are
612 /// colour bars`), at `-crf 5 -cpu-used 2`, which is the measured corner
613 /// where libaom answers with sub-8x8 intra partitions. Measured on this
614 /// exact stream: red before either half of the fix (134k/134k samples
615 /// off), green with both.
616 #[test]
617 fn a_segmented_key_frame_with_sub_8x8_intra_leaves_decodes_exactly() {
618 const NAME: &str = "a_segmented_key_frame_with_sub_8x8_intra_leaves_decodes_exactly";
619 let _gate_lock = lock_gate_counters();
620 if !have_ffmpeg() {
621 eprintln!("SKIP {NAME}: no ffmpeg");
622 return;
623 }
624 const FRAMES: usize = 4;
625 let (w, h) = (384usize, 152usize);
626 let src = format!("color=c=gray:s={w}x{h}:r=25,noise=alls=80:all_seed=7:allf=t+u");
627 let args: Vec<String> = [
628 "-v",
629 "error",
630 "-f",
631 "lavfi",
632 "-i",
633 &src,
634 "-frames:v",
635 "4",
636 "-pix_fmt",
637 "yuv420p",
638 "-an",
639 "-threads",
640 "1",
641 "-g",
642 "4",
643 "-c:v",
644 "libaom-av1",
645 "-cpu-used",
646 "2",
647 "-b:v",
648 "0",
649 "-crf",
650 "5",
651 "-aq-mode",
652 "1",
653 "-f",
654 "obu",
655 "-",
656 ]
657 .iter()
658 .map(|s| (*s).to_string())
659 .collect();
660 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
661 .args(&args)
662 .stdin(Stdio::null())
663 .stdout(Stdio::piped())
664 .stderr(Stdio::piped()), None, |c| c.output())
665 .expect("ffmpeg failed to run");
666 if !out.status.success() {
667 eprintln!(
668 "SKIP {NAME}: ffmpeg cannot encode with libaom-av1 ({})",
669 String::from_utf8_lossy(&out.stderr)
670 .lines()
671 .last()
672 .unwrap_or("")
673 );
674 return;
675 }
676 let stream = out.stdout;
677 crate::decode::reset_segment_hits();
678 let want = ffmpeg_decode_sequence(&stream, w, h, FRAMES);
679 let got = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: refused: {e}"));
680 assert_eq!(got.len(), want.len(), "{NAME}: frame count");
681 for (f, (o, r)) in got.iter().zip(&want).enumerate() {
682 for (plane, a, b) in [("Y", &o.y, &r.y), ("U", &o.u, &r.u), ("V", &o.v, &r.v)] {
683 if let Some(i) = a.iter().zip(b.iter()).position(|(x, y)| x != y) {
684 let stride = if plane == "Y" { w } else { w / 2 };
685 panic!(
686 "{NAME}: frame {f} plane {plane} sample ({}, {}): ours {} vs ffmpeg {}",
687 i % stride,
688 i / stride,
689 a[i],
690 b[i],
691 );
692 }
693 assert_eq!(
694 a.len(),
695 b.len(),
696 "{NAME}: frame {f} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
697 short plane would zip-truncate the walk above and hide a chroma-span \
698 defect",
699 a.len(),
700 b.len()
701 );
702 }
703 }
704 // The property is asserted, not hoped for: without more than one
705 // segment this row would pass with the defect still in.
706 assert!(
707 crate::decode::segment_ids_seen() >= 2,
708 "{NAME}: vacuous run -- {} distinct segment ids",
709 crate::decode::segment_ids_seen()
710 );
711 eprintln!(
712 "{NAME}: {FRAMES} frames sample-exact, {} segment_id symbols, {} distinct ids",
713 crate::decode::segment_id_hits(),
714 crate::decode::segment_ids_seen()
715 );
716 }
717
718 /// lane-av1leftref: the left chroma reference's `+ss_y` ROW term
719 /// (libaom `av1_common_int.h:1400-1401`, `chroma_left_mi =
720 /// base_mi[ss_y * mi_stride - 1]` -- one mi row DOWN at 4:2:0 and 4:4:0,
721 /// on its own row at 4:2:2 and 4:4:4). This decoder read its own row at
722 /// every subsampling until this lane.
723 ///
724 /// The read is only observable when the two cells hold DIFFERENT blocks --
725 /// a left neighbour at most 1 mi tall (1 mi = 4 luma px, so a 4x4/8x4/16x4
726 /// /32x4/64x4 leaf). lane-av1leftwit measured that shape off a per-cell
727 /// owner stamp instead of the mode value: `uv_left_1mi_split_hits()` counts
728 /// decode-path reads whose two cells were written by DIFFERENT blocks, and
729 /// it is NOT zero -- five committed fixtures carry it (15 reads in all,
730 /// `lanes/av1leftwit.report.md`). What no committed fixture shows is the two
731 /// blocks DISAGREEING on `uv_mode`, which is what `mode_diff`/`smooth_diff`
732 /// below measure. So this gate pins both halves honestly: the arm runs
733 /// thousands of times, the shape it needs is genuinely reached, and the
734 /// term has not yet been seen to change an answer. Its exactness arms are
735 /// what would decide the shipped read if a DIFF bucket ever went non-zero.
736 ///
737 /// A non-zero DIFF bucket is not a failure here -- it is the first stream
738 /// that witnesses the term, and the exactness arms below are what then
739 /// decide whether the shipped read is the one that matches the oracle.
740 #[test]
741 fn a_4to20_key_frame_takes_the_left_chroma_reference_read_its_libaom_row() {
742 const NAME: &str = "a_4to20_key_frame_takes_the_left_chroma_reference_read_its_libaom_row";
743 if !have_ffmpeg() {
744 eprintln!("SKIP {NAME}: no ffmpeg");
745 return;
746 }
747 // 3840x1608 10-bit key frame, the densest 4:2:0 intra leaf mix in the
748 // fixture set and the stream that carries the most `+ss_y` reads.
749 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_kf900.obu");
750 let stream = std::fs::read(&path)
751 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
752 let (width, height) = (3840usize, 1608usize);
753 let before = crate::decode::uv_left_ss_y_reads();
754 let frames = match decode_stream(&stream) {
755 Ok(frames) => frames,
756 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
757 };
758 let reads = crate::decode::uv_left_ss_y_reads() - before;
759 let mode_diff = crate::decode::uv_left_ss_y_mode_diff_hits();
760 let smooth_diff = crate::decode::uv_left_ss_y_smooth_diff_hits();
761 assert!(
762 reads > 1000,
763 "{NAME}: only {reads} chroma edge-filter reads took the `+ss_y` left \
764 reference -- the arm this test pins is barely exercised, so the gate \
765 proves little"
766 );
767 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
768 assert_eq!((frames[0].width, frames[0].height), (width, height));
769 // The term is unreachable on this stream, so luma and BOTH chroma
770 // planes must come out byte-identical to ffmpeg's decode. Luma alone
771 // (what the kf900 gate asserts) would not notice a chroma edge-filter
772 // type moving.
773 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
774 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
775 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
776 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
777 eprintln!(
778 "{NAME}: {reads} left-reference reads, +ss_y changed the mode {mode_diff} \
779 and the smooth boolean {smooth_diff} times, all three planes pixel-exact"
780 );
781 }
782
783 /// lane-av1leftwit: the `+ss_y` term's SHAPE is reachable on the decode
784 /// path, and this is the gate that says so.
785 ///
786 /// lane-av1leftref shipped the left read's `+ss_y` row term with the
787 /// argument that the shape it needs -- a left neighbour at most 1 mi tall,
788 /// so the cell this decoder read and the cell libaom reads belong to
789 /// different blocks -- is "structurally absent, because aomenc never starts
790 /// a block on an odd mi row". Both halves of that are wrong. libaom's
791 /// `PARTITION_HORZ_4` puts its `i == 0` child on the PARENT's own mi row
792 /// (`decode_partition`, `av1/decoder/decodeframe.c`: `mi_row + i * bw / 4`),
793 /// and a 16x16 parent sits on a 4-mi grid, so a 1-mi-tall leaf at an EVEN
794 /// row is what the syntax asks for, not forbids. And the shape is measured
795 /// in the corpus: these two fixtures each present it to a real decode-path
796 /// read.
797 ///
798 /// The counter is `decode::uv_left_1mi_split_hits()`, incremented only
799 /// where `decode_path` is true -- the snapping form every decode call site
800 /// uses -- so the 16x4/4x16 pair witness's counter-only mirror (which
801 /// reads an odd mi row and feeds `RECT4_16_UV_PAIR_FILT_HITS`) cannot
802 /// inflate it. `UV_LEFT_SS_Y_READS` alone would prove nothing: it counts
803 /// every read with a left neighbour, whether or not the two cells differ.
804 ///
805 /// NON-VACUITY: the `uv_owner` stamp the counter turns on was removed for
806 /// one build; both arms fell to 0 and this gate failed on the census
807 /// (report §5), so a decoder that stops recording which block owns a cell
808 /// fails here instead of passing vacuously. It is deliberately NOT a
809 /// mutation of the `+ss_y` term itself: the term's own mutation leaves
810 /// these reads untouched, which is the honest limit of what the fixture
811 /// set can decide (the kf900 gate above owns the exactness side).
812 #[test]
813 fn a_committed_4to20_stream_presents_a_one_mi_left_neighbour_to_a_decode_path_read() {
814 const NAME: &str =
815 "a_committed_4to20_stream_presents_a_one_mi_left_neighbour_to_a_decode_path_read";
816 // (fixture, frames, width, height, measured split-owner reads)
817 let arms: [(&str, usize, usize, usize, usize); 2] = [
818 ("gm_small_side_witness.obu", 33, 1920, 792, 5),
819 ("reelc_sb128_inter_witness.obu", 15, 1920, 792, 7),
820 ];
821 for (fixture, want_frames, width, height, want_split) in arms {
822 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
823 .join("fixtures")
824 .join(fixture);
825 let stream = std::fs::read(&path)
826 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
827 let before_split = crate::decode::uv_left_1mi_split_hits();
828 let before_reads = crate::decode::uv_left_ss_y_reads();
829 let before_mode = crate::decode::uv_left_ss_y_mode_diff_hits();
830 let before_smooth = crate::decode::uv_left_ss_y_smooth_diff_hits();
831 let frames = match decode_stream(&stream) {
832 Ok(frames) => frames,
833 Err(e) => panic!("{NAME}: {fixture} refused: {e}"),
834 };
835 let split = crate::decode::uv_left_1mi_split_hits() - before_split;
836 assert_eq!(frames.len(), want_frames, "{NAME}: {fixture} frame count");
837 assert!(
838 frames
839 .iter()
840 .all(|f| (f.width, f.height) == (width, height)),
841 "{NAME}: {fixture} is not {width}x{height}"
842 );
843 assert_eq!(
844 split, want_split,
845 "{NAME}: {fixture} presented {split} 1-mi-tall left neighbours to \
846 a decode-path read, measured {want_split} -- the census this \
847 gate pins moved"
848 );
849 // Printed, not asserted: `== 0` would pin an accident, and a
850 // non-zero value is the first WITNESS of the term rather than a
851 // failure (that is what the kf900 gate above then decides against
852 // the oracle).
853 eprintln!(
854 "{NAME}: {fixture}: {split} 1-mi-tall left neighbours in \
855 {} decode-path reads, +ss_y changed the mode {} and the smooth \
856 boolean {} times",
857 crate::decode::uv_left_ss_y_reads() - before_reads,
858 crate::decode::uv_left_ss_y_mode_diff_hits() - before_mode,
859 crate::decode::uv_left_ss_y_smooth_diff_hits() - before_smooth,
860 );
861 }
862 }
863
864 /// lane-av1formatsweep: the ODD CODED DIMENSION cell -- a frame whose
865 /// width or height is not a multiple of 8, so the last mode-info column
866 /// and the last chroma plane row/column are PARTIAL (`mi_cols * 8 >
867 /// width`, and at 4:2:0 the chroma plane is `ceil(w/2) x ceil(h/2)`).
868 ///
869 /// Nothing else in this file ever encoded one: every frame size in the
870 /// suite (the `tiny_frame_size_sweep` ladder included -- 8,16,24,32,48,
871 /// 64,72,136,192) is a multiple of 8, so the partial-chroma-plane walk
872 /// had no committed exactness evidence at any depth. The class matters
873 /// for a 4:2:2 lift too: at ss (1,0) the chroma plane is
874 /// `ceil(w/2) x h`, so the partial extent lands on the OTHER axis.
875 ///
876 /// NON-VACUITY: `decode::inter_edge_strip_hits()` (the frame-edge strip
877 /// walk) is asserted to fire, and the even-size control arm is asserted
878 /// to leave it at zero -- measured: 130x122 -> `[0,2,0,4,0,6]`,
879 /// 130x130 -> `[0,3,0,2,24,6]`, 128x96 -> all zero. Without that pair a
880 /// decoder that dropped the partial column entirely would still pass the
881 /// pixel compare (class `gate-blind-to-feature`).
882 ///
883 /// Recipe (deterministic: single pass, single thread, no row-mt):
884 /// `ffmpeg -f lavfi -i testsrc2=size=<W>x<H>:rate=25 -frames:v 4
885 /// -pix_fmt <pix> -f yuv4mpegpipe -` piped to
886 /// `aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20
887 /// --cpu-used=2 --threads=1 --row-mt=0 --lag-in-frames=0
888 /// --kf-max-dist=100 --limit=4 --obu -o - -`, plus
889 /// `--input-bit-depth=N --bit-depth=N` at 10 and 12 bits. The 12-bit arm
890 /// uses the smoothed `mandelbrot` source because a sharp-edged source
891 /// makes aomenc set `allow_screen_content_tools`, which this decoder
892 /// refuses BY NAME at 12 bits (see `a_12bit_screen_content_stream_is_
893 /// refused_by_name`).
894 ///
895 /// NON-VACUITY, RED-BEFORE PROVEN: the mode-info grid's ceil is the
896 /// arithmetic this cell depends on, and mutating it turns every arm red
897 /// -- `ec-av1-syntax`'s `h.mi_cols = 2 * ((h.frame_width + 7) >> 3)`
898 /// floored to `2 * (h.frame_width >> 3)` makes the first arm fail at
899 /// decode-order frame 0, byte 128 (ours 74 vs oracle 170, 11538 bytes
900 /// differ); reverted, the gate is green again. A NEARER mutation,
901 /// flooring `decode::round_ss` from libaom's `ROUND_POWER_OF_TWO`,
902 /// leaves this gate GREEN and is not evidence either way: aomenc rounds
903 /// a 4:2:0 frame's coded size DOWN to even, so no stream this recipe can
904 /// produce codes an odd luma dimension, and the chroma-extent ceil only
905 /// differs from its floor when the luma dimension is itself odd.
906 ///
907 /// Also asserted, so a recipe that silently became even-dimensioned can
908 /// not pass as this cell: the header's `ss (1,1)` and bit depth, the
909 /// partial mode-info grid (`mi*8 > dim`), every frame's chroma plane
910 /// being `ceil(w/2)*ceil(h/2)`, and
911 /// `decode::inter_edge_strip_hits()` non-zero after a per-arm reset --
912 /// measured per arm: `[0,6,0,4,48,12]`, `[0,0,0,4,0,6]`,
913 /// `[0,4,0,10,0,10]`, `[0,4,0,8,0,12]`, `[0,4,0,8,0,8]`,
914 /// `[0,0,0,12,0,14]`, where the even-size control (128x96) reads all
915 /// zeros. Without the counter a decoder that dropped the partial column
916 /// entirely would still pass the pixel compare (class
917 /// `gate-blind-to-feature`).
918 #[test]
919 fn a_real_aomenc_odd_coded_dimension_streams_decode_pixel_exact() {
920 const NAME: &str = "a_real_aomenc_odd_coded_dimension_streams_decode_pixel_exact";
921 let _gate_lock = lock_gate_counters();
922 if !have_ffmpeg() || !have_aomenc() {
923 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
924 return;
925 }
926 // (width, height, pix_fmt, bit_depth, smooth_source)
927 let arms: &[(usize, usize, &str, usize, bool)] = &[
928 (130, 130, "yuv420p", 8, false),
929 (66, 66, "yuv420p", 8, false),
930 (194, 122, "yuv420p", 8, false),
931 (130, 122, "yuv420p", 8, false),
932 (130, 122, "yuv420p10le", 10, false),
933 (130, 122, "yuv420p12le", 12, true),
934 ];
935 let mut odd_arms = 0usize;
936 for &(width, height, pix_fmt, bit_depth, smooth) in arms {
937 let stream = odd_dim_stream(width, height, pix_fmt, bit_depth, smooth);
938 // The header must really carry the odd geometry, or the arm
939 // silently degrades to an even-dimension stream (class
940 // `arrival-not-intent`).
941 let (mi_cols, mi_rows) = odd_dim_header_mi_grid(&stream, NAME, bit_depth);
942 assert!(
943 mi_cols * 8 > width || mi_rows * 8 > height,
944 "{NAME}: {width}x{height} is not an odd coded dimension \
945 (mi grid {mi_cols}x{mi_rows})"
946 );
947 // Reset per attempt, never a delta across arms (class
948 // `counter-from-refused-stream`).
949 crate::decode::reset_inter_edge_strip_hits();
950 let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME);
951 let frames = decode_stream(&stream)
952 .unwrap_or_else(|e| panic!("{NAME}: refused {width}x{height}: {e}"));
953 let chroma = width.div_ceil(2) * height.div_ceil(2);
954 for (i, f) in frames.iter().enumerate() {
955 assert_eq!(f.y.len(), width * height, "{NAME}: frame {i} luma extent");
956 assert_eq!(
957 f.u.len(),
958 chroma,
959 "{NAME}: frame {i} chroma extent -- a {width}x{height} frame's \
960 chroma plane is ceil(w/2)*ceil(h/2) = {chroma}, not w/2*h/2"
961 );
962 }
963 let edge = crate::decode::inter_edge_strip_hits();
964 assert!(
965 edge.iter().any(|&n| n > 0),
966 "{NAME}: {width}x{height} decoded byte-exact but walked NO \
967 frame-edge strip -- the partial-column chroma extent this \
968 cell exists for was never reached (class \
969 `gate-blind-to-feature`): {edge:?}"
970 );
971 eprintln!(
972 "{NAME}: {width}x{height} {pix_fmt}: {frames_decoded} frames \
973 byte-exact vs aomdec, frame-edge walk {edge:?}"
974 );
975 odd_arms += 1;
976 }
977 assert!(odd_arms == arms.len(), "{NAME}: arm loop ended early");
978 }
979
980 /// lane-av1formatsweep: the 4:4:4 x 10-BIT cell. Every committed 4:4:4
981 /// exactness gate in this file is `--lossless=1` at 8 bits
982 /// (`a_real_aomenc_lossless_444_key_frame_decodes_sample_exact`,
983 /// `a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact`,
984 /// `a_lossless_444_defaultp_inter_strip_stream_decodes_byte_exact`, the
985 /// `ll444_*` pins), so the whole committed 4:4:4 evidence base is LOSSLESS
986 /// 8-bit: no 4:4:4 stream above 8 bits had a committed exactness gate.
987 ///
988 /// NON-VACUITY: `decode::rect_split_lossless_chroma444_hits()` -- the
989 /// per-4x4 chroma unit walk a lossless HORZ/VERT strip takes at
990 /// subsampling 0/0 -- is asserted to fire (measured 32 units on this
991 /// recipe), and the sequence header is asserted to say ss (0,0) at
992 /// 10-bit before any pixel is trusted. A 4:2:0 stream of the same
993 /// content leaves that counter at zero, so the pixel compare alone would
994 /// not prove the 4:4:4 chroma path ran (class `gate-blind-to-feature`).
995 ///
996 /// Recipe: `testsrc2 128x96` yuv444p10le 6 frames, `aomenc --codec=av1
997 /// --profile=1 --input-bit-depth=10 --bit-depth=10 --lossless=1
998 /// --enable-palette=0 --enable-intrabc=0 --cq-level=20 --cpu-used=2
999 /// --passes=1 --end-usage=q --threads=1 --row-mt=0 --lag-in-frames=0
1000 /// --kf-max-dist=100 --limit=6 --obu -o - -`.
1001 #[test]
1002 fn a_lossless_444_10bit_inter_stream_decodes_pixel_exact() {
1003 const NAME: &str = "a_lossless_444_10bit_inter_stream_decodes_pixel_exact";
1004 let _gate_lock = lock_gate_counters();
1005 if !have_ffmpeg() || !have_aomenc() {
1006 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
1007 return;
1008 }
1009 let stream = chroma_format_stream(
1010 128,
1011 96,
1012 "yuv444p10le",
1013 10,
1014 6,
1015 &[
1016 "--lossless=1",
1017 "--enable-palette=0",
1018 "--enable-intrabc=0",
1019 // `--cpu-used=2`, NOT 0: at `--cpu-used=0` aomenc reaches
1020 // the 128-root partition (measured `part128: split=1
1021 // none=5` where this recipe reads `none=0`) and THAT stream
1022 // diverges at 10-bit 4:4:4 from frame 1 on -- 11152 of
1023 // 36864 samples, first at Y(8,4), with ffmpeg and aomdec
1024 // agreeing on the reference. Handoff, not this gate's
1025 // subject; see `lanes/av1formatsweep.report.md`.
1026 "--cpu-used=2",
1027 "--cq-level=20",
1028 ],
1029 0,
1030 );
1031 assert_444_header(&stream, NAME, 10);
1032 let before_444 = crate::decode::rect_split_lossless_chroma444_hits();
1033 let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME);
1034 assert!(
1035 crate::decode::rect_split_lossless_chroma444_hits() > before_444,
1036 "{NAME} went blind: no lossless strip walked its chroma as 4:4:4 \
1037 4x4 units"
1038 );
1039 assert!(
1040 frames_decoded >= 6,
1041 "{NAME}: expected the six-frame recipe to decode"
1042 );
1043 eprintln!("{NAME}: {frames_decoded} frames byte-exact vs aomdec at 10-bit 4:4:4");
1044 }
1045
1046 /// lane-av1formatsweep: the 4:4:4 x 12-BIT cell -- the deepest chroma
1047 /// format the spec allows, and the one no committed gate reached. A
1048 /// sharp-edged source makes aomenc set `allow_screen_content_tools`,
1049 /// which this decoder refuses BY NAME at 12 bits (palette and intrabc
1050 /// have no 12-bit witness), so the arm encodes the SMOOTHED
1051 /// `mandelbrot` source -- the same trick `a_real_aomenc_12bit_stream_
1052 /// decodes_pixel_exact`'s in-tree source exists for.
1053 ///
1054 /// NON-VACUITY: the header is asserted to say ss (0,0) at 12 bits,
1055 /// `mc::mc_subpel_hits()` (the 12-bit-sensitive subpel round pair) must
1056 /// fire -- a key-frame-only stream would pass the pixel compare without
1057 /// touching it -- and every decoded frame's chroma plane is asserted to
1058 /// be FULL resolution, which is the 4:4:4 extent itself.
1059 ///
1060 /// Recipe: `mandelbrot 128x96` + `-vf gblur=sigma=6` yuv444p12le 6 frames,
1061 /// `aomenc --codec=av1 --input-bit-depth=12 --bit-depth=12 --passes=1
1062 /// --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 --row-mt=0
1063 /// --lag-in-frames=0 --kf-max-dist=100 --limit=6 --obu -o - -`.
1064 /// aomenc picks `seq_profile=2` here (12-bit forces it) with
1065 /// `subsampling_x/y = 0,0` -- still 4:4:4 planes. lane-av1422lift: 4:2:2
1066 /// (1,0) is DECODED now, so the only subsampling the decoder still asserts
1067 /// against is the uncodable 4:4:0 (0,1) cell, closed by
1068 /// `the_440_cell_is_not_a_codable_chroma_shape`.
1069 #[test]
1070 fn a_444_12bit_inter_sequence_decodes_pixel_exact() {
1071 const NAME: &str = "a_444_12bit_inter_sequence_decodes_pixel_exact";
1072 let _gate_lock = lock_gate_counters();
1073 if !have_ffmpeg() || !have_aomenc() {
1074 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
1075 return;
1076 }
1077 let stream = chroma_format_stream(128, 96, "yuv444p12le", 12, 6, &["--cq-level=20"], 1);
1078 assert_444_header(&stream, NAME, 12);
1079 let before_subpel = crate::mc::mc_subpel_hits();
1080 let frames = decode_stream(&stream)
1081 .unwrap_or_else(|e| panic!("{NAME}: refused a real 12-bit 4:4:4 stream: {e}"));
1082 let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME);
1083 assert!(
1084 crate::mc::mc_subpel_hits() > before_subpel,
1085 "{NAME} went blind: no subpel inter prediction ran, so the \
1086 12-bit round pair is unexercised"
1087 );
1088 // The 4:4:4 chroma EXTENT is the cell's own claim: at ss (0,0) the
1089 // chroma planes are full resolution, so a decoder that kept the
1090 // 4:2:0 extent would produce quarter-size chroma planes and a
1091 // byte-length the oracle cannot even match. (CDEF is NOT asserted
1092 // here: on this smoothed source CDEF runs but skips every band --
1093 // measured `cdef_band: rect_skip_writes=11`, zero index literals --
1094 // so a CDEF assertion would be a claim the witness cannot carry.)
1095 for (i, f) in frames.iter().enumerate() {
1096 assert_eq!(
1097 f.u.len(),
1098 128 * 96,
1099 "{NAME}: frame {i} chroma plane is {} samples -- at 4:4:4 it \
1100 must be full resolution (128x96), not the 4:2:0 quarter",
1101 f.u.len()
1102 );
1103 }
1104 eprintln!("{NAME}: {frames_decoded} frames byte-exact vs aomdec at 12-bit 4:4:4");
1105 }
1106
1107 /// lane-av1tilemeasure: 12-BIT 4:2:0 with tile ROWS genuinely enabled, and
1108 /// with a 2x2 tile grid. `gate_coverage.rs` records that the multi-tile
1109 /// 2D grid is covered "at both bit depths" -- meaning 8 and 10; 12 was the
1110 /// gap, and the sweep's 12-bit "tile rows" cell (t420_12_row) never
1111 /// encoded an untiled control, so nobody could say which stream it had
1112 /// measured.
1113 ///
1114 /// Recipe (per arm): `mandelbrot 256x256` + `-vf gblur=sigma=6`
1115 /// yuv420p12le 6 frames (the 12-bit screen-tools refusal fires on a sharp
1116 /// source -- H6), `aomenc --codec=av1 --passes=1 --end-usage=q
1117 /// --cq-level=20 --cpu-used=2 --enable-palette=0 --enable-intrabc=0
1118 /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=6
1119 /// --input-bit-depth=12 --bit-depth=12 --obu -o - -` plus `--tile-rows=1`
1120 /// (arm 1) or `--tile-columns=1 --tile-rows=1` (arm 2).
1121 ///
1122 /// NON-VACUITY, in the order a reader should check it:
1123 /// 1. the sequence header is `ss (1,1)` at 12 bits
1124 /// (`odd_dim_header_mi_grid`);
1125 /// 2. EVERY frame header's parsed `tile_info` is 1x2 / 2x2 -- the trap-2
1126 /// guard: an untiled stream fails here before a pixel is read;
1127 /// 3. `decode::tile_hits()` advances by at least one hit per tile per
1128 /// frame, so tile 1 (and the second ROW) really decoded rather than the
1129 /// first tile being decoded twice;
1130 /// 4. every decoded plane is 256*256 samples -- a truncated or
1131 /// quarter-extent decode fails the shape assert;
1132 /// 5. `decode_all_frames_vs_oracle` asserts the decode-order frame COUNT
1133 /// and each frame's byte LENGTH against the instrumented `aomdec`
1134 /// before any sample is compared (a prefix compare is not a compare --
1135 /// the same report's trap 1).
1136 #[test]
1137 fn a_real_aomenc_12bit_stream_with_two_tile_rows_and_a_two_by_two_tile_grid_decodes_pixel_exact()
1138 {
1139 const NAME: &str = "a_real_aomenc_12bit_stream_with_two_tile_rows_and_a_two_by_two_tile_grid_decodes_pixel_exact";
1140 let _gate_lock = lock_gate_counters();
1141 if !have_ffmpeg() || !have_aomenc() {
1142 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
1143 return;
1144 }
1145 let arms: [(&str, &[&str], u32, u32); 2] = [
1146 ("two tile rows", &["--tile-rows=1"], 1, 2),
1147 (
1148 "a 2x2 tile grid",
1149 &["--tile-columns=1", "--tile-rows=1"],
1150 2,
1151 2,
1152 ),
1153 ];
1154 for (label, tiles, want_cols, want_rows) in arms {
1155 let mut extra = vec![
1156 "--cq-level=20",
1157 "--cpu-used=2",
1158 "--enable-palette=0",
1159 "--enable-intrabc=0",
1160 ];
1161 extra.extend_from_slice(tiles);
1162 let stream = chroma_format_stream(256, 256, "yuv420p12le", 12, 6, &extra, 1);
1163 odd_dim_header_mi_grid(&stream, NAME, 12);
1164 let facts = frame_facts(&stream, NAME);
1165 assert_eq!(
1166 facts.len(),
1167 6,
1168 "{NAME} ({label}): expected six frame headers, parsed {}",
1169 facts.len()
1170 );
1171 for (i, f) in facts.iter().enumerate() {
1172 assert_eq!(
1173 (f.tile_cols, f.tile_rows),
1174 (want_cols, want_rows),
1175 "{NAME} ({label}): decode-order frame {i} parses tile_info {}x{}, not \
1176 {want_cols}x{want_rows} -- the aomenc tile flag was a NO-OP at this \
1177 geometry, so this arm would be measuring an untiled stream",
1178 f.tile_cols,
1179 f.tile_rows
1180 );
1181 }
1182 let before_tiles = crate::decode::tile_hits();
1183 let frames = decode_stream(&stream)
1184 .unwrap_or_else(|e| panic!("{NAME} ({label}): refused the stream: {e}"));
1185 let tile_hits = crate::decode::tile_hits() - before_tiles;
1186 assert!(
1187 tile_hits >= facts.len() * (want_cols * want_rows) as usize,
1188 "{NAME} ({label}): tile_hits advanced by {tile_hits} over {} frames of a \
1189 {}x{} grid -- not every tile decoded",
1190 facts.len(),
1191 want_cols,
1192 want_rows
1193 );
1194 for (i, f) in frames.iter().enumerate() {
1195 assert_eq!(
1196 f.y.len(),
1197 256 * 256,
1198 "{NAME} ({label}): frame {i} luma plane is {} samples, not 256x256",
1199 f.y.len()
1200 );
1201 }
1202 let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME);
1203 assert!(
1204 frames_decoded >= 6,
1205 "{NAME} ({label}): {frames_decoded} decode-order frames"
1206 );
1207 eprintln!(
1208 "{NAME} ({label}): {frames_decoded} frames byte-exact vs aomdec, tiles \
1209 {want_cols}x{want_rows} confirmed on every frame header, tile_hits {tile_hits}"
1210 );
1211 }
1212 }
1213
1214 /// lane-av1tilemeasure: 4:4:4 SUPERRES at 8, 10 and 12 bits. The sweep's
1215 /// superres row was `--superres-mode=1` alone, and measured that recipe
1216 /// at 4:4:4 8 bits: this lane re-encoded it and read `use_superres` on
1217 /// every frame header -- ZERO frames carried it, so that cell never
1218 /// exercised the upscaler at all (the same "an aomenc flag is not
1219 /// evidence" trap as tile rows, one axis over). libaom only signals
1220 /// `use_superres` when a DENOMINATOR is given, so the arms here spell
1221 /// `--superres-denominator=12 --superres-kf-denominator=12` and the
1222 /// header says `use_superres=1` on all four frames.
1223 ///
1224 /// Recipe: `testsrc2 128x128` yuv444p10le (12-bit: the gblur'd
1225 /// `mandelbrot`, H6) 4 frames, `aomenc --codec=av1 --passes=1
1226 /// --end-usage=q --cq-level=20 --cpu-used=2 --enable-palette=0
1227 /// --enable-intrabc=0 --superres-mode=1 --superres-denominator=12
1228 /// --superres-kf-denominator=12 --threads=1 --row-mt=0 --lag-in-frames=0
1229 /// --kf-max-dist=100 --limit=4 --input-bit-depth=N --bit-depth=N --obu
1230 /// -o - -`. Coded width comes out 85px, upscaled to 128.
1231 ///
1232 /// NON-VACUITY: `ss (0,0)` at the claimed depth; EVERY frame header has
1233 /// `use_superres` with a coded width strictly below the upscaled one (a
1234 /// stream without it fails here, not at the pixel compare);
1235 /// `superres::superres_hits()` advances once per frame (the upscaler
1236 /// really ran); every decoded plane is the UPSCALED 128x128 -- a decoder
1237 /// that forgot the upsample would hand back 85x128 and fail the shape
1238 /// assert, and at `ss (0,0)` the chroma planes must be full resolution
1239 /// too; then the length-asserting `aomdec` compare.
1240 #[test]
1241 fn a_real_aomenc_444_superres_stream_at_8_10_and_12_bit_decodes_pixel_exact() {
1242 const NAME: &str =
1243 "a_real_aomenc_444_superres_stream_at_8_10_and_12_bit_decodes_pixel_exact";
1244 let _gate_lock = lock_gate_counters();
1245 if !have_ffmpeg() || !have_aomenc() {
1246 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
1247 return;
1248 }
1249 for (depth, pix_fmt, smooth) in [
1250 (8usize, "yuv444p", 0u8),
1251 (10, "yuv444p10le", 0),
1252 (12, "yuv444p12le", 1),
1253 ] {
1254 let stream = chroma_format_stream(
1255 128,
1256 128,
1257 pix_fmt,
1258 depth,
1259 4,
1260 &[
1261 "--cq-level=20",
1262 "--cpu-used=2",
1263 "--enable-palette=0",
1264 "--enable-intrabc=0",
1265 "--superres-mode=1",
1266 "--superres-denominator=12",
1267 "--superres-kf-denominator=12",
1268 ],
1269 smooth,
1270 );
1271 assert_444_header(&stream, NAME, depth);
1272 let facts = frame_facts(&stream, NAME);
1273 for (i, f) in facts.iter().enumerate() {
1274 assert!(
1275 f.use_superres,
1276 "{NAME} ({depth}-bit): decode-order frame {i} has use_superres=0 -- the \
1277 superres cell would be measuring an ordinary 4:4:4 stream"
1278 );
1279 assert!(
1280 f.coded_w < f.upscaled_w,
1281 "{NAME} ({depth}-bit): frame {i} codes {}px and upscaled_width says {}px",
1282 f.coded_w,
1283 f.upscaled_w
1284 );
1285 assert_eq!(f.upscaled_w, 128, "{NAME} ({depth}-bit): upscaled width");
1286 }
1287 let before_sr = crate::superres::superres_hits();
1288 let frames = decode_stream(&stream)
1289 .unwrap_or_else(|e| panic!("{NAME} ({depth}-bit): refused the stream: {e}"));
1290 let superres_hits = crate::superres::superres_hits() - before_sr;
1291 assert!(
1292 superres_hits >= facts.len(),
1293 "{NAME} ({depth}-bit): superres_hits advanced by {superres_hits} over {} \
1294 frames -- the upscaler never ran",
1295 facts.len()
1296 );
1297 for (i, f) in frames.iter().enumerate() {
1298 assert_eq!(
1299 f.y.len(),
1300 128 * 128,
1301 "{NAME} ({depth}-bit): frame {i} luma is {} samples -- a superres decode \
1302 must hand back the UPSCALED 128x128, not the 85px coded width",
1303 f.y.len()
1304 );
1305 assert_eq!(
1306 f.u.len(),
1307 128 * 128,
1308 "{NAME} ({depth}-bit): frame {i} chroma is {} samples -- at 4:4:4 the chroma \
1309 plane is full resolution at the upscaled size",
1310 f.u.len()
1311 );
1312 }
1313 let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME);
1314 assert!(
1315 frames_decoded >= 4,
1316 "{NAME} ({depth}-bit): {frames_decoded} decode-order frames"
1317 );
1318 eprintln!(
1319 "{NAME} ({depth}-bit): {frames_decoded} frames byte-exact vs aomdec, \
1320 use_superres on every frame, superres_hits {superres_hits}"
1321 );
1322 }
1323 }
1324
1325 /// lane-av1tilemeasure: 4:4:4 at PARTIAL and ODD coded dimensions,
1326 /// 8/10/12 bits -- and a correction to what the sweep's "odd dims" cell
1327 /// was measuring.
1328 ///
1329 /// **The sweep's odd-dimension 4:4:4 cells were not odd.** 66x66,
1330 /// 130x122 and 194x130 are even in BOTH axes; what they are is "not a
1331 /// multiple of 8", the same class as the 4:2:0 row the sweep measured as
1332 /// "even, not a multiple of 8". This gate's own assert said so out loud
1333 /// on its first run: `the 66x66 arm is even in BOTH axes`. The genuinely
1334 /// odd arms are the two 12-bit ones, and they are producible only at 12
1335 /// bits: at 8 and 10 bits aomenc rounds a 4:4:4 odd size DOWN to even
1336 /// (`67x67` -> coded 66x66, `131x131` -> coded 130x130, both measured),
1337 /// the same rounding the sweep proved for 4:2:0. 12-bit (seq_profile 2)
1338 /// keeps 67x67 and 65x67 odd, and both decode byte-exact.
1339 ///
1340 /// The sweep's 130x122 DIVERGENT verdict is also corrected here: this
1341 /// lane re-encoded the identical stream (the bytes reproduce the
1342 /// sweep's sha256 `c87ac65b…`) and it is byte-exact against `aomdec`.
1343 /// That published verdict came from the prefix compare the same report
1344 /// documents as its trap 1.
1345 ///
1346 /// Recipe per arm: `testsrc2 WxH` yuv444p[10le|12le] 4 frames (12-bit:
1347 /// the gblur'd `mandelbrot`, H6), `aomenc --codec=av1 --passes=1
1348 /// --end-usage=q --cq-level=20 --cpu-used=2 --enable-palette=0
1349 /// --enable-intrabc=0 --threads=1 --row-mt=0 --lag-in-frames=0
1350 /// --kf-max-dist=100 --limit=4 --obu -o - -` (plus `--input-bit-depth` /
1351 /// `--bit-depth` above 8).
1352 ///
1353 /// NON-VACUITY: `ss (0,0)` at the claimed depth; the arm is not a
1354 /// multiple of 8 in some axis, and the `odd` flag says whether an axis is
1355 /// odd, so an arm cannot quietly become the cell next door; EVERY frame
1356 /// header's coded width and height are exactly the claimed sizes -- a
1357 ///omenc rounding would make the arm measure a different geometry and fails
1358 /// here rather than at the pixel compare; the mode-info grid is PARTIAL
1359 /// (`mi_cols*8 > width` or `mi_rows*8 > height`), the partial-plane walk
1360 /// the cell exists for; every decoded plane is exactly `width*height` (at
1361 /// `ss (0,0)` the chroma planes are full resolution, so a 4:2:0 extent or
1362 /// a truncated decode fails the shape assert); then the
1363 /// length-asserting `aomdec` compare.
1364 #[test]
1365 fn a_real_aomenc_444_partial_and_odd_coded_dimension_streams_decode_pixel_exact() {
1366 const NAME: &str =
1367 "a_real_aomenc_444_partial_and_odd_coded_dimension_streams_decode_pixel_exact";
1368 let _gate_lock = lock_gate_counters();
1369 if !have_ffmpeg() || !have_aomenc() {
1370 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
1371 return;
1372 }
1373 // (width, height, bit depth, smooth source, an axis is odd)
1374 let arms: [(usize, usize, usize, u8, bool); 10] = [
1375 (66, 66, 8, 0, false),
1376 (98, 66, 8, 0, false),
1377 (130, 122, 8, 0, false),
1378 (66, 66, 10, 0, false),
1379 (194, 130, 10, 0, false),
1380 (130, 122, 10, 0, false),
1381 (66, 66, 12, 1, false),
1382 (130, 122, 12, 1, false),
1383 (67, 67, 12, 1, true),
1384 (65, 67, 12, 1, true),
1385 ];
1386 for (w, h, depth, smooth, odd) in arms {
1387 assert!(
1388 w % 8 != 0 || h % 8 != 0,
1389 "{NAME}: the {w}x{h} arm is a multiple of 8 -- it is not a partial-size cell"
1390 );
1391 assert_eq!(
1392 w % 2 == 1 || h % 2 == 1,
1393 odd,
1394 "{NAME}: the {w}x{h} arm's `odd` flag is wrong"
1395 );
1396 let pix_fmt = match depth {
1397 8 => "yuv444p",
1398 10 => "yuv444p10le",
1399 _ => "yuv444p12le",
1400 };
1401 let stream = chroma_format_stream(
1402 w,
1403 h,
1404 pix_fmt,
1405 depth,
1406 4,
1407 &[
1408 "--cq-level=20",
1409 "--cpu-used=2",
1410 "--enable-palette=0",
1411 "--enable-intrabc=0",
1412 ],
1413 smooth,
1414 );
1415 assert_444_header(&stream, NAME, depth);
1416 let facts = frame_facts(&stream, NAME);
1417 for (i, f) in facts.iter().enumerate() {
1418 assert_eq!(
1419 (f.coded_w as usize, f.coded_h as usize),
1420 (w, h),
1421 "{NAME} ({w}x{h} {depth}-bit): decode-order frame {i} codes {}x{} -- the arm \
1422 is not measuring the geometry it names",
1423 f.coded_w,
1424 f.coded_h
1425 );
1426 assert!(
1427 f.mi_cols as usize * 8 > w || f.mi_rows as usize * 8 > h,
1428 "{NAME} ({w}x{h} {depth}-bit): frame {i} has a {}x{} mode-info grid, which \
1429 covers the frame exactly -- the partial-plane walk never runs",
1430 f.mi_cols,
1431 f.mi_rows
1432 );
1433 }
1434 let frames = decode_stream(&stream)
1435 .unwrap_or_else(|e| panic!("{NAME} ({w}x{h} {depth}-bit): refused: {e}"));
1436 for (i, f) in frames.iter().enumerate() {
1437 assert_eq!(
1438 f.y.len(),
1439 w * h,
1440 "{NAME} ({w}x{h} {depth}-bit): frame {i} luma is {} samples",
1441 f.y.len()
1442 );
1443 assert_eq!(
1444 f.u.len(),
1445 w * h,
1446 "{NAME} ({w}x{h} {depth}-bit): frame {i} chroma is {} samples -- at 4:4:4 \
1447 the chroma plane is full resolution even at an odd coded size",
1448 f.u.len()
1449 );
1450 }
1451 let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME);
1452 assert!(
1453 frames_decoded >= 4,
1454 "{NAME} ({w}x{h} {depth}-bit): {frames_decoded} decode-order frames"
1455 );
1456 eprintln!(
1457 "{NAME}: {w}x{h} {depth}-bit codes exactly as named (odd axis: {odd}), \
1458 {frames_decoded} frames byte-exact vs aomdec"
1459 );
1460 }
1461 }
1462
1463 /// lane-av1tilemeasure: the H3 CONTROL -- 4:4:4 LOSSLESS 8-bit with NO
1464 /// tiles -- beside its two-tile-column sibling at the same geometry. The
1465 /// sweep's H3 named a 90-chroma-sample divergence on a lossless 4:4:4
1466 /// tile-column stream; the control it never encoded is the untiled stream
1467 /// at the same size, and without it "tiles cause it" and "4:4:4 lossless
1468 /// chroma causes it" are the same sentence. Measured here: BOTH arms are
1469 /// byte-exact against the oracle at 256x128, so at THIS geometry the
1470 /// defect does not reproduce with or without tiles; the first 4:4:4
1471 /// lossless fork measured in this lane is at 192x192 (34 chroma samples,
1472 /// first U(90,25)), where the tiled and untiled streams diverge at the
1473 /// very same sample -- see `lanes/av1tilemeasure.report.md`.
1474 ///
1475 /// Recipe per arm: `testsrc2 256x128` yuv444p 6 frames, `aomenc
1476 /// --codec=av1 --lossless=1 --passes=1 --end-usage=q --threads=1
1477 /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=6
1478 /// --enable-palette=0 --enable-intrabc=0 --obu -o - -`, plus
1479 /// `--tile-columns=1` on the sibling.
1480 ///
1481 /// NON-VACUITY: `ss (0,0)` at 8 bits; every frame header's parsed
1482 /// `tile_info` is 1x1 for the control and 2x1 for the sibling (so the
1483 /// control cannot silently become a tiled stream, which is the whole
1484 /// point of the arm); `decode::rect_split_lossless_chroma444_hits()`
1485 /// advances, i.e. a lossless strip really walked its chroma as 4:4:4 4x4
1486 /// units; then the length-asserting `aomdec` compare.
1487 #[test]
1488 fn a_lossless_444_8bit_untiled_control_and_its_two_tile_column_sibling_decode_pixel_exact() {
1489 const NAME: &str = "a_lossless_444_8bit_untiled_control_and_its_two_tile_column_sibling_decode_pixel_exact";
1490 let _gate_lock = lock_gate_counters();
1491 if !have_ffmpeg() || !have_aomenc() {
1492 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
1493 return;
1494 }
1495 let arms: [(&str, &[&str], u32, u32); 2] = [
1496 (
1497 "untiled control",
1498 &["--lossless=1", "--enable-palette=0", "--enable-intrabc=0"],
1499 1,
1500 1,
1501 ),
1502 (
1503 "two tile columns",
1504 &[
1505 "--lossless=1",
1506 "--enable-palette=0",
1507 "--enable-intrabc=0",
1508 "--tile-columns=1",
1509 ],
1510 2,
1511 1,
1512 ),
1513 ];
1514 for (label, flags, want_cols, want_rows) in arms {
1515 let stream = chroma_format_stream(256, 128, "yuv444p", 8, 6, flags, 0);
1516 assert_444_header(&stream, NAME, 8);
1517 let facts = frame_facts(&stream, NAME);
1518 for (i, f) in facts.iter().enumerate() {
1519 assert_eq!(
1520 (f.tile_cols, f.tile_rows),
1521 (want_cols, want_rows),
1522 "{NAME} ({label}): decode-order frame {i} parses tile_info {}x{}, not \
1523 {want_cols}x{want_rows}",
1524 f.tile_cols,
1525 f.tile_rows
1526 );
1527 }
1528 let before_444 = crate::decode::rect_split_lossless_chroma444_hits();
1529 let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME);
1530 assert!(
1531 crate::decode::rect_split_lossless_chroma444_hits() > before_444,
1532 "{NAME} ({label}) went blind: no lossless strip walked its chroma as 4:4:4 4x4 \
1533 units, so the cell never reached the 4:4:4 chroma path"
1534 );
1535 assert!(
1536 frames_decoded >= 6,
1537 "{NAME} ({label}): {frames_decoded} decode-order frames"
1538 );
1539 eprintln!(
1540 "{NAME} ({label}): {frames_decoded} frames byte-exact vs aomdec, tiles \
1541 {want_cols}x{want_rows} confirmed on every frame header"
1542 );
1543 }
1544 }
1545
1546 /// lane-av1loss444kf: the 4:4:4 lossless 256x256 key frame's 49-sample
1547 /// chroma damage, and the `Reach` a transform unit inside a sub-8x8 RECT
1548 /// leaf must be given.
1549 ///
1550 /// The cell: `testsrc2 256x256 rate=25` yuv444p, 6 frames,
1551 /// `aomenc --lossless=1 --enable-palette=0 --enable-intrabc=0` -- **109215
1552 /// bytes, sha256 `4563a01f1778600020ffa9f15bc05f5559321cf5712b99a29ed7192675dee6a4`,
1553 /// fnv1a64 `0xbbb56442f393a9b2`**. Its key frame decodes with **21 U + 28 V
1554 /// samples wrong** (U over x 196..207 / y 200..203, V over x 196..206),
1555 /// luma exact, entropy bit-locked over all 81933 of its symbol reads and
1556 /// its 12288 transform units at identical absolute `(plane, x, y)`.
1557 ///
1558 /// The defect: libaom's `has_bottom_left` (`reconintra.c:381`) is asked
1559 /// with the **leaf's** `bsize`, the unit's `(row_off, col_off)` and
1560 /// `tx_size` -- and its first branch inside the left column is
1561 /// `if (row_off + bottom_left_count_unit < plane_bh_unit) return 1;`, the
1562 /// block's OWN next row, already reconstructed. A 4x8 leaf's first TX_4X4
1563 /// unit therefore HAS four bottom-left samples. `sub8_leaf_chroma444`
1564 /// instead looked a standalone `BLOCK_4X4` up at the unit's own position
1565 /// (`Reach::of(4, upx, upy, ..)`), which answers false there, so
1566 /// [`PlaneBuf::edges`] replicated the last left sample out to the edge's
1567 /// full `bw + bh` reach and the unit predicted D203/CFL from a fabricated
1568 /// edge. The 4:2:2 twin of the same function was fixed this way already
1569 /// (lane-av1-422kf2, whose comment names the old lookup); this is its
1570 /// 4:4:4 twin, still carrying the stale copy.
1571 ///
1572 /// Non-vacuity, in order:
1573 /// 1. the live re-encode's length AND fnv1a64 -- a recipe or encoder drift
1574 /// fails here instead of passing as this cell;
1575 /// 2. [`assert_444_header`] -- at 4:2:0 the arm is unreachable (every
1576 /// caller of `sub8_leaf_chroma444` sits behind `chroma_444`) and every
1577 /// assert below would pass for free;
1578 /// 3. [`key_frame_diffs`] == 0 samples, with the first differing sample
1579 /// NAMED in the failure so a regression is a location, not a count;
1580 /// 4. [`crate::decode::sub8_chroma444_lossless_tu_reach_hits`] rose over
1581 /// the decode -- the units where the block-relative answer and the
1582 /// standalone one disagree, which is what makes this a witness of the
1583 /// FIXED path and not of a stream that merely has rect leaves.
1584 #[test]
1585 fn a_lossless_444_sub8_rect_leaf_chroma_reach_decodes_the_key_frame_pixel_exact() {
1586 const NAME: &str = "lossless-444-sub8-rect-leaf-chroma-reach";
1587 let _gate_lock = lock_gate_counters();
1588 if !have_ffmpeg() || !have_aomenc() {
1589 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
1590 return;
1591 }
1592 let stream = chroma_format_stream(
1593 256,
1594 256,
1595 "yuv444p",
1596 8,
1597 6,
1598 &["--lossless=1", "--enable-palette=0", "--enable-intrabc=0"],
1599 0,
1600 );
1601 assert_eq!(
1602 (stream.len(), fnv1a64(&stream)),
1603 (109215, 0xbbb5_6442_f393_a9b2),
1604 "{NAME}: the pinned 4:4:4 lossless 256x256 cell is {} bytes / fnv1a64 {:#x}, \
1605 not 109215 / 0xbbb56442f393a9b2 -- the recipe or the encoder drifted, so a \
1606 result here is not a result about this cell",
1607 stream.len(),
1608 fnv1a64(&stream)
1609 );
1610 assert_444_header(&stream, NAME, 8);
1611 crate::decode::reset_sub8_chroma444_tu_reach_hits();
1612 let (differing, first) = key_frame_diffs(&stream, NAME);
1613 assert_eq!(
1614 differing, 0,
1615 "{NAME}: the 4:4:4 lossless key frame differs from aomdec in {differing} samples \
1616 (first {first:?} as (plane, x, y, ours, oracle)) -- a sub-8x8 RECT leaf's chroma \
1617 unit must be given the reach libaom's has_bottom_left computes for the LEAF, not a \
1618 standalone BLOCK_4X4 lookup at the unit's own position"
1619 );
1620 let reach_hits = crate::decode::sub8_chroma444_lossless_tu_reach_hits();
1621 assert!(
1622 reach_hits > 0,
1623 "{NAME}: went blind -- not one 4:4:4 lossless rect-leaf chroma unit had the \
1624 block-relative reach disagree with the standalone BLOCK_4X4 lookup, so the cell \
1625 never reached the fixed path and the byte-exactness above proves nothing about it"
1626 );
1627 eprintln!(
1628 "{NAME}: key frame byte-exact vs aomdec (0 of 196608 samples differ), {reach_hits} \
1629 rect-leaf chroma unit(s) took the block-relative reach"
1630 );
1631 }
1632
1633 /// lane-av1distwtd: the gate that pays the `enable-dist-wtd-comp` entry in
1634 /// `gate_coverage.rs`'s [`NEVER_EXERCISED_8BIT`], and corrects its stated
1635 /// reason. The entry said "distance-weighted compound is unimplemented" --
1636 /// it is NOT: [`crate::compound::dist_wtd_comp_weight_assign`] (lane-av1comp)
1637 /// and `mc::combine_compound`'s weighted path have been in the tree since.
1638 /// What was missing is a stream that CARRIES the tool. Proved producible
1639 /// against aom 3.13.3: the flag maps onto the sequence header's
1640 /// `enable_jnt_comp` bit (`av1_cx_iface.c:1062` ->
1641 /// `order_hint_info.enable_dist_wtd_comp` -> `bitstream.c:2681` writes it
1642 /// under `enable_order_hint`), and this recipe's parsed header prints
1643 /// `jnt_comp=true` with `=1` and `jnt_comp=false` with `=0` -- the parsed
1644 /// value is asserted, never the flag spelling, per the class
1645 /// `knob-never-reached-the-tool` trap that mislabelled a cell once already.
1646 ///
1647 /// Three hard asserts, all load-bearing:
1648 /// 1. the PARSED sequence header carries `enable_jnt_comp == true` (the
1649 /// off-arm asserts `false` from the same recipe, so the bit is proven to
1650 /// MOVE with the flag rather than to be set by something else);
1651 /// 2. `dist_wtd_comp_hits() > 0` -- the `compound_idx == 0` arm, the only
1652 /// branch whose blend weights are not the constant (8, 8). A stream
1653 /// carrying the header bit while coding every compound block with
1654 /// `compound_idx == 1` leaves this at 0 and decodes byte-identically
1655 /// without the whole distance-weight path, so the counter -- not the
1656 /// header bit -- is what makes this a witness of the TOOL;
1657 /// 3. every frame pixel-compared against the oracle through
1658 /// [`decode_all_frames_vs_oracle`], which length-asserts each
1659 /// decode-order frame before zipping.
1660 ///
1661 /// `--min-partition-size=32` is what makes the arm fire: at 16 the encoder
1662 /// emits 8x8 inter leaves this decoder refuses BY NAME, so a smaller
1663 /// min-partition refuses before the `compound_idx` read ever runs (measured:
1664 /// the `min=16` arm of the same recipe refuses with "an inter partition
1665 /// below 16x16" and dumps zero `compound_idx` lines). `--cq-level=30` is
1666 /// likewise load-bearing: at cq 45/55 the same arm encodes a single-ref
1667 /// stream (zero `compound_idx` reads) and the counter assert would be
1668 /// vacuous.
1669 #[test]
1670 fn a_distance_weighted_compound_stream_decodes_pixel_exact() {
1671 const NAME: &str = "distwtd-comp";
1672 let _gate_lock = lock_gate_counters();
1673 if !have_aomenc() {
1674 return;
1675 }
1676 assert!(have_ffmpeg(), "{NAME}: ffmpeg required");
1677 assert!(
1678 aomdec_path().is_file(),
1679 "{NAME}: aomenc resolved to {} but no aomdec sits beside it -- a \
1680 pixel-exactness gate that compares nothing is worse than no gate",
1681 aomenc_path().display()
1682 );
1683 let (width, height, frame_count) = (64usize, 64usize, 24usize);
1684 // mandelbrot + a slow rotation: two genuinely different references at
1685 // different temporal distances, which is what `dist_wtd_comp_weight_
1686 // assign` weights BY. A static or flat source has equal distances
1687 // everywhere and every block collapses onto one weight row.
1688 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1689 .args([
1690 "-v",
1691 "error",
1692 "-f",
1693 "lavfi",
1694 "-i",
1695 "mandelbrot=size=128x128:rate=25:start_x=-0.6:start_y=-0.4,\
1696 rotate=a=0.01*n:ow=128:oh=128:c=black,scale=64:64",
1697 "-t",
1698 "0.96",
1699 "-pix_fmt",
1700 "yuv420p",
1701 "-strict",
1702 "-1",
1703 "-f",
1704 "yuv4mpegpipe",
1705 "-",
1706 ])
1707 .stdin(Stdio::null())
1708 .stdout(Stdio::piped())
1709 .stderr(Stdio::piped()), None, |c| c.output())
1710 .expect("ffmpeg failed to run");
1711 assert!(
1712 y4m.status.success(),
1713 "{NAME}: ffmpeg fixture: {}",
1714 String::from_utf8_lossy(&y4m.stderr)
1715 );
1716 // the shared recipe; the flag under test is appended per arm so the
1717 // two arms differ in exactly one argument.
1718 let recipe: Vec<&str> = vec![
1719 "--codec=av1",
1720 "--passes=1",
1721 "--end-usage=q",
1722 "--cq-level=30",
1723 "--cpu-used=0",
1724 "--kf-max-dist=1000",
1725 "--threads=1",
1726 "--row-mt=0",
1727 "--auto-alt-ref=1",
1728 "--lag-in-frames=25",
1729 "--enable-fwd-kf=0",
1730 // `enable_jnt_comp` is only READ when order hints are on
1731 // (`av1_cx_iface.c:1491` ANDs the two).
1732 "--enable-order-hint=1",
1733 "--enable-warped-motion=1",
1734 "--tune-content=default",
1735 "--min-partition-size=32",
1736 "--max-partition-size=64",
1737 // partition/intra tools this decoder does not code -- the same
1738 // exclusion list every compound gate in this file carries.
1739 "--enable-rect-partitions=0",
1740 "--enable-ab-partitions=0",
1741 "--enable-1to4-partitions=0",
1742 "--enable-filter-intra=0",
1743 "--enable-smooth-intra=0",
1744 "--enable-paeth-intra=0",
1745 "--enable-directional-intra=0",
1746 "--enable-angle-delta=0",
1747 "--enable-tx-size-search=0",
1748 "--enable-cdef=0",
1749 "--enable-restoration=0",
1750 "--enable-palette=0",
1751 "--enable-intrabc=0",
1752 "--enable-cfl-intra=0",
1753 "--enable-ref-frame-mvs=0",
1754 ];
1755 let encode = |flag: &str| -> Vec<u8> {
1756 let out = run_with_stdin(
1757 Command::new(aomenc_path()).args(
1758 recipe
1759 .iter()
1760 .copied()
1761 .chain([flag, "--obu", "-o", "-", "-"]),
1762 ),
1763 &y4m.stdout,
1764 );
1765 assert!(
1766 out.status.success(),
1767 "{NAME}: aomenc refused the fixture with {flag}: {}",
1768 String::from_utf8_lossy(&out.stderr)
1769 );
1770 out.stdout
1771 };
1772 // The PARSED header, read back off the encoded bytes -- never the
1773 // command line. `Av1Parser` walks the real OBUs, so a flag the encoder
1774 // ignored is caught here rather than inherited into coverage.
1775 let parsed_jnt_comp = |stream: &[u8]| -> bool {
1776 let mut parser = Av1Parser::new();
1777 let mut pos = 0usize;
1778 while pos < stream.len() {
1779 let obu = parser
1780 .parse_obu(&stream[pos..])
1781 .expect("parsing our own OBUs");
1782 pos += obu.total_size;
1783 }
1784 parser
1785 .sequence_header()
1786 .expect("the stream carries a sequence header")
1787 .enable_jnt_comp
1788 };
1789 // NB: the OFF arm is spelled FIRST on purpose. `gate_coverage.rs`'s
1790 // `flags_in` keeps the LAST `--enable-<tool>=<value>` it finds in a gate
1791 // body, so a trailing `=0` would make the whole gate read as "tool
1792 // disabled" to the census and leave the entry unretired even though
1793 // this gate does exercise the tool. Both arms are still asserted below.
1794 let off = encode("--enable-dist-wtd-comp=0");
1795 let on = encode("--enable-dist-wtd-comp=1");
1796 // the bit MOVES with the flag, and it moves the BYTES: a flag the
1797 // encoder accepted but ignored would fail both of these.
1798 assert!(
1799 parsed_jnt_comp(&on),
1800 "{NAME}: the recipe spelled --enable-dist-wtd-comp=1 but the PARSED \
1801 sequence header carries enable_jnt_comp == false (class \
1802 knob-never-reached-the-tool) -- the gate would be vacuous"
1803 );
1804 assert!(
1805 !parsed_jnt_comp(&off),
1806 "{NAME}: the same recipe with --enable-dist-wtd-comp=0 still parses \
1807 enable_jnt_comp == true, so the ON arm proves nothing about the flag"
1808 );
1809 assert_ne!(
1810 on.len(),
1811 off.len(),
1812 "{NAME}: both arms encoded {} bytes -- the flag changed nothing on \
1813 the wire, so neither arm is evidence for anything",
1814 on.len()
1815 );
1816 // shape non-vacuity, before any compare: at 4:2:0 a decoder keeping a
1817 // subsampled extent would hand quarter-size planes to the byte compare.
1818 let frames = decode_stream(&on).unwrap_or_else(|e| panic!("{NAME}: refused: {e}"));
1819 assert_eq!(
1820 frames.len(),
1821 frame_count,
1822 "{NAME}: expected {frame_count} shown frames"
1823 );
1824 for (i, f) in frames.iter().enumerate() {
1825 assert_eq!(
1826 (f.width, f.height),
1827 (width, height),
1828 "{NAME}: frame {i} is {}x{}",
1829 f.width,
1830 f.height
1831 );
1832 assert_eq!(
1833 f.u.len(),
1834 width * height / 4,
1835 "{NAME}: frame {i} U plane is {} samples, not 4:2:0",
1836 f.u.len()
1837 );
1838 assert_eq!(f.v.len(), f.u.len(), "{NAME}: frame {i} V plane extent");
1839 assert_eq!(f.y.len(), width * height, "{NAME}: frame {i} luma extent");
1840 }
1841 crate::decode::reset_dist_wtd_comp_hits();
1842 let hits_before = crate::decode::dist_wtd_comp_hits();
1843 let (oracle_frames, hidden) = decode_all_frames_vs_oracle(&on, NAME);
1844 let dist_wtd = crate::decode::dist_wtd_comp_hits() - hits_before;
1845 eprintln!(
1846 "{NAME}: {oracle_frames} oracle frames ({hidden} hidden), \
1847 dist_wtd_comp_hits={dist_wtd}, on={} B off={} B",
1848 on.len(),
1849 off.len()
1850 );
1851 assert!(
1852 dist_wtd > 0,
1853 "{NAME}: no block took the distance-weighted compound combine \
1854 (compound_idx == 0) across {oracle_frames} frames that carry \
1855 enable_jnt_comp = true -- every compound block used the simple \
1856 average, so this gate proves nothing about the tool"
1857 );
1858 }
1859
1860 /// lane-whtshape: a LOSSLESS 4:4:4 frame whose rect intra-BC blocks used
1861 /// to code their chroma plane block as ONE rect transform unit -- a shape
1862 /// libaom cannot code. `read_tx_mode` (`av1/decoder/decodeframe.c:140`)
1863 /// returns `ONLY_4X4` for a `coded_lossless` frame BEFORE it looks at the
1864 /// `tx_mode` symbol, `read_tx_size` (`:1117`) returns `TX_4X4` before it
1865 /// looks at a tree, `get_vartx_max_txsize` (`av1/common/blockd.h:1447`)
1866 /// returns `TX_4X4` for EVERY plane of a lossless block, and of
1867 /// `av1/common/idct.c`'s `highbd_inv_txfm_add_*_c` only the 4x4 one carries
1868 /// a `lossless` branch -- the rest fall through to the IDCT, because there
1869 /// is no non-4x4 lossless inverse transform to dispatch to.
1870 ///
1871 /// The 8x4 unit that resulted reached the lossless Walsh-Hadamard path,
1872 /// where a `debug_assert_eq!` named it in DEBUG and the RELEASE build died
1873 /// one frame later with an opaque `range end index 8 out of range for slice
1874 /// of length 0` (measured, not assumed -- see
1875 /// lanes/whtshape.report.md r1).
1876 ///
1877 /// The witness is `fixtures/ll444_sb64_1to4_lossless.obu` (51107 bytes,
1878 /// sha256 `fdb6467987095b99c8eb51b48743691d906b2d99d069f71f1d51b1abb6d2056e`),
1879 /// encoded with the instrumented oracle
1880 /// (`scripts/build-aom-oracle.sh`'s `aomenc`, 4:4:4 10-bit, `--lossless=1
1881 /// --profile=1 --i444 --enable-rect-partitions=1
1882 /// --enable-1to4-partitions=1 --min-partition-size=4 --max-partition-size=64
1883 /// --sb-size=64 --tune-content=screen --enable-intrabc=1 --enable-palette=1
1884 /// --cq-level=60 --enable-tx-size-search=0 --cpu-used=0 --limit=2`) over
1885 /// `ffmpeg -f lavfi -i testsrc2=size=256x256:rate=25:duration=1 -pix_fmt
1886 /// yuv444p10le -f rawvideo`. 4:2:0 cannot produce the shape at all -- its
1887 /// smallest lossless chroma plane block is already 4x4 -- which is why the
1888 /// 4:4:4 10-bit header is asserted.
1889 ///
1890 /// Four assertions, each with its own failure:
1891 ///
1892 /// 1. the route fired: `INTRABC_RECT_LOSSLESS_CHROMA4_HITS` is EXCLUSIVE to
1893 /// the per-4x4 chroma walk (no other caller walks a rect intra-BC
1894 /// block's chroma), so `>= 1` cannot be satisfied by the old
1895 /// single-unit read;
1896 /// 2. NO non-4x4 lossless transform unit was reconstructed
1897 /// (`LOSSLESS_WHT_SPLIT_UNITS` delta 0) -- the shape-total WHT entry is
1898 /// not quietly papering over a caller that is still wrong;
1899 /// 3. the stream DECODES both frames (before the fix the same bytes were a
1900 /// RELEASE panic and a Golomb-tail refusal in DEBUG); and
1901 /// 4. a PIXEL comparison against the instrumented oracle's own
1902 /// `EC_AV1_FINAL_DUMP`, in DECODE order.
1903 ///
1904 /// **(4) is a PREFIX floor, not an exactness claim, and it says so.**
1905 /// Measured against the oracle, decode-order frame 0 (the key frame) is
1906 /// byte-exact on all three planes for its first 32992 of 65536 samples --
1907 /// the whole frame above row 128, plus row 128 out to column 224. The
1908 /// first differing sample there is (x=224, y=128) on Y, U and V alike: the
1909 /// first column PAST the 16x8 lossless intra-BC block at mi (32, 52),
1910 /// whose own 16x8 luma and chroma are byte-exact -- so the fork is at the
1911 /// block boundary, in the block that FOLLOWS it. Decode-order frame 1 (the
1912 /// inter frame) is exact to 55008 on luma and to 9378 on chroma. Both forks
1913 /// are a SEPARATE defect this lane does not own; each is named with its
1914 /// measurement in lanes/whtshape.report.md r3. Asserting "our output is
1915 /// wrong by exactly N" would encode those defects as expected behaviour;
1916 /// the per-frame, per-plane floor is the honest form, and it only grows.
1917 #[test]
1918 fn a_444_lossless_sb64_intrabc_rect_chroma_walks_4x4_units() {
1919 const NAME: &str = "a_444_lossless_sb64_intrabc_rect_chroma_walks_4x4_units";
1920 const FIXTURE: &str = "ll444_sb64_1to4_lossless.obu";
1921 const FIXTURE_LEN: usize = 51107;
1922 const FIXTURE_FNV: u64 = 0x7664_6a62_ddd3_4df2;
1923 const FRAMES: usize = 2;
1924 const PLANE: usize = 256 * 256;
1925 /// Per decode-order frame, per plane (0=Y, 1=U, 2=V), the number of
1926 /// leading samples MEASURED byte-exact against the oracle's
1927 /// `EC_AV1_FINAL_DUMP`; the first differing sample is exactly this
1928 /// index on that plane. Key frame: the whole frame above row 128 plus
1929 /// row 128 out to column 224. Inter frame: luma exact to (224, 214),
1930 /// chroma diverging early at (162, 36).
1931 const EXACT_PREFIX: [[usize; 3]; 2] = [[32992, 32992, 32992], [55008, 9378, 9378]];
1932 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1933 .join(format!("fixtures/{FIXTURE}"));
1934 let stream = read_pin(&obu, FIXTURE_LEN, FIXTURE_FNV, NAME);
1935 assert_444_header(&stream, NAME, 10);
1936
1937 let _guard = lock_gate_counters();
1938 crate::decode::reset_intrabc_rect_lossless_chroma4_hits();
1939 let split_before = crate::decode::lossless_wht_split_units();
1940 let wht_before = crate::decode::lossless_wht_units();
1941 let frames = decode_stream(&stream)
1942 .unwrap_or_else(|e| panic!("{NAME}: the pinned witness was refused: {e}"));
1943 let chroma4 = crate::decode::intrabc_rect_lossless_chroma4_hits();
1944 let split = crate::decode::lossless_wht_split_units() - split_before;
1945 let wht = crate::decode::lossless_wht_units() - wht_before;
1946
1947 assert!(
1948 chroma4 > 0,
1949 "{NAME}: no LOSSLESS rect intra-BC block walked its chroma as 4x4 units \
1950 -- the corrected route never ran, so this gate is measuring the old \
1951 single rect unit (class gate-blind-to-feature)"
1952 );
1953 assert_eq!(
1954 split, 0,
1955 "{NAME}: {split} 4x4 WHT unit(s) were reconstructed inside a LOSSLESS \
1956 transform unit that was itself not 4x4 -- a caller is still sizing a \
1957 lossless unit wrongly and the shape-total WHT entry is hiding it"
1958 );
1959 assert!(
1960 wht > 0,
1961 "{NAME}: no lossless WHT unit ran at all -- vacuous"
1962 );
1963 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
1964
1965 // The probe decides; its own SKIP (and its assert under
1966 // EC_AV1_REQUIRE_AOMDEC / EC_AV1_REQUIRE_AOMENC) has already been said.
1967 if !aomdec_available(NAME) {
1968 eprintln!(
1969 "{NAME}: {chroma4} lossless rect intra-BC block(s) walked 4x4 chroma units, \
1970 {wht} WHT units, 0 split"
1971 );
1972 return;
1973 }
1974 // The oracle's own final-frame dumps, in DECODE order, against ours.
1975 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
1976 let _ = std::fs::remove_dir_all(&dir);
1977 std::fs::create_dir_all(&dir).expect("scratch dir");
1978 let in_obu = dir.join("in.obu");
1979 std::fs::write(&in_obu, &stream).expect("writing the stream");
1980 let aom_prefix = dir.join("aom");
1981 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
1982 .args(["--codec=av1", "-o"])
1983 .arg(dir.join("out.y4m"))
1984 .arg(&in_obu)
1985 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
1986 .stdin(Stdio::null())
1987 .stdout(Stdio::piped())
1988 .stderr(Stdio::piped()), None, |c| c.output())
1989 .expect("aomdec failed to run");
1990 assert!(
1991 out.status.success(),
1992 "{NAME}: the oracle aomdec refused the stream: {}",
1993 String::from_utf8_lossy(&out.stderr)
1994 );
1995 let ours_prefix = dir.join("ours");
1996 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
1997 let shown = decode_stream(&stream)
1998 .unwrap_or_else(|e| panic!("{NAME}: the second decode was refused: {e}"))
1999 .len();
2000 set_final_dump_prefix(None);
2001 let count = |prefix: &std::path::Path| -> usize {
2002 let mut n = 0usize;
2003 while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() {
2004 n += 1;
2005 }
2006 n
2007 };
2008 let oracle_frames = count(&aom_prefix);
2009 let our_frames = count(&ours_prefix);
2010 assert_eq!(
2011 our_frames, oracle_frames,
2012 "{NAME}: decoded {our_frames} frames in decode order, the oracle decoded \
2013 {oracle_frames}"
2014 );
2015 for i in 0..oracle_frames {
2016 let want =
2017 std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
2018 let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
2019 assert_eq!(
2020 got.len(),
2021 want.len(),
2022 "{NAME}: decode-order frame {i} is {} bytes, the oracle's is {}",
2023 got.len(),
2024 want.len()
2025 );
2026 assert_eq!(
2027 got.len(),
2028 3 * PLANE * 2,
2029 "{NAME}: decode-order frame {i} is not three 256x256 16-bit planes"
2030 );
2031 for (plane, name) in [(0usize, "Y"), (1, "U"), (2, "V")] {
2032 let at = plane * PLANE * 2;
2033 let floor = EXACT_PREFIX[i.min(EXACT_PREFIX.len() - 1)][plane].min(PLANE);
2034 if got[at..at + floor * 2] == want[at..at + floor * 2] {
2035 continue;
2036 }
2037 let first = (0..floor)
2038 .find(|&s| got[at + s * 2..at + s * 2 + 2] != want[at + s * 2..at + s * 2 + 2])
2039 .unwrap_or(floor);
2040 panic!(
2041 "{NAME}: decode-order frame {i} plane {name} diverges from the oracle at \
2042 sample {first} of {PLANE} (x={}, y={}) -- the exact prefix this gate pins \
2043 is {floor} and it only grows; the rest is the OPEN defect named in \
2044 lanes/whtshape.report.md r3",
2045 first % 256,
2046 first / 256
2047 );
2048 }
2049 }
2050 let _ = std::fs::remove_dir_all(&dir);
2051 eprintln!(
2052 "{NAME}: {chroma4} lossless rect intra-BC block(s) walked 4x4 chroma units, \
2053 {wht} WHT units, 0 split; {oracle_frames} decode-order frame(s) ({shown} shown) \
2054 byte-exact against the oracle up to the per-frame, per-plane exact prefix \
2055 -- the tail is the OPEN r3 defect, not an assertion"
2056 );
2057 }
2058
2059 /// lane-av1444edge: the two 4:4:4 lossy cells the chroma-format sweep
2060 /// (§6.2) left as "unassigned, neither reduces to a known class". They
2061 /// are one class, and it is the sibling gate's: a 1:4 (HORZ_4 / VERT_4)
2062 /// inter strip's chroma coefficient context gathered at the 4:2:0 PAIR
2063 /// extent at ss (0,0), where `is_chroma_reference`
2064 /// (av1_common_int.h:1454) makes every block its own chroma reference so
2065 /// no pair exists. What these two add is the geometry and the depth the
2066 /// sibling's 128x96 gate does not reach.
2067 ///
2068 /// **Arm A -- partial-frame right edge, 130x122.** Neither dimension is a
2069 /// multiple of 8 (the sweep's own odd-dimension gate covers 4:2:0 only, so
2070 /// the 4:4:4 partial-column walk had no exactness evidence), and 66x66 is
2071 /// EXACT at the same settings, so the walk is right at one odd geometry
2072 /// and wrong at another. Arm B -- 256x128, 4 frames, with CDEF and loop
2073 /// restoration both live on the last two frames.
2074 ///
2075 /// **The recipes** (the sweep's, byte-reproduced -- the truncated sha256
2076 /// prefixes it recorded, `c87ac65b…` and `06621606…`, match):
2077 /// ```text
2078 /// ffmpeg -f lavfi -i "testsrc2=size=<W>x<H>:rate=25" -frames:v 4 \
2079 /// -pix_fmt yuv444p -strict -1 -f yuv4mpegpipe - | \
2080 /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 \
2081 /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 \
2082 /// --limit=4 --obu -o - -
2083 /// ```
2084 /// (`rate=25` is load-bearing for the same reason as the sibling gate:
2085 /// `testsrc2`'s pattern is time-parameterised.)
2086 ///
2087 /// Red before the fix, both arms: arm A frame 3, 11521 samples, first at
2088 /// Y(128,16) (ours 134, oracle 170); arm B frame 2, 25296 samples, first
2089 /// at Y(192,0) (ours 92, oracle 106), frame 3 51108 more. The
2090 /// pre-loop-filter reconstruction already carries the identical first
2091 /// wrong sample on both, so no filter is involved; in arm B the first
2092 /// wrong superblock in DECODE order is SBcol2/SBrow0 (first wrong pixel
2093 /// (128,48) = mi(12,32), whose mode/ref/mv are identical on both sides),
2094 /// and the arithmetic fork lands on the very next block, mi(13,32), where
2095 /// the oracle reads ref0 = LAST and we read GOLDEN.
2096 ///
2097 /// Non-vacuity, three ways per arm: the pinned bytes (length + FNV-1a);
2098 /// the decoded chroma planes are full resolution, which is the ss (0,0)
2099 /// shape claim; and `decode::rect4_inter_own_chroma444_hits()` must be
2100 /// non-zero AND `inter16_rect4_counters()` must report 1:4 inter strips,
2101 /// so the corrected route is known to have run rather than the gate
2102 /// passing on a stream that never reached it.
2103 #[test]
2104 fn a_444_lossy_rect4_strip_stream_decodes_pixel_exact_at_odd_and_wide_geometries() {
2105 const NAME: &str =
2106 "a_444_lossy_rect4_strip_stream_decodes_pixel_exact_at_odd_and_wide_geometries";
2107 // (fixture, len, fnv1a64, width, height, strips HORZ_4 + VERT_4)
2108 const ARMS: [(&str, usize, u64, usize, usize, usize); 2] = [
2109 (
2110 "fixtures/444_lossy_rect4_odd_130x122.obu",
2111 8945,
2112 0x5125_0554_751c_bf12,
2113 130,
2114 122,
2115 28, // measured 8 HORZ_4 + 20 VERT_4
2116 ),
2117 (
2118 "fixtures/444_lossy_rect4_wide_256x128.obu",
2119 15239,
2120 0xf94a_0218_bb34_4f9e,
2121 256,
2122 128,
2123 76, // measured 60 HORZ_4 + 16 VERT_4
2124 ),
2125 ];
2126 let _guard = lock_gate_counters();
2127 for (fixture, len, fnv, w, h, min_strips) in ARMS {
2128 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(fixture);
2129 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
2130 panic!(
2131 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot \
2132 run, which is a failure, not a skip",
2133 obu.display()
2134 )
2135 });
2136 assert_eq!(stream.len(), len, "{NAME}: {fixture} length moved");
2137 assert_eq!(fnv1a64(&stream), fnv, "{NAME}: {fixture} bytes moved");
2138
2139 // The 1:4-strip counters are process-wide with no reset, so read
2140 // them as a DELTA: a full-suite run has already put 1:4 strips
2141 // through the decoder by the time this test starts, and an
2142 // absolute count would be a non-vacuity assertion that passes on
2143 // residue from another stream.
2144 let before_strips = {
2145 let (h, v, _, _) = crate::decode::inter16_rect4_counters();
2146 h + v
2147 };
2148 crate::decode::reset_rect4_inter_own_chroma444_hits();
2149 let frames = decode_stream(&stream)
2150 .unwrap_or_else(|e| panic!("{NAME}: {fixture} no longer decodes cleanly: {e}"));
2151 let own_chroma = crate::decode::rect4_inter_own_chroma444_hits();
2152 let strips = {
2153 let (h, v, _, _) = crate::decode::inter16_rect4_counters();
2154 h + v - before_strips
2155 };
2156 assert!(
2157 strips >= min_strips,
2158 "{NAME}: {fixture} coded only {strips} 1:4 inter strips \
2159 (HORZ_4 + VERT_4), expected about {min_strips} -- the stream \
2160 moved, and the route this gate witnesses may no longer be on it"
2161 );
2162 assert!(
2163 own_chroma > 0,
2164 "{NAME}: {fixture} ran no 1:4 inter strip over its own chroma \
2165 extent -- the corrected route never ran (class \
2166 gate-blind-to-feature)"
2167 );
2168 assert_eq!(frames.len(), 4, "{NAME}: {fixture} frame count");
2169 for (i, f) in frames.iter().enumerate() {
2170 assert_eq!(
2171 (f.width, f.height),
2172 (w, h),
2173 "{NAME}: {fixture} frame {i} dimensions"
2174 );
2175 // At 4:4:4 the chroma planes are full resolution; a decoder
2176 // that kept the 4:2:0 extent would hand quarter-size chroma
2177 // planes to the byte compare, which cannot pass. Say it here
2178 // rather than let the compare stand in for the shape claim.
2179 assert_eq!(
2180 f.u.len(),
2181 w * h,
2182 "{NAME}: {fixture} frame {i} chroma plane is {} samples; at \
2183 4:4:4 it must be full resolution ({w}x{h})",
2184 f.u.len()
2185 );
2186 }
2187 if aomdec_available(NAME) {
2188 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2189 eprintln!(
2190 "{NAME}: {fixture} {decoded} decode-order frame(s) \
2191 ({hidden} hidden) byte-exact vs aomdec, {own_chroma} own-extent \
2192 1:4 chroma gather(s), {strips} 1:4 inter strip(s)"
2193 );
2194 }
2195 }
2196 }
2197
2198 /// lane-av1444d10: the 10-bit 4:4:4 352x242 cell the 4:2:2 census
2199 /// (`lanes/av1422census.report.md` §4 class D) found diverging on chroma
2200 /// only -- 0 / 1166 / 1413 over 17 of 17 decode frames, first bad sample
2201 /// at decode frame 0 plane U row 224 col 64 -- and the fix for it, a byte
2202 /// exact gate. 4:4:4 is a format this decoder claims to support, so the
2203 /// cell is not probe-only evidence.
2204 ///
2205 /// **Why this cell and not its five same-depth controls.** `s444_*_10b`
2206 /// at 320x242, 320x250, 352x250, 416x242 and 416x250, same encoder recipe,
2207 /// same 10-bit depth, were all byte-exact before the fix and still are; only
2208 /// 352x242 diverged. What 352x242 has is the first block of the cell whose
2209 /// chroma is TALLER than the 32-pixel unit cap at ss (0,0): a 32x64 luma
2210 /// strip keeps its 32x64 chroma, and `decode_block_rect`'s tiled chroma
2211 /// walk splits it into `nh = 2` units of 32x32. Every other cell's chroma
2212 /// blocks are <= 32 on both axes, so `nw * nh == 1` and the whole-block
2213 /// buffer IS the unit's window -- the bug is invisible there. That is why
2214 /// the census could report "geometry-sensitive" without the mechanism:
2215 /// the sensitive axis is chroma UNIT COUNT, not frame width or height.
2216 ///
2217 /// **The defect.** Both tiled arms handed the unit the WHOLE block's
2218 /// palette prediction buffer, and `PlaneBuf::reconstruct` reads its first
2219 /// `side * side` entries, so unit (0,1) at pixel (64, 224) reconstructed
2220 /// the block's row-192 palette values (flat 209) where libaom writes
2221 /// row 224's (216). The neighbouring 32x32 `PAETH_PRED` block at
2222 /// (96, 224), whose left edge sample IS that pixel, then propagated 19
2223 /// more wrong columns along its own top row -- which is why the census saw
2224 /// 53 wrong columns rather than 32.
2225 ///
2226 /// **Red before the fix, by this gate's own name:** with the two
2227 /// `palette_window` calls reverted the first wrong sample is decode frame
2228 /// 0 plane U row 224 col 64 (ours 209, oracle 216) and the totals are
2229 /// 0 / 1166 / 1413 over 17 decode frames.
2230 ///
2231 /// **Non-vacuity, four ways.** (1) The pinned bytes: length 24875 and
2232 /// FNV-1a64 `0x7fda_dbb4_3bbf_9af3`, sha256
2233 /// `84df2f37cc7982f9a572443d85dfcc13bf366a64f3fb567391dcd5acd58a0ad2`.
2234 /// (2) 17 decode-order frames at 352x242 with FULL-RESOLUTION chroma, so
2235 /// a decoder that kept the 4:2:0 extent cannot pass the compare.
2236 /// (3) `decode::chroma_palette_window_hits()` read as a delta must be at
2237 /// least 1. After the refutation pass read the numbers back, that counter
2238 /// is guarded on `nw * nh > 1`, so it fires ONLY for units of a block the
2239 /// 32-cap actually tiled -- a hit is therefore proof that the tiled arm ran,
2240 /// not merely that some palette chroma block existed, and a gate that
2241 /// passed with the tiled arm removed would be gate-blind-to-feature. (4) The oracle comparator this gate leans on has
2242 /// its own per-plane one-byte-flip liveness control in the crate
2243 /// (`every_oracle_comparator_reds_on_a_one_byte_wrong_oracle`).
2244 #[test]
2245 fn a_444_lossy_palette_chroma_unit_window_is_byte_exact_at_352x242_10bit() {
2246 const NAME: &str = "a_444_lossy_palette_chroma_unit_window_is_byte_exact_at_352x242_10bit";
2247 const FIXTURE: &str = "fixtures/444_lossy_palette_chroma_352x242_10b.obu";
2248 const LEN: usize = 24875;
2249 const FNV: u64 = 0x7fda_dbb4_3bbf_9af3;
2250 const W: usize = 352;
2251 const H: usize = 242;
2252 // 16 SHOWN frames (`--limit=16`); the oracle compare below is the one
2253 // that walks all 17 DECODE-order pictures (16 shown + 1 hidden altref).
2254 const FRAMES: usize = 16;
2255 // measured 4 on this stream (two tiled palette chroma blocks x U and V)
2256 const MIN_WINDOWED_UNITS: usize = 4;
2257 let _guard = lock_gate_counters();
2258 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(FIXTURE);
2259 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
2260 panic!(
2261 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
2262 which is a failure, not a skip",
2263 obu.display()
2264 )
2265 });
2266 assert_eq!(stream.len(), LEN, "{NAME}: {FIXTURE} length moved");
2267 assert_eq!(fnv1a64(&stream), FNV, "{NAME}: {FIXTURE} bytes moved");
2268
2269 // Process-wide with no reset: read as a DELTA, or a full-suite run
2270 // leaves residue that would make the reachability assert vacuous.
2271 crate::decode::reset_chroma_palette_window_hits();
2272 let frames = decode_stream(&stream)
2273 .unwrap_or_else(|e| panic!("{NAME}: {FIXTURE} no longer decodes cleanly: {e}"));
2274 let windowed = crate::decode::chroma_palette_window_hits();
2275 assert!(
2276 windowed >= MIN_WINDOWED_UNITS,
2277 "{NAME}: {FIXTURE} ran {windowed} windowed palette chroma unit(s), \
2278 expected at least {MIN_WINDOWED_UNITS} -- the tiled chroma walk did \
2279 not reach a palette block, so the fixed lines never ran and this \
2280 gate is blind to the defect (class gate-blind-to-feature)"
2281 );
2282 assert_eq!(
2283 frames.len(),
2284 FRAMES,
2285 "{NAME}: {FIXTURE} decode-order frame count"
2286 );
2287 for (i, f) in frames.iter().enumerate() {
2288 assert_eq!(
2289 (f.width, f.height),
2290 (W, H),
2291 "{NAME}: {FIXTURE} frame {i} dimensions"
2292 );
2293 assert_eq!(
2294 f.u.len(),
2295 W * H,
2296 "{NAME}: {FIXTURE} frame {i} chroma plane is {} samples; at 4:4:4 \
2297 it must be full resolution ({W}x{H})",
2298 f.u.len()
2299 );
2300 }
2301 if aomdec_available(NAME) {
2302 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2303 eprintln!(
2304 "{NAME}: {FIXTURE} {decoded} decode-order frame(s) ({hidden} hidden) \
2305 byte-exact vs aomdec, {windowed} windowed palette chroma unit(s)"
2306 );
2307 }
2308 }
2309
2310 /// lane-av1444palw: the gate for the arm
2311 /// `a_444_lossy_palette_chroma_unit_window_is_byte_exact_at_352x242_10bit`
2312 /// could NOT reach -- the HORIZONTAL half of the same 32-capped chroma
2313 /// walk in `decode_block_rect64` (`palette_window(pbuf, chroma_w,
2314 /// cu_col * uw, cu_row * uh, uw, uh)`, the arms at decode.rs:20131 and
2315 /// :20199). Its `cu_col` term is the axis the corpus census never
2316 /// exercised: a 106-fixture trace of that walk found 16 windowed units and
2317 /// every one had `nw == 1`, i.e. only the `cu_row` term (`nh = 2`) was
2318 /// ever load-bearing.
2319 ///
2320 /// **What makes `nw >= 2` reachable.** At ss (0,0) the chroma plane block
2321 /// equals the luma one, so a 64-WIDE luma rect block keeps `cw = 64` and
2322 /// the 32-cap tiles it into `nw = 2` units. `decode_block_rect64` is the
2323 /// only function owning this walk at a 64-wide block, reached from
2324 /// `PARTITION_HORZ`/`HORZ_A`/`HORZ_B` (64x32) and `HORZ_4` (64x16). The
2325 /// cells here came from sweeping `--min-partition-size` x `--cq-level` over
2326 /// a 4:4:4 testsrc2 640x480 cell encoded with the lane-av1rect14
2327 /// `ibc640` flag set (rect + 1:4 partitions, `--min-partition-size=8
2328 /// --sb-size=64 --tune-content=screen --enable-palette=1
2329 /// --enable-intrabc=1 --enable-tx-size-search=0 --cpu-used=0
2330 /// --lag-in-frames=0 --kf-max-dist=1 --limit=1 --threads=1
2331 /// --tile-columns=0 --passes=1 --end-usage=q --profile=1`):
2332 /// `--min-partition-size=8` is what yields the 64-wide strip, and
2333 /// `cq-level=45` is what makes the chroma palette win on it. Census read
2334 /// off `EC_PALWALK=1`, the diagnostic rung this lane added to
2335 /// `decode_block_rect64`:
2336 ///
2337 /// * 10-bit `cq 45`: `bw=64 bh=16 cw=64 ch=16 uw=32 uh=16 nw=2 nh=1 puv=1`
2338 /// -- the RECT-unit arm (`uw != uh`) carrying a chroma palette, `nw = 2`.
2339 /// * 12-bit `cq 45`: `bw=64 bh=32 cw=64 ch=32 uw=32 uh=32 nw=2 nh=1 puv=1`
2340 /// -- the SQUARE-unit arm carrying a chroma palette, `nw = 2`, on the
2341 /// 12-bit chroma plane no prior gate had built.
2342 ///
2343 /// **Both cells are byte-exact against the instrumented `aomdec`** per
2344 /// plane over the single decode-order frame (10-bit 0/0/0, 12-bit 0/0/0),
2345 /// and the comparator's liveness is proved by a one-byte oracle tamper
2346 /// moving the mismatch count 0 -> 1 at each depth.
2347 ///
2348 /// **Red without the per-unit window, by this gate's own numbers.**
2349 /// Reverting both `palette_window` calls to the whole-block buffer (the
2350 /// counter left armed) gives 0 / 25553 / 26139 on the 10-bit cell, first
2351 /// wrong sample decode frame 0 plane U row 96 col 448 (mutant 810, oracle
2352 /// 763; plane V the same sample 891 vs 767), and 0 / 6400 / 6400 on the
2353 /// 12-bit cell, first wrong sample plane U row 352 col 160 (866 vs 2004).
2354 /// Both are the `cu_col = 1` unit reading the block's column 0 -- this arm,
2355 /// not a cascade.
2356 ///
2357 /// **Non-vacuity.** (1) pinned bytes: 3301 / 2571 with FNV-1a64 and
2358 /// sha256 asserted. (2) the DERIVED condition: the counter is guarded on
2359 /// `nw * nh > 1`, so a hit proves the tiled arm ran, and the floors below
2360 /// are re-measured on these two streams (the pinned gate's floor of 4 was
2361 /// a floor from ONE stream, not a census). (3) 640x480 with
2362 /// FULL-RESOLUTION chroma, so a 4:2:0 extent cannot pass. (4) the crate's
2363 /// own one-byte oracle-comparator liveness control.
2364 #[test]
2365 fn a_444_palette_chroma_horizontal_unit_window_is_byte_exact_10bit_and_12bit() {
2366 const NAME: &str =
2367 "a_444_palette_chroma_horizontal_unit_window_is_byte_exact_10bit_and_12bit";
2368 // (fixture, len, fnv1a64, bit_depth, min_windowed_units)
2369 const ARMS: [(&str, usize, u64, usize, usize); 2] = [
2370 (
2371 "fixtures/444_palette_chroma_hstrip_640x480_10b.obu",
2372 3301,
2373 0x6f94_da75_95cd_9a17,
2374 10,
2375 8,
2376 ),
2377 (
2378 "fixtures/444_palette_chroma_hstrip_640x480_12b.obu",
2379 2571,
2380 0x65a5_8561_c1f3_538e,
2381 12,
2382 4,
2383 ),
2384 ];
2385 const W: usize = 640;
2386 const H: usize = 480;
2387 let _guard = lock_gate_counters();
2388 for (fixture, len, fnv, depth, min_units) in ARMS {
2389 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(fixture);
2390 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
2391 panic!(
2392 "{NAME}: pinned fixture {fixture} is missing ({e}) -- the gate cannot \
2393 run, which is a failure, not a skip"
2394 )
2395 });
2396 assert_eq!(stream.len(), len, "{NAME}: {fixture} length moved");
2397 assert_eq!(fnv1a64(&stream), fnv, "{NAME}: {fixture} bytes moved");
2398
2399 crate::decode::reset_chroma_palette_window_hits();
2400 let frames = decode_stream(&stream)
2401 .unwrap_or_else(|e| panic!("{NAME}: {fixture} no longer decodes cleanly: {e}"));
2402 let windowed = crate::decode::chroma_palette_window_hits();
2403 assert!(
2404 windowed >= min_units,
2405 "{NAME}: {fixture} ran {windowed} windowed palette chroma unit(s), expected \
2406 at least {min_units} -- the 32-cap tiled chroma walk did not reach enough \
2407 palette blocks, so the horizontal windowing under test never ran and this \
2408 gate is blind to the defect (class gate-blind-to-feature)"
2409 );
2410 assert_eq!(
2411 frames.len(),
2412 1,
2413 "{NAME}: {fixture} decode-order frame count"
2414 );
2415 for (i, f) in frames.iter().enumerate() {
2416 assert_eq!(
2417 (f.width, f.height),
2418 (W, H),
2419 "{NAME}: {fixture} frame {i} dimensions"
2420 );
2421 assert_eq!(
2422 f.u.len(),
2423 W * H,
2424 "{NAME}: {fixture} frame {i} chroma plane is {} samples; at 4:4:4 it must \
2425 be full resolution ({W}x{H}) -- a {depth}-bit decoder that kept the \
2426 4:2:0 extent cannot pass this compare",
2427 f.u.len()
2428 );
2429 }
2430 if aomdec_available(NAME) {
2431 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2432 eprintln!(
2433 "{NAME}: {fixture} ({depth}-bit) {decoded} decode-order frame(s) \
2434 ({hidden} hidden) byte-exact vs aomdec, {windowed} windowed palette \
2435 chroma unit(s)"
2436 );
2437 }
2438 }
2439 }
2440
2441 /// lane-av1cfl: the 4:4:4 CfL AC body is a DIFFERENT function from the
2442 /// 4:2:0 one, and this gate is the proof that the format-blind
2443 /// `cfl_ac_q3_at` (`bw / 2, bh / 2`, a 2x2 luma average per chroma
2444 /// sample) is reached only at 4:2:0.
2445 ///
2446 /// **The claim this closes.** `cfl_ac_q3_at` has no `fctx`/`ss`
2447 /// parameter, so at 4:4:4 it would be wrong twice over: the chroma
2448 /// extent equals the luma extent when `ss_x == ss_y == 0`, and libaom
2449 /// averages 2x2 luma per chroma sample at 4:2:0 but 1x1 at 4:4:4
2450 /// (`cfl_luma_subsampling_420_lbd_c` vs `cfl_luma_subsampling_444_lbd_c`,
2451 /// `~/.cache/aom-oracle/src/av1/common/cfl.c:230` and `:257`). The
2452 /// inherited report claimed "188 rung hits on the 4:4:4 set"
2453 /// (`lanes/av1chromahalvings.report.md` r3.4). **It does not
2454 /// reproduce**: the env-gated rung `EC_HALVSWEEP` in `cfl_ac_q3_at`,
2455 /// swept over all 27 `*444*` pins, printed **0 hits on every one**,
2456 /// while the 4:4:4 arm of `cfl_ac_ss` fired 4..312 times on the same
2457 /// fixtures. The 4:4:4 CfL path is real and heavily exercised; it just
2458 /// does not go through this function. `cfl_ac_ss` dispatches 4:4:4 and
2459 /// 4:2:2 to their own transcriptions of libaom's 444/422 subsampling
2460 /// bodies BEFORE the 4:2:0 fallthrough, and the fallthrough is the only
2461 /// road to `cfl_ac_q3_at`.
2462 ///
2463 /// Two-sided on purpose. The 4:4:4 arm asserts `> 0` (the CfL path
2464 /// fired, so the `== 0` below is a routing fact and not an absence of
2465 /// CfL) and the 4:2:0 arm asserts `> 0` on the SAME counter (so the
2466 /// counter is live and the 4:4:4 zero is not a dead one). Both arms
2467 /// compare every decoded frame to the instrumented `aomdec`
2468 /// plane by plane, and the 4:2:0 arm is the "unchanged" quote: its
2469 /// per-plane mismatch counts must be 0/0/0.
2470 ///
2471 /// Provenance: both fixtures are aomenc-produced and already pinned
2472 /// with sha256 by the gates named beside them. 4:4:4 lossy
2473 /// `444_lossy_superres_mode2_256x128.obu` (16620 bytes, sha256
2474 /// `c18496cf3b7db0feca9aa904024cec2115be80b5b94f87c848ac52f9b32ffd97`,
2475 /// `testsrc2=size=256x128:rate=25 -pix_fmt yuv444p`, `--passes=1
2476 /// --end-usage=q --cq-level=20 --cpu-used=2 --superres-mode=2
2477 /// --limit=4 --obu`, 4 frames); 4:2:0 lossy
2478 /// `420_intrabc_rect4_witness.obu` (890 bytes, sha256
2479 /// `d01352af5059919cdce733abdcbae8e8240ac3c2a6190fa1bd96d3c6f945b979`).
2480 #[test]
2481 fn cfl_ac_444_routes_to_its_own_1x1_luma_body_and_420_to_the_2x2_average() {
2482 const NAME: &str = "cfl_ac_444_routes_to_its_own_1x1_luma_body_and_420_to_the_2x2_average";
2483 // (fixture, len, fnv1a64, sha256, (w, h), frames, cfL arm index, is_444)
2484 const ARMS: [(&str, usize, u64, &str, (usize, usize), usize, usize, bool); 2] = [
2485 (
2486 "fixtures/444_lossy_superres_mode2_256x128.obu",
2487 16620,
2488 0x8cbb_36b2_5e0f_07ab,
2489 "c18496cf3b7db0feca9aa904024cec2115be80b5b94f87c848ac52f9b32ffd97",
2490 (256, 128),
2491 4,
2492 0,
2493 true,
2494 ),
2495 (
2496 "fixtures/420_intrabc_rect4_witness.obu",
2497 890,
2498 0x57ec_3da2_a63b_403a,
2499 "d01352af5059919cdce733abdcbae8e8240ac3c2a6190fa1bd96d3c6f945b979",
2500 (640, 480),
2501 1,
2502 2,
2503 false,
2504 ),
2505 ];
2506 let _guard = lock_gate_counters();
2507 for (fixture, len, fnv, sha, (w, h), want_frames, arm_idx, is_444) in ARMS {
2508 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(fixture);
2509 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
2510 panic!(
2511 "{NAME}: pinned fixture {fixture} is missing ({e}) -- the gate cannot run, \
2512 which is a failure, not a skip"
2513 )
2514 });
2515 assert_eq!(stream.len(), len, "{NAME}: {fixture} length moved");
2516 assert_eq!(fnv1a64(&stream), fnv, "{NAME}: {fixture} bytes moved");
2517
2518 // The arm counters are process-wide with no reset, so every read
2519 // is a DELTA: a full-suite run has already put other streams'
2520 // CfL blocks through this decoder, and an absolute count would be
2521 // a non-vacuity assertion satisfied by residue.
2522 let arms_before = crate::decode::cfl_ac_arm_hits();
2523 let q3_before = crate::decode::cfl_ac_q3_at_hits();
2524 let frames = decode_stream(&stream)
2525 .unwrap_or_else(|e| panic!("{NAME}: {fixture} no longer decodes cleanly: {e}"));
2526 let arms = crate::decode::cfl_ac_arm_hits();
2527 let q3_delta = crate::decode::cfl_ac_q3_at_hits() - q3_before;
2528 let arm_delta: Vec<usize> = (0..4).map(|i| arms[i] - arms_before[i]).collect();
2529
2530 // The arm this stream's format MUST take, and the count that
2531 // proves the CfL path is live on it. At 4:4:4 that is arm 0
2532 // (`cfl_luma_subsampling_444_lbd_c`'s 1x1 body); at 4:2:0 it is
2533 // arm 2 (the square fallthrough into `cfl_ac_q3`).
2534 assert!(
2535 arm_delta[arm_idx] > 0,
2536 "{NAME}: {fixture} ran {} 4:4:4 / {} 4:2:2 / {} 4:2:0-square / \
2537 {} 4:2:0-rect CfL blocks; arm {arm_idx} is the one this format must \
2538 take and it is ZERO -- the stream no longer exercises CfL, so the \
2539 routing assertion below would be vacuous (class gate-blind-to-feature)",
2540 arm_delta[0],
2541 arm_delta[1],
2542 arm_delta[2],
2543 arm_delta[3],
2544 );
2545 if is_444 {
2546 assert_eq!(
2547 q3_delta, 0,
2548 "{NAME}: {fixture} is 4:4:4 and entered the format-blind cfl_ac_q3_at \
2549 {q3_delta} time(s) -- its extent is bw/2, bh/2 and its footprint is a \
2550 2x2 luma average, both wrong at ss (0,0) (libaom cfl.c:230 vs :257). \
2551 Arm deltas {arm_delta:?}. Either cfl_ac_ss lost its 4:4:4 arm or a new \
2552 caller reached cfl_ac_q3_at directly; both make this site LIVE"
2553 );
2554 assert_eq!(
2555 (arm_delta[2], arm_delta[3]),
2556 (0, 0),
2557 "{NAME}: {fixture} is 4:4:4 but ran the 4:2:0 CfL arms -- the format test \
2558 that keeps cfl_ac_q3_at format-blind has moved"
2559 );
2560 } else {
2561 assert!(
2562 q3_delta > 0,
2563 "{NAME}: {fixture} is 4:2:0 and cfl_ac_q3_at was entered ZERO times \
2564 (arm deltas {arm_delta:?}) -- the counter this gate proves 4:4:4 never \
2565 touches is dead on 4:2:0 too, so the 4:4:4 assertion is a dead zero"
2566 );
2567 assert_eq!(
2568 (arm_delta[0], arm_delta[1]),
2569 (0, 0),
2570 "{NAME}: {fixture} is 4:2:0 but ran a 4:4:4 or 4:2:2 CfL arm"
2571 );
2572 }
2573 assert_eq!(frames.len(), want_frames, "{NAME}: {fixture} frame count");
2574 for (i, f) in frames.iter().enumerate() {
2575 assert_eq!(
2576 (f.width, f.height),
2577 (w, h),
2578 "{NAME}: {fixture} frame {i} dimensions"
2579 );
2580 if is_444 {
2581 assert_eq!(
2582 f.u.len(),
2583 w * h,
2584 "{NAME}: {fixture} frame {i} chroma plane is {} samples; at 4:4:4 it \
2585 must be full resolution ({w}x{h})",
2586 f.u.len()
2587 );
2588 }
2589 }
2590 // Per-plane mismatch counts against the instrumented oracle, so
2591 // the "4:2:0 unchanged" claim is a number rather than a claim.
2592 if aomdec_available(NAME) {
2593 let [y, u, v] = oracle_plane_diffs(
2594 &stream,
2595 NAME,
2596 [frames[0].y.len(), frames[0].u.len(), frames[0].v.len()],
2597 );
2598 assert!(
2599 y == 0 && u == 0 && v == 0,
2600 "{NAME}: {fixture} differs from the oracle on {y}/{u}/{v} of the \
2601 {w}x{h} Y/U/V samples -- sha256 {sha}"
2602 );
2603 eprintln!(
2604 "{NAME}: {fixture} arm{arm_idx} {arm_delta:?}, cfl_ac_q3_at {q3_delta}, \
2605 per-plane Y/U/V mismatches vs aomdec {y}/{u}/{v} of {w}x{h}; \
2606 sha256 {sha}"
2607 );
2608 }
2609 }
2610 }
2611
2612 /// lane-av1cfl: the STATIC half of the same claim -- `cfl_ac_q3_at`'s
2613 /// caller set, read out of the sources themselves, is what makes its
2614 /// `bw / 2, bh / 2` extent and 2x2 luma footprint correct rather than
2615 /// merely untested. The counter gate above measures that on two pinned
2616 /// streams; this one survives a change no fixture would catch.
2617 ///
2618 /// **What is asserted, and why each part is load-bearing.**
2619 ///
2620 /// 1. `cfl_ac_q3_at` has exactly **three** call sites -- the two 4:2:0
2621 /// wrappers `cfl_ac_q3` / `cfl_ac_q3_rect` in `decode.rs` and the
2622 /// encoder's CfL candidate in `encode.rs`. A fourth would be a new
2623 /// road to a format-blind body.
2624 /// 2. Both `decode.rs` wrappers are called from **exactly one** function,
2625 /// `cfl_ac_ss`, and only from its LAST two arms -- the ones after the
2626 /// `ss_x == 0 && ss_y == 0` (4:4:4) and `ss_x == 1 && ss_y == 0`
2627 /// (4:2:2) tests. So every decode-side entry is 4:2:0 by
2628 /// construction, whatever a stream's header says.
2629 /// 3. The encoder's call site is 4:2:0 because `Colour::color_config` and
2630 /// `unspecified_color_config` both hardcode `subsampling_x: 1,
2631 /// subsampling_y: 1` -- there is no 4:4:4 encoder colour config in the
2632 /// crate. A future encoder that grows one must thread `ss` into this
2633 /// call, and the `subsampling_x: 0` count going above zero is what
2634 /// says so.
2635 ///
2636 /// (0, 1) needs no arm: `ec-av1-syntax` reads `subsampling_y` only when
2637 /// `subsampling_x == 1` (`crates/ec-av1-syntax/src/sequence.rs:483-485`),
2638 /// so the pair is structurally uncodable and the 4:2:0 fallthrough is the
2639 /// only residual. lane-av1422lift: this sentence used to end "4:2:2 is
2640 /// refused at the sequence header", which was the wrong reason -- the
2641 /// claim holds because `cfl_ac_ss` DISPATCHES `ss (1,0)` before the 4:2:0
2642 /// fallthrough, not because the format could not arrive. The gate's
2643 /// mechanism is unchanged; only the reason was stale.
2644 #[test]
2645 fn cfl_ac_q3_at_is_reached_only_through_the_420_fallthrough_of_cfl_ac_ss() {
2646 const NAME: &str = "cfl_ac_q3_at_is_reached_only_through_the_420_fallthrough_of_cfl_ac_ss";
2647 let decode = crate::test_source::module_source("decode");
2648 let encode = crate::test_source::module_source("encode");
2649
2650 // (1) The call-site set, definition excluded. A declaration is
2651 // preceded by "pub(crate) fn " / "fn "; a call is not.
2652 let mut sites: Vec<&str> = Vec::new();
2653 for src in [decode, encode] {
2654 for (i, _) in src.match_indices("cfl_ac_q3_at(") {
2655 if src[..i].ends_with("fn ") {
2656 continue;
2657 }
2658 sites.push(if src == decode {
2659 "decode.rs"
2660 } else {
2661 "encode.rs"
2662 });
2663 }
2664 }
2665 let mut per_file: std::collections::BTreeMap<&str, usize> =
2666 std::collections::BTreeMap::new();
2667 for s in &sites {
2668 *per_file.entry(s).or_default() += 1;
2669 }
2670 assert_eq!(
2671 per_file,
2672 std::collections::BTreeMap::from([("decode.rs", 2), ("encode.rs", 1)]),
2673 "{NAME}: cfl_ac_q3_at's call-site set changed -- {per_file:?} against an expected \
2674 2 in decode.rs (the cfl_ac_q3 / cfl_ac_q3_rect wrappers) and 1 in encode.rs (the \
2675 encoder's CfL candidate). A new call site must thread the frame's subsampling in; \
2676 the body is a 4:2:0 2x2 luma average over a bw/2 x bh/2 extent and is WRONG at \
2677 4:4:4 on both counts (libaom cfl_luma_subsampling_444_lbd_c is 1x1 over the full \
2678 extent, cfl.c:257)"
2679 );
2680
2681 // (2) Both wrappers have exactly one caller, and it is cfl_ac_ss.
2682 let cfl_ac_ss_at = decode
2683 .find("fn cfl_ac_ss(")
2684 .expect("cfl_ac_ss is gone -- re-derive the fallthrough arms below");
2685 for wrapper in ["cfl_ac_q3(", "cfl_ac_q3_rect("] {
2686 let mut ats = Vec::new();
2687 for (i, _) in decode.match_indices(wrapper) {
2688 if decode[..i].ends_with("fn ") {
2689 continue;
2690 }
2691 ats.push(i);
2692 }
2693 // The scan string carries its own open paren, so it cannot match
2694 // `cfl_ac_q3_rect(` or `cfl_ac_q3_at(` -- those are `cfl_ac_q3`
2695 // followed by `_`, not `(`. No prefix filter is needed.
2696 assert_eq!(
2697 ats.len(),
2698 1,
2699 "{NAME}: `{wrapper}` is called {} time(s) outside its own definition, expected \
2700 exactly 1 (from cfl_ac_ss) -- a second caller is a new road to the 4:2:0 \
2701 average that this gate's counter arm measures only on 4:2:0",
2702 ats.len()
2703 );
2704 assert!(
2705 ats[0] > cfl_ac_ss_at && ats[0] < cfl_ac_ss_at + 4000,
2706 "{NAME}: `{wrapper}`'s only call site is at byte {} and cfl_ac_ss is at {} -- \
2707 the call has moved out of the 4:2:0 fallthrough into something that may be \
2708 handed a 4:4:4 or 4:2:2 block",
2709 ats[0],
2710 cfl_ac_ss_at
2711 );
2712 }
2713
2714 // Inside cfl_ac_ss, the two format tests must come BEFORE both
2715 // wrapper calls, and the wrappers must be the fallthrough -- a 4:4:4
2716 // block returns from the first arm and never reaches either.
2717 let body_end = decode[cfl_ac_ss_at..]
2718 .find("\nfn ")
2719 .expect("cfl_ac_ss must be a top-level fn")
2720 + cfl_ac_ss_at;
2721 let body = &decode[cfl_ac_ss_at..body_end];
2722 let t444 = body.find("if ss_x == 0 && ss_y == 0 {").expect(
2723 "cfl_ac_ss lost its 4:4:4 arm -- every 4:4:4 CfL block now falls into the \
27242:0 average",
2725 );
2726 let t422 = body
2727 .find("} else if ss_x == 1 && ss_y == 0 {")
2728 .expect("cfl_ac_ss lost its 4:2:2 arm -- a 4:2:2 block would take the 4:2:0 average");
2729 let sq = body
2730 .find("cfl_ac_q3(y, px, py, bw)")
2731 .expect("cfl_ac_ss lost its 4:2:0 square fallthrough");
2732 let rect = body
2733 .find("cfl_ac_q3_rect(y, px, py, bw, bh)")
2734 .expect("cfl_ac_ss lost its 4:2:0 rect fallthrough");
2735 assert!(
2736 t444 < t422 && t422 < sq && sq < rect,
2737 "{NAME}: cfl_ac_ss's arm order moved (4:4:4 at {t444}, 4:2:2 at {t422}, 4:2:0 square \
2738 at {sq}, 4:2:0 rect at {rect}) -- the format-blind 2x2 average must stay the \
2739 FALLTHROUGH, after both format tests have had their chance to return"
2740 );
2741
2742 // (3) The encoder's colour configs are 4:2:0 only.
2743 for (src, label) in [
2744 (encode, "encode.rs"),
2745 (crate::test_source::module_source("encoder"), "encoder.rs"),
2746 ] {
2747 let n = src.matches("subsampling_x: 0").count();
2748 assert_eq!(
2749 n, 0,
2750 "{NAME}: {label} now builds a 4:4:4 ColorConfig ({n} site(s)) -- the encoder's \
2751 cfl_ac_q3_at call (encode.rs) is a 4:2:0 2x2 average over a half extent and \
2752 must thread ss before any encoder can emit one"
2753 );
2754 }
2755 }
2756
2757 /// lane-av1444edge r3: the FIRST 4:4:4 superres cell in the crate, and
2758 /// the cell the chroma-format sweep's "4:4:4 superres" row was supposed
2759 /// to be.
2760 ///
2761 /// **Why this gate exists at all.** §6.2 of
2762 /// `lanes/av1formatsweep.report.md` recorded that cell as DIVERGENT from
2763 /// frame 2 with a first wrong sample of Y(192,0). It was never a superres
2764 /// cell: the recipe passed `--superres-mode=1` and no denominator, so
2765 /// libaom's `get_superres_denom_for_qindex`
2766 /// (`av1/encoder/superres_scale.c:143`) chose 8, and all four frame
2767 /// headers of that stream read `use_superres=false denom=8`. Nothing was
2768 /// ever scaled; it was a plain 4:4:4 lossy cq-20 stream, and its
2769 /// divergence was the same H1 class as the 130x122 cell beside it (see
2770 /// `lanes/av1444edge.report.md` §2). That is the trap this gate is built
2771 /// to make impossible to repeat: it asserts the scaled geometry from the
2772 /// PARSED HEADERS, so a future flag or heuristic change that silently
2773 /// unsizes the stream makes the gate red on a header assertion instead of
2774 /// turning into a differently-shaped exactness claim.
2775 ///
2776 /// **This is the only 4:4:4 superres coverage here.** All eight
2777 /// pre-existing superres gates are 4:2:0, checked rather than assumed:
2778 /// the two pinned fixtures parse `ss (1,1)` from their own sequence
2779 /// headers (`superres_kf_cdef_lr_64x64.obu` 8-bit,
2780 /// `superres_alltools_sb128_320x180.obu` 10-bit) and the six live-aomenc
2781 /// gates all feed a `yuv420p` / `yuv420p10le` source. So this cell's
2782 /// claim is scoped honestly: it is the FIRST 4:4:4 superres stream, not
2783 /// a broadening of an existing family.
2784 ///
2785 /// **The recipe** (sha256
2786 /// `450caa3e31526a8973b9f64d5030a2f11b87bd60fac07aef121cb62af9bf85ff`,
2787 /// 14808 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p):
2788 /// ```text
2789 /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \
2790 /// -pix_fmt yuv444p -strict -1 -f yuv4mpegpipe - | \
2791 /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 \
2792 /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 \
2793 /// --limit=4 --superres-mode=1 --superres-denominator=12 \
2794 /// --superres-kf-denominator=12 --obu -o - -
2795 /// ```
2796 /// The two denominator flags are the whole point: without them the cell
2797 /// does not exist. Verified byte-reproducible — re-encoding this recipe
2798 /// reproduces the pinned 14808 bytes exactly.
2799 ///
2800 /// **What the cell exercises.** Coded 171x128 upscaled to 256x128 at
2801 /// `denom = 12`, so a 4:4:4 chroma plane is upscaled at FULL resolution
2802 /// (a 4:2:0 stream halves it first, and libaom's `av1_superres_upscale`
2803 /// takes a different path per chroma format). Measured `superres_hits` 4
2804 /// and `mc::predict_scaled_hits` 2130 — the upscaler and scaled inter
2805 /// prediction both run, so the cell is not passing on an unscaled
2806 /// stream.
2807 ///
2808 /// Non-vacuity, four ways: the pinned bytes (length + FNV-1a); the parsed
2809 /// headers really are `use_superres` at `denom 12` with the SCALED coded
2810 /// size, and the coded width is re-derived from `UpscaledWidth` and the
2811 /// denominator rather than only compared to a literal, so a re-pinned
2812 /// fixture cannot drift past the assertion; both counters are asserted as
2813 /// DELTAS; and every decode-order frame is compared byte-for-byte
2814 /// through `decode_all_frames_vs_oracle`, which is what makes the
2815 /// upscaled width on both sides a real check.
2816 #[test]
2817 fn a_444_lossy_superres_stream_decodes_pixel_exact() {
2818 const NAME: &str = "a_444_lossy_superres_stream_decodes_pixel_exact";
2819 const FIXTURE: &str = "fixtures/444_lossy_superres_256x128_d12.obu";
2820 const FIXTURE_LEN: usize = 14808;
2821 const FIXTURE_FNV: u64 = 0x44e0_d12f_1155_0e09;
2822 /// Quoted so a re-pin has to be deliberate; the FNV above is what the
2823 /// gate actually compares, this is what a human reads.
2824 const FIXTURE_SHA256: &str =
2825 "450caa3e31526a8973b9f64d5030a2f11b87bd60fac07aef121cb62af9bf85ff";
2826 const UPSCALED: (usize, usize) = (256, 128);
2827 const CODED: (usize, usize) = (171, 128);
2828 const DENOM: u8 = 12;
2829 const FRAMES: usize = 4;
2830 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(FIXTURE);
2831 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
2832 panic!(
2833 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
2834 which is a failure, not a skip",
2835 obu.display()
2836 )
2837 });
2838 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
2839 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
2840
2841 // --- the header facts the CELL depends on, parsed not assumed ------
2842 let mut parser = Av1Parser::new();
2843 let mut pos = 0usize;
2844 let mut seq = None;
2845 let mut heads: Vec<FrameHeader> = Vec::new();
2846 while pos < stream.len() {
2847 let obu = parser
2848 .parse_obu(&stream[pos..])
2849 .unwrap_or_else(|e| panic!("{NAME}: aomenc OBU does not parse: {e:?}"));
2850 if obu.total_size == 0 {
2851 break;
2852 }
2853 pos += obu.total_size;
2854 match obu.kind {
2855 ObuKind::SequenceHeader(s) => seq = Some(s),
2856 ObuKind::FrameHeader(h) => heads.push(*h),
2857 ObuKind::Frame(h, _) => heads.push(*h),
2858 _ => {}
2859 }
2860 }
2861 let seq = seq.unwrap_or_else(|| panic!("{NAME}: the stream carries no sequence header"));
2862 assert_eq!(
2863 (
2864 seq.color_config.subsampling_x,
2865 seq.color_config.subsampling_y
2866 ),
2867 (0, 0),
2868 "{NAME}: the stream is not 4:4:4 (ss = ({}, {}))",
2869 seq.color_config.subsampling_x,
2870 seq.color_config.subsampling_y
2871 );
2872 assert_eq!(
2873 seq.color_config.bit_depth, 8,
2874 "{NAME}: not the 8-bit cell this gate names"
2875 );
2876 assert!(
2877 seq.enable_superres,
2878 "{NAME}: the sequence header does not enable superres at all"
2879 );
2880 assert_eq!(
2881 heads.len(),
2882 FRAMES,
2883 "{NAME}: {} frame headers, expected {FRAMES}",
2884 heads.len()
2885 );
2886 for (i, h) in heads.iter().enumerate() {
2887 // The assertion the phantom cell failed. Without the denominator
2888 // flags aomenc picks 8 and this is false while the stream still
2889 // decodes, which is how a whole sweep cell ends up mislabelled.
2890 assert!(
2891 h.use_superres,
2892 "{NAME}: frame {i} has use_superres = false -- this is an UNSCALED \
2893 stream and the gate would be measuring something other than the \
2894 cell it names (class gate-blind-to-feature)"
2895 );
2896 assert_eq!(
2897 h.superres_denom, DENOM,
2898 "{NAME}: frame {i} denominator moved from {DENOM}"
2899 );
2900 assert_eq!(
2901 (h.upscaled_width as usize, h.frame_height as usize),
2902 (UPSCALED.0, UPSCALED.1),
2903 "{NAME}: frame {i} upscaled size moved"
2904 );
2905 assert_eq!(
2906 (h.frame_width as usize, h.frame_height as usize),
2907 (CODED.0, CODED.1),
2908 "{NAME}: frame {i} CODED size moved -- this is the scaled half of \
2909 the cell and the part an unsized stream gets wrong"
2910 );
2911 // Re-derive rather than only compare literals, so a re-pinned
2912 // fixture cannot satisfy the numbers above while the scaled-size
2913 // arithmetic has moved under them.
2914 assert_eq!(
2915 (h.upscaled_width * 8 + u32::from(DENOM) / 2) / u32::from(DENOM),
2916 h.frame_width,
2917 "{NAME}: frame {i}: FrameWidth is not (UpscaledWidth*8 + denom/2)/denom -- \
2918 the scaled size the cell rests on is not the spec's"
2919 );
2920 }
2921
2922 // --- the pixels -----------------------------------------------------
2923 let _guard = lock_gate_counters();
2924 let before_sr = crate::superres::superres_hits();
2925 let before_scaled = crate::mc::predict_scaled_hits();
2926 let frames = decode_stream(&stream).unwrap_or_else(|e| {
2927 panic!("{NAME}: the pinned 4:4:4 superres stream was refused: {e}")
2928 });
2929 let scaled_up = crate::superres::superres_hits() - before_sr;
2930 let scaled_mc = crate::mc::predict_scaled_hits() - before_scaled;
2931 assert!(
2932 scaled_up > 0,
2933 "{NAME}: zero superres_hits -- the upscaler never ran (class \
2934 gate-blind-to-feature)"
2935 );
2936 assert!(
2937 scaled_mc > 0,
2938 "{NAME}: zero predict_scaled_hits -- no inter block read a scaled reference, \
2939 so the scaled-PREDICTION half of the cell is unexercised (class \
2940 gate-blind-to-feature)"
2941 );
2942 assert_eq!(frames.len(), FRAMES, "{NAME}: decoded frame count");
2943 for (i, f) in frames.iter().enumerate() {
2944 // The upscale must have REPLACED the frame: a decoder that
2945 // returned the 171-wide coded picture fails here, and without
2946 // this check the chroma-shape assertion below could be satisfied
2947 // by quarter-size planes.
2948 assert_eq!(
2949 (f.width, f.height),
2950 UPSCALED,
2951 "{NAME}: frame {i} came back {}x{}, not the UPSCALED {}x{}",
2952 f.width,
2953 f.height,
2954 UPSCALED.0,
2955 UPSCALED.1
2956 );
2957 assert_eq!(
2958 f.u.len(),
2959 UPSCALED.0 * UPSCALED.1,
2960 "{NAME}: frame {i} chroma plane is {} samples; at 4:4:4 upscaled it must \
2961 be full resolution ({}x{})",
2962 f.u.len(),
2963 UPSCALED.0,
2964 UPSCALED.1
2965 );
2966 assert_eq!(
2967 f.v.len(),
2968 UPSCALED.0 * UPSCALED.1,
2969 "{NAME}: frame {i} V plane is {} samples, expected full resolution",
2970 f.v.len()
2971 );
2972 }
2973 if aomdec_available(NAME) {
2974 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
2975 eprintln!(
2976 "{NAME}: {decoded} decode-order frame(s) ({hidden} hidden) byte-exact vs \
2977 aomdec at {UPSCALED:?} upscaled from {CODED:?} denom {DENOM}, \
2978 {scaled_up} upscale(s), {scaled_mc} scaled MC block(s); fixture sha256 \
2979 {FIXTURE_SHA256}"
2980 );
2981 }
2982 }
2983
2984 /// lane-av1superpin (a): `--superres-mode=1 --superres-denominator=9`, the
2985 /// WIDEST frame-edge margin this 256x128 geometry allows -- coded 228x128
2986 /// upscaled to 256x128, `denom = 9`, on all four frames.
2987 ///
2988 /// **Why 9 and not 12.** The den=12 cell beside it (coded 171x128) is the
2989 /// one the chroma-format sweep's matrix row ended up pointing at, and
2990 /// denom 16 (coded 128x128) is the degenerate one where the coded width
2991 /// equals the superblock grid exactly. Nine is the largest denominator
2992 /// libaom's own `SUPERRES_NUM` ladder accepts here and still scales, and
2993 /// it is the member that leaves the most coded samples at the frame's
2994 /// right edge: `228 * 8 / 256` of the frame is a 28-column upscale margin,
2995 /// against 12's 85 columns. A wide margin is where a round-trip is most
2996 /// likely to read past the coded picture, so it is the member worth
2997 /// pinning next to the den=12 one.
2998 ///
2999 /// **The recipe** (sha256
3000 /// `3d619ee0fda3d9bb9cf8ff0541ba00ea5d83ae38cd8eec1322f8dbbbe6a5ec96`,
3001 /// 17437 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p):
3002 /// ```text
3003 /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \
3004 /// -pix_fmt yuv444p -strict -1 -f yuv4mpegpipe - | \
3005 /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 \
3006 /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 \
3007 /// --limit=4 --superres-mode=1 --superres-denominator=9 \
3008 /// --superres-kf-denominator=9 --obu -o - -
3009 /// ```
3010 /// Byte-reproducible: re-encoding this recipe reproduces the pinned 17437
3011 /// bytes exactly, and the PARSED headers of that re-encode were read
3012 /// (`frame=228x128 upscaled=256 use_superres=true denom=9` on all four) --
3013 /// which is where the numbers below come from, not from the flags.
3014 #[test]
3015 fn a_444_lossy_superres_mode1_den9_stream_decodes_pixel_exact() {
3016 a_444_superres_arm(
3017 "a_444_lossy_superres_mode1_den9_stream_decodes_pixel_exact",
3018 "fixtures/444_lossy_superres_256x128_d9.obu",
3019 17437,
3020 0x1ff2_fb84_528f_aa05,
3021 "3d619ee0fda3d9bb9cf8ff0541ba00ea5d83ae38cd8eec1322f8dbbbe6a5ec96",
3022 (256, 128),
3023 &[(9, 228); 4],
3024 );
3025 }
3026
3027 /// lane-av1superpin (b): `--superres-mode=2` (random denominator), coded
3028 /// 186x128 on the first frame and a DIFFERENT denominator on each frame
3029 /// after it.
3030 ///
3031 /// **This is the cell that makes the flag-vs-header distinction
3032 /// unavoidable.** Measured on the pinned bytes by parsing every frame
3033 /// header, `--superres-mode=2` does not honour `--superres-denominator`
3034 /// at all -- encoding the recipe four times (no denominator, then 9, 12,
3035 /// 16) produced ONE stream, sha256
3036 /// `c18496cf3b7db0feca9aa904024cec2115be80b5b94f87c848ac52f9b32ffd97`
3037 /// (16620 bytes), byte-identical every time -- and the parsed headers of
3038 /// that stream are:
3039 ///
3040 /// ```text
3041 /// FH0 frame=186x128 upscaled=256 use_superres=true denom=11
3042 /// FH1 frame=146x128 upscaled=256 use_superres=true denom=14
3043 /// FH2 frame=137x128 upscaled=256 use_superres=true denom=15
3044 /// FH3 frame=228x128 upscaled=256 use_superres=true denom=9
3045 /// ```
3046 ///
3047 /// So a gate written against this cell that read the flag instead of the
3048 /// header would assert `denom == 9` (or 12, or 16) and be wrong on three
3049 /// of four frames -- or, worse, pass while printing numbers the stream does
3050 /// not carry. Three of the four parsed denominators (11, 14, 15) are values
3051 /// no flag on the command line ever named, which is the property the arm
3052 /// below asserts directly.
3053 ///
3054 /// **Why it is worth a gate of its own** beyond the flag-ignoring point:
3055 /// the den=12 and den=9 cells both scale every frame at one denominator,
3056 /// so `av1_superres_upscale` is only ever handed one coded-to-upscaled
3057 /// ratio. This stream hands it four (256->186, 256->146, 256->137,
3058 /// 256->228) in one decode, and libaom's upscaler picks its filter taps
3059 /// from `denom` per frame. That is the case a single-denominator gate
3060 /// cannot reach.
3061 ///
3062 /// **The recipe**:
3063 /// ```text
3064 /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \
3065 /// -pix_fmt yuv444p -strict -1 -f yuv4mpegpipe - | \
3066 /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 \
3067 /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 \
3068 /// --limit=4 --superres-mode=2 --obu -o - -
3069 /// ```
3070 #[test]
3071 fn a_444_lossy_superres_mode2_random_denom_stream_decodes_pixel_exact() {
3072 const NAME: &str = "a_444_lossy_superres_mode2_random_denom_stream_decodes_pixel_exact";
3073 let heads = a_444_superres_arm(
3074 NAME,
3075 "fixtures/444_lossy_superres_mode2_256x128.obu",
3076 16620,
3077 0x8cbb_36b2_5e0f_07ab,
3078 "c18496cf3b7db0feca9aa904024cec2115be80b5b94f87c848ac52f9b32ffd97",
3079 (256, 128),
3080 &[(11, 186), (14, 146), (15, 137), (9, 228)],
3081 );
3082
3083 // The flag-ignoring arm. Every denominator libaom accepted on the
3084 // command line, plus the recipe's own "no denominator at all", must
3085 // land on the SAME bytes as the pinned fixture. If a future libaom
3086 // starts honouring the flag under mode 2 this goes red -- and that is
3087 // the point: the gate above is pinned to parsed denominators, so the
3088 // day the flag starts mattering the pin has to be re-derived from the
3089 // stream, not from the recipe.
3090 if !have_ffmpeg() || !have_aomenc() {
3091 eprintln!("{NAME}: flag-ignoring arm skipped (no ffmpeg/aomenc)");
3092 return;
3093 }
3094 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3095 .args([
3096 "-v",
3097 "error",
3098 "-f",
3099 "lavfi",
3100 "-i",
3101 "testsrc2=size=256x128:rate=25",
3102 "-frames:v",
3103 "4",
3104 "-pix_fmt",
3105 "yuv444p",
3106 "-strict",
3107 "-1",
3108 "-f",
3109 "yuv4mpegpipe",
3110 "-",
3111 ])
3112 .stdin(Stdio::null())
3113 .stdout(Stdio::piped())
3114 .stderr(Stdio::piped()), None, |c| c.output())
3115 .expect("ffmpeg failed to run");
3116 assert!(
3117 y4m.status.success(),
3118 "{NAME}: ffmpeg refused to generate the y4m source: {}",
3119 String::from_utf8_lossy(&y4m.stderr)
3120 );
3121 let pinned = std::fs::read(
3122 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3123 .join("fixtures/444_lossy_superres_mode2_256x128.obu"),
3124 )
3125 .expect("pinned fixture disappeared between the two reads");
3126 for extra in [
3127 vec![],
3128 vec!["--superres-denominator=9"],
3129 vec!["--superres-denominator=12"],
3130 vec!["--superres-denominator=16"],
3131 ] {
3132 let mut args: Vec<&str> = vec![
3133 "--codec=av1",
3134 "--passes=1",
3135 "--end-usage=q",
3136 "--cq-level=20",
3137 "--cpu-used=2",
3138 "--threads=1",
3139 "--row-mt=0",
3140 "--lag-in-frames=0",
3141 "--kf-max-dist=100",
3142 "--limit=4",
3143 "--superres-mode=2",
3144 ];
3145 args.extend(extra.iter().copied());
3146 args.extend(["--obu", "-o", "-", "-"]);
3147 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3148 assert!(
3149 out.status.success(),
3150 "{NAME}: aomenc refused the recipe with {extra:?}: {}",
3151 String::from_utf8_lossy(&out.stderr)
3152 );
3153 assert_eq!(
3154 out.stdout.len(),
3155 pinned.len(),
3156 "{NAME}: --superres-mode=2 {extra:?} produced {} bytes, pinned is {} -- \
3157 mode 2 now honours --superres-denominator (or stopped scaling), and this \
3158 gate's per-frame denominators are pinned to the PARSED headers, not to \
3159 the recipe",
3160 out.stdout.len(),
3161 pinned.len()
3162 );
3163 assert_eq!(
3164 fnv1a64(&out.stdout),
3165 fnv1a64(&pinned),
3166 "{NAME}: --superres-mode=2 {extra:?} does NOT reproduce the pinned bytes"
3167 );
3168 }
3169 // And the denominators the stream carries must include values no flag
3170 // on the command line ever named -- the property that makes "read the
3171 // parsed header" the only correct source for the table above.
3172 let flagged = [9u8, 12, 16];
3173 assert!(
3174 heads
3175 .iter()
3176 .any(|h| h.superres_denom > 0 && !flagged.contains(&h.superres_denom)),
3177 "{NAME}: every parsed denominator is one of the flags {flagged:?} -- if libaom \
3178 ever starts honouring --superres-denominator under mode 2 this cell stops being \
3179 the flag-ignoring one and the pin has to be re-derived"
3180 );
3181 eprintln!(
3182 "{NAME}: --superres-mode=2 with no/9/12/16 denominator flags all reproduce the \
3183 pinned {} bytes; parsed denominators {:?} (flag values {flagged:?} ignored)",
3184 pinned.len(),
3185 heads.iter().map(|h| h.superres_denom).collect::<Vec<_>>()
3186 );
3187 }
3188
3189 /// lane-av1lossy128x96: the 128x96 sibling of the pinned 128x128 witness
3190 /// `a_pinned_444_inter_stream_chroma_units_inherit_their_own_quadrants_tx_type`
3191 /// (commit 6c33f204). That fix closed the "4:4:4 lossy + TX size search"
3192 /// divergence (H2) for the 128x128 twin; the 128x96 geometry -- two whole
3193 /// 64x64 roots over a frame whose second block row is only 32 rows tall,
3194 /// which is why it exercises BOTH chroma planes and a partial block row --
3195 /// was left ungated, and it is the geometry the sweep measured the
3196 /// U+V form of the defect on (608 wrong samples from decode-order frame 2).
3197 ///
3198 /// Measured for this lane on the fix's parent `4155c7c7`: decode-order
3199 /// frames 2 and 3 differ from the oracle in 608 and 692 samples (luma
3200 /// exact, U and V wrong), entropy bit-identical; at HEAD and at `6c33f204`
3201 /// all four frames are byte-exact. So the defect is FIXED and this gate is
3202 /// the pin that keeps it fixed.
3203 ///
3204 /// Recipe (encoded LIVE, no fixture): `testsrc2 128x96:rate=25` yuv444p
3205 /// 4 frames, `aomenc --profile=1 --codec=av1 --passes=1 --end-usage=q
3206 /// --cq-level=20 --cpu-used=2 --sb-size=64 --min-partition-size=64
3207 /// --max-partition-size=64 --enable-tx-size-search=1 --threads=1 --row-mt=0
3208 /// --lag-in-frames=0 --kf-max-dist=100 --limit=4 --obu -o - -`.
3209 /// Search ON: 21830 B, sha256 `7380bcbbfb791c6a369850357211223e20fab959423135951f6eb43ffbfcfebd`,
3210 /// fnv1a64 `0x1ba3fe9a4335bdbb`. Control arm, same recipe with
3211 /// `--enable-tx-size-search=0`: 21296 B, sha256
3212 /// `347edcc9f4899fb05b15174b82d37f6562dcc6fe7691af0ed9ba4efd6cc878c6`,
3213 /// fnv1a64 `0x2f87d8e98c9db686`.
3214 ///
3215 /// NON-VACUITY, and the search flag is NOT the assert: the recipe SPELLS
3216 /// `--enable-tx-size-search=1` (aomenc keeps the FIRST occurrence, and a
3217 /// flag left defaulted is "unknown", not "on"), and then
3218 /// 1. every frame header's PARSED `tx_mode` is `TxMode::Select`
3219 /// (`TX_MODE_SELECT`) -- the searched transform mode is really in the
3220 /// bitstream, not merely requested. The control arm asserts the
3221 /// opposite (`TxMode::Largest`), so neither arm can pass on the other's
3222 /// stream;
3223 /// 2. the sequence header is `ss (0,0)` at 8 bits (`assert_444_header`),
3224 /// and the stream is byte-identical to the recorded encode (length +
3225 /// fnv1a64), so an aomenc that stopped producing this cell fails here
3226 /// rather than silently measuring something else;
3227 /// 3. `decode::chroma_quad_leaf_tx_diff_hits()` strictly increases on the
3228 /// search arm -- the number that says the per-quadrant resolve CHANGED
3229 /// an answer, which is the defect itself. It must be exactly 0 on the
3230 /// search-off control: with no var-tx there is no four-leaf luma tree,
3231 /// so the arm is unreachable and a counter that fired there would be
3232 /// counting something else;
3233 /// 4. every decoded plane is 128*96 (at `ss (0,0)` chroma is full
3234 /// resolution, so a subsampled extent fails the shape assert);
3235 /// 5. `decode_all_frames_vs_oracle` asserts the decode-order frame COUNT
3236 /// and each frame's byte LENGTH before any sample is compared.
3237 ///
3238 /// Red-before: reverting ONLY the per-quadrant resolve in
3239 /// `decode_inter_block`'s 64x64 four-unit chroma arm (the `covering_leaf_tx_type`
3240 /// call back to the block-level `first_tx_type`, counters and this gate
3241 /// untouched) turns this gate red on decode-order frame 2 with 608 bytes
3242 /// differing, and green again on restore.
3243 #[test]
3244 fn a_real_aomenc_444_whole_64_root_tx_size_search_stream_decodes_pixel_exact_at_128x96() {
3245 const NAME: &str =
3246 "a_real_aomenc_444_whole_64_root_tx_size_search_stream_decodes_pixel_exact_at_128x96";
3247 let _gate_lock = lock_gate_counters();
3248 if !have_ffmpeg() || !have_aomenc() {
3249 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
3250 return;
3251 }
3252 // (label, --enable-tx-size-search, parsed tx mode, bytes, fnv1a64)
3253 let arms: [(&str, &str, TxMode, usize, u64); 2] = [
3254 (
3255 "tx size search on",
3256 "1",
3257 TxMode::Select,
3258 21830,
3259 0x1ba3_fe9a_4335_bdbb,
3260 ),
3261 (
3262 "tx size search off (control)",
3263 "0",
3264 TxMode::Largest,
3265 21296,
3266 0x2f87_d8e9_8c9d_b686,
3267 ),
3268 ];
3269 for (label, search, want_mode, want_len, want_fnv) in arms {
3270 let search_flag = format!("--enable-tx-size-search={search}");
3271 let stream = chroma_format_stream(
3272 128,
3273 96,
3274 "yuv444p",
3275 8,
3276 4,
3277 &[
3278 "--profile=1",
3279 "--cq-level=20",
3280 "--cpu-used=2",
3281 "--sb-size=64",
3282 "--min-partition-size=64",
3283 "--max-partition-size=64",
3284 &search_flag,
3285 ],
3286 0,
3287 );
3288 assert_444_header(&stream, NAME, 8);
3289 assert_eq!(
3290 stream.len(),
3291 want_len,
3292 "{NAME} ({label}): aomenc produced {} bytes, not the recorded {want_len} -- the \
3293 recipe no longer makes this cell",
3294 stream.len()
3295 );
3296 assert_eq!(
3297 fnv1a64(&stream),
3298 want_fnv,
3299 "{NAME} ({label}): the encoded bytes moved"
3300 );
3301 // PARSED, not requested: the transform mode the bitstream carries.
3302 let mut parser = Av1Parser::new();
3303 let mut pos = 0usize;
3304 let mut modes: Vec<TxMode> = Vec::new();
3305 while pos < stream.len() {
3306 let obu = parser
3307 .parse_obu(&stream[pos..])
3308 .unwrap_or_else(|e| panic!("{NAME}: aomenc OBU does not parse: {e:?}"));
3309 if obu.total_size == 0 {
3310 break;
3311 }
3312 pos += obu.total_size;
3313 if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = obu.kind {
3314 modes.push(h.tx_mode);
3315 }
3316 }
3317 assert_eq!(
3318 modes.len(),
3319 4,
3320 "{NAME} ({label}): four frame headers expected"
3321 );
3322 for (i, mode) in modes.iter().enumerate() {
3323 assert_eq!(
3324 *mode, want_mode,
3325 "{NAME} ({label}): decode-order frame {i} carries tx_mode {mode:?}, not \
3326 {want_mode:?} -- the searched-transform claim is about the bitstream"
3327 );
3328 }
3329 let diff0 = crate::decode::chroma_quad_leaf_tx_diff_hits();
3330 let frames = decode_stream(&stream)
3331 .unwrap_or_else(|e| panic!("{NAME} ({label}): refused the stream: {e}"));
3332 let diff = crate::decode::chroma_quad_leaf_tx_diff_hits() - diff0;
3333 for (i, f) in frames.iter().enumerate() {
3334 assert_eq!(
3335 f.y.len(),
3336 128 * 96,
3337 "{NAME} ({label}): frame {i} luma is {} samples, not 128x96",
3338 f.y.len()
3339 );
3340 assert_eq!(
3341 f.u.len(),
3342 128 * 96,
3343 "{NAME} ({label}): frame {i} U is {} samples -- at 4:4:4 the chroma plane is \
3344 full resolution",
3345 f.u.len()
3346 );
3347 }
3348 // Pixel compare FIRST: it is the informative failure (it names the
3349 // decode-order frame and the sample), and the counter assert below
3350 // is the guard that says WHY the cell is not vacuous.
3351 let (frames_decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME);
3352 assert!(
3353 frames_decoded >= 4,
3354 "{NAME} ({label}): {frames_decoded} decode-order frames"
3355 );
3356 if label.starts_with("tx size search on") {
3357 assert!(
3358 diff >= 2,
3359 "{NAME}: the per-quadrant tx_type resolve never CHANGED an answer (diff \
3360 {diff}) -- on this stream the four-leaf luma tree under a searched transform \
3361 is exactly what makes the block-level value wrong"
3362 );
3363 } else {
3364 assert_eq!(
3365 diff, 0,
3366 "{NAME}: the four-unit 4:4:4 chroma arm fired with tx size search OFF \
3367 ({diff} resolves) -- the counter is not measuring the searched path"
3368 );
3369 }
3370 eprintln!(
3371 "{NAME} ({label}): {frames_decoded} frames byte-exact vs aomdec, tx_mode \
3372 {want_mode:?} on every frame, quad-tx resolves that differed {diff}"
3373 );
3374 }
3375 }
3376
3377 /// lane-ibc444c: the 4:4:4 intra-BC chroma cell. `decode_intrabc_rect`
3378 /// sized a rect intra-BC block's chroma plane block with a hardcoded 4:2:0
3379 /// halving (`bw / 2`, `bh / 2`, origin `px / 2`).
3380 /// `av1_get_max_uv_txsize` (`av1/common/blockd.h`) is `ss_size_lookup[bsize]`
3381 /// and applies NO halving of its own, and `get_vartx_max_txsize` (`:1447`)
3382 /// then reads that plane block as `max_txsize_rect_lookup[plane_bsize]`. So
3383 /// at 4:4:4 an 8x16 luma block's chroma plane block is 8x16 and libaom
3384 /// codes it as ONE TX_8X16, while the halving read the same 8x16 footprint
3385 /// as ONE 4x8 rect unit.
3386 ///
3387 /// **Localised by trace, not by reading** (`EC_IBCTX`, this commit's rung
3388 /// on `read_coeffs_rect`, paired against the oracle's `EC_ECDUMP_IN` by
3389 /// STREAM BIT POSITION — never by the 16-bit `rng`, which collides at this
3390 /// scale, and never by a plane label, which is the ORACLE's side of the
3391 /// pairing):
3392 ///
3393 /// ```text
3394 /// oracle bit 6870 plane=0 mi=(92,104) tx=7 (TX_8X16) all_zero=0
3395 /// ours bit 6885 8x16 skip_ctx=0 decode.rs (read_inter_plane_rect)
3396 /// oracle bit 6878 plane=1 mi=(92,104) tx=7 (TX_8X16) all_zero=1
3397 /// ours bit 6893 4x8 skip_ctx=0 decode.rs <-- FORK
3398 /// oracle bit 6879 plane=2 mi=(92,104) tx=7 (TX_8X16) all_zero=1
3399 /// ours bit 6902 4x8 skip_ctx=0 decode.rs
3400 /// ```
3401 ///
3402 /// The `txb_skip` VALUE first disagrees one unit before the bit position
3403 /// does: the oracle skips the U unit, we do not, we burn 14 extra bits, and
3404 /// every later symbol decodes from the wrong place. Reverting the two
3405 /// arithmetic lines reproduces luma sample **205264** as the first wrong
3406 /// sample — the exact ceiling `lanes/av1444rect.report.md` rounds 3-4
3407 /// documented — which is the red-before proof.
3408 ///
3409 /// **The 4:4:4 pixel arm is a PREFIX, not an exactness claim, and the
3410 /// residual is an ENTROPY fork — NOT a reconstruction one.** An earlier
3411 /// round of this lane claimed the coefficient ladder was "bit-exact for all
3412 /// 2359 oracle units" and inferred from that the tail was reconstruction.
3413 /// **That claim was wrong and is retracted** (see this branch's report r2):
3414 /// the walk compared entry bits at matching LIST INDICES across two traces
3415 /// of different lengths, and the square `read_coeffs` reader logs an
3416 /// `all_zero` step even for a read that consumes ZERO bits, so it paired
3417 /// 0-bit lines against real units. Measured on this branch, with the
3418 /// 0-bit filter applied to BOTH sides:
3419 ///
3420 /// ```text
3421 /// oracle all_zero reads 2395 (2359 with a real position)
3422 /// our all_zero lines 3999
3423 /// our lines that consumed bits 1326
3424 /// 1:1 entry-bit matches, monotone merge 71
3425 /// ```
3426 ///
3427 /// We perform ~1069 FEWER real symbol reads than the oracle. A
3428 /// reconstruction-only defect cannot make a symbol count come up short, so
3429 /// the tail is a second entropy fork, first visible in U and V at
3430 /// **(x=160, y=80) = mi (20, 40)**, spreading to the whole x[320,640)
3431 /// y[160,480) quadrant. (A figure of "1910 units matching 1:1 with 486 vs
3432 /// 486 non-zero-bit reads" was relayed to this lane and does NOT reproduce
3433 /// here — re-measure before quoting either number.)
3434 ///
3435 /// **The next reader must pair by BIT INTERVAL, not by index.** The oracle's
3436 /// `EC_ECDUMP_IN` prints only the ENTRY position; there is no post position,
3437 /// and entry bits alone drift the moment per-unit bit consumption differs.
3438 /// The unblock is one line of oracle instrumentation OUTSIDE the repo —
3439 /// print `aom_reader_tell(r)` after the `aom_read_symbol` at
3440 /// `~/.cache/aom-oracle/src/av1/decoder/decodetxb.c:158` — then pair on
3441 /// `(entry, post)`, which is exact and collision-free. Coordinate the
3442 /// rebuild with the main session; every lane's oracle binary moves.
3443 ///
3444 /// 4:2:0 identity is a first-class arm, not a claim: `ss_x = ss_y = 1`
3445 /// makes `bw >> ss_x` the same arithmetic as the halving, and the pinned
3446 /// 4:2:0 twin (`420_intrabc_rect4_witness.obu`) is asserted byte-exact
3447 /// against the oracle in the same run.
3448 /// lane-av1offtile: a lossless HORZ/VERT strip's PLANE-MAJOR 4x4 chroma
3449 /// walk is bounded by the CHROMA PLANE, not by the block's own footprint.
3450 ///
3451 /// libaom bounds every transform walk per PLANE -- `max_block_wide` /
3452 /// `max_block_high` (`av1_common_int.h:1565`) add `mb_to_right_edge >>
3453 /// (3 + pd->subsampling_x)` to the plane block's size before the
3454 /// `>> MI_SIZE_LOG2`, and `av1_foreach_transformed_block_in_plane`
3455 /// (`decodeframe.c:1124`) drops any unit whose `blk_col`/`blk_row` is past
3456 /// them. `decode_rect_split`'s luma walk carries that clip
3457 /// (`decode.rs`, the `tu_px >= y.true_width` guard lane-hgkf r1 added for
3458 /// the LUMA plane); its lossless chroma walk counted `chroma_w / 4` x
3459 /// `chroma_h / 4` off the block instead, so a block overhanging the bottom-
3460 /// right frame edge read chroma transform units that do not exist.
3461 ///
3462 /// MEASURED on `mix176_offtile_chroma_clip.obu`, whose bytes are frame 0
3463 /// of the 4:2:0 8-bit `mix_176x144_6.obu`
3464 /// (`ffmpeg -f lavfi -i testsrc2=size=176x144:rate=25 -frames:v 6
3465 /// -pix_fmt yuv420p`, then `aomenc --codec=av1 --obu --passes=1
3466 /// --cpu-used=4 --limit=6 --end-usage=q --cq-level=0 --aq-mode=1`; the
3467 /// whole 6-frame stream is 20 069 B, sha256
3468 /// `02b15d0d5b08aa5aebf139aee94c31b4f8363d14649c238cd7a19a9785ef124a`,
3469 /// and this fixture is its first 4 581 B -- the temporal delimiter,
3470 /// sequence header and frame-0 OBU, nothing else). The bottom-right
3471 /// superblock is the 48x16 sliver of a 176x144 frame, and its block at
3472 /// `mi=(32,32)` `px=(128,128)` is `bw=64 bh=32`, so the chroma plane
3473 /// block (`cpx=64 cpy=64`, plane 88x72) is 32x16 where only 24x8 is coded.
3474 /// That is `cw_n` 8 -> 6 and `ch_n` 4 -> 2: **20 phantom units per plane,
3475 /// 40 in total**, and 40 is exactly the extra-read count the paired
3476 /// `EC_SYMR` ladder measures (ours 25792..25831, the oracle doing a
3477 /// range-coder init for the next frame there).
3478 ///
3479 /// The unit count below is the load-bearing number, not the pixels: the
3480 /// 40 phantom reads all carry `all_zero` and consume no data (the bit
3481 /// position freezes at 36288), so frame 0's pixels are byte-exact EITHER
3482 /// WAY and a pixel compare alone would be blind to this defect. Frame 0's
3483 /// transform-unit count is 2413 without the clip and 2373 with it, and
3484 /// **2373 is the oracle's own count** -- the number of `EC_ECDUMP_IN`
3485 /// lines the shared `aomdec` prints for the same bytes. Reverting the
3486 /// clip restores 2413 and fails this assert; that is the mutation proof.
3487 ///
3488 /// What the 40 reads cost, on the FULL 6-frame stream rather than this
3489 /// prefix: the desync is 11 970 reads downstream of them, where the
3490 /// exhausted tile yields an unbounded `read_golomb` tail and the decoder
3491 /// refuses with `unsupported: AV1 tile (a Golomb tail longer than this
3492 /// decoder reads)` -- a supported 4:2:0 8-bit cell lost to a walk that ran
3493 /// off its own tile. Fixing the walk moves the first remaining divergence
3494 /// on the full stream from SYMR 25 792 to 29 411, a different block at a
3495 /// different geometry (the var-tx/`lossless` conjunct lane-av1mixllfork
3496 /// and lane-av1golomb320 own), and both this clip and that one applied
3497 /// together decode the cell and match the oracle byte for byte. That
3498 /// composition is measured, not claimed: this gate pins only the walk
3499 /// this commit fixes.
3500 #[test]
3501 fn a_420_lossless_rect_chroma_walk_is_bounded_by_the_chroma_plane() {
3502 const NAME: &str = "a_420_lossless_rect_chroma_walk_is_bounded_by_the_chroma_plane";
3503 const FIXTURE: &str = "mix176_offtile_chroma_clip.obu";
3504 const FIXTURE_LEN: usize = 4581;
3505 const FIXTURE_FNV: u64 = 0x5e31be5efc9c3c1d;
3506 /// The oracle's own `EC_ECDUMP_IN` count for these bytes.
3507 const ORACLE_UNITS: usize = 2373;
3508 const W: usize = 176;
3509 const H: usize = 144;
3510
3511 let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3512 .join(format!("fixtures/{FIXTURE}"));
3513 let stream = read_pin(&path, FIXTURE_LEN, FIXTURE_FNV, NAME);
3514 assert_eq!(
3515 stream_bit_depth(&stream, NAME),
3516 8,
3517 "{NAME}: the pinned witness is not 8-bit"
3518 );
3519
3520 let _guard = lock_gate_counters();
3521 crate::decode::reset_rect_split_lossless_chroma_offtile_hits();
3522 crate::decode::reset_census_unit_n();
3523 let frames = decode_stream(&stream)
3524 .unwrap_or_else(|e| panic!("{NAME}: the pinned witness no longer decodes: {e}"));
3525 assert_eq!(frames.len(), 1, "{NAME}: frame count");
3526 assert_eq!(
3527 (frames[0].width, frames[0].height),
3528 (W, H),
3529 "{NAME}: dimensions"
3530 );
3531
3532 // Non-vacuity: the clip must have run on this fixture, or the unit
3533 // count below is just "the walk happened to be short here" (class
3534 // gate-blind-to-feature).
3535 let clipped = crate::decode::rect_split_lossless_chroma_offtile_hits();
3536 assert!(
3537 clipped > 0,
3538 "{NAME}: no lossless rect chroma unit fell outside the chroma plane -- \
3539 the corrected walk never ran, so this gate is measuring the \
3540 unclipped one (class gate-blind-to-feature)"
3541 );
3542
3543 // The oracle-anchored red-before/green-after: 2413 without the clip.
3544 let units = crate::decode::census_unit_n();
3545 assert_eq!(
3546 units, ORACLE_UNITS,
3547 "{NAME}: frame 0 walked {units} transform units, the oracle's own \
3548 EC_ECDUMP_IN census for these bytes is {ORACLE_UNITS}"
3549 );
3550
3551 decode_all_frames_vs_oracle(&stream, NAME);
3552 }
3553
3554 #[test]
3555 fn a_444_intrabc_rect_chroma_plane_block_is_the_block_footprint() {
3556 const NAME: &str = "a_444_intrabc_rect_chroma_plane_block_is_the_block_footprint";
3557 const F444: &str = "444_intrabc_rect4_witness.obu";
3558 const F444_LEN: usize = 1016;
3559 const F420: &str = "420_intrabc_rect4_witness.obu";
3560 const F420_LEN: usize = 890;
3561 let read = |name: &str, file: &str, len: usize| -> Vec<u8> {
3562 let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3563 .join(format!("fixtures/{file}"));
3564 let bytes = std::fs::read(&path)
3565 .unwrap_or_else(|e| panic!("{name}: pinned fixture {file} missing: {e}"));
3566 assert_eq!(bytes.len(), len, "{name}: {file} length moved");
3567 bytes
3568 };
3569 let stream444 = read(NAME, F444, F444_LEN);
3570 let stream420 = read(NAME, F420, F420_LEN);
3571 // The defect only exists where `ss_size_lookup` != the 4:2:0 halving.
3572 assert_444_header(&stream444, NAME, 8);
3573
3574 let _guard = lock_gate_counters();
3575 crate::decode::reset_ibc_rect_chroma_footprint_444_hits();
3576 let frames = decode_stream(&stream444)
3577 .unwrap_or_else(|e| panic!("{NAME}: the pinned 4:4:4 witness was refused: {e}"));
3578 let hits = crate::decode::ibc_rect_chroma_footprint_444_hits();
3579 assert_eq!(frames.len(), 1, "{NAME}: frame count");
3580 assert!(
3581 hits > 0,
3582 "{NAME}: no rect intra-BC block was sized at 4:4:4 -- the corrected \
3583 footprint never ran, so this gate is measuring the hardcoded 4:2:0 \
3584 halving (class gate-blind-to-feature)"
3585 );
3586
3587 // lane-av1oraclepost: main's shared probe. With
3588 // EC_AV1_REQUIRE_AOMDEC / EC_AV1_REQUIRE_AOMENC set it is a HARD
3589 // failure, so a batch run cannot report GREEN with the compare never
3590 // run -- ONE presence-check shape in the crate.
3591 if !aomdec_available(NAME) {
3592 eprintln!("{NAME}: {hits} rect intra-BC block(s) sized at 4:4:4; pixel arm SKIPPED");
3593 return;
3594 }
3595
3596 // 4:2:0 identity FIRST and in full.
3597 decode_all_frames_vs_oracle(&stream420, &format!("{NAME}-420"));
3598
3599 // 4:4:4 is a per-plane exact PREFIX, not an exactness claim, and the
3600 // doc above says why. Asserting "wrong by exactly N" would encode the
3601 // open entropy fork as expected behaviour; the floor is the honest form
3602 // and it only ever grows.
3603 const PLANE: usize = 640 * 480;
3604 const EXACT_PREFIX: [usize; 3] = [PLANE, 51360, 51360];
3605 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
3606 let _ = std::fs::remove_dir_all(&dir);
3607 std::fs::create_dir_all(&dir).expect("scratch dir");
3608 let in_obu = dir.join("in.obu");
3609 std::fs::write(&in_obu, &stream444).expect("writing the stream");
3610 let aom_prefix = dir.join("aom");
3611 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
3612 .args(["--codec=av1", "-o"])
3613 .arg(dir.join("out.y4m"))
3614 .arg(&in_obu)
3615 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
3616 .stdin(Stdio::null())
3617 .stdout(Stdio::piped())
3618 .stderr(Stdio::piped()), None, |c| c.output())
3619 .expect("aomdec failed to run");
3620 assert!(
3621 out.status.success(),
3622 "{NAME}: the oracle aomdec refused the stream: {}",
3623 String::from_utf8_lossy(&out.stderr)
3624 );
3625 let ours_prefix = dir.join("ours");
3626 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
3627 let _ = decode_stream(&stream444).expect("second decode");
3628 set_final_dump_prefix(None);
3629 let aom_dump = std::fs::read(format!("{}.f0", aom_prefix.display())).expect("oracle dump");
3630 let our_dump = std::fs::read(format!("{}.f0", ours_prefix.display())).expect("our dump");
3631 assert_eq!(
3632 our_dump.len(),
3633 aom_dump.len(),
3634 "{NAME}: our frame is {} bytes, the oracle's is {}",
3635 our_dump.len(),
3636 aom_dump.len()
3637 );
3638 assert_eq!(aom_dump.len(), 3 * PLANE, "{NAME}: 8-bit 4:4:4 640x480");
3639 for (plane, name) in [(0usize, "Y"), (1, "U"), (2, "V")] {
3640 let at = plane * PLANE;
3641 let floor = EXACT_PREFIX[plane];
3642 if our_dump[at..at + floor] == aom_dump[at..at + floor] {
3643 continue;
3644 }
3645 let first = (0..floor)
3646 .find(|&s| our_dump[at + s] != aom_dump[at + s])
3647 .unwrap_or(floor);
3648 panic!(
3649 "{NAME}: plane {name} diverges from the oracle at sample {first} of {PLANE} \
3650 (x={}, y={}) -- the exact prefix this gate pins is {floor} and it only \
3651 grows; the chroma tail is the OPEN entropy fork in \
3652 lanes/ibc444c.report.md r2",
3653 first % 640,
3654 first / 640
3655 );
3656 }
3657 let _ = std::fs::remove_dir_all(&dir);
3658 eprintln!(
3659 "{NAME}: {hits} rect intra-BC block(s) sized at 4:4:4; 4:2:0 twin \
3660 byte-exact; 4:4:4 luma byte-exact (307200/307200), U and V byte-exact to \
3661 sample 51360 -- the chroma tail is the OPEN entropy fork \
3662 (lanes/ibc444c.report.md r2), NOT an assertion"
3663 );
3664 }
3665
3666 /// lane-av1chromarect: the 128-root intra-BC HORZ/VERT strip's chroma
3667 /// plane block, on the 4:4:4 LOSSY witness `fixtures/r512.obu` that
3668 /// reaches `decode_intrabc_owned_rect` five times.
3669 ///
3670 /// The extent is the ss-derived one (`bw >> ss_x` by `bh >> ss_y`;
3671 /// `av1_get_max_uv_txsize` = `ss_size_lookup[bsize]`, blockd.h:1372), and
3672 /// the plane block is walked by `get_vartx_max_txsize` steps -- a 4:4:4
3673 /// 32x64 luma block's chroma plane block is 32x64, which libaom codes as
3674 /// TWO `TX_32X32` units, not as one 32x64 transform.
3675 ///
3676 /// This gate WAS the refusal assertion "a rectangular inter chroma
3677 /// transform unit whose shape has no coefficient table set here", put
3678 /// there one commit earlier so that the day the arm landed it would go
3679 /// RED and force this rewrite. The refusal string is GONE from the
3680 /// witness's decode because nothing reaches it any more, not because it
3681 /// was deleted: `rect_inter_chroma_set` still refuses (32, 64) and the
3682 /// string is still in the source, it is just not on this path any more.
3683 ///
3684 /// The floors were RAISED to full byte-exactness on all three planes of
3685 /// all three frames by lane-av1chromadc, which closed the "open chroma
3686 /// fork" this gate used to carry: a skipped 64x64 square block at 4:4:4
3687 /// has a 64x64 chroma plane block, libaom walks it as a 2x2 grid of
3688 /// `TX_32X32` units, and the intra-BC chroma override was handed to every
3689 /// unit whole instead of windowed per unit (see
3690 /// `a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit`
3691 /// and lanes/av1chromadc.report.md). The history of these floors:
3692 ///
3693 /// * lane-av1chromarect, after the ss-derived extent and the multi-unit
3694 /// walk: `[[262144, 229728, 229728], [262144, 65704, 65704],
3695 /// [262144, 262144, 262144]]` -- luma exact on all three frames, frame 2
3696 /// exact on all three planes, 79969 chroma samples still wrong.
3697 /// * lane-av1chromadc: `[[262144; 3]; 3]` -- every plane of every frame
3698 /// byte-exact against aomdec. Floors only ever grow.
3699 #[test]
3700 fn a_444_intrabc_owned_rect_strip_sizes_its_chroma_plane_block_and_decodes() {
3701 const NAME: &str =
3702 "a_444_intrabc_owned_rect_strip_sizes_its_chroma_plane_block_and_decodes";
3703 const FILE: &str = "r512.obu";
3704 const LEN: usize = 6948;
3705 /// 512x512 8-bit 4:4:4, one plane.
3706 const PLANE: usize = 512 * 512;
3707 /// Exact prefix per (frame, plane), decode order. FULL: every plane of
3708 /// every frame is byte-exact against the oracle.
3709 const EXACT_PREFIX: [[usize; 3]; 3] = [[PLANE; 3]; 3];
3710 let path =
3711 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("fixtures/{FILE}"));
3712 let stream = std::fs::read(&path)
3713 .unwrap_or_else(|e| panic!("{NAME}: pinned fixture {FILE} missing: {e}"));
3714 assert_eq!(stream.len(), LEN, "{NAME}: {FILE} length moved");
3715 assert_444_header(&stream, NAME, 8);
3716
3717 let _guard = lock_gate_counters();
3718 reset_ibc_owned_rect_chroma_footprint_444_hits();
3719 // The refusal this gate used to assert must NOT be what happens now.
3720 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
3721 let _ = std::fs::remove_dir_all(&dir);
3722 std::fs::create_dir_all(&dir).expect("scratch dir");
3723 let obu = dir.join("in.obu");
3724 std::fs::write(&obu, &stream).expect("writing the stream");
3725 let aom_prefix = dir.join("aom");
3726 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
3727 .args(["--codec=av1", "-o"])
3728 .arg(dir.join("out.y4m"))
3729 .arg(&obu)
3730 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
3731 .stdin(Stdio::null())
3732 .stdout(Stdio::piped())
3733 .stderr(Stdio::piped()), None, |c| c.output())
3734 .expect("aomdec failed to run");
3735 assert!(
3736 out.status.success(),
3737 "{NAME}: the oracle aomdec refused the stream: {}",
3738 String::from_utf8_lossy(&out.stderr)
3739 );
3740 let ours_prefix = dir.join("ours");
3741 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
3742 let decoded = decode_stream(&stream);
3743 set_final_dump_prefix(None);
3744 if let Err(e) = decoded {
3745 panic!(
3746 "{NAME}: this decoder refused the witness: {e} -- the chroma plane block is \
3747 sized ss-wide and walked in `get_vartx_max_txsize` units, so the 4:4:4 32x64 \
3748 plane block is two TX_32X32 units, NOT the rect unit the refusal named"
3749 );
3750 }
3751 let hits = ibc_owned_rect_chroma_footprint_444_hits();
3752 assert_eq!(
3753 hits, 5,
3754 "{NAME}: {hits} 128-root intra-BC strip(s) sized at 4:4:4, not 5 -- the witness \
3755 stopped exercising the arm"
3756 );
3757 assert!(
3758 !std::fs::read(format!("{}.f0", ours_prefix.display()))
3759 .unwrap_or_default()
3760 .is_empty(),
3761 "{NAME}: our decoder wrote no frame"
3762 );
3763 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
3764 #[allow(clippy::needless_range_loop)]
3765 for f in 0..3 {
3766 let aom_dump = std::fs::read(format!("{}.f{f}", aom_prefix.display()))
3767 .unwrap_or_else(|e| panic!("{NAME}: oracle dump f{f} missing: {e}"));
3768 let our_dump = std::fs::read(format!("{}.f{f}", ours_prefix.display()))
3769 .unwrap_or_else(|e| panic!("{NAME}: our dump f{f} missing: {e}"));
3770 assert_eq!(
3771 our_dump.len(),
3772 3 * PLANE,
3773 "{NAME}: frame {f} is not 8-bit 4:4:4 512x512"
3774 );
3775 assert_eq!(
3776 our_dump.len(),
3777 aom_dump.len(),
3778 "{NAME}: frame {f} length differs"
3779 );
3780 for (plane, name) in [(0usize, "Y"), (1, "U"), (2, "V")] {
3781 let at = plane * PLANE;
3782 let floor = EXACT_PREFIX[f][plane];
3783 if our_dump[at..at + floor] == aom_dump[at..at + floor] {
3784 continue;
3785 }
3786 let first = (0..floor)
3787 .find(|&s| our_dump[at + s] != aom_dump[at + s])
3788 .unwrap_or(floor);
3789 panic!(
3790 "{NAME}: frame {f} plane {name} diverges from the oracle at sample {first} \
3791 of {PLANE} (x={}, y={}) -- the exact prefix this gate pins is {floor} and \
3792 it only grows",
3793 first % 512,
3794 first / 512
3795 );
3796 }
3797 }
3798 let _ = std::fs::remove_dir_all(&dir);
3799 }
3800
3801 /// lane-av1ibcfork: the SECOND 4:4:4 intra-BC witness, and the one the
3802 /// entropy investigation was chartered against. `444_intrabc_rect4_witness.obu`
3803 /// reaches `decode_intrabc_owned_rect`'s SKIP arm once -- the 64x32 block at
3804 /// mi (40,80) -- and is byte-exact on all three planes.
3805 ///
3806 /// Why a second witness and not a repeat of
3807 /// `a_444_intrabc_owned_rect_strip_sizes_its_chroma_plane_block_and_decodes`
3808 /// (which pins `r512.obu`): the skip arm's defect was a wrong PLACE, not a
3809 /// wrong size, and the two shapes produce DIFFERENT symptoms. `r512.obu`'s
3810 /// 128-root strips fail as a sizing error inside the coefficient walk; this
3811 /// witness's 64x32 skip block read no coefficient at all, so the only
3812 /// symptom was pixels -- a 32x16 window committed at (px/2, py/2) =
3813 /// (160,80) over a region another block had already reconstructed, and its
3814 /// own 64x32 footprint at (320,160) left unwritten. Measured before the
3815 /// ss correction: U 72945 / V 64865 of 307200 wrong, first at (160,80) on
3816 /// both planes, luma byte-exact; the two 8x8-cell difference components
3817 /// were 8 cells at x[160,192) y[80,96) and 1182 cells over the whole
3818 /// x[320,640) y[160,480) quadrant -- one wrong-place write, not two.
3819 ///
3820 /// Full byte-exactness, not a prefix. That is possible only because
3821 /// `lane-av1chromarect` (the ss-derived extent and origins, this function
3822 /// included -- the skip arm was where the defect was first reached) and
3823 /// `lane-av1chromadc` (the per-unit windowed chroma override) both landed;
3824 /// before them this witness carried the open tail
3825 /// `lanes/ibc444c.report.md` r2 recorded. The 4:2:0 twin is asserted
3826 /// byte-exact in the same run, where `>> ss_x` IS `/ 2`.
3827 #[test]
3828 fn a_444_intrabc_rect4_witness_is_byte_exact_after_the_skip_arm_footprint() {
3829 const NAME: &str = "a_444_intrabc_rect4_witness_is_byte_exact_after_the_skip_arm_footprint";
3830 const F444: &str = "444_intrabc_rect4_witness.obu";
3831 const F444_LEN: usize = 1016;
3832 const F420: &str = "420_intrabc_rect4_witness.obu";
3833 const F420_LEN: usize = 890;
3834 const PLANE: usize = 640 * 480;
3835 let read = |file: &str, len: usize| -> Vec<u8> {
3836 let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3837 .join(format!("fixtures/{file}"));
3838 let data =
3839 std::fs::read(&path).unwrap_or_else(|e| panic!("{NAME}: reading {file}: {e}"));
3840 assert_eq!(data.len(), len, "{NAME}: {file} is pinned at {len} bytes");
3841 data
3842 };
3843 let stream444 = read(F444, F444_LEN);
3844 let stream420 = read(F420, F420_LEN);
3845 assert_444_header(&stream444, NAME, 8);
3846
3847 let _guard = lock_gate_counters();
3848 if !aomdec_available(NAME) {
3849 eprintln!("{NAME}: SKIP -- no aomdec; run scripts/build-aom-oracle.sh");
3850 return;
3851 }
3852 // 4:2:0 identity FIRST and in full: `>> ss_x` is `/ 2` at ss=1, so
3853 // this arm is the measurement, not a claim about it.
3854 decode_all_frames_vs_oracle(&stream420, &format!("{NAME}-420"));
3855
3856 crate::decode::reset_ibc_owned_rect_chroma_footprint_444_hits();
3857 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
3858 let _ = std::fs::remove_dir_all(&dir);
3859 std::fs::create_dir_all(&dir).expect("scratch dir");
3860 let in_obu = dir.join("in.obu");
3861 std::fs::write(&in_obu, &stream444).expect("writing the stream");
3862 let aom_prefix = dir.join("aom");
3863 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
3864 .args(["--codec=av1", "-o"])
3865 .arg(dir.join("out.y4m"))
3866 .arg(&in_obu)
3867 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
3868 .stdin(Stdio::null())
3869 .stdout(Stdio::piped())
3870 .stderr(Stdio::piped()), None, |c| c.output())
3871 .expect("aomdec failed to run");
3872 assert!(
3873 out.status.success(),
3874 "{NAME}: the oracle aomdec refused the stream: {}",
3875 String::from_utf8_lossy(&out.stderr)
3876 );
3877 let ours_prefix = dir.join("ours");
3878 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
3879 let _ = decode_stream(&stream444).expect("second decode");
3880 set_final_dump_prefix(None);
3881 let hits = crate::decode::ibc_owned_rect_chroma_footprint_444_hits();
3882 assert!(
3883 hits > 0,
3884 "{NAME}: no rect intra-BC block committed a 4:4:4 chroma plane block -- the \
3885 ss-derived footprint never ran, so this gate is measuring a hardcoded halving \
3886 (class gate-blind-to-feature)"
3887 );
3888 let aom_dump = std::fs::read(format!("{}.f0", aom_prefix.display())).expect("oracle dump");
3889 let our_dump = std::fs::read(format!("{}.f0", ours_prefix.display())).expect("our dump");
3890 assert_eq!(aom_dump.len(), 3 * PLANE, "{NAME}: 8-bit 4:4:4 640x480");
3891 assert_eq!(
3892 our_dump.len(),
3893 aom_dump.len(),
3894 "{NAME}: our frame is {} bytes, the oracle's is {}",
3895 our_dump.len(),
3896 aom_dump.len()
3897 );
3898 for (plane, name) in [(0usize, "Y"), (1, "U"), (2, "V")] {
3899 let at = plane * PLANE;
3900 if our_dump[at..at + PLANE] == aom_dump[at..at + PLANE] {
3901 continue;
3902 }
3903 let first = (0..PLANE)
3904 .find(|&s| our_dump[at + s] != aom_dump[at + s])
3905 .unwrap_or(PLANE);
3906 panic!(
3907 "{NAME}: plane {name} diverges from the oracle at sample {first} of {PLANE} \
3908 (x={}, y={}) -- this gate pins FULL byte-exactness on all three planes",
3909 first % 640,
3910 first / 640
3911 );
3912 }
3913 let _ = std::fs::remove_dir_all(&dir);
3914 eprintln!(
3915 "{NAME}: {hits} rect intra-BC block(s) committed a 4:4:4 chroma plane block; \
3916 4:2:0 twin byte-exact; 4:4:4 byte-exact on all three planes \
3917 (307200 samples each)"
3918 );
3919 }
3920
3921 /// lane-av1chromadc: a SKIPPED 64x64 square block at 4:4:4 has a 64x64
3922 /// chroma plane block, which libaom walks as a 2x2 grid of `TX_32X32` units
3923 /// (`get_vartx_max_txsize`: `av1_get_adjusted_tx_size(TX_64X64) =
3924 /// TX_32X32`). The intra-BC / UV-palette chroma override
3925 /// ([`decode_block`]'s `intrabc_bufs` / `palette_uv_bufs`, the
3926 /// `PALETTE_PRED` slot) is a whole-`chroma_side x chroma_height` buffer and
3927 /// must be WINDOWED per unit: `PlaneBuf::reconstruct` uses the buffer it
3928 /// takes as the unit's own `side x side` prediction. At 4:2:0 the chroma
3929 /// plane block is one 32x32 unit, so the whole buffer IS that unit's
3930 /// window and the bug is invisible -- which is why it survived every 4:2:0
3931 /// gate. At 4:4:4 every unit was handed the buffer's FIRST 32x32, so the
3932 /// block's right and bottom chroma columns were a copy of its top-left
3933 /// unit.
3934 ///
3935 /// The witness: `fixtures/r512.obu`, 4:4:4 8-bit 512x512, three frames. The
3936 /// seed is frame 0, `mi=(112,80)`, `px=(320,448)`, `side=64`, `skip=1`,
3937 /// `mode=0`, `uv_mode=0` -- a skipped intra-BC block at the frame's bottom
3938 /// edge. Its chroma unit `cu=(1,0)` at `px=(352,448)` reconstructs a flat
3939 /// 241 (U) / 110 (V) where the oracle has 202 / 222, because it read the
3940 /// same override window as `cu=(0,0)`.
3941 ///
3942 /// This gate asserts FULL frame exactness on all three planes of all three
3943 /// frames. It is the red-before: on the unpatched tree it fails at
3944 /// `(352,448)` of frame 0, which is the seed's second chroma unit.
3945 #[test]
3946 fn a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit() {
3947 const NAME: &str = "a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit";
3948 const FILE: &str = "r512.obu";
3949 const LEN: usize = 6948;
3950 const PLANE: usize = 512 * 512;
3951 let path =
3952 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("fixtures/{FILE}"));
3953 let stream = std::fs::read(&path)
3954 .unwrap_or_else(|e| panic!("{NAME}: pinned fixture {FILE} missing: {e}"));
3955 assert_eq!(stream.len(), LEN, "{NAME}: {FILE} length moved");
3956 assert_444_header(&stream, NAME, 8);
3957
3958 let _guard = lock_gate_counters();
3959 reset_skip_chroma_override_window_hits();
3960 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
3961 let _ = std::fs::remove_dir_all(&dir);
3962 std::fs::create_dir_all(&dir).expect("scratch dir");
3963 let obu = dir.join("in.obu");
3964 std::fs::write(&obu, &stream).expect("writing the stream");
3965 let aom_prefix = dir.join("aom");
3966 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
3967 .args(["--codec=av1", "-o"])
3968 .arg(dir.join("out.y4m"))
3969 .arg(&obu)
3970 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
3971 .stdin(Stdio::null())
3972 .stdout(Stdio::piped())
3973 .stderr(Stdio::piped()), None, |c| c.output())
3974 .expect("aomdec failed to run");
3975 assert!(
3976 out.status.success(),
3977 "{NAME}: the oracle aomdec refused the stream: {}",
3978 String::from_utf8_lossy(&out.stderr)
3979 );
3980 let ours_prefix = dir.join("ours");
3981 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
3982 if let Err(e) = decode_stream(&stream) {
3983 panic!("{NAME}: this decoder refused the witness: {e}");
3984 }
3985 set_final_dump_prefix(None);
3986 // Non-vacuity: the windowed arm must have run, or the exactness below
3987 // is measuring a witness that never reached the 2x2 chroma walk.
3988 let windows = skip_chroma_override_window_hits();
3989 assert!(
3990 windows >= 8,
3991 "{NAME}: {windows} windowed chroma override unit(s) on this witness, expected at \
3992 least 8 (two skipped 64x64 intra-BC blocks x 2x2 units x 2 planes) -- the witness \
3993 stopped exercising the arm, so the exactness below is vacuous"
3994 );
3995 for f in 0..3 {
3996 let aom_dump = std::fs::read(format!("{}.f{f}", aom_prefix.display()))
3997 .unwrap_or_else(|e| panic!("{NAME}: oracle dump f{f} missing: {e}"));
3998 let our_dump = std::fs::read(format!("{}.f{f}", ours_prefix.display()))
3999 .unwrap_or_else(|e| panic!("{NAME}: our dump f{f} missing: {e}"));
4000 assert_eq!(
4001 our_dump.len(),
4002 3 * PLANE,
4003 "{NAME}: frame {f} is not 8-bit 4:4:4 512x512"
4004 );
4005 for (plane, name) in [(0usize, "Y"), (1, "U"), (2, "V")] {
4006 let at = plane * PLANE;
4007 if our_dump[at..at + PLANE] == aom_dump[at..at + PLANE] {
4008 continue;
4009 }
4010 let first = (0..PLANE)
4011 .find(|&s| our_dump[at + s] != aom_dump[at + s])
4012 .unwrap_or(PLANE);
4013 let wrong = (0..PLANE)
4014 .filter(|&s| our_dump[at + s] != aom_dump[at + s])
4015 .count();
4016 panic!(
4017 "{NAME}: decode-order frame {f} plane {name} is byte-exact nowhere -- first \
4018 divergence at sample {first} of {PLANE} (x={}, y={}), {wrong} samples \
4019 wrong. The seed is frame 0, mi=(112,80) px=(320,448) side=64 skip=1, whose \
4020 chroma unit cu=(1,0) at px=(352,448) must be the SECOND 32x32 window of \
4021 the block's chroma override and not a copy of cu=(0,0)'s.",
4022 first % 512,
4023 first / 512
4024 );
4025 }
4026 }
4027 let _ = std::fs::remove_dir_all(&dir);
4028 }
4029
4030 /// lane-av1rectreach, the 2x1 / 1x2 half of the class sweep
4031 /// `a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit`
4032 /// opened: `decode_rect_split`'s `chroma_tiled` walk is the THIRD site that
4033 /// walks a 4:4:4 chroma plane block as a grid of Chroma32 units, and the
4034 /// only one that handed every unit the BLOCK's reach.
4035 ///
4036 /// The other two are already per-unit and are not touched by this gate:
4037 /// `decode_block`'s skip arm (`chroma_window`, lane-av1chromadc) and
4038 /// `decode_block`'s coded arm (its own `tu_reach_rect`) both resolve
4039 /// `has_top_right` per transform unit, the way libaom's
4040 /// `av1_build_intra_predictors` does
4041 /// (`has_top_right`, defined reconintra.c:196, called from
4042 /// `av1_build_intra_predictors` at reconintra.c:1847),
4043 /// fed the chroma txb walk's own `blk_col`/`blk_row`).
4044 ///
4045 /// Witness `fixtures/r512_rect2x1_1x2_444.obu`, 2697 B,
4046 /// sha256 `a009ec580a1ff24250be53e11b8d09616da71e095cefd5eb621c941d40a8688b`:
4047 ///
4048 /// ```text
4049 /// ffmpeg -f lavfi -i testsrc2=size=256x256:rate=1:duration=1 -pix_fmt yuv444p \
4050 /// -f rawvideo in.yuv
4051 /// aomenc --codec=av1 -w 256 -h 256 --i444 --sb-size=64 --enable-palette=1 \
4052 /// --enable-rect-partitions=1 --enable-1to4-partitions=1 \
4053 /// --min-partition-size=32 --cq-level=40 --profile=1 --obu --limit=1 \
4054 /// -o r512_rect2x1_1x2_444.obu in.yuv
4055 /// ```
4056 ///
4057 /// (aom-affine aomenc, one key frame, 4:4:4 8-bit 256x256.) It reaches
4058 /// BOTH grid shapes: a 64x32 chroma plane block as `nw=2 nh=1` of 32x32
4059 /// and a 32x64 one as `nw=1 nh=2`.
4060 ///
4061 /// RED-BEFORE, on the unpatched tree, measured with `EC_AV1_FINAL_DUMP`
4062 /// (aomdec) against `set_final_dump_prefix` (ours), 786432 B per frame:
4063 /// frame 0 plane Y 0 wrong, plane U 130 wrong, plane V 30 wrong -- all of
4064 /// them in the right 6 columns of the `cu=(0,0)` unit at `mi=(48,48)`
4065 /// `px=(192,192)`, a 64x32 block whose right edge IS the frame's, so the
4066 /// block-level reach denied an above-right that libaom's per-unit
4067 /// `col_off + top_right_count_unit < plane_bw_unit` (0 + 8 < 16) grants.
4068 /// After: 0 wrong on all three planes.
4069 #[test]
4070 fn a_444_rect_strip_chroma_tiled_2x1_and_1x2_units_take_their_own_above_right_reach() {
4071 const NAME: &str =
4072 "a_444_rect_strip_chroma_tiled_2x1_and_1x2_units_take_their_own_above_right_reach";
4073 const FILE: &str = "r512_rect2x1_1x2_444.obu";
4074 const LEN: usize = 2697;
4075 const SHA: &str = "a009ec580a1ff24250be53e11b8d09616da71e095cefd5eb621c941d40a8688b";
4076 const W: usize = 256;
4077 const PLANE: usize = W * W;
4078 let path =
4079 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("fixtures/{FILE}"));
4080 let stream = std::fs::read(&path)
4081 .unwrap_or_else(|e| panic!("{NAME}: pinned fixture {FILE} missing: {e}"));
4082 assert_eq!(stream.len(), LEN, "{NAME}: {FILE} length moved");
4083 assert_444_header(&stream, NAME, 8);
4084 // The byte pin is fnv1a64, the same load-bearing-identity hash every
4085 // other pinned gate here uses; the sha256 in this test's comment is
4086 // the provenance half. A silent stream swap under the same name
4087 // cannot stay green.
4088 assert_eq!(
4089 fnv1a64(&stream),
4090 0x2751ccaa079cc422,
4091 "{NAME}: {FILE} bytes drifted from the fnv1a64 pin above (provenance sha256 \
4092 {SHA}) -- regenerate the stream with the recipe in this test's comment and \
4093 re-pin the length, the fnv1a64 and the sha256 together"
4094 );
4095
4096 let _guard = lock_gate_counters();
4097 reset_rect_tiled_chroma_grid_hits();
4098 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
4099 let _ = std::fs::remove_dir_all(&dir);
4100 std::fs::create_dir_all(&dir).expect("scratch dir");
4101 let obu = dir.join("in.obu");
4102 std::fs::write(&obu, &stream).expect("writing the stream");
4103 let aom_prefix = dir.join("aom");
4104 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
4105 .args(["--codec=av1", "-o"])
4106 .arg(dir.join("out.y4m"))
4107 .arg(&obu)
4108 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
4109 .stdin(Stdio::null())
4110 .stdout(Stdio::piped())
4111 .stderr(Stdio::piped()), None, |c| c.output())
4112 .expect("aomdec failed to run");
4113 assert!(
4114 out.status.success(),
4115 "{NAME}: the oracle aomdec refused the stream: {}",
4116 String::from_utf8_lossy(&out.stderr)
4117 );
4118 let ours_prefix = dir.join("ours");
4119 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
4120 if let Err(e) = decode_stream(&stream) {
4121 panic!("{NAME}: this decoder refused the witness: {e}");
4122 }
4123 set_final_dump_prefix(None);
4124
4125 // Non-vacuity, in the order the claim depends on it: the walk must
4126 // have reached a 2x1 AND a 1x2 grid, and at least one unit must have
4127 // a per-unit reach that DIFFERS from the block-level one. Without the
4128 // last one the two answers would be interchangeable everywhere and
4129 // the exactness below would be measuring a witness the fix cannot
4130 // touch. (It does not check the argument identity -- see
4131 // `RECT_TILED_CHROMA_UNIT_REACH_HITS`; the exactness assert below is
4132 // what reds when the substitution is deleted.)
4133 let (reach_hits, h2x1, h1x2, h_nxn) = rect_tiled_chroma_grid_hits();
4134 assert!(
4135 h2x1 >= 4 && h1x2 >= 4,
4136 "{NAME}: the walk reached {h2x1} unit(s) in a 2x1 grid and {h1x2} in a 1x2 grid \
4137 (other multi-unit shapes: {h_nxn}), expected at least 4 of each -- the witness \
4138 stopped exercising one of the two grid shapes, so half the claim is vacuous"
4139 );
4140 assert!(
4141 reach_hits >= 1,
4142 "{NAME}: {reach_hits} chroma unit(s) had a per-unit reach differing from the \
4143 block-level one, expected at least 1 -- on the unpatched tree every unit took \
4144 the block's reach, so the exactness below is vacuous"
4145 );
4146
4147 let aom_dump = std::fs::read(format!("{}.f0", aom_prefix.display()))
4148 .unwrap_or_else(|e| panic!("{NAME}: oracle dump f0 missing: {e}"));
4149 let our_dump = std::fs::read(format!("{}.f0", ours_prefix.display()))
4150 .unwrap_or_else(|e| panic!("{NAME}: our dump f0 missing: {e}"));
4151 assert_eq!(
4152 our_dump.len(),
4153 3 * PLANE,
4154 "{NAME}: frame 0 is not 8-bit 4:4:4 256x256"
4155 );
4156 for (plane, pname) in [(0usize, "Y"), (1, "U"), (2, "V")] {
4157 let at = plane * PLANE;
4158 if our_dump[at..at + PLANE] == aom_dump[at..at + PLANE] {
4159 continue;
4160 }
4161 let first = (0..PLANE)
4162 .find(|&s| our_dump[at + s] != aom_dump[at + s])
4163 .unwrap_or(PLANE);
4164 let wrong = (0..PLANE)
4165 .filter(|&s| our_dump[at + s] != aom_dump[at + s])
4166 .count();
4167 panic!(
4168 "{NAME}: frame 0 plane {pname} is byte-exact nowhere -- first divergence at \
4169 sample {first} of {PLANE} (x={}, y={}), {wrong} samples wrong. Each unit of \
4170 this walk must resolve `has_top_right` over ITS OWN extent \
4171 (reconintra.c:196/1847), not the block's: the seed unit is cu=(0,0) of \
4172 64x32 chroma grid at mi=(48,48) px=(192,192), whose right 6 columns are the \
4173 ones the truncated above row moved.",
4174 first % W,
4175 first / W
4176 );
4177 }
4178 let _ = std::fs::remove_dir_all(&dir);
4179 }
4180
4181 /// The UV-PALETTE half of the same class, and the cell
4182 /// `lanes/av1chromadc.report.md` §5 left explicitly UNMEASURED ("every
4183 /// multi-unit walk on this witness is `src=intrabc`; the UV-palette source
4184 /// never reaches a multi-unit chroma walk here, so its arm of the sweep is
4185 /// argued from the shared code path, not witnessed"). This witness is the
4186 /// measurement: it puts a UV-palette block on a 1x2 16x64 chroma grid
4187 /// (`mi=(32,12)`) as well as plenty of non-palette ones.
4188 ///
4189 /// Witness `fixtures/r512_rect1x2_444_palette.obu`, 2250 B,
4190 /// sha256 `fad03c69087f316c1a117e8d8a70769d161b332bce7b2998e646312bb78fb067`:
4191 ///
4192 /// ```text
4193 /// ffmpeg -f lavfi -i testsrc2=size=256x256:rate=1:duration=1 -pix_fmt yuv444p \
4194 /// -f rawvideo in.yuv
4195 /// aomenc --codec=av1 -w 256 -h 256 --i444 --sb-size=64 --enable-palette=1 \
4196 /// --enable-rect-partitions=1 --enable-1to4-partitions=1 \
4197 /// --min-partition-size=16 --cq-level=40 --profile=1 --obu --limit=1 \
4198 /// -o r512_rect1x2_444_palette.obu in.yuv
4199 /// ```
4200 ///
4201 /// (`--min-partition-size=16` is what puts the 16x64 chroma grid on a
4202 /// strip at all; at 32 the encoder only ever picks 32x64 / 64x32.) The
4203 /// per-unit reach the fix installs is the same line for the palette and
4204 /// the non-palette unit -- the palette only supplies the PREDICTION
4205 /// (`palette_window`, decode.rs:12784), never the reach -- so this gate
4206 /// exists to pin the prediction source down, not to re-prove the reach.
4207 #[test]
4208 fn a_444_rect_strip_chroma_tiled_1x2_palette_grid_decodes_byte_exact() {
4209 const NAME: &str = "a_444_rect_strip_chroma_tiled_1x2_palette_grid_decodes_byte_exact";
4210 const FILE: &str = "r512_rect1x2_444_palette.obu";
4211 const LEN: usize = 2250;
4212 const SHA: &str = "fad03c69087f316c1a117e8d8a70769d161b332bce7b2998e646312bb78fb067";
4213 const W: usize = 256;
4214 const PLANE: usize = W * W;
4215 let path =
4216 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("fixtures/{FILE}"));
4217 let stream = std::fs::read(&path)
4218 .unwrap_or_else(|e| panic!("{NAME}: pinned fixture {FILE} missing: {e}"));
4219 assert_eq!(stream.len(), LEN, "{NAME}: {FILE} length moved");
4220 assert_444_header(&stream, NAME, 8);
4221 assert_eq!(
4222 fnv1a64(&stream),
4223 0x7759753a0d3f75a2,
4224 "{NAME}: {FILE} bytes drifted from the fnv1a64 pin above (provenance sha256 \
4225 {SHA}) -- regenerate the stream with the recipe in this test's comment and \
4226 re-pin the length, the fnv1a64 and the sha256 together"
4227 );
4228
4229 let _guard = lock_gate_counters();
4230 reset_rect_tiled_chroma_grid_hits();
4231 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
4232 let _ = std::fs::remove_dir_all(&dir);
4233 std::fs::create_dir_all(&dir).expect("scratch dir");
4234 let obu = dir.join("in.obu");
4235 std::fs::write(&obu, &stream).expect("writing the stream");
4236 let aom_prefix = dir.join("aom");
4237 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
4238 .args(["--codec=av1", "-o"])
4239 .arg(dir.join("out.y4m"))
4240 .arg(&obu)
4241 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
4242 .stdin(Stdio::null())
4243 .stdout(Stdio::piped())
4244 .stderr(Stdio::piped()), None, |c| c.output())
4245 .expect("aomdec failed to run");
4246 assert!(
4247 out.status.success(),
4248 "{NAME}: the oracle aomdec refused the stream: {}",
4249 String::from_utf8_lossy(&out.stderr)
4250 );
4251 let ours_prefix = dir.join("ours");
4252 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
4253 if let Err(e) = decode_stream(&stream) {
4254 panic!("{NAME}: this decoder refused the witness: {e}");
4255 }
4256 set_final_dump_prefix(None);
4257
4258 let (_reach_hits, h2x1, h1x2, _h_nxn) = rect_tiled_chroma_grid_hits();
4259 assert!(
4260 h1x2 >= 4,
4261 "{NAME}: the walk reached {h1x2} unit(s) in a 1x2 grid ({h2x1} in a 2x1), expected \
4262 at least 4 of the 1x2 -- the witness stopped exercising the arm"
4263 );
4264
4265 let aom_dump = std::fs::read(format!("{}.f0", aom_prefix.display()))
4266 .unwrap_or_else(|e| panic!("{NAME}: oracle dump f0 missing: {e}"));
4267 let our_dump = std::fs::read(format!("{}.f0", ours_prefix.display()))
4268 .unwrap_or_else(|e| panic!("{NAME}: our dump f0 missing: {e}"));
4269 assert_eq!(
4270 our_dump.len(),
4271 3 * PLANE,
4272 "{NAME}: frame 0 is not 8-bit 4:4:4 256x256"
4273 );
4274 for (plane, pname) in [(0usize, "Y"), (1, "U"), (2, "V")] {
4275 let at = plane * PLANE;
4276 if our_dump[at..at + PLANE] == aom_dump[at..at + PLANE] {
4277 continue;
4278 }
4279 let first = (0..PLANE)
4280 .find(|&s| our_dump[at + s] != aom_dump[at + s])
4281 .unwrap_or(PLANE);
4282 let wrong = (0..PLANE)
4283 .filter(|&s| our_dump[at + s] != aom_dump[at + s])
4284 .count();
4285 panic!(
4286 "{NAME}: frame 0 plane {pname} is byte-exact nowhere -- first divergence at \
4287 sample {first} of {PLANE} (x={}, y={}), {wrong} samples wrong.",
4288 first % W,
4289 first / W
4290 );
4291 }
4292 let _ = std::fs::remove_dir_all(&dir);
4293 }