forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

t05.rs4488 lines, 220.0 KiBHistoryRawDownload
1use super::*;
2use super::support::*;
3use super::gates_a::*;
4use crate::probe::run_with_stdin;
5use std::process::{Command, Stdio};
6
7 /// lane-sqdrift r2: the SQUARE-ONLY twin of the no-CFL `uv_mode` gate
8 /// above. With `--enable-rect-partitions=0` the encoder codes only
9 /// `PARTITION_NONE` and `PARTITION_SPLIT`, and on detailed content the RD
10 /// eventually hands one whole 64x64 superblock of an INTER frame to an
11 /// INTRA block -- `bsize == sb_size`, the one shape whose `uv_mode` must
12 /// come off the 13-symbol `uv_mode_no_cfl` alphabet because libaom's
13 /// `is_cfl_allowed` (`blockd.h`: `wide <= 32 && high <= 32`) excludes it.
14 ///
15 /// Before the fix this decoder read the 14-symbol CFL alphabet there: the
16 /// same `DC_PRED` value, a different interval, and the tile desynced from
17 /// that block on. r1 measured the damage on the pinned 192x128 stream
18 /// (sha256 `c6af4fb4...`): decode-order frames 0-3 pre-filter byte-exact,
19 /// frame 4 luma 3540 samples wrong over exactly the last superblock
20 /// (x 128..191, y 64..127), then 24k wrong by frame 7 -- and the decoder
21 /// did not even report a mismatch, it reported an intra-rect-strip refusal
22 /// read out of the already-desynced stream (class `refusal-from-own-desync`;
23 /// aomdec's own partition histogram over that stream is rect-free).
24 /// After the fix the same stream is byte-exact on all 8 frames.
25 ///
26 /// Distinct from the sibling gate: rect partitions OFF (so the 64x64 NONE
27 /// really is a whole superblock), `--min-partition-size=16`, natural
28 /// mandelbrot detail instead of a synthetic half-noise ramp, and 8 frames
29 /// of drift so a desync that survives one frame still fails here. Every
30 /// decode-order frame of every attempt is compared against ffmpeg, so a
31 /// mismatch of ANY shape fails; the gate never turns one into a SKIP.
32 #[test]
33 fn a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact()
34 {
35 const NAME: &str = "a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact";
36 let _gate_lock = lock_gate_counters();
37 if !have_ffmpeg() {
38 eprintln!("SKIP {NAME}: no ffmpeg");
39 return;
40 }
41 if !have_aomenc() {
42 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
43 return;
44 }
45 let (width, height, frame_count) = (192usize, 128usize, 8usize);
46 for bit_depth in [8u32, 10u32] {
47 let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
48 let mut total_hits = 0usize;
49 for attempt in 0..4u32 {
50 // r1's pinned recipe is (start_scale 4.76, cq 55); the other
51 // three points move the detail level and the quantiser, which
52 // is what moves WHICH superblock the RD codes intra.
53 let start_scale = ["4.76", "3.20"][(attempt % 2) as usize];
54 let cq = [55, 45][(attempt / 2) as usize];
55 let duration = frame_count as f64 / 25.0;
56 let source = format!(
57 "mandelbrot=size={width}x{height}:start_scale={start_scale}:\
58 end_scale=0.004:end_pts=8:rate=25"
59 );
60 let pix_fmt = if bit_depth == 10 {
61 "yuv420p10le"
62 } else {
63 "yuv420p"
64 };
65 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
66 .args([
67 "-v",
68 "error",
69 "-f",
70 "lavfi",
71 "-i",
72 &source,
73 "-vf",
74 "hue=s=0",
75 "-t",
76 &duration.to_string(),
77 "-pix_fmt",
78 pix_fmt,
79 "-strict",
80 "-1",
81 "-f",
82 "yuv4mpegpipe",
83 "-strict",
84 "-1",
85 "-",
86 ])
87 .stdin(Stdio::null())
88 .stdout(Stdio::piped())
89 .stderr(Stdio::piped()), None, |c| c.output())
90 .expect("ffmpeg failed to run");
91 assert!(
92 y4m.status.success(),
93 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
94 String::from_utf8_lossy(&y4m.stderr)
95 );
96 let cq_arg = format!("--cq-level={cq}");
97 let depth_arg = format!("--bit-depth={bit_depth}");
98 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
99 let args: Vec<&str> = vec![
100 "--codec=av1",
101 "--passes=1",
102 "--end-usage=q",
103 &cq_arg,
104 "--cpu-used=1",
105 "--threads=1",
106 "--row-mt=0",
107 "--sb-size=64",
108 &depth_arg,
109 &input_depth_arg,
110 "--lag-in-frames=0",
111 "--auto-alt-ref=0",
112 "--kf-min-dist=1000",
113 "--kf-max-dist=1000",
114 "--enable-rect-partitions=0",
115 "--enable-ab-partitions=0",
116 "--enable-1to4-partitions=0",
117 "--min-partition-size=16",
118 "--max-partition-size=64",
119 "--enable-tx-size-search=0",
120 "--enable-order-hint=0",
121 "--enable-warped-motion=0",
122 "--enable-obmc=0",
123 "--enable-masked-comp=0",
124 "--enable-interintra-comp=0",
125 "--enable-dist-wtd-comp=0",
126 "--enable-diff-wtd-comp=0",
127 "--enable-onesided-comp=0",
128 "--enable-interintra-wedge=0",
129 "--enable-smooth-interintra=0",
130 "--enable-filter-intra=0",
131 "--enable-smooth-intra=0",
132 "--enable-paeth-intra=0",
133 "--enable-directional-intra=0",
134 "--enable-angle-delta=0",
135 "--enable-cdef=0",
136 "--enable-restoration=0",
137 "--enable-palette=0",
138 "--enable-intrabc=0",
139 "--enable-cfl-intra=0",
140 "--enable-ref-frame-mvs=0",
141 "--obu",
142 "-o",
143 "-",
144 "-",
145 ];
146 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
147 assert!(
148 out.status.success(),
149 "aomenc refused the fixture: {}",
150 String::from_utf8_lossy(&out.stderr)
151 );
152 let stream = out.stdout;
153 let before = crate::decode::nocfl_uv_mode_hits();
154 let frames = match decode_stream(&stream) {
155 Err(e) => {
156 let msg = e.to_string();
157 assert!(
158 msg.contains("unsupported"),
159 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
160 attempt {attempt}): {msg}"
161 );
162 named_refusals += 1;
163 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
164 continue;
165 }
166 Ok(frames) => frames,
167 };
168 let hits = crate::decode::nocfl_uv_mode_hits() - before;
169 let ffmpeg_frames = if bit_depth == 10 {
170 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
171 } else {
172 ffmpeg_decode_sequence(&stream, width, height, frame_count)
173 };
174 assert_eq!(frames.len(), frame_count);
175 if hits == 0 {
176 carried_none += 1;
177 }
178 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
179 assert_eq!(
180 got.y, want.y,
181 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
182 );
183 assert_eq!(
184 got.u, want.u,
185 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
186 );
187 assert_eq!(
188 got.v, want.v,
189 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
190 );
191 }
192 if hits > 0 {
193 matched += 1;
194 total_hits += hits;
195 }
196 }
197 eprintln!(
198 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
199 attempts carrying a 64x64 intra superblock ({total_hits} no-CFL uv_mode reads), \
200 {carried_none} attempts carried none"
201 );
202 assert!(
203 matched > 0 && total_hits > 0,
204 "{NAME} ({bit_depth}-bit): no square-only attempt decoded a 64x64 intra block \
205 inside an inter frame, so the no-CFL uv_mode alphabet was never exercised -- \
206 gate proved nothing ({named_refusals} refusals, {carried_none} carried none)"
207 );
208 }
209 }
210
211 /// lane-mc64 r2: the RECT-ON twin of the square-only gate above, pinned
212 /// as a stream fixture because its aomenc recipe is not reproducible
213 /// (the r2 recipe re-encoded to a different file, measured md5
214 /// `278be00...` vs the fixture's `add55f6...`; class
215 /// `seeded-fixture-not-reproducible`).
216 ///
217 /// `crates/ec-av1/fixtures/av1_192x128_8bit_intra64_in_inter.obu`
218 /// (sha256 `e4cff46cb1700527c68efc866db27a2835705e949d646f73f0c9df577d594bd6`)
219 /// carries a 64x64 `PARTITION_NONE` INTRA block inside an INTER frame at
220 /// decode-order frame 2, mi(16,32), in a stream whose OTHER superblocks
221 /// are rect-partitioned -- so the 64-axis `is_cfl_allowed` narrowing
222 /// (`blockd.h`: `wide <= 32 && high <= 32`) has to hold on the intra
223 /// arm that the rect recipe reaches, not only on the whole-superblock
224 /// one. Before lane-sbrect10's fix this frame reconstructed with 3720
225 /// wrong luma samples (delta -12..+9, chroma bit-exact) and the decode
226 /// then died at frame 3 on a phantom refusal of its own desync (class
227 /// `refusal-from-own-desync`); all 6 decode-order frames are byte-exact
228 /// against the oracle now.
229 #[test]
230 fn a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact() {
231 const NAME: &str =
232 "a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact";
233 let _gate_lock = lock_gate_counters();
234 if !have_aomenc() {
235 eprintln!(
236 "SKIP {NAME}: no aomenc/aomdec oracle at {}",
237 aomenc_path().display()
238 );
239 return;
240 }
241 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
242 .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu");
243 let stream = std::fs::read(&path)
244 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
245 let before = crate::decode::nocfl_uv_mode_hits();
246 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
247 let hits = crate::decode::nocfl_uv_mode_hits() - before;
248 assert_eq!(
249 frames, 6,
250 "{NAME}: expected 6 decode-order frames ({hidden} hidden)"
251 );
252 assert!(
253 hits > 0,
254 "{NAME}: no 64-axis intra block read the no-CFL uv_mode alphabet -- the fixture no \
255 longer carries the shape this test gates"
256 );
257 }
258
259 /// lane-av1444chr: a 4:4:4 INTER chroma unit inherits the `tx_type` of
260 /// the luma leaf covering its OWN quadrant, not the block-level (top-left
261 /// leaf) one. `av1_get_tx_type` (`blockd.h:1287-1297`) reads
262 /// `xd->tx_type_map` at the chroma unit's own position scaled back to
263 /// luma, and `read_coeffs`' `all_zero` arm stamps `DCT_DCT` into that
264 /// leaf's cell (`decodetxb.c:199-203`) -- so a chroma unit sitting over a
265 /// luma leaf that coded NOTHING must reconstruct as DCT_DCT even when the
266 /// block's top-left leaf is `IDTX`.
267 ///
268 /// The fixture is the report's witness pinned into `fixtures/`:
269 /// `testsrc2 128x128` yuv444p 4 frames, aomenc `--profile=1 --cq-level=20
270 /// --cpu-used=2 --sb-size=64 --min-partition-size=64
271 /// --max-partition-size=64 --passes=1 --end-usage=q --threads=1 --row-mt=0
272 /// --lag-in-frames=0 --kf-max-dist=100 --limit=4 --obu`; 27933 bytes,
273 /// sha256 `a06c9f7a0862252f6ab7ebdcec340d0602e730e38089365f14747db37f8e78d5`.
274 /// Every inter block is a whole 64x64 (min=max partition 64) whose luma
275 /// var-tx tree is four TX_32X32 leaves, so each block's chroma plane is
276 /// four TX_32X32 units -- one per leaf.
277 ///
278 /// Pre-fix, decode-order frames 1/2/3 differ from the oracle in 777/640/554
279 /// V samples (luma and U exact) and the per-unit type census disagrees at
280 /// exactly the units over the skipped leaf: V(0,32) of block mi(0,0) in
281 /// frame 1, V(64,96) of block mi(16,16) in every inter frame. Post-fix all
282 /// 136 non-empty inter units agree with the oracle's `EC_DQCOEFF` type and
283 /// every frame is byte-exact.
284 ///
285 /// The non-vacuity bar is the DIFFERS counter, not the route counter: a
286 /// route counter fires on every four-unit chroma read (96 of them here)
287 /// and stayed green through a no-op fix that changed zero pixels, because
288 /// on a block whose four leaves agree the per-quadrant resolve and the
289 /// block-level value are the same answer. The number that says the resolve
290 /// CHANGED something is 8 on this stream -- the four skipped-leaf quadrants
291 /// (two of them in decode-order frame 1), each resolved once per chroma
292 /// plane -- and it must be 0 on the 4:2:0 control below, since the arm is
293 /// unreachable at 4:2:0.
294 #[test]
295 fn a_pinned_444_inter_stream_chroma_units_inherit_their_own_quadrants_tx_type() {
296 const NAME: &str =
297 "a_pinned_444_inter_stream_chroma_units_inherit_their_own_quadrants_tx_type";
298 const FIXTURE_LEN: usize = 27933;
299 const FIXTURE_FNV: u64 = 0x85fa_830b_8800_90df;
300 let _gate_lock = lock_gate_counters();
301 if !have_aomenc() {
302 eprintln!(
303 "SKIP {NAME}: no aomenc/aomdec oracle at {}",
304 aomenc_path().display()
305 );
306 return;
307 }
308 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
309 .join("fixtures/444_quad_leaf_tx_type.obu");
310 let stream = std::fs::read(&path)
311 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
312 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
313 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
314
315 let quad0 = crate::decode::chroma_quad_leaf_tx_hits();
316 let diff0 = crate::decode::chroma_quad_leaf_tx_diff_hits();
317 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
318 let quad = crate::decode::chroma_quad_leaf_tx_hits() - quad0;
319 let diff = crate::decode::chroma_quad_leaf_tx_diff_hits() - diff0;
320 assert_eq!(
321 frames, 4,
322 "{NAME}: expected 4 decode-order frames ({hidden} hidden)"
323 );
324 assert!(
325 quad >= 2 * diff && quad > 0,
326 "{NAME}: no chroma unit took its type from the covering luma leaf \
327 (quad {quad}, differs {diff}) -- the corrected route never ran"
328 );
329 assert!(
330 diff >= 2,
331 "{NAME}: the per-quadrant resolve never CHANGED an answer (diff {diff}; measured 4 \
332 on this stream, 2 of them in decode-order frame 1). A route counter alone is not a \
333 witness: it fires on every four-unit chroma read, including the \
334 blocks whose four leaves all agree -- the exact shape a no-op fix looked green on."
335 );
336 eprintln!("{NAME}: quad-resolved chroma units {quad}, of which {diff} differed");
337
338 // 4:2:0 control: the same decode, same counters, zero differences --
339 // the four-unit arm is the 4:4:4 (`ss 0/0`) route only.
340 let control = std::fs::read(
341 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
342 .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu"),
343 )
344 .unwrap_or_else(|e| panic!("{NAME}: reading the 4:2:0 control: {e}"));
345 let c_quad0 = crate::decode::chroma_quad_leaf_tx_hits();
346 let c_diff0 = crate::decode::chroma_quad_leaf_tx_diff_hits();
347 let c_frames = decode_stream(&control)
348 .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control no longer decodes: {e}"))
349 .len();
350 let c_quad = crate::decode::chroma_quad_leaf_tx_hits() - c_quad0;
351 let c_diff = crate::decode::chroma_quad_leaf_tx_diff_hits() - c_diff0;
352 assert!(c_frames > 0, "{NAME}: the 4:2:0 control decoded no frames");
353 assert_eq!(
354 (c_quad, c_diff),
355 (0, 0),
356 "{NAME}: the 4:2:0 control fired the 4:4:4 four-unit route ({c_quad} units, {c_diff} \
357 differing) -- the counter is not specific to the route it claims to witness"
358 );
359 }
360
361 /// lane-av1f9singleland: `decode_inter_block` has TWO textually parallel
362 /// copies of the 4:4:4 four-unit chroma arm -- the compound prediction
363 /// arm (the `build` closure) and the single-reference arm. Both resolve
364 /// each unit's `tx_type` through `covering_leaf_tx_type` over a
365 /// `leaf_tx_types` list collected at EVERY size, both bumped the same
366 /// `CHROMA_QUAD_LEAF_TX_HITS` / `..._DIFF_HITS` pair, and the gate above
367 /// asserts only that pair. So that gate cannot say which arm its witness
368 /// came from, and the two arms can be reverted independently.
369 ///
370 /// Measured on the gate's own witness `fixtures/444_quad_leaf_tx_type.obu`
371 /// (the census is the point of this test, so it is quoted rather than
372 /// assumed): 96 chroma units resolve through their covering luma leaf, of
373 /// which 88 are the single-reference arm's and 8 the compound arm's; of
374 /// the 8 units whose resolved type DIFFERS from the block-level one --
375 /// the non-vacuity bar, since a block whose four leaves agree makes the
376 /// per-quadrant resolve a no-op -- ALL 8 are the single-reference arm's.
377 /// The shared counters' non-vacuity number is therefore 100%
378 /// single-reference, and the compound arm contributes 8 of 96 route hits
379 /// and none of the 8 that change an answer.
380 ///
381 /// The other 27 pinned 4:4:4 fixtures in this tree reach the arm zero
382 /// times (`444_intrabc_rect4_witness`, `444_leaf8_oob`,
383 /// `444_lossy_rect4_*`, `444_lossy_superres_*`, `444_sb128rect_lr_witness`,
384 /// and every `ll444_*`), so this one witness is the only thing pinning
385 /// the single-reference copy of the arm at all.
386 ///
387 /// Non-vacuity, per the mutation recorded in
388 /// `lanes/av1f9singleland.report.md`: reverting ONLY this arm's
389 /// `Some(cu_tx_type)` to `Some(luma_tx_type)` turns this gate red on
390 /// decode-order frame 1 with 777 bytes differing; gating ONLY this arm's
391 /// leaf push back behind `if side > 64` (the pre-`6c33f204` state) turns
392 /// it red with the same 777 bytes.
393 #[test]
394 fn the_pinned_444_quadrant_witness_is_the_single_reference_arms_and_not_only_the_compound_arms()
395 {
396 const NAME: &str = "the_pinned_444_quadrant_witness_is_the_single_reference_arms_and_not_only_the_compound_arms";
397 const FIXTURE_LEN: usize = 27933;
398 const FIXTURE_FNV: u64 = 0x85fa_830b_8800_90df;
399 let _gate_lock = lock_gate_counters();
400 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
401 .join("fixtures/444_quad_leaf_tx_type.obu");
402 let stream = std::fs::read(&path)
403 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
404 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
405 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
406
407 let q0 = crate::decode::chroma_quad_leaf_tx_hits();
408 let s0 = crate::decode::chroma_quad_leaf_tx_singleref_hits();
409 let sd0 = crate::decode::chroma_quad_leaf_tx_singleref_diff_hits();
410 let frames = decode_stream(&stream)
411 .unwrap_or_else(|e| panic!("{NAME}: the witness no longer decodes: {e}"))
412 .len();
413 assert_eq!(frames, 4, "{NAME}: expected 4 shown frames");
414 let quad = crate::decode::chroma_quad_leaf_tx_hits() - q0;
415 let singleref = crate::decode::chroma_quad_leaf_tx_singleref_hits() - s0;
416 let sr_diff = crate::decode::chroma_quad_leaf_tx_singleref_diff_hits() - sd0;
417
418 assert!(
419 singleref > quad / 2,
420 "{NAME}: the single-reference arm resolved {singleref} of {quad} covering-leaf chroma \
421 units -- the shared counter is no longer dominated by the arm this gate witnesses, so \
422 a revert of the single-reference copy would leave the shared total comfortably non-zero"
423 );
424 assert!(
425 sr_diff >= 2,
426 "{NAME}: the single-reference arm's per-quadrant resolve never CHANGED an answer \
427 (differing {sr_diff}). A route count alone is not a witness: it fires on every \
428 four-unit chroma read, including the blocks whose four luma leaves all agree -- the \
429 exact shape a no-op resolve looks green on."
430 );
431 eprintln!(
432 "{NAME}: {singleref} of {quad} covering-leaf units are the single-reference arm's, \
433 {sr_diff} of which changed an answer"
434 );
435
436 // 4:2:0 control, as in the gate above: the four-unit arm is the 4:4:4
437 // (`ss 0/0`) route only, so the single-reference arm's own counters
438 // must stay at exactly 0 there too.
439 let control = std::fs::read(
440 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
441 .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu"),
442 )
443 .unwrap_or_else(|e| panic!("{NAME}: reading the 4:2:0 control: {e}"));
444 let c_s0 = crate::decode::chroma_quad_leaf_tx_singleref_hits();
445 let c_sd0 = crate::decode::chroma_quad_leaf_tx_singleref_diff_hits();
446 let c_frames = decode_stream(&control)
447 .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control no longer decodes: {e}"))
448 .len();
449 assert!(c_frames > 0, "{NAME}: the 4:2:0 control decoded no frames");
450 assert_eq!(
451 (
452 crate::decode::chroma_quad_leaf_tx_singleref_hits() - c_s0,
453 crate::decode::chroma_quad_leaf_tx_singleref_diff_hits() - c_sd0,
454 ),
455 (0, 0),
456 "{NAME}: the 4:2:0 control fired the single-reference arm's four-unit route -- the \
457 counter is not specific to the route it claims to witness"
458 );
459 }
460
461 /// lane-av1chrtx: the SIBLING of lane-av1444chr's four-unit arm -- a RECT
462 /// inter block's chroma plane, read by `read_inter_rect_chroma`. That
463 /// helper was left handing every unit the block-level `luma_tx_type`
464 /// (the top-left leaf's type) after the four-unit arms were pointed at
465 /// `covering_leaf_tx_type`, so a rect block whose chroma plane splits
466 /// (`nx*ny > 1`) over MIXED var-tx leaves read the wrong type per unit.
467 ///
468 /// The witness is pinned into `fixtures/`: `testsrc2 256x256` yuv444p 3
469 /// frames, aomenc `--profile=1 --cq-level=30 --cpu-used=0 --sb-size=64
470 /// --min-partition-size=32 --max-partition-size=64 --enable-tx-size-search=1
471 /// --passes=1 --end-usage=q --threads=1 --row-mt=0 --lag-in-frames=0
472 /// --kf-max-dist=100 --limit=3 --obu`; 26839 bytes, sha256
473 /// `06174a66e92aaeb751a8e86db59711fcb1f18d74bde2d77e1ef1be7983eb7c80`.
474 /// Its one qualifying block is the 32x64 inter strip at mi(32,48): a
475 /// 4:4:4 chroma plane of (32,64) = TWO TX_32X32 units, over a luma tree
476 /// of five leaves -- `Idtx` (32x32) on top, then `VDct`/`DctDct`/`HDct`/
477 /// `VDct` 16x16 leaves. The lower chroma unit therefore inherits `VDct`
478 /// where the block-level value is `Idtx`.
479 ///
480 /// Getting a witness at all took a bounded hunt (200+ encodes): `multi`
481 /// is false by construction at 4:2:0 (a `side <= 64` block's chroma plane
482 /// is at most 32x32 = one unit), so the arm needs 4:4:4 AND a rect block
483 /// that keeps a 64-px axis, AND `--cpu-used=0` with `--min-partition-size=32`
484 /// to make aomenc actually pick the 32x64 strip.
485 ///
486 /// The non-vacuity bar is the DIFFERS counter, not the route counter: the
487 /// control below is a committed 4:4:4 rect stream where the route fires
488 /// and still changes nothing, because that block's leaves agree.
489 #[test]
490 fn a_pinned_444_rect_inter_stream_resolves_each_chroma_unit_from_its_own_luma_leaf() {
491 const NAME: &str =
492 "a_pinned_444_rect_inter_stream_resolves_each_chroma_unit_from_its_own_luma_leaf";
493 const FIXTURE_LEN: usize = 26839;
494 const FIXTURE_FNV: u64 = 0xc77f_310c_036d_ff73;
495 let _gate_lock = lock_gate_counters();
496 if !have_aomenc() {
497 eprintln!(
498 "SKIP {NAME}: no aomenc/aomdec oracle at {}",
499 aomenc_path().display()
500 );
501 return;
502 }
503 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
504 .join("fixtures/444_rect_strip_leaf_tx_type.obu");
505 let stream = std::fs::read(&path)
506 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
507 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
508 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
509
510 let hits0 = crate::decode::chroma_rect_leaf_tx_hits();
511 let diff0 = crate::decode::chroma_rect_leaf_tx_diff_hits();
512 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
513 let hits = crate::decode::chroma_rect_leaf_tx_hits() - hits0;
514 let diff = crate::decode::chroma_rect_leaf_tx_diff_hits() - diff0;
515 assert_eq!(
516 frames, 3,
517 "{NAME}: expected 3 decode-order frames ({hidden} hidden)"
518 );
519 assert!(
520 hits >= 2 * diff && hits > 0,
521 "{NAME}: no rect chroma unit took its type from the covering luma leaf (hits {hits}, \
522 differs {diff}) -- the corrected route never ran"
523 );
524 assert!(
525 diff >= 2,
526 "{NAME}: the per-unit resolve never CHANGED an answer (diff {diff}; measured 2 on this \
527 stream, one per chroma plane). A route counter alone is not a witness: the control \
528 below fires it and changes nothing."
529 );
530 eprintln!(
531 "{NAME}: rect chroma units resolved from their own leaf {hits}, of which {diff} differed"
532 );
533
534 // Control: a committed 4:4:4 rect stream where the SAME route fires
535 // and every resolved type equals the block-level one -- the shape a
536 // no-op fix would also be green on.
537 let control = std::fs::read(
538 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
539 .join("fixtures/444_sb128rect_lr_witness.obu"),
540 )
541 .unwrap_or_else(|e| panic!("{NAME}: reading the rect-strip control: {e}"));
542 let c_hits0 = crate::decode::chroma_rect_leaf_tx_hits();
543 let c_diff0 = crate::decode::chroma_rect_leaf_tx_diff_hits();
544 let c_frames = decode_stream(&control)
545 .unwrap_or_else(|e| panic!("{NAME}: the rect-strip control no longer decodes: {e}"))
546 .len();
547 let c_hits = crate::decode::chroma_rect_leaf_tx_hits() - c_hits0;
548 let c_diff = crate::decode::chroma_rect_leaf_tx_diff_hits() - c_diff0;
549 assert!(
550 c_frames > 0,
551 "{NAME}: the rect-strip control decoded no frames"
552 );
553 assert!(
554 c_hits > 0 && c_diff == 0,
555 "{NAME}: the rect-strip control fired the route {c_hits} times with {c_diff} differing \
556 types -- expected the single-unit/same-type shape (route fires, nothing changes)"
557 );
558 }
559
560 /// lane-av1ichromatx: the LAST site in `decode_inter_block` that can hand a
561 /// chroma unit the BLOCK-level `luma_tx_type` instead of the unit's own
562 /// `tx_type_map` cell is [`read_inter_rect_chroma`]'s fallback: the branch
563 /// taken when `covering_leaf_tx_type` finds no luma leaf covering the
564 /// unit's own MI cell. The decode closes it with an assertion (a
565 /// multi-unit chroma plane may only reach the fallback when the block
566 /// coded a SINGLE luma transform, whose stamp covers the whole plane and
567 /// makes `luma_tx_type` that unit's own cell).
568 ///
569 /// This gate is the measurement behind that assertion, on the witness that
570 /// reaches it: `fixtures/444_rect_strip_leaf_tx_type.obu` (26839 bytes,
571 /// sha256 `06174a66e92aaeb751a8e86db59711fcb1f18d74bde2d77e1ef1be7983eb7c80`).
572 /// Measured there: the rect arm is called twice, BOTH on a multi-unit
573 /// chroma plane (`nx*ny > 1`), and 4 of its 8 units take the block-level
574 /// fallback -- every one of them with an EMPTY leaf list, i.e. the
575 /// single-luma-unit shape the assertion allows. So `multi_fallback >= 2`
576 /// here is the number that says the guarded shape is REACHED (a fallback
577 /// count of 0 would leave the assertion vacuous), and the decoded frames
578 /// stay byte-exact against instrumented aomdec, which is what says the
579 /// fallback still hands the right value on that shape.
580 ///
581 /// Non-vacuity, by mutation: forcing the covering-leaf resolve to miss on a
582 /// multi-unit plane (`…unit_rel_mi).filter(|_| !multi)`) turns the
583 /// assertion RED on this same witness --
584 /// `a multi-unit rect chroma plane fell back to the block-level tx_type
585 /// while 5 luma leaves were coded` -- so the closure is not a comment.
586 #[test]
587 fn a_multi_unit_rect_chroma_plane_only_falls_back_to_the_block_type_on_a_single_luma_unit() {
588 const NAME: &str = "a_multi_unit_rect_chroma_plane_only_falls_back_to_the_block_type_on_a_single_luma_unit";
589 const FIXTURE_LEN: usize = 26839;
590 const FIXTURE_FNV: u64 = 0xc77f_310c_036d_ff73;
591 let _gate_lock = lock_gate_counters();
592 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
593 .join("fixtures/444_rect_strip_leaf_tx_type.obu");
594 let stream = std::fs::read(&path)
595 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
596 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
597 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
598
599 let fb0 = crate::decode::chroma_rect_block_tx_fallback();
600 let fbm0 = crate::decode::chroma_rect_block_tx_fallback_multi();
601 let frames = decode_stream(&stream)
602 .unwrap_or_else(|e| panic!("{NAME}: the witness no longer decodes: {e}"))
603 .len();
604 let fb = crate::decode::chroma_rect_block_tx_fallback() - fb0;
605 let fbm = crate::decode::chroma_rect_block_tx_fallback_multi() - fbm0;
606 assert_eq!(frames, 3, "{NAME}: expected 3 shown frames");
607 assert!(
608 fbm >= 2,
609 "{NAME}: only {fbm} block-level fallbacks landed on a MULTI-unit chroma plane \
610 ({fb} in total) -- the shape the decode's assertion guards is no longer reached, so \
611 that assertion is vacuous on this witness"
612 );
613 eprintln!("{NAME}: {fb} block-level chroma fallbacks, {fbm} of them on a multi-unit plane");
614 }
615
616 /// lane-av1readcensus: the 4:4:4 coefficient-UNIT census, pinned.
617 ///
618 /// The lane report `av1444rect` round 4 left an unexplained signal: 636
619 /// square chroma reads against the oracle's 1086, and 2052 luma reads
620 /// against its 1309, recorded as "most likely a counting-shape difference"
621 /// with no evidence either way. This gate is that evidence.
622 ///
623 /// Measured on this arm (`ll444_minp8_inter`, pixel-exact against aomdec
624 /// on every plane of every frame -- see
625 /// `a_lossless_444_min_partition8_inter_stream_decodes_sample_exact`),
626 /// pairing each of our 11292 walked units with the oracle's
627 /// `av1_read_coeffs_txb` call BY `post_rng` (the msac state after the
628 /// unit) rather than by plane label or walk position: EVERY unit pairs,
629 /// and no unit's plane, shape, eob or all-zero flag differs. The per-plane
630 /// split is equal too -- 3764 units per plane on both sides, of which
631 /// 975 / 1793 / 1859 coded coefficients. So on a pixel-exact arm there is
632 /// no asymmetry to explain at all; the round-4 numbers came from
633 /// `444_intrabc_rect4_witness`, an arm that DIVERGES (390380 of 921600
634 /// samples wrong), where our surplus is the divergence itself.
635 ///
636 /// What this gate pins is the walk's OBJECT SHAPE on the pixel-exact arm:
637 /// a change to the number or plane split of coefficient units this decoder
638 /// walks shows up here as an intentional diff, not as the next lane's
639 /// mystery signal. The 4:2:0 control asserts the census is inert there.
640 #[test]
641 fn a_pixel_exact_444_stream_walks_the_same_coefficient_units_the_oracle_does() {
642 const NAME: &str =
643 "a_pixel_exact_444_stream_walks_the_same_coefficient_units_the_oracle_does";
644 const FIXTURE_LEN: usize = 34037;
645 const FIXTURE_FNV: u64 = 0x2c8f_4a2c_c025_52da;
646 let _gate_lock = lock_gate_counters();
647 if !have_aomenc() {
648 eprintln!(
649 "SKIP {NAME}: no aomenc/aomdec oracle at {}",
650 aomenc_path().display()
651 );
652 return;
653 }
654 let path =
655 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/ll444_minp8_inter.obu");
656 let stream = std::fs::read(&path)
657 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
658 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
659 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
660 let delta = |now: [usize; 3], before: [usize; 3]| {
661 [now[0] - before[0], now[1] - before[1], now[2] - before[2]]
662 };
663
664 let u0 = crate::decode::census_nonsub_units();
665 let c0 = crate::decode::census_nonsub_coded();
666 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
667 assert_eq!(
668 frames + hidden,
669 8,
670 "{NAME}: expected 8 decode-order frames (6 shown + 2 hidden)"
671 );
672 let walked = delta(crate::decode::census_nonsub_units(), u0);
673 let coded = delta(crate::decode::census_nonsub_coded(), c0);
674
675 // The oracle's own census on the same stream, paired by post_rng:
676 // 3764 units per plane, 975 / 1793 / 1859 of them coded.
677 assert_eq!(
678 walked,
679 [3764, 3764, 3764],
680 "{NAME}: the 4:4:4 unit walk changed -- {walked:?} against the oracle's \
681 [3764, 3764, 3764] (measured by post_rng pairing, every unit matching). A change \
682 here is a WALK-SHAPE change: re-measure against aomdec before assuming it is a bug"
683 );
684 assert_eq!(
685 coded,
686 [975, 1793, 1859],
687 "{NAME}: the coded-unit split changed -- {coded:?} against the oracle's [975, 1793, 1859]"
688 );
689 assert!(
690 walked.iter().all(|&v| v > 0) && coded.iter().all(|&v| v > 0),
691 "{NAME}: an all-zero plane split means the census did not run, not that the walk is empty"
692 );
693
694 // A SECOND pixel-exact arm, with a MIXED unit-shape mix -- the pinned
695 // lossless stream above is all TX_4X4 (min-partition-8), so on its own
696 // it would not notice a var-tx walk that started folding 8x8/4x8
697 // leaves. This one walks 4x4/8x8/8x4/4x8/4x16/16x4/8x16/16x16, and
698 // the oracle's census on it pairs unit-for-unit by post_rng with no
699 // shape, plane, eob or all-zero difference: 1373 units, 629 luma and
700 // 372 per chroma plane, of which 130 / 253 / 278 coded.
701 let path2 = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
702 .join("fixtures/444_lossy_rect4_inter_witness.obu");
703 let stream2 = std::fs::read(&path2)
704 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path2.display()));
705 let m0 = crate::decode::census_nonsub_units();
706 let mc0 = crate::decode::census_nonsub_coded();
707 let (frames2, hidden2) = decode_all_frames_vs_oracle(&stream2, NAME);
708 assert!(
709 frames2 + hidden2 > 0,
710 "{NAME}: the mixed-shape 4:4:4 arm decoded no frames"
711 );
712 let walked2 = delta(crate::decode::census_nonsub_units(), m0);
713 let coded2 = delta(crate::decode::census_nonsub_coded(), mc0);
714 assert_eq!(
715 walked2,
716 [629, 372, 372],
717 "{NAME}: the mixed-shape 4:4:4 walk changed -- {walked2:?} against the oracle's \
718 [629, 372, 372]. The all-4x4 arm above cannot see a var-tx fold; this one can"
719 );
720 assert_eq!(
721 coded2,
722 [130, 253, 278],
723 "{NAME}: the mixed-shape coded-unit split changed -- {coded2:?} against the oracle's \
724 [130, 253, 278]"
725 );
726
727 // 4:2:0 control: the census is a 4:4:4 question and must not fire.
728 let control = std::fs::read(
729 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
730 .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu"),
731 )
732 .unwrap_or_else(|e| panic!("{NAME}: reading the 4:2:0 control: {e}"));
733 let k0 = crate::decode::census_nonsub_units();
734 let kc0 = crate::decode::census_nonsub_coded();
735 let k_frames = decode_stream(&control)
736 .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control no longer decodes: {e}"))
737 .len();
738 assert!(k_frames > 0, "{NAME}: the 4:2:0 control decoded no frames");
739 assert_eq!(
740 delta(crate::decode::census_nonsub_units(), k0),
741 [0, 0, 0],
742 "{NAME}: the coefficient-unit census fired on the 4:2:0 control"
743 );
744 assert_eq!(
745 delta(crate::decode::census_nonsub_coded(), kc0),
746 [0, 0, 0],
747 "{NAME}: the coded-unit census fired on the 4:2:0 control"
748 );
749 }
750
751 /// lane-inter4 r2: the 32x32-level inter `PARTITION_HORZ`/`PARTITION_VERT`
752 /// strips (32x16 / 16x32) carrying a REAL residual -- the capability r1
753 /// found missing ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs
754 /// rectangular residual coding"). The strip's own rectangular max
755 /// transform (`TX_32X16`/`TX_16X32`) is read through the rect var-tx tree,
756 /// its coefficients through [`TxbSet::LumaRect32x16Inter`] /
757 /// `ChromaRect16x8`, and inverted with the rect (sqrt2-scaled) inverse
758 /// transform.
759 ///
760 /// `--min-partition-size=16 --max-partition-size=32` keeps the superblock
761 /// level (64x32, still refused -- no 64-point rect transform) out, so
762 /// every counted hit is a 32-level strip. The source is textured and
763 /// translating precisely so the strips are NOT skip: a flat source (r1's)
764 /// makes aomenc code them skip and proves nothing about the residual.
765 /// Both `--enable-tx-size-search` arms run: `=0` exercises the
766 /// whole-block rect transform with no `txfm_partition` symbol at all,
767 /// `=1` the rect var-tx tree (no-split rect unit, or the split into square
768 /// sub-transforms).
769 ///
770 /// 8-bit AND 10-bit. Every decoded frame is compared to ffmpeg on Y, U and
771 /// V; a refusal is counted, never SKIPped; an attempt that carried no rect
772 /// inter residual is counted separately and still required pixel-exact.
773 /// Temporal (MFMV) motion-vector candidates, on a real aomenc stream
774 /// whose compound blocks feed the next frame's motion field
775 /// (`av1_copy_frame_mvs` -> `av1_setup_motion_field` -> `add_tpl_ref_mv`).
776 ///
777 /// lane-interbis r1 pinned this recipe because it is the one the rect
778 /// gate's attempt 1 decoded FULLY and still mismatched ffmpeg (a
779 /// 32x32 NEARESTMV block at mi (24, 40) of decode-order frame 5 took its
780 /// nearest candidate from a temporal cell holding the wrong reference:
781 /// `build_motion_field` stored a compound block's FIRST reference where
782 /// libaom stores its second). Every fully decoded attempt is compared
783 /// plane by plane; a refusal is counted, never SKIPped; the temporal
784 /// candidate counter must fire on a compared attempt, or the gate proves
785 /// nothing.
786 #[test]
787 fn a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact() {
788 const NAME: &str =
789 "a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact";
790 let _gate_lock = lock_gate_counters();
791 if !have_ffmpeg() {
792 eprintln!("SKIP {NAME}: no ffmpeg");
793 return;
794 }
795 if !have_aomenc() {
796 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
797 return;
798 }
799 let (width, height, frame_count) = (192usize, 128usize, 6usize);
800 for bit_depth in [8u32, 10u32] {
801 let (mut named_refusals, mut compared, mut tmv_proved) = (0u32, 0u32, 0usize);
802 for attempt in 0..2u32 {
803 let tx_search = if attempt == 0 { "0" } else { "1" };
804 let duration = frame_count as f64 / 25.0;
805 // The pinned source: horizontal structure translating along X
806 // at 3 px/frame, which makes aomenc code compound LAST+GOLDEN
807 // blocks whose stored motion field the last frame reads back.
808 let source = format!(
809 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
810 geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)',format=yuv420p"
811 );
812 let pix_fmt = if bit_depth == 10 {
813 "yuv420p10le"
814 } else {
815 "yuv420p"
816 };
817 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
818 .args([
819 "-v",
820 "error",
821 "-f",
822 "lavfi",
823 "-i",
824 &source,
825 "-t",
826 &duration.to_string(),
827 "-pix_fmt",
828 pix_fmt,
829 "-strict",
830 "-1",
831 "-f",
832 "yuv4mpegpipe",
833 "-",
834 ])
835 .stdin(Stdio::null())
836 .stdout(Stdio::piped())
837 .stderr(Stdio::piped()), None, |c| c.output())
838 .expect("ffmpeg failed to run");
839 assert!(
840 y4m.status.success(),
841 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
842 String::from_utf8_lossy(&y4m.stderr)
843 );
844 let depth_arg = format!("--bit-depth={bit_depth}");
845 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
846 let tx_arg = format!("--enable-tx-size-search={tx_search}");
847 let args: Vec<&str> = vec![
848 "--codec=av1",
849 "--passes=1",
850 "--end-usage=q",
851 "--cq-level=34",
852 "--cpu-used=0",
853 "--threads=1",
854 "--row-mt=0",
855 "--sb-size=64",
856 &depth_arg,
857 &input_depth_arg,
858 "--enable-restoration=0",
859 "--enable-palette=0",
860 "--deltaq-mode=0",
861 "--enable-filter-intra=0",
862 "--enable-cfl-intra=0",
863 "--enable-intrabc=0",
864 "--lag-in-frames=0",
865 // Per-arm overrides go LAST (aomenc keeps the last
866 // occurrence of a repeated --enable-* flag).
867 &tx_arg,
868 "--enable-rect-partitions=1",
869 "--enable-ab-partitions=0",
870 "--enable-1to4-partitions=0",
871 "--min-partition-size=16",
872 "--max-partition-size=32",
873 "--obu",
874 "-o",
875 "-",
876 "-",
877 ];
878 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
879 assert!(
880 out.status.success(),
881 "aomenc refused the fixture: {}",
882 String::from_utf8_lossy(&out.stderr)
883 );
884 let stream = out.stdout;
885 let before = decode::tmv_hits();
886 let frames = match decode_stream(&stream) {
887 Err(e) => {
888 let msg = e.to_string();
889 assert!(
890 msg.contains("unsupported"),
891 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
892 attempt {attempt}): {msg}"
893 );
894 named_refusals += 1;
895 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
896 continue;
897 }
898 Ok(frames) => frames,
899 };
900 let tmv = decode::tmv_hits() - before;
901 let ffmpeg_frames = if bit_depth == 10 {
902 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
903 } else {
904 ffmpeg_decode_sequence(&stream, width, height, frame_count)
905 };
906 assert_eq!(frames.len(), frame_count);
907 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
908 assert_eq!(
909 got.y, want.y,
910 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
911 );
912 assert_eq!(
913 got.u, want.u,
914 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
915 );
916 assert_eq!(
917 got.v, want.v,
918 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
919 );
920 }
921 compared += 1;
922 tmv_proved += tmv;
923 }
924 eprintln!(
925 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
926 pixel-exact attempts, blocks with a temporal MV candidate={tmv_proved}"
927 );
928 assert!(
929 compared > 0,
930 "{NAME} ({bit_depth}-bit): every attempt refused -- gate proved nothing"
931 );
932 assert!(
933 tmv_proved > 0,
934 "{NAME} ({bit_depth}-bit): no compared attempt ever folded a temporal MV \
935 candidate into a block's stack -- gate proved nothing"
936 );
937 }
938 }
939
940 /// lane-refstamp r1: `av1_setup_motion_field`'s `ref_stamp` budget in the
941 /// presence of FORWARD KEY FRAMES (`--enable-fwd-kf=1`), which is the only
942 /// configuration where a *forward* reference slot (BWDREF/ALTREF2/ALTREF)
943 /// holds a key frame while temporal MV projection runs. libaom's
944 /// `motion_field_projection` returns 0 for such a start frame, so it costs
945 /// no `ref_stamp`; ours used to project the (empty) field and report
946 /// success, spending the slot ALTREF/LAST2 should have had and losing
947 /// their temporal candidates.
948 ///
949 /// Both bit depths; EVERY decoded frame (including the hidden alt-refs)
950 /// compared to the oracle in decode order; a refusal is counted, never
951 /// SKIPped. Two hard counters make the gate non-vacuous: frames that
952 /// actually took the >=2-intra-forward-refs `ref_stamp` path, and blocks
953 /// that folded a temporal MV candidate into their stack.
954 #[test]
955 fn a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact() {
956 const NAME: &str = "a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact";
957 let _gate_lock = lock_gate_counters();
958 if !have_ffmpeg() {
959 eprintln!("SKIP {NAME}: no ffmpeg");
960 return;
961 }
962 if !have_aomenc() {
963 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
964 return;
965 }
966 let (width, height, frame_count) = (192usize, 128usize, 24usize);
967 for bit_depth in [8u32, 10u32] {
968 let (mut named_refusals, mut compared, mut tmv_proved, mut stamp_proved) =
969 (0u32, 0u32, 0usize, 0usize);
970 let mut stamp2_proved = 0usize;
971 for attempt in 0..2u32 {
972 let duration = frame_count as f64 / 25.0;
973 // Natural-ish motion: structure translating along X at 3 px per
974 // frame plus a slow vertical drift, the source family the
975 // temporal-MV gate already decodes fully.
976 let source = format!(
977 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
978 geq=lum='128+58*sin((X+N*3)/6)+18*sin((Y+N*2)/23)',format=yuv420p"
979 );
980 let pix_fmt = if bit_depth == 10 {
981 "yuv420p10le"
982 } else {
983 "yuv420p"
984 };
985 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
986 .args([
987 "-v",
988 "error",
989 "-f",
990 "lavfi",
991 "-i",
992 &source,
993 "-t",
994 &duration.to_string(),
995 "-pix_fmt",
996 pix_fmt,
997 "-strict",
998 "-1",
999 "-f",
1000 "yuv4mpegpipe",
1001 "-",
1002 ])
1003 .stdin(Stdio::null())
1004 .stdout(Stdio::piped())
1005 .stderr(Stdio::piped()), None, |c| c.output())
1006 .expect("ffmpeg failed to run");
1007 assert!(
1008 y4m.status.success(),
1009 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1010 String::from_utf8_lossy(&y4m.stderr)
1011 );
1012 let depth_arg = format!("--bit-depth={bit_depth}");
1013 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1014 let cq_arg = format!("--cq-level={}", if attempt == 0 { 34 } else { 45 });
1015 let args: Vec<&str> = vec![
1016 "--codec=av1",
1017 "--passes=1",
1018 "--end-usage=q",
1019 &cq_arg,
1020 "--cpu-used=0",
1021 "--threads=1",
1022 "--row-mt=0",
1023 "--sb-size=64",
1024 &depth_arg,
1025 &input_depth_arg,
1026 "--enable-restoration=0",
1027 "--enable-palette=0",
1028 "--deltaq-mode=0",
1029 "--enable-filter-intra=0",
1030 "--enable-cfl-intra=0",
1031 "--enable-intrabc=0",
1032 "--enable-rect-partitions=1",
1033 "--enable-ab-partitions=0",
1034 "--enable-1to4-partitions=0",
1035 "--min-partition-size=16",
1036 "--max-partition-size=32",
1037 // Per-arm/feature overrides go LAST (aomenc keeps the LAST
1038 // occurrence of a repeated --enable-* flag).
1039 "--enable-order-hint=1",
1040 "--enable-ref-frame-mvs=1",
1041 "--enable-fwd-kf=1",
1042 "--fwd-kf-dist=8",
1043 "--kf-max-dist=1000",
1044 "--lag-in-frames=16",
1045 "--auto-alt-ref=1",
1046 "--arnr-maxframes=0",
1047 "--obu",
1048 "-o",
1049 "-",
1050 "-",
1051 ];
1052 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1053 assert!(
1054 out.status.success(),
1055 "aomenc refused the fixture: {}",
1056 String::from_utf8_lossy(&out.stderr)
1057 );
1058 let stream = out.stdout;
1059 let before_tmv = decode::tmv_hits();
1060 let before_stamp = crate::motion_field::refstamp_intra_frames();
1061 if let Err(e) = decode_stream(&stream) {
1062 let msg = e.to_string();
1063 assert!(
1064 msg.contains("unsupported"),
1065 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
1066 attempt {attempt}): {msg}"
1067 );
1068 named_refusals += 1;
1069 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
1070 continue;
1071 }
1072 let tmv = decode::tmv_hits() - before_tmv;
1073 let stamp = crate::motion_field::refstamp_intra_frames().0 - before_stamp.0;
1074 let stamp2 = crate::motion_field::refstamp_intra_frames().1 - before_stamp.1;
1075 // Every frame, hidden ones included, compared in DECODE order.
1076 let (total, hidden) = decode_all_frames_vs_oracle(
1077 &stream,
1078 &format!("{NAME}-{bit_depth}bit-attempt{attempt}"),
1079 );
1080 eprintln!(
1081 "{NAME} ({bit_depth}-bit attempt {attempt}): {total} frames decoded \
1082 ({hidden} hidden), temporal candidates={tmv}, frames with a key/intra \
1083 forward ref={stamp} (two or more: {stamp2})"
1084 );
1085 compared += 1;
1086 tmv_proved += tmv;
1087 stamp_proved += stamp;
1088 stamp2_proved += stamp2;
1089 }
1090 assert!(
1091 compared > 0,
1092 "{NAME} ({bit_depth}-bit): every attempt refused ({named_refusals}) -- gate \
1093 proved nothing"
1094 );
1095 assert!(
1096 tmv_proved > 0,
1097 "{NAME} ({bit_depth}-bit): no compared attempt folded a temporal MV candidate \
1098 into a block's stack -- gate proved nothing"
1099 );
1100 assert!(
1101 stamp_proved > 0,
1102 "{NAME} ({bit_depth}-bit): no compared attempt ever had a forward reference \
1103 holding a key/intra frame ({stamp2_proved} frames had two) -- the ref_stamp \
1104 path this gate exists for never ran"
1105 );
1106 }
1107 }
1108
1109 #[test]
1110 // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter
1111 // residual path IS implemented and reached, but no aomenc recipe swept
1112 // this round produced a stream whose FIRST rect inter block is a 32x16 /
1113 // 16x32 one: real motion content always codes a 16x8/8x16 inter leaf (or
1114 // an intra rect strip) earlier in the tile, and both of those still refuse
1115 // by name, so the decode stops before any 32-level 2:1 strip. The 16x8
1116 // shape additionally needs `default_inter_ext_tx_cdf[2][TX_8X8]` (the
1117 // 12-symbol DTT9_IDTX_1DDCT row, only reachable through a rect
1118 // transform), which this round did not add. See lanes/inter4-r2.report.md.
1119 // Un-ignored 2026-09-04: the intra-rect-strip and 16-level AB/1:4 inter refusals that blocked every attempt are gone and the gate passes.
1120 fn a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact() {
1121 const NAME: &str =
1122 "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact";
1123 let _gate_lock = lock_gate_counters();
1124 if !have_ffmpeg() {
1125 eprintln!("SKIP {NAME}: no ffmpeg");
1126 return;
1127 }
1128 if !have_aomenc() {
1129 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1130 return;
1131 }
1132 let (width, height, frame_count) = (192usize, 128usize, 6usize);
1133 for bit_depth in [8u32, 10u32] {
1134 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
1135 (0u32, 0u32, 0u32, 0u32);
1136 let (mut tu_proved, mut split_proved) = (0usize, 0usize);
1137 for attempt in 0..16u32 {
1138 // Two sources (a translating textured ramp, and testsrc2's
1139 // natural motion) x two quantisers x two tx-size-search arms x
1140 // two motion steps.
1141 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
1142 let cq = [34, 22][(attempt / 2 % 2) as usize];
1143 let natural = attempt / 4 % 2 == 1;
1144 let sp = 3 + (attempt / 8) * 5;
1145 let duration = frame_count as f64 / 25.0;
1146 // Continuous-tone, mid-frequency, translating: a flat or
1147 // banded source makes aomenc code the strips `skip` (r1's
1148 // gate) and its screen-content detector fires on the
1149 // synthetic ramps, stopping the decode at an unrelated intra
1150 // refusal long before any inter strip.
1151 // Structure ALONG one axis is what makes aomenc's RD pick a
1152 // 2:1 rect partition on that axis: horizontal bands drifting
1153 // vertically favour PARTITION_HORZ (32x16 strips), the
1154 // transposed source PARTITION_VERT (16x32).
1155 let lum = if natural {
1156 format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)")
1157 } else {
1158 format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)")
1159 };
1160 let source = format!(
1161 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
1162 geq=lum='{lum}',format=yuv420p"
1163 );
1164 let pix_fmt = if bit_depth == 10 {
1165 "yuv420p10le"
1166 } else {
1167 "yuv420p"
1168 };
1169 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1170 .args([
1171 "-v",
1172 "error",
1173 "-f",
1174 "lavfi",
1175 "-i",
1176 &source,
1177 "-t",
1178 &duration.to_string(),
1179 "-pix_fmt",
1180 pix_fmt,
1181 "-strict",
1182 "-1",
1183 "-f",
1184 "yuv4mpegpipe",
1185 "-",
1186 ])
1187 .stdin(Stdio::null())
1188 .stdout(Stdio::piped())
1189 .stderr(Stdio::piped()), None, |c| c.output())
1190 .expect("ffmpeg failed to run");
1191 assert!(
1192 y4m.status.success(),
1193 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1194 String::from_utf8_lossy(&y4m.stderr)
1195 );
1196 let cq_arg = format!("--cq-level={cq}");
1197 let depth_arg = format!("--bit-depth={bit_depth}");
1198 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1199 let tx_arg = format!("--enable-tx-size-search={tx_search}");
1200 let args: Vec<&str> = vec![
1201 "--codec=av1",
1202 "--passes=1",
1203 "--end-usage=q",
1204 &cq_arg,
1205 "--cpu-used=0",
1206 "--threads=1",
1207 "--row-mt=0",
1208 "--sb-size=64",
1209 &depth_arg,
1210 &input_depth_arg,
1211 "--enable-restoration=0",
1212 "--enable-palette=0",
1213 "--deltaq-mode=0",
1214 "--enable-filter-intra=0",
1215 "--enable-cfl-intra=0",
1216 "--enable-intrabc=0",
1217 "--lag-in-frames=0",
1218 // Per-arm overrides go LAST: aomenc keeps the last
1219 // occurrence of a repeated --enable-* flag.
1220 &tx_arg,
1221 "--enable-rect-partitions=1",
1222 "--enable-ab-partitions=0",
1223 "--enable-1to4-partitions=0",
1224 "--min-partition-size=16",
1225 "--max-partition-size=32",
1226 "--obu",
1227 "-o",
1228 "-",
1229 "-",
1230 ];
1231 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1232 assert!(
1233 out.status.success(),
1234 "aomenc refused the fixture: {}",
1235 String::from_utf8_lossy(&out.stderr)
1236 );
1237 let stream = out.stdout;
1238 let before = (
1239 decode::rect_inter_tu_hits(),
1240 decode::rect_inter_txsplit_hits(),
1241 );
1242 let frames = match decode_stream(&stream) {
1243 Err(e) => {
1244 let msg = e.to_string();
1245 assert!(
1246 msg.contains("unsupported"),
1247 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
1248 attempt {attempt}): {msg}"
1249 );
1250 named_refusals += 1;
1251 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
1252 continue;
1253 }
1254 Ok(frames) => frames,
1255 };
1256 let after = (
1257 decode::rect_inter_tu_hits(),
1258 decode::rect_inter_txsplit_hits(),
1259 );
1260 let (tu, split) = (after.0 - before.0, after.1 - before.1);
1261 let ffmpeg_frames = if bit_depth == 10 {
1262 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1263 } else {
1264 ffmpeg_decode_sequence(&stream, width, height, frame_count)
1265 };
1266 assert_eq!(frames.len(), frame_count);
1267 let mismatched = frames
1268 .iter()
1269 .zip(&ffmpeg_frames)
1270 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1271 if tu + split == 0 {
1272 out_of_scope += 1;
1273 if mismatched {
1274 oos_mismatch += 1;
1275 eprintln!(
1276 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
1277 coded rect inter transform units -- another shape's defect"
1278 );
1279 }
1280 continue;
1281 }
1282 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1283 assert_eq!(
1284 got.y, want.y,
1285 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
1286 );
1287 assert_eq!(
1288 got.u, want.u,
1289 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
1290 );
1291 assert_eq!(
1292 got.v, want.v,
1293 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
1294 );
1295 }
1296 tu_proved += tu;
1297 split_proved += split;
1298 matched += 1;
1299 }
1300 eprintln!(
1301 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
1302 attempts carrying a coded rect inter residual, whole-block rect TUs={tu_proved}, \
1303 rect trees that split={split_proved}, {out_of_scope} attempts carried none \
1304 ({oos_mismatch} of them mismatched)"
1305 );
1306 assert_eq!(
1307 oos_mismatch, 0,
1308 "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \
1309 mismatched ffmpeg -- a defect of another shape, not a pass"
1310 );
1311 assert!(
1312 tu_proved > 0,
1313 "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever coded a rectangular inter \
1314 residual (tu={tu_proved}, split={split_proved}, {named_refusals} refusals, \
1315 {out_of_scope} out of scope) -- gate proved nothing"
1316 );
1317 }
1318 }
1319
1320 /// lane-intersub8: `PARTITION_SPLIT` below 8x8 on an INTER frame -- four
1321 /// `BLOCK_4X4` inter sub-blocks with one shared 4x4 chroma unit per plane,
1322 /// predicted the sub8x8 way (2x2 chroma piece per luma sub-block mv,
1323 /// `dec_build_inter_predictors`' `is_sub8x8` branch). Reality of the shape
1324 /// was established BEFORE the code (class refusal-from-own-desync): the
1325 /// oracle `aomdec`'s `EC_TRACE` prints `EC_PART_VAL ... bsize=3 value=3`
1326 /// on this recipe's inter frames.
1327 ///
1328 /// Attempts 0..7 run `--enable-rect-partitions=0`, where aomenc can only
1329 /// pick SPLIT below 8x8; attempts 8..15 repeat the schedule with rect on,
1330 /// where it picks HORZ/VERT below 8x8 far more often than SPLIT -- the VERT
1331 /// arm (two `BLOCK_4X8` inter leaves, `decode_inter_sub8_rect2`) is what the
1332 /// `rect_fired` assert pins. The HORZ twin decodes but is refused by name
1333 /// (lane-intersub8 r3: a measured sweep desyncs the block to its right).
1334 #[test]
1335 fn a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact() {
1336 const NAME: &str =
1337 "a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact";
1338 let _gate_lock = lock_gate_counters();
1339 if !have_ffmpeg() {
1340 eprintln!("SKIP {NAME}: no ffmpeg");
1341 return;
1342 }
1343 if !have_aomenc() {
1344 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1345 return;
1346 }
1347 let (width, height, frame_count) = (192usize, 128usize, 6usize);
1348 let mut fired = 0u32;
1349 // lane-intersub8 r3: attempts 8..15 repeat the same schedule with
1350 // `--enable-rect-partitions=1`, where aomenc picks PARTITION_VERT below
1351 // 8x8 (two BLOCK_4X8 inter leaves, one shared 4x4 chroma unit predicted
1352 // from BOTH sub-blocks' mvs). The HORZ twin is still refused by name.
1353 let mut rect_fired = 0u32;
1354 // lane-intersub8 r5: the two rect axes counted apart. Attempts 16..23
1355 // are the same recipe family with the geq source TRANSPOSED (the sine
1356 // that moves runs along Y, not X): measured over a 56-arm sweep
1357 // (~/.cache/intersub8-sweep-r5.log, cq {8,12,14,16,20,26,32} x sp
1358 // {3,6,9,12} x both depths, rect on), aomenc picks PARTITION_HORZ
1359 // below 8x8 on that source and PARTITION_VERT on the untransposed one
1360 // -- neither schedule reaches the other axis, so both are needed.
1361 let (mut horz_fired, mut vert_fired) = (0u32, 0u32);
1362 // Rect (non-square) masked-compound blocks on attempts that DECODED
1363 // and were pixel-compared -- never off a refused stream (class
1364 // counter-from-refused-stream). This is the shape whose
1365 // `compound_type`/`wedge_idx` CDF row lane-intersub8 r4 fixed.
1366 let mut rect_masked = 0usize;
1367 let mut refusals: Vec<String> = Vec::new();
1368 let mut out_of_scope_mismatch = 0u32;
1369 for bit_depth in [8u32, 10u32] {
1370 for attempt in 0..24u32 {
1371 let rect = if attempt >= 16 { 1 } else { attempt / 8 };
1372 let rect_arg = format!("--enable-rect-partitions={rect}");
1373 // lane-intersub8 r2, measured schedule (sweep of cq
1374 // {8,10,12,14,16,18,20} x sp {3,6,9,12} x both depths,
1375 // `decode_probe`'s `sub8_inter_split:` counter vs an ffmpeg
1376 // rawvideo compare): sub-8x8 inter SPLIT groups fire at
1377 // (8-bit, cq 12, sp 3) = 1 group and (10-bit, cq 12, sp 6) =
1378 // 3 groups, both pixel-exact. cq 8 and 10 are NOT used: at
1379 // those quantizers this recipe also carries a CDEF defect of
1380 // another shape -- three luma samples of |d| = 1 on
1381 // decode-order frames 3/4, zero sub-8x8 inter split groups,
1382 // and the identical recipe re-encoded with `--enable-cdef=0`
1383 // decodes all six frames exact. Deferred to a CDEF lane
1384 // rather than hidden: cq 16..20 are all exact, so this gate
1385 // is not selecting quantizers that hide a defect of its own
1386 // shape.
1387 // Attempts 16..23: the (cq, sp) pairs the r5 sweep measured
1388 // as HORZ-firing on the transposed source -- 8-bit
1389 // (14,3)/(20,3)/(32,9), 10-bit (12,3)/(16,3); the rest of the
1390 // eight are non-firing neighbours kept so a schedule that
1391 // stops firing shows up as out-of-scope, not as a silent pass.
1392 const HORZ_SCHEDULE: [(u32, u32); 8] = [
1393 (14, 3),
1394 (20, 3),
1395 (32, 9),
1396 (12, 3),
1397 (16, 3),
1398 (12, 9),
1399 (14, 9),
1400 (26, 3),
1401 ];
1402 let (cq, sp) = if attempt >= 16 {
1403 HORZ_SCHEDULE[(attempt - 16) as usize]
1404 } else {
1405 (
1406 [12, 14][(attempt % 2) as usize],
1407 3 + ((attempt % 8) / 2) * 3,
1408 )
1409 };
1410 let duration = frame_count as f64 / 25.0;
1411 let source = if attempt >= 16 {
1412 format!(
1413 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
1414 geq=lum='128+58*sin((Y+N*{sp})/6)+18*sin(X/23)',format=yuv420p"
1415 )
1416 } else {
1417 format!(
1418 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
1419 geq=lum='128+58*sin((X+N*{sp})/6)+18*sin(Y/23)',format=yuv420p"
1420 )
1421 };
1422 let pix_fmt = if bit_depth == 10 {
1423 "yuv420p10le"
1424 } else {
1425 "yuv420p"
1426 };
1427 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1428 .args([
1429 "-v",
1430 "error",
1431 "-f",
1432 "lavfi",
1433 "-i",
1434 &source,
1435 "-t",
1436 &duration.to_string(),
1437 "-pix_fmt",
1438 pix_fmt,
1439 "-strict",
1440 "-1",
1441 "-f",
1442 "yuv4mpegpipe",
1443 "-",
1444 ])
1445 .stdin(Stdio::null())
1446 .stdout(Stdio::piped())
1447 .stderr(Stdio::piped()), None, |c| c.output())
1448 .expect("ffmpeg failed to run");
1449 assert!(
1450 y4m.status.success(),
1451 "{NAME}: ffmpeg refused the fixture: {}",
1452 String::from_utf8_lossy(&y4m.stderr)
1453 );
1454 let cq_arg = format!("--cq-level={cq}");
1455 let depth_arg = format!("--bit-depth={bit_depth}");
1456 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1457 let args: Vec<&str> = vec![
1458 "--codec=av1",
1459 "--passes=1",
1460 "--end-usage=q",
1461 &cq_arg,
1462 "--cpu-used=0",
1463 "--threads=1",
1464 "--row-mt=0",
1465 "--sb-size=64",
1466 &depth_arg,
1467 &input_depth_arg,
1468 "--enable-restoration=0",
1469 "--enable-palette=0",
1470 "--deltaq-mode=0",
1471 "--enable-filter-intra=0",
1472 "--enable-cfl-intra=0",
1473 "--enable-intrabc=0",
1474 "--lag-in-frames=0",
1475 "--enable-obmc=0",
1476 "--enable-tx-size-search=1",
1477 // Per-arm overrides last (aomenc keeps the LAST occurrence).
1478 "--enable-rect-partitions=0",
1479 "--enable-ab-partitions=0",
1480 "--enable-1to4-partitions=0",
1481 "--min-partition-size=4",
1482 "--max-partition-size=16",
1483 &rect_arg,
1484 "--obu",
1485 "-o",
1486 "-",
1487 "-",
1488 ];
1489 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1490 assert!(
1491 out.status.success(),
1492 "{NAME}: aomenc refused the fixture: {}",
1493 String::from_utf8_lossy(&out.stderr)
1494 );
1495 let stream = out.stdout;
1496 let before = decode::sub8_inter_split_hits();
1497 let before_rect = decode::sub8_inter_rect_hits();
1498 let before_masked = decode::rect_masked_compound_hits();
1499 let frames = match decode_stream(&stream) {
1500 Err(e) => {
1501 let msg = e.to_string();
1502 assert!(
1503 msg.contains("unsupported"),
1504 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
1505 attempt {attempt}): {msg}"
1506 );
1507 refusals.push(format!("{bit_depth}-bit attempt {attempt}: {msg}"));
1508 continue;
1509 }
1510 Ok(frames) => frames,
1511 };
1512 let split_groups = decode::sub8_inter_split_hits() - before;
1513 let rect_now = decode::sub8_inter_rect_hits();
1514 let rect_groups = (rect_now.0 - before_rect.0) + (rect_now.1 - before_rect.1);
1515 let groups = split_groups + rect_groups;
1516 let ffmpeg_frames = if bit_depth == 10 {
1517 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1518 } else {
1519 ffmpeg_decode_sequence(&stream, width, height, frame_count)
1520 };
1521 assert_eq!(frames.len(), frame_count);
1522 let mismatched = frames
1523 .iter()
1524 .zip(&ffmpeg_frames)
1525 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1526 if groups == 0 {
1527 // Out of scope: no sub-8x8 inter split in this attempt.
1528 if mismatched {
1529 out_of_scope_mismatch += 1;
1530 eprintln!(
1531 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
1532 sub-8x8 inter group -- another shape's defect"
1533 );
1534 }
1535 refusals.push(format!(
1536 "{bit_depth}-bit attempt {attempt}: decoded, but no sub-8x8 inter split"
1537 ));
1538 continue;
1539 }
1540 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1541 assert_eq!(
1542 got.y, want.y,
1543 "luma frame {i} ({bit_depth}-bit attempt {attempt}, {groups} sub-8x8 \
1544 inter split groups)"
1545 );
1546 assert_eq!(
1547 got.u, want.u,
1548 "U frame {i} ({bit_depth}-bit attempt {attempt})"
1549 );
1550 assert_eq!(
1551 got.v, want.v,
1552 "V frame {i} ({bit_depth}-bit attempt {attempt})"
1553 );
1554 }
1555 fired += 1;
1556 if rect_groups > 0 {
1557 rect_fired += 1;
1558 }
1559 if rect_now.0 - before_rect.0 > 0 {
1560 horz_fired += 1;
1561 }
1562 if rect_now.1 - before_rect.1 > 0 {
1563 vert_fired += 1;
1564 }
1565 // Only now, past the pixel compare, is this attempt's
1566 // masked-compound count admissible.
1567 rect_masked += decode::rect_masked_compound_hits() - before_masked;
1568 }
1569 }
1570 eprintln!(
1571 "{NAME}: fired={fired} horz={horz_fired} vert={vert_fired} rect_masked={rect_masked}"
1572 );
1573 assert_eq!(
1574 out_of_scope_mismatch, 0,
1575 "{NAME}: attempts mismatched with no sub-8x8 inter group"
1576 );
1577 assert!(
1578 fired >= 2,
1579 "{NAME}: fewer than 2 firing+pixel-exact attempts:\n{}",
1580 refusals.join("\n")
1581 );
1582 assert!(
1583 rect_fired >= 2,
1584 "{NAME}: fewer than 2 firing+pixel-exact attempts with a RECTANGULAR sub-8x8 \
1585 inter leaf (4x8):\n{}",
1586 refusals.join("\n")
1587 );
1588 assert!(
1589 vert_fired >= 2,
1590 "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter VERT \
1591 pair (two BLOCK_4X8 leaves):\n{}",
1592 refusals.join("\n")
1593 );
1594 // lane-intersub8 r5, measured `rect_masked=2` over the 48 attempts:
1595 // the rect masked-compound blocks whose `compound_type`/`wedge_idx`
1596 // CDF row r4 corrected, counted only on pixel-compared attempts.
1597 assert!(
1598 rect_masked >= 1,
1599 "{NAME}: no RECTANGULAR masked-compound block on any pixel-compared attempt -- \
1600 the r4 compound_type/wedge_idx CDF-row fix is unexercised:\n{}",
1601 refusals.join("\n")
1602 );
1603 assert!(
1604 horz_fired >= 2,
1605 "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter HORZ \
1606 pair (two BLOCK_8X4 leaves):\n{}",
1607 refusals.join("\n")
1608 );
1609 }
1610
1611 #[test]
1612 // lane-inter4 r3: the 16x16-level rect INTER leaf -- PARTITION_HORZ /
1613 // PARTITION_VERT at 16x16 on an inter frame, i.e. two 16x8 / 8x16 inter
1614 // blocks, mode info + rectangular residual + prediction. Every decoded
1615 // frame is compared Y/U/V against ffmpeg, refusals are counted and never
1616 // SKIPped, and the gate asserts a pixel-exact attempt for BOTH axes that
1617 // also coded a rectangular inter transform unit (i.e. was not `skip`).
1618 fn a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact() {
1619 const NAME: &str =
1620 "a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact";
1621 let _gate_lock = lock_gate_counters();
1622 if !have_ffmpeg() {
1623 eprintln!("SKIP {NAME}: no ffmpeg");
1624 return;
1625 }
1626 if !have_aomenc() {
1627 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1628 return;
1629 }
1630 let (width, height, frame_count) = (192usize, 128usize, 6usize);
1631 // Coded (non-skip) rect inter transform units, summed over both bit
1632 // depths: at 10 bits this recipe's rect leaves all come out `skip`
1633 // (measured at cq 34/22, 30/26 and 24/12 -- the lower pairs stop
1634 // reaching a rect leaf at all), so the RESIDUAL half of the claim is
1635 // proven by the 8-bit arm while the 10-bit arm proves the mode-info,
1636 // prediction and neighbour halves on both axes.
1637 let mut tu_total = 0usize;
1638 for bit_depth in [8u32, 10u32] {
1639 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
1640 (0u32, 0u32, 0u32, 0u32);
1641 let (mut tu_proved, mut split_proved) = (0usize, 0usize);
1642 let (mut horz_proved, mut vert_proved, mut sub16_split) = (0u32, 0u32, 0usize);
1643 // lane-inter4 r4, measured residue of this recipe family (sweep
1644 // over cq {8,12,16,22} x {both axes} x both depths, tx-size-search
1645 // on, via `decode_probe`'s `rect_inter:` counters): the rect
1646 // var-tx SPLIT arm never fires (txsplit=0 everywhere) and a 10-bit
1647 // rect leaf is always `skip` (tu=0 at every cq that decodes) --
1648 // below cq 22 every attempt stops at another lane's intra refusal
1649 // ("a HORZ/VERT intra strip below 16x16 with a split transform").
1650 // Both are asserted here only where they DO fire (8-bit tu>0);
1651 // shipped-but-unexercised, see lanes/inter4-r4.report.md.
1652 // lane-inter4 r4: attempts 16..32 repeat the same sweep with
1653 // `--enable-obmc=1`. r3 refused OBMC on this shape; r4's
1654 // instrumented-aomdec comparison showed the neighbour list AND
1655 // every pre-filter frame bit-exact, so the arm is a gate now.
1656 let mut obmc_leaf_proved = 0usize;
1657 for attempt in 0..32u32 {
1658 let obmc_arg = if attempt >= 16 {
1659 "--enable-obmc=1"
1660 } else {
1661 "--enable-obmc=0"
1662 };
1663 let attempt = attempt % 16;
1664 // Two sources (a translating textured ramp, and testsrc2's
1665 // natural motion) x two quantisers x two tx-size-search arms x
1666 // two motion steps.
1667 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
1668 // A 10-bit encode of the same source spends fewer bits on
1669 // residual at a given cq, so it needs the lower pair to make
1670 // a rect leaf non-skip at all (measured: cq 34/22 gives zero
1671 // coded rect inter TUs in 16 10-bit attempts).
1672 let cq = [34, 22][(attempt / 2 % 2) as usize];
1673 let natural = attempt / 4 % 2 == 1;
1674 let sp = 3 + (attempt / 8) * 5;
1675 let duration = frame_count as f64 / 25.0;
1676 // Continuous-tone, mid-frequency, translating: a flat or
1677 // banded source makes aomenc code the strips `skip` (r1's
1678 // gate) and its screen-content detector fires on the
1679 // synthetic ramps, stopping the decode at an unrelated intra
1680 // refusal long before any inter strip.
1681 // Structure ALONG one axis is what makes aomenc's RD pick a
1682 // 2:1 rect partition on that axis: horizontal bands drifting
1683 // vertically favour PARTITION_HORZ (32x16 strips), the
1684 // transposed source PARTITION_VERT (16x32).
1685 let lum = if natural {
1686 format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)")
1687 } else {
1688 format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)")
1689 };
1690 let source = format!(
1691 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
1692 geq=lum='{lum}',format=yuv420p"
1693 );
1694 let pix_fmt = if bit_depth == 10 {
1695 "yuv420p10le"
1696 } else {
1697 "yuv420p"
1698 };
1699 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1700 .args([
1701 "-v",
1702 "error",
1703 "-f",
1704 "lavfi",
1705 "-i",
1706 &source,
1707 "-t",
1708 &duration.to_string(),
1709 "-pix_fmt",
1710 pix_fmt,
1711 "-strict",
1712 "-1",
1713 "-f",
1714 "yuv4mpegpipe",
1715 "-",
1716 ])
1717 .stdin(Stdio::null())
1718 .stdout(Stdio::piped())
1719 .stderr(Stdio::piped()), None, |c| c.output())
1720 .expect("ffmpeg failed to run");
1721 assert!(
1722 y4m.status.success(),
1723 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1724 String::from_utf8_lossy(&y4m.stderr)
1725 );
1726 let cq_arg = format!("--cq-level={cq}");
1727 let depth_arg = format!("--bit-depth={bit_depth}");
1728 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1729 let tx_arg = format!("--enable-tx-size-search={tx_search}");
1730 let args: Vec<&str> = vec![
1731 "--codec=av1",
1732 "--passes=1",
1733 "--end-usage=q",
1734 &cq_arg,
1735 "--cpu-used=0",
1736 "--threads=1",
1737 "--row-mt=0",
1738 "--sb-size=64",
1739 &depth_arg,
1740 &input_depth_arg,
1741 "--enable-restoration=0",
1742 "--enable-palette=0",
1743 "--deltaq-mode=0",
1744 "--enable-filter-intra=0",
1745 "--enable-cfl-intra=0",
1746 "--enable-intrabc=0",
1747 "--lag-in-frames=0",
1748 // Per-arm overrides go LAST: aomenc keeps the last
1749 // occurrence of a repeated --enable-* flag.
1750 &tx_arg,
1751 "--enable-rect-partitions=1",
1752 "--enable-ab-partitions=0",
1753 "--enable-1to4-partitions=0",
1754 "--min-partition-size=8",
1755 "--max-partition-size=16",
1756 obmc_arg,
1757 "--obu",
1758 "-o",
1759 "-",
1760 "-",
1761 ];
1762 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1763 assert!(
1764 out.status.success(),
1765 "aomenc refused the fixture: {}",
1766 String::from_utf8_lossy(&out.stderr)
1767 );
1768 let stream = out.stdout;
1769 let before = (
1770 decode::rect_inter_tu_hits(),
1771 decode::rect_inter_txsplit_hits(),
1772 );
1773 let before_obmc_leaf = decode::obmc_rect_leaf_hits();
1774 let before_leaf = (
1775 decode::inter_leaf16_horz_hits(),
1776 decode::inter_leaf16_vert_hits(),
1777 decode::inter_sub16_split_hits(),
1778 );
1779 let frames = match decode_stream(&stream) {
1780 Err(e) => {
1781 let msg = e.to_string();
1782 assert!(
1783 msg.contains("unsupported"),
1784 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
1785 attempt {attempt}): {msg}"
1786 );
1787 named_refusals += 1;
1788 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
1789 continue;
1790 }
1791 Ok(frames) => frames,
1792 };
1793 let after = (
1794 decode::rect_inter_tu_hits(),
1795 decode::rect_inter_txsplit_hits(),
1796 );
1797 let (tu, split) = (after.0 - before.0, after.1 - before.1);
1798 let obmc_leaf = decode::obmc_rect_leaf_hits() - before_obmc_leaf;
1799 let (horz, vert, splits16) = (
1800 decode::inter_leaf16_horz_hits() - before_leaf.0,
1801 decode::inter_leaf16_vert_hits() - before_leaf.1,
1802 decode::inter_sub16_split_hits() - before_leaf.2,
1803 );
1804 let ffmpeg_frames = if bit_depth == 10 {
1805 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1806 } else {
1807 ffmpeg_decode_sequence(&stream, width, height, frame_count)
1808 };
1809 assert_eq!(frames.len(), frame_count);
1810 let mismatched = frames
1811 .iter()
1812 .zip(&ffmpeg_frames)
1813 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1814 if horz + vert == 0 {
1815 out_of_scope += 1;
1816 if mismatched {
1817 oos_mismatch += 1;
1818 eprintln!(
1819 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
1820 16-level rect inter leaf -- another shape's defect"
1821 );
1822 }
1823 continue;
1824 }
1825 if mismatched {
1826 // lane-inter4 r3: where, not just that -- a handful of
1827 // 4x4-aligned pixels is a prediction/reconstruction
1828 // defect, a whole band from the first row down is a
1829 // desync.
1830 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1831 let bad: Vec<usize> = (0..got.y.len())
1832 .filter(|&k| got.y[k] != want.y[k])
1833 .collect();
1834 if !bad.is_empty() {
1835 eprintln!(
1836 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
1837 pixels differ, first at ({}, {}), max |delta| {}",
1838 bad.len(),
1839 bad[0] % width,
1840 bad[0] / width,
1841 bad.iter()
1842 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
1843 .max()
1844 .unwrap_or(0)
1845 );
1846 }
1847 }
1848 }
1849 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1850 assert_eq!(
1851 got.y, want.y,
1852 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
1853 );
1854 assert_eq!(
1855 got.u, want.u,
1856 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
1857 );
1858 assert_eq!(
1859 got.v, want.v,
1860 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
1861 );
1862 }
1863 tu_proved += tu;
1864 obmc_leaf_proved += obmc_leaf;
1865 split_proved += split;
1866 sub16_split += splits16;
1867 if horz > 0 {
1868 horz_proved += 1;
1869 }
1870 if vert > 0 {
1871 vert_proved += 1;
1872 }
1873 matched += 1;
1874 }
1875 eprintln!(
1876 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
1877 attempts carrying a 16-level rect inter leaf, 16x8-carrying={horz_proved}, \
1878 8x16-carrying={vert_proved}, whole-block rect TUs={tu_proved}, rect trees that \
1879 split={split_proved}, 16x16 SPLITs={sub16_split}, OBMC blends on a rect \
1880 leaf={obmc_leaf_proved}, {out_of_scope} attempts \
1881 carried none ({oos_mismatch} of them mismatched)"
1882 );
1883 assert_eq!(
1884 oos_mismatch, 0,
1885 "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \
1886 mismatched ffmpeg -- a defect of another shape, not a pass"
1887 );
1888 assert!(
1889 horz_proved > 0 && vert_proved > 0,
1890 "{NAME} ({bit_depth}-bit): the 16-level rect inter leaf is not proven on both \
1891 axes (16x8={horz_proved}, 8x16={vert_proved}, tu={tu_proved}, 16x16 \
1892 SPLITs={sub16_split}, {named_refusals} refusals, {out_of_scope} out of \
1893 scope) -- gate proved nothing"
1894 );
1895 assert!(
1896 obmc_leaf_proved > 0,
1897 "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever ran the OBMC blend on a \
1898 16x8/8x16 inter leaf -- the `--enable-obmc=1` arm proved nothing"
1899 );
1900 tu_total += tu_proved;
1901 }
1902 assert!(
1903 tu_total > 0,
1904 "{NAME}: no pixel-exact attempt at either bit depth coded a rectangular inter \
1905 residual on a 16-level leaf -- the residual half of the claim is unproven"
1906 );
1907 }
1908
1909 #[test]
1910 // lane-inter16ab r1: the 16x16-level AB partitions on an INTER frame --
1911 // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter
1912 // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is
1913 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
1914 // out-of-scope mismatches fail the gate, and EACH of the four arms must
1915 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
1916 // proof of four). `--enable-1to4-partitions=0` because the 16-level 1:4
1917 // pair (16x4/4x16 inter strips) is still refused by name.
1918 fn a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact() {
1919 const NAME: &str =
1920 "a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact";
1921 let _gate_lock = lock_gate_counters();
1922 if !have_ffmpeg() {
1923 eprintln!("SKIP {NAME}: no ffmpeg");
1924 return;
1925 }
1926 if !have_aomenc() {
1927 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1928 return;
1929 }
1930 let (width, height, frame_count) = (192usize, 128usize, 6usize);
1931 // Per arm, over both bit depths: how many pixel-exact attempts fired
1932 // it at least once.
1933 let mut arms_total = [0u32; 4];
1934 for bit_depth in [8u32, 10u32] {
1935 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
1936 (0u32, 0u32, 0u32, 0u32);
1937 let mut arms_proved = [0u32; 4];
1938 for attempt in 0..32u32 {
1939 // Two sources (structure along X vs along Y -- an AB
1940 // partition needs an L/T-shaped feature, so both orientations
1941 // are swept), four quantisers, two motion steps, two tiling
1942 // arms. r1 measured (sweep script in the report): a 16-attempt
1943 // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A
1944 // at 8 bits, so the quantiser axis is four wide here; cq 46 on
1945 // the X-structured source is deliberately NOT in the list --
1946 // that stream's decode-order frame 4 desyncs on a defect this
1947 // lane does not own (aomdec's own EC_PART trace reads ZERO
1948 // AB partitions at BLOCK_16X16 anywhere in it, so the AB
1949 // counters it raises are read out of an already-diverged
1950 // stream; see lanes/inter16ab-r1.report.md).
1951 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
1952 // The 10-bit arm swaps cq 40 for 28 on the same sources: at
1953 // cq 40 the X-structured 10-bit stream mismatches ffmpeg with
1954 // ZERO 16-level AB partitions in it (another shape's defect,
1955 // measured r1 -- the gate's own `oos_mismatch` counter is
1956 // what found it, and it is reported, not silenced).
1957 let cq = if bit_depth == 10 {
1958 [18, 22, 34, 28][(attempt / 2 % 4) as usize]
1959 } else {
1960 [18, 22, 34, 40][(attempt / 2 % 4) as usize]
1961 };
1962 let natural = attempt / 8 % 2 == 1;
1963 let group = attempt / 16;
1964 // r1: a `--tile-columns=1` arm of this same sweep PANICS in
1965 // `mc::from_switchable_symbol` (a 4th symbol out of a
1966 // 3-symbol alphabet = someone else's desync, the signature
1967 // the ledger already pins for the below-8x8 inter leaf), not
1968 // in anything this lane added -- so the tiled arm is left out
1969 // rather than turned into a SKIP or a weakened assert.
1970 // Reported as residue in lanes/inter16ab-r1.report.md.
1971 let tile_cols = "0";
1972 let sp = 3 + (group % 2) * 5;
1973 let duration = frame_count as f64 / 25.0;
1974 // Continuous-tone translating texture with a second, coarser
1975 // component on the cross axis: aomenc's RD picks an AB
1976 // partition where one 16x16 quadrant differs from its three
1977 // siblings, which the two sinusoids at different periods
1978 // produce all over the frame.
1979 let lum = if natural {
1980 format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)")
1981 } else {
1982 format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)")
1983 };
1984 let source = format!(
1985 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
1986 geq=lum='{lum}',format=yuv420p"
1987 );
1988 let pix_fmt = if bit_depth == 10 {
1989 "yuv420p10le"
1990 } else {
1991 "yuv420p"
1992 };
1993 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1994 .args([
1995 "-v",
1996 "error",
1997 "-f",
1998 "lavfi",
1999 "-i",
2000 &source,
2001 "-t",
2002 &duration.to_string(),
2003 "-pix_fmt",
2004 pix_fmt,
2005 "-strict",
2006 "-1",
2007 "-f",
2008 "yuv4mpegpipe",
2009 "-",
2010 ])
2011 .stdin(Stdio::null())
2012 .stdout(Stdio::piped())
2013 .stderr(Stdio::piped()), None, |c| c.output())
2014 .expect("ffmpeg failed to run");
2015 assert!(
2016 y4m.status.success(),
2017 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
2018 String::from_utf8_lossy(&y4m.stderr)
2019 );
2020 let cq_arg = format!("--cq-level={cq}");
2021 let depth_arg = format!("--bit-depth={bit_depth}");
2022 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
2023 let tx_arg = format!("--enable-tx-size-search={tx_search}");
2024 let tile_arg = format!("--tile-columns={tile_cols}");
2025 let args: Vec<&str> = vec![
2026 "--codec=av1",
2027 "--passes=1",
2028 "--end-usage=q",
2029 &cq_arg,
2030 "--cpu-used=0",
2031 "--threads=1",
2032 "--row-mt=0",
2033 "--sb-size=64",
2034 &depth_arg,
2035 &input_depth_arg,
2036 "--enable-restoration=0",
2037 "--enable-palette=0",
2038 "--deltaq-mode=0",
2039 "--enable-filter-intra=0",
2040 "--enable-cfl-intra=0",
2041 "--enable-intrabc=0",
2042 "--lag-in-frames=0",
2043 "--kf-max-dist=9999",
2044 &tile_arg,
2045 // Per-arm overrides go LAST: aomenc keeps the last
2046 // occurrence of a repeated --enable-* flag.
2047 &tx_arg,
2048 "--enable-rect-partitions=1",
2049 "--enable-ab-partitions=1",
2050 "--enable-1to4-partitions=0",
2051 "--min-partition-size=8",
2052 "--max-partition-size=16",
2053 "--obu",
2054 "-o",
2055 "-",
2056 "-",
2057 ];
2058 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2059 assert!(
2060 out.status.success(),
2061 "aomenc refused the fixture: {}",
2062 String::from_utf8_lossy(&out.stderr)
2063 );
2064 let stream = out.stdout;
2065 let before = decode::ab16_inter_hits_by_arm();
2066 let frames = match decode_stream(&stream) {
2067 Err(e) => {
2068 let msg = e.to_string();
2069 assert!(
2070 msg.contains("unsupported"),
2071 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
2072 attempt {attempt}): {msg}"
2073 );
2074 named_refusals += 1;
2075 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
2076 continue;
2077 }
2078 Ok(frames) => frames,
2079 };
2080 let after = decode::ab16_inter_hits_by_arm();
2081 let fired: Vec<usize> = (0..4).map(|a| after[a] - before[a]).collect();
2082 let ffmpeg_frames = if bit_depth == 10 {
2083 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
2084 } else {
2085 ffmpeg_decode_sequence(&stream, width, height, frame_count)
2086 };
2087 assert_eq!(frames.len(), frame_count);
2088 let mismatched = frames
2089 .iter()
2090 .zip(&ffmpeg_frames)
2091 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2092 if fired.iter().sum::<usize>() == 0 {
2093 out_of_scope += 1;
2094 if mismatched {
2095 oos_mismatch += 1;
2096 eprintln!(
2097 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
2098 16-level inter AB partition -- another shape's defect"
2099 );
2100 }
2101 continue;
2102 }
2103 if mismatched {
2104 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2105 let bad: Vec<usize> = (0..got.y.len())
2106 .filter(|&k| got.y[k] != want.y[k])
2107 .collect();
2108 if !bad.is_empty() {
2109 eprintln!(
2110 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
2111 pixels differ, first at ({}, {}), max |delta| {}",
2112 bad.len(),
2113 bad[0] % width,
2114 bad[0] / width,
2115 bad.iter()
2116 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
2117 .max()
2118 .unwrap_or(0)
2119 );
2120 }
2121 }
2122 }
2123 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2124 assert_eq!(
2125 got.y, want.y,
2126 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
2127 );
2128 assert_eq!(
2129 got.u, want.u,
2130 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
2131 );
2132 assert_eq!(
2133 got.v, want.v,
2134 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
2135 );
2136 }
2137 for a in 0..4 {
2138 if fired[a] > 0 {
2139 arms_proved[a] += 1;
2140 arms_total[a] += 1;
2141 }
2142 }
2143 matched += 1;
2144 }
2145 eprintln!(
2146 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
2147 attempts carrying a 16-level inter AB partition, per-arm attempts \
2148 HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \
2149 none ({oos_mismatch} of them mismatched)"
2150 );
2151 assert_eq!(
2152 oos_mismatch, 0,
2153 "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter AB partition decoded \
2154 but mismatched ffmpeg -- a defect of another shape, not a pass"
2155 );
2156 }
2157 assert!(
2158 arms_total.iter().all(|&n| n > 0),
2159 "{NAME}: not every 16-level inter AB arm fired on a pixel-exact attempt \
2160 (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven"
2161 );
2162 }
2163
2164 #[test]
2165 // lane-inter16ab r2: the 16x16-level 1:4 partitions on an INTER frame --
2166 // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter
2167 // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is
2168 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
2169 // out-of-scope mismatches fail the gate, and EACH of the four arms must
2170 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
2171 // proof of four). `--min-partition-size=4` is what lets aomenc's RD reach
2172 // `PARTITION_HORZ_4`/`_VERT_4` at BLOCK_16X16 (16x4 / 4x16 inter strips);
2173 // the last two counters are the chroma half of the claim -- the odd
2174 // strip's `is_chroma_reference` pair and the pairs whose chroma was built
2175 // from two different strips' motion vectors
2176 // (`build_inter_predictors_sub8x8`).
2177 fn a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact() {
2178 const NAME: &str =
2179 "a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact";
2180 let _gate_lock = lock_gate_counters();
2181 if !have_ffmpeg() {
2182 eprintln!("SKIP {NAME}: no ffmpeg");
2183 return;
2184 }
2185 if !have_aomenc() {
2186 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2187 return;
2188 }
2189 let (width, height, frame_count) = (192usize, 128usize, 6usize);
2190 // Per arm, over both bit depths: how many pixel-exact attempts fired
2191 // it at least once.
2192 let mut arms_total = [0u32; 5];
2193 // lane-inter16ab r5: attempts refused on "a non-skip rectangular
2194 // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding".
2195 let mut rect_residual_refusals = 0u32;
2196 for bit_depth in [8u32, 10u32] {
2197 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
2198 (0u32, 0u32, 0u32, 0u32);
2199 let mut arms_proved = [0u32; 5];
2200 // lane-inter16ab r4: a 4-recipe widening (fine `sin(X/3)` stripes
2201 // at cq 8..14, both depths) was measured and REMOVED again -- every
2202 // extra 1:4 partition it produced is in the KEY frame, and this
2203 // gate's arms count INTER-frame strips. Frame-aware histogram
2204 // script + table in lanes/inter16ab-r4.report.md; the only recipe
2205 // in the whole sweep with an inter-frame `PARTITION_VERT_4` is
2206 // attempt 1's, which refuses on the rect wedge-interintra mask.
2207 for attempt in 0..32u32 {
2208 // Two sources (structure along X vs along Y -- an AB
2209 // partition needs an L/T-shaped feature, so both orientations
2210 // are swept), four quantisers, two motion steps, two tiling
2211 // arms. r1 measured (sweep script in the report): a 16-attempt
2212 // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A
2213 // at 8 bits, so the quantiser axis is four wide here; cq 46 on
2214 // the X-structured source is deliberately NOT in the list --
2215 // that stream's decode-order frame 4 desyncs on a defect this
2216 // lane does not own (aomdec's own EC_PART trace reads ZERO
2217 // AB partitions at BLOCK_16X16 anywhere in it, so the AB
2218 // counters it raises are read out of an already-diverged
2219 // stream; see lanes/inter16ab-r1.report.md).
2220 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
2221 // The 10-bit arm swaps cq 40 for 28 on the same sources: at
2222 // cq 40 the X-structured 10-bit stream mismatches ffmpeg with
2223 // ZERO 16-level AB partitions in it (another shape's defect,
2224 // measured r1 -- the gate's own `oos_mismatch` counter is
2225 // what found it, and it is reported, not silenced).
2226 let cq = if bit_depth == 10 {
2227 [18, 22, 34, 28][(attempt / 2 % 4) as usize]
2228 } else {
2229 [18, 22, 34, 40][(attempt / 2 % 4) as usize]
2230 };
2231 let natural = attempt / 8 % 2 == 1;
2232 let group = attempt / 16;
2233 // r1: a `--tile-columns=1` arm of this same sweep PANICS in
2234 // `mc::from_switchable_symbol` (a 4th symbol out of a
2235 // 3-symbol alphabet = someone else's desync, the signature
2236 // the ledger already pins for the below-8x8 inter leaf), not
2237 // in anything this lane added -- so the tiled arm is left out
2238 // rather than turned into a SKIP or a weakened assert.
2239 // Reported as residue in lanes/inter16ab-r1.report.md.
2240 let tile_cols = "0";
2241 let sp = 3 + (group % 2) * 5;
2242 let duration = frame_count as f64 / 25.0;
2243 // Continuous-tone translating texture with a second, coarser
2244 // component on the cross axis: aomenc's RD picks an AB
2245 // partition where one 16x16 quadrant differs from its three
2246 // siblings, which the two sinusoids at different periods
2247 // produce all over the frame.
2248 let lum = if natural {
2249 format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)")
2250 } else {
2251 format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)")
2252 };
2253 let source = format!(
2254 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
2255 geq=lum='{lum}',format=yuv420p"
2256 );
2257 let pix_fmt = if bit_depth == 10 {
2258 "yuv420p10le"
2259 } else {
2260 "yuv420p"
2261 };
2262 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2263 .args([
2264 "-v",
2265 "error",
2266 "-f",
2267 "lavfi",
2268 "-i",
2269 &source,
2270 "-t",
2271 &duration.to_string(),
2272 "-pix_fmt",
2273 pix_fmt,
2274 "-strict",
2275 "-1",
2276 "-f",
2277 "yuv4mpegpipe",
2278 "-",
2279 ])
2280 .stdin(Stdio::null())
2281 .stdout(Stdio::piped())
2282 .stderr(Stdio::piped()), None, |c| c.output())
2283 .expect("ffmpeg failed to run");
2284 assert!(
2285 y4m.status.success(),
2286 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
2287 String::from_utf8_lossy(&y4m.stderr)
2288 );
2289 let cq_arg = format!("--cq-level={cq}");
2290 let depth_arg = format!("--bit-depth={bit_depth}");
2291 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
2292 let tx_arg = format!("--enable-tx-size-search={tx_search}");
2293 let tile_arg = format!("--tile-columns={tile_cols}");
2294 let args: Vec<&str> = vec![
2295 "--codec=av1",
2296 "--passes=1",
2297 "--end-usage=q",
2298 &cq_arg,
2299 "--cpu-used=0",
2300 "--threads=1",
2301 "--row-mt=0",
2302 "--sb-size=64",
2303 &depth_arg,
2304 &input_depth_arg,
2305 "--enable-restoration=0",
2306 "--enable-palette=0",
2307 "--deltaq-mode=0",
2308 "--enable-filter-intra=0",
2309 "--enable-cfl-intra=0",
2310 "--enable-intrabc=0",
2311 "--lag-in-frames=0",
2312 "--kf-max-dist=9999",
2313 &tile_arg,
2314 // Per-arm overrides go LAST: aomenc keeps the last
2315 // occurrence of a repeated --enable-* flag.
2316 &tx_arg,
2317 "--enable-rect-partitions=1",
2318 "--enable-ab-partitions=1",
2319 "--enable-1to4-partitions=1",
2320 "--min-partition-size=4",
2321 "--max-partition-size=16",
2322 "--obu",
2323 "-o",
2324 "-",
2325 "-",
2326 ];
2327 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2328 assert!(
2329 out.status.success(),
2330 "aomenc refused the fixture: {}",
2331 String::from_utf8_lossy(&out.stderr)
2332 );
2333 let stream = out.stdout;
2334 let before = decode::inter16_rect4_counters();
2335 let leaf4_before = crate::stream::vartx_rect_leaf4_hits();
2336 let frames = match decode_stream(&stream) {
2337 Err(e) => {
2338 let msg = e.to_string();
2339 assert!(
2340 msg.contains("unsupported"),
2341 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
2342 attempt {attempt}): {msg}"
2343 );
2344 // lane-inter16ab r5: attempt 1 is the ONLY recipe in
2345 // r4's 100+ stream frame-aware sweep with an
2346 // inter-frame PARTITION_VERT_4. In r4 it refused on
2347 // the rect wedge codebook (lifted this round); it now
2348 // walks further and stops on rect RESIDUAL coding, a
2349 // refusal this lane does not own -- tracked so the
2350 // VERT_4 / split-tx arms can name their blocker
2351 // instead of silently reading 0.
2352 if msg.contains("needs rectangular residual coding") {
2353 rect_residual_refusals += 1;
2354 }
2355 named_refusals += 1;
2356 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
2357 continue;
2358 }
2359 Ok(frames) => frames,
2360 };
2361 let after = decode::inter16_rect4_counters();
2362 let leaf4_after = crate::stream::vartx_rect_leaf4_hits();
2363 // [16x4 strips, 4x16 strips, chroma pairs closed, chroma
2364 // pairs built from two strips' motion vectors].
2365 let fired = [
2366 after.0 - before.0,
2367 after.1 - before.1,
2368 after.2 - before.2,
2369 after.3 - before.3,
2370 // lane-inter16ab r4: the SPLIT-transform arm --
2371 // `sub_tx_size_map[TX_16X4] == TX_8X4`, so a 1:4 strip
2372 // that splits its transform codes 8x4/4x8 RECTANGULAR
2373 // var-tx leaves (`--enable-tx-size-search=1`).
2374 (leaf4_after[0] - leaf4_before[0]) + (leaf4_after[1] - leaf4_before[1]),
2375 ];
2376 let ffmpeg_frames = if bit_depth == 10 {
2377 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
2378 } else {
2379 ffmpeg_decode_sequence(&stream, width, height, frame_count)
2380 };
2381 assert_eq!(frames.len(), frame_count);
2382 let mismatched = frames
2383 .iter()
2384 .zip(&ffmpeg_frames)
2385 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2386 if fired[0] + fired[1] == 0 {
2387 out_of_scope += 1;
2388 if mismatched {
2389 oos_mismatch += 1;
2390 eprintln!(
2391 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
2392 16-level inter AB partition -- another shape's defect"
2393 );
2394 }
2395 continue;
2396 }
2397 if mismatched {
2398 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2399 let bad: Vec<usize> = (0..got.y.len())
2400 .filter(|&k| got.y[k] != want.y[k])
2401 .collect();
2402 if !bad.is_empty() {
2403 eprintln!(
2404 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
2405 pixels differ, first at ({}, {}), max |delta| {}",
2406 bad.len(),
2407 bad[0] % width,
2408 bad[0] / width,
2409 bad.iter()
2410 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
2411 .max()
2412 .unwrap_or(0)
2413 );
2414 }
2415 }
2416 }
2417 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2418 assert_eq!(
2419 got.y, want.y,
2420 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
2421 );
2422 assert_eq!(
2423 got.u, want.u,
2424 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
2425 );
2426 assert_eq!(
2427 got.v, want.v,
2428 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
2429 );
2430 }
2431 for a in 0..5 {
2432 if fired[a] > 0 {
2433 arms_proved[a] += 1;
2434 arms_total[a] += 1;
2435 }
2436 }
2437 matched += 1;
2438 }
2439 eprintln!(
2440 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
2441 attempts carrying a 16-level inter 1:4 partition, per-arm attempts \
2442 HORZ_4/VERT_4/chroma-pair/sub8x8-chroma/split-tx-8x4={arms_proved:?}, {out_of_scope} attempts carried \
2443 none ({oos_mismatch} of them mismatched)"
2444 );
2445 assert_eq!(
2446 oos_mismatch, 0,
2447 "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter 1:4 partition decoded \
2448 but mismatched ffmpeg -- a defect of another shape, not a pass"
2449 );
2450 }
2451 // lane-t900 r36 (class [[gate-blind-to-feature]]): this counter was
2452 // incremented and never read. What it was there to prove is that the
2453 // VERT_4 / split-tx arms' blocker is still the rect-residual refusal.
2454 // It no longer is: `decode.rs`'s "a non-skip rectangular
2455 // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding" still
2456 // exists but is narrowed (lane-rectres + lane-inter4 +
2457 // lane-intrarect), and this sweep now reaches it ZERO times at either
2458 // depth -- attempt 1, the one recipe r5 recorded stopping there,
2459 // decodes. So the counter is reported and pinned at 0: a non-zero
2460 // reading means the refusal came back for this shape.
2461 eprintln!("{NAME}: rect-residual refusals over both depths: {rect_residual_refusals}");
2462 assert_eq!(
2463 rect_residual_refusals, 0,
2464 "{NAME}: {rect_residual_refusals} attempt(s) stopped on \"a non-skip rectangular \
2465 (HORZ/VERT/HORZ_B) strip needs rectangular residual coding\" -- that refusal was \
2466 lifted for this shape and must not block the VERT_4 / split-tx arms again"
2467 );
2468 // Arms 1/3/4 (HORZ_4, the odd-strip `is_chroma_reference` pair, the
2469 // `build_inter_predictors_sub8x8` two-mv chroma build) are proven
2470 // outright.
2471 for (a, what) in [
2472 (0usize, "HORZ_4 16x4 strips"),
2473 (2, "odd-strip chroma pairs"),
2474 (3, "sub8x8 two-mv chroma pairs"),
2475 ] {
2476 assert!(
2477 arms_total[a] > 0,
2478 "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \
2479 (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})"
2480 );
2481 }
2482 // lane-inter16ab r5, MEASURED reason for the other two arms: the only
2483 // recipe in r4's 100+ stream frame-aware sweep carrying an
2484 // inter-frame `PARTITION_VERT_4` is attempt 1, and in r4 it refused on
2485 // the rect wedge-interintra codebook. That refusal is LIFTED this
2486 // round -- the stream now walks past it and stops on "a non-skip
2487 // rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual
2488 // coding", a refusal this lane does not own. VERT_4 (and with it the
2489 // split-transform 8x4 leaf it feeds) is blocked on THAT, and the gate
2490 // asserts exactly that -- if rect residual coding lands and the arms
2491 // still read 0, or the blocker changes, this fails.
2492 assert!(
2493 arms_total[1] > 0,
2494 "{NAME}: the VERT_4 arm read 0 \
2495 (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})"
2496 );
2497 // lane-gaterecipe r1 -- the split-transform arm (index 4) is NOT
2498 // asserted, and this is the measured reason, not a weakening. Its old
2499 // escape hatch was "some attempt refused on rectangular residual
2500 // coding"; lane-rectres lifted that refusal, so the hatch closed and
2501 // the arm read 0. A ~40-recipe sweep (192x128 and 384x256, cq 8..50,
2502 // min-partition-size 4/8/16, both source orientations; script and
2503 // table in lanes/gaterecipe-r1.report.md) shows NO 192x128 recipe of
2504 // this shape ever makes aomenc split a 16x4/4x16 strip's transform --
2505 // an aomdec EC_TRACE_COEFF histogram of those streams carries whole
2506 // TX_16X4/TX_4X16 units and no sub-transform. The one recipe that DOES
2507 // split it (384x256 product texture, cq 10, --min-partition-size=8)
2508 // was RE-MEASURED by lane-vartxsplit r2 on the merged tree: that
2509 // stream now decodes PIXEL-EXACT on all six frames and fires ZERO
2510 // rectangular var-tx leaves of any size -- the "6 split-tx 8x4 leaves"
2511 // were counted out of an already-desynced decode (the desync is what
2512 // lane-sub8x4 fixed). r2 also swept THIS gate's own source family at
2513 // cq 46/56/63 (12 streams, both orientations, both motion steps,
2514 // --min-partition-size=4 --enable-tx-size-search=1): zero
2515 // TX_16X4/TX_4X16 split symbols in aomdec's EC_VARTX histogram, all 12
2516 // pixel-exact. What does split a 16x4/4x16 transform is the product
2517 // texture at --min-partition-size=4 (140 + 238 splits at cq 44), and
2518 // every such stream either stops at a refusal our own desync raises or
2519 // mismatches ffmpeg from decode-order frame 1 -- an open defect handed
2520 // off in lanes/vartxsplit-r2.report.md. So the arm stays
2521 // reported-unproven instead of asserted on a stream nobody has decoded
2522 // exactly.
2523 eprintln!(
2524 "{NAME}: split-tx-8x4 arm unproven (arms {arms_total:?}) -- no recipe of this \
2525 sweep produces a split 16x4/4x16 transform; see lanes/gaterecipe-r1.report.md"
2526 );
2527 }
2528
2529 #[test]
2530 // Un-ignored 2026-09-04: the intra 16x4/4x16-in-inter refusal this recipe stopped at is gone and every arm now decodes pixel-exact.
2531 // lane-intra16x4 r1: an INTRA-coded 16x4 / 4x16 strip inside an INTER
2532 // frame's 16x16-level 1:4 partition -- the wall all six of his film cuts
2533 // stopped at once lane-rectres landed. The shape's chroma is the pair's:
2534 // `is_chroma_reference` (av1_common_int.h:1454) is false on the even
2535 // strips (which read no `uv_mode` and code no chroma at all) and the odd
2536 // one codes ONE 8x4 (4x8) chroma unit at the pair's origin -- and when the
2537 // pair mixes an intra and an inter strip, the chroma is predicted per the
2538 // strip that CARRIES it, which is exactly what routing the intra strip
2539 // through the key frame's own proven per-strip body
2540 // (`decode_rect4_16_strip`) gives.
2541 //
2542 // Recipes found by a 24 + 24 run sweep (three sources x cq 16..63 x two
2543 // sizes, `~/.cache/intra16x4-tmp/sweep*.sh`): aomenc only picks an INTRA
2544 // 1:4 strip on an inter frame at HIGH cq over content its MC cannot
2545 // predict -- a per-frame-random bright bar sweeping the frame (HORZ_4
2546 // strips) and a `X*Y` product sinusoid under temporal noise (VERT_4).
2547 // Both sources hash identically twice (report).
2548 fn a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact()
2549 {
2550 const NAME: &str = "a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact";
2551 let _gate_lock = lock_gate_counters();
2552 if !have_ffmpeg() {
2553 eprintln!("SKIP {NAME}: no ffmpeg");
2554 return;
2555 }
2556 if !have_aomenc() {
2557 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2558 return;
2559 }
2560 let frame_count = 6usize;
2561 // (source kind, cq, width, height) -- the four recipes of the 48-run
2562 // sweep (`~/.cache/intra16x4-tmp/sweep*.sh`, table in the report) that
2563 // reach an INTRA 1:4 strip on an inter frame. `bar` is a per-frame
2564 // random bright bar sweeping the frame (its MC failure is what makes
2565 // aomenc's RD pick intra at 16x4), `prod` an `X*Y` product sinusoid
2566 // under temporal noise; `_v` transposes the structure so the RD picks
2567 // PARTITION_VERT_4.
2568 // lane-intra16x4 r2: the last field is `--min-partition-size` -- the
2569 // `bar_h` recipe (a horizontal bar sweeping DOWN the frame) at
2570 // `--min-partition-size=8` is the one recipe of the r2 96-run sweep
2571 // (`~/.cache/intra16x4-tmp/sweep_r2.sh`) that fires intra 16x4 strips
2572 // WITHOUT also carrying the sub-8x8 intra block another lane refuses,
2573 // so it is the arm that can be pixel-compared at all.
2574 const RECIPES: [(&str, u32, usize, usize, u32); 5] = [
2575 ("noise", 60, 128, 128, 4),
2576 ("bar", 60, 192, 128, 4),
2577 ("prod_v", 56, 128, 128, 4),
2578 ("prod", 56, 160, 128, 4),
2579 ("bar_h", 63, 192, 128, 8),
2580 ];
2581 // [16x4 intra strips, 4x16 intra strips, of which chroma-reference]:
2582 // how many pixel-exact attempts fired each, over both bit depths.
2583 let mut arms_total = [0u32; 3];
2584 // Attempts that refused on the sub-8x8 intra block inside an inter
2585 // frame -- a DIFFERENT lane's shape, and the measured blocker of every
2586 // VERT_4-carrying recipe in the sweep.
2587 let mut sub8_intra_refusals = 0u32;
2588 // Every failure the sweep sees, asserted ONCE at the end.
2589 let mut failures: Vec<String> = Vec::new();
2590 // Per bit depth: attempts that decoded at all, and attempts that fired an
2591 // intra 1:4 strip AND compared pixel-exact.
2592 let mut decoded_per_depth = [0u32; 2];
2593 let mut fired_exact_per_depth = [0u32; 2];
2594 for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() {
2595 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
2596 (0u32, 0u32, 0u32, 0u32);
2597 let mut arms_proved = [0u32; 3];
2598 for attempt in 0..RECIPES.len() as u32 {
2599 let (kind, cq, width, height, min_part) = RECIPES[attempt as usize];
2600 let duration = frame_count as f64 / 25.0;
2601 // Both sources are deterministic (two identical y4m hashes,
2602 // report): `random()` here is geq's own indexed PRNG and the
2603 // noise filter carries an explicit `all_seed`.
2604 let (lum, noise) = match kind {
2605 "noise" => (
2606 "128+58*sin((X+N*3)/6)+40*sin(Y/11)".to_string(),
2607 ",noise=alls=40:allf=t+u:all_seed=7",
2608 ),
2609 "bar" => (
2610 format!(
2611 "if(lt(mod(X+N*37,{width}),24),random(N*100+X+Y)*255,128+50*sin(Y/7))"
2612 ),
2613 "",
2614 ),
2615 "bar_h" => (
2616 format!(
2617 "if(lt(mod(Y+N*37,{height}),24),random(N*100+X+Y)*255,128+50*sin(X/7))"
2618 ),
2619 "",
2620 ),
2621 "prod_v" => (
2622 "128+60*sin((X*Y+N*97)/13)+50*sin((Y+N*11)/5)".to_string(),
2623 ",noise=alls=25:allf=t:all_seed=11",
2624 ),
2625 _ => (
2626 "128+60*sin((X*Y+N*97)/13)+50*sin((X+N*11)/5)".to_string(),
2627 ",noise=alls=25:allf=t:all_seed=11",
2628 ),
2629 };
2630 let source = format!(
2631 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
2632 geq=lum='{lum}',format=yuv420p{noise}"
2633 );
2634 let pix_fmt = if bit_depth == 10 {
2635 "yuv420p10le"
2636 } else {
2637 "yuv420p"
2638 };
2639 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2640 .args([
2641 "-v",
2642 "error",
2643 "-f",
2644 "lavfi",
2645 "-i",
2646 &source,
2647 "-t",
2648 &duration.to_string(),
2649 "-pix_fmt",
2650 pix_fmt,
2651 "-strict",
2652 "-1",
2653 "-f",
2654 "yuv4mpegpipe",
2655 "-",
2656 ])
2657 .stdin(Stdio::null())
2658 .stdout(Stdio::piped())
2659 .stderr(Stdio::piped()), None, |c| c.output())
2660 .expect("ffmpeg failed to run");
2661 assert!(
2662 y4m.status.success(),
2663 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
2664 String::from_utf8_lossy(&y4m.stderr)
2665 );
2666 let cq_arg = format!("--cq-level={cq}");
2667 let min_part_arg = format!("--min-partition-size={min_part}");
2668 let depth_arg = format!("--bit-depth={bit_depth}");
2669 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
2670 let args: Vec<&str> = vec![
2671 "--codec=av1",
2672 "--passes=1",
2673 "--end-usage=q",
2674 &cq_arg,
2675 "--cpu-used=0",
2676 "--threads=1",
2677 "--row-mt=0",
2678 "--sb-size=64",
2679 &depth_arg,
2680 &input_depth_arg,
2681 "--enable-restoration=0",
2682 "--enable-palette=0",
2683 "--deltaq-mode=0",
2684 "--enable-filter-intra=0",
2685 "--enable-cfl-intra=0",
2686 "--enable-intrabc=0",
2687 "--lag-in-frames=0",
2688 "--kf-max-dist=9999",
2689 "--tile-columns=0",
2690 // Per-arm overrides go LAST (aomenc keeps the last
2691 // occurrence of a repeated --enable-* flag).
2692 "--enable-tx-size-search=1",
2693 "--enable-rect-partitions=1",
2694 "--enable-ab-partitions=1",
2695 "--enable-1to4-partitions=1",
2696 "--enable-intra-edge-filter=1",
2697 &min_part_arg,
2698 "--max-partition-size=16",
2699 "--obu",
2700 "-o",
2701 "-",
2702 "-",
2703 ];
2704 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2705 assert!(
2706 out.status.success(),
2707 "aomenc refused the fixture: {}",
2708 String::from_utf8_lossy(&out.stderr)
2709 );
2710 let stream = out.stdout;
2711 let before = crate::stream::intra16x4_in_inter_hits();
2712 let frames = match decode_stream(&stream) {
2713 Err(e) => {
2714 let msg = e.to_string();
2715 // lane-intra16x4 r3: the ONLY refusals the 120-run sweep
2716 // (`~/.cache/intra16x4-tmp/sweep_r3.sh`, table in the
2717 // report) reaches over these recipes -- each another
2718 // lane's shape. A refusal outside this list is a new wall
2719 // and fails the gate rather than being counted.
2720 const MEASURED_REFUSALS: [&str; 3] = [
2721 "an intra 8x4/4x8 block inside an inter frame's sub-8x8 HORZ/VERT partition",
2722 "an intra 4x4 block inside an inter frame's sub-8x8 split",
2723 "an OBMC neighbour whose switchable interp filter was never recorded",
2724 ];
2725 if !MEASURED_REFUSALS.iter().any(|r| msg.contains(r)) {
2726 failures.push(format!(
2727 "{bit_depth}-bit attempt {attempt}: refusal outside the measured \
2728 list: {msg}"
2729 ));
2730 continue;
2731 }
2732 if msg.contains("sub-8x8") {
2733 sub8_intra_refusals += 1;
2734 }
2735 named_refusals += 1;
2736 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
2737 continue;
2738 }
2739 Ok(frames) => frames,
2740 };
2741 decoded_per_depth[depth_idx] += 1;
2742 let after = crate::stream::intra16x4_in_inter_hits();
2743 let fired = [
2744 (after.0 - before.0) as u32,
2745 (after.1 - before.1) as u32,
2746 (after.2 - before.2) as u32,
2747 ];
2748 let ffmpeg_frames = if bit_depth == 10 {
2749 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
2750 } else {
2751 ffmpeg_decode_sequence(&stream, width, height, frame_count)
2752 };
2753 assert_eq!(frames.len(), frame_count);
2754 let mismatched = frames
2755 .iter()
2756 .zip(&ffmpeg_frames)
2757 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2758 if fired[0] + fired[1] == 0 {
2759 out_of_scope += 1;
2760 if mismatched {
2761 oos_mismatch += 1;
2762 eprintln!(
2763 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
2764 intra 1:4 strip -- another shape's defect"
2765 );
2766 }
2767 continue;
2768 }
2769 if mismatched {
2770 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2771 let bad: Vec<usize> = (0..got.y.len())
2772 .filter(|&k| got.y[k] != want.y[k])
2773 .collect();
2774 if !bad.is_empty() {
2775 eprintln!(
2776 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
2777 pixels differ, first at ({}, {}), max |delta| {}",
2778 bad.len(),
2779 bad[0] % width,
2780 bad[0] / width,
2781 bad.iter()
2782 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
2783 .max()
2784 .unwrap_or(0)
2785 );
2786 }
2787 }
2788 }
2789 // lane-intra16x4 r3: continue-and-sweep -- a mismatching attempt is
2790 // RECORDED and the sweep goes on, so one arm's defect can no longer
2791 // hide every later arm (r2's attempt 0 panicked before arm 4 ran).
2792 // The end-of-sweep assert below fails on any recorded mismatch.
2793 if mismatched {
2794 failures.push(format!(
2795 "{bit_depth}-bit attempt {attempt} (arms {fired:?}) mismatched ffmpeg"
2796 ));
2797 continue;
2798 }
2799 for a in 0..3 {
2800 if fired[a] > 0 {
2801 arms_proved[a] += 1;
2802 arms_total[a] += 1;
2803 }
2804 }
2805 matched += 1;
2806 fired_exact_per_depth[depth_idx] += 1;
2807 }
2808 eprintln!(
2809 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
2810 attempts carrying an intra 1:4 strip, per-arm attempts \
2811 16x4/4x16/chroma-reference={arms_proved:?}, {out_of_scope} attempts carried none \
2812 ({oos_mismatch} of them mismatched)"
2813 );
2814 if oos_mismatch > 0 {
2815 failures.push(format!(
2816 "{bit_depth}-bit: {oos_mismatch} attempt(s) with no intra 1:4 strip decoded \
2817 but mismatched ffmpeg -- another shape's defect, not a pass"
2818 ));
2819 }
2820 }
2821 assert!(
2822 failures.is_empty(),
2823 "{NAME}: {} sweep failure(s): {failures:#?}",
2824 failures.len()
2825 );
2826 // The counter must have fired on a pixel-exact attempt at every bit depth
2827 // the sweep actually decoded at.
2828 for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() {
2829 assert!(
2830 decoded_per_depth[depth_idx] == 0 || fired_exact_per_depth[depth_idx] > 0,
2831 "{NAME}: {bit_depth}-bit decoded {} attempt(s) but none of them fired an intra \
2832 1:4 strip on a pixel-exact compare",
2833 decoded_per_depth[depth_idx]
2834 );
2835 }
2836 // MEASURED (48-run sweep, report table): every recipe that makes
2837 // aomenc pick an intra PARTITION_VERT_4 strip ALSO contains an intra
2838 // 8x4/4x8 or 4x4 block inside a sub-8x8 partition, a refusal this lane
2839 // does not own -- so the 4x16 orientation is blocked on THAT and the
2840 // gate asserts exactly that. If the sub-8x8 lane lands and this arm
2841 // still reads 0, or the blocker changes, this fails.
2842 assert!(
2843 arms_total[1] > 0 || sub8_intra_refusals > 0,
2844 "{NAME}: the 4x16 (PARTITION_VERT_4) arm read 0 \
2845 (16x4/4x16/chroma-reference={arms_total:?}) and NO attempt refused on the sub-8x8 \
2846 intra block -- its documented blocker is gone, so a zero arm is now unexplained"
2847 );
2848 for (a, what) in [
2849 (0usize, "intra 16x4 strips (PARTITION_HORZ_4)"),
2850 (
2851 2,
2852 "chroma-reference (odd) intra strips carrying the pair's 8x4/4x8 chroma",
2853 ),
2854 ] {
2855 assert!(
2856 arms_total[a] > 0,
2857 "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \
2858 (16x4/4x16/chroma-reference={arms_total:?}) -- unproven"
2859 );
2860 }
2861 }
2862
2863 #[test]
2864 // lane-sbab r1: the SUPERBLOCK-level (64x64) AB partitions on an INTER
2865 // frame -- PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 64x64, i.e. two
2866 // 32x32 inter squares plus one true 64x32/32x64 inter strip, decoded in
2867 // libaom `decode_partition`'s visit order. Every decode-order frame is
2868 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
2869 // out-of-scope mismatches fail the gate, and EACH of the four arms must
2870 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
2871 // proof of four). `--min-partition-size=32` keeps every AB piece at or
2872 // above 32x32, `--max-partition-size=64` puts the AB symbol at the SB
2873 // root, and `--enable-1to4-partitions=0` because the 64-level 1:4 pair is
2874 // a different lane's shape.
2875 fn a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact() {
2876 const NAME: &str =
2877 "a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact";
2878 let _gate_lock = lock_gate_counters();
2879 if !have_ffmpeg() {
2880 eprintln!("SKIP {NAME}: no ffmpeg");
2881 return;
2882 }
2883 if !have_aomenc() {
2884 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2885 return;
2886 }
2887 let (width, height, frame_count) = (256usize, 192usize, 6usize);
2888 // Per arm, over both bit depths: how many pixel-exact attempts fired
2889 // it at least once.
2890 let mut arms_total = [0u32; 4];
2891 for bit_depth in [8u32, 10u32] {
2892 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
2893 (0u32, 0u32, 0u32, 0u32);
2894 let mut arms_proved = [0u32; 4];
2895 for attempt in 0..20u32 {
2896 // Axes measured live by the r1 sweep
2897 // (~/.cache/sbab-tmp/sweep.sh, table in the report): two
2898 // motion steps x two source orientations x five quantisers x
2899 // a single-tile and a two-tile-column arm. All four arms
2900 // appear in that table at both depths; no single (sp, shape,
2901 // cq) point carries more than three of them, which is why the
2902 // sweep is this wide.
2903 let cq = [18, 26, 34, 45, 55][(attempt % 5) as usize];
2904 let natural = attempt / 5 % 2 == 1;
2905 let sp = if attempt / 10 % 2 == 0 { 3 } else { 8 };
2906 // r1: a `--tile-columns=1` twin of these 20 attempts was run
2907 // and is deliberately NOT in the gate -- its streams PANIC in
2908 // `mc::from_switchable_symbol` (a 4th symbol out of a
2909 // 3-symbol alphabet), the exact signature lane-inter16ab r1
2910 // recorded for its own tiled arm and which the ledger pins to
2911 // the below-8x8 inter leaf, not to anything this lane
2912 // touches. Recorded as open residue in
2913 // lanes/sbab-r1.report.md rather than turned into a SKIP or a
2914 // weakened assert.
2915 let tile_cols = "0";
2916 let duration = frame_count as f64 / 25.0;
2917 // Long-period continuous tone: the 64-level AB partitions
2918 // need the L/T-shaped feature to span 32 px, so the sinusoid
2919 // periods here are ~3x the 16-level gate's.
2920 let lum = if natural {
2921 format!("128+58*sin((Y+N*{sp})/17)+40*sin(X/29)+20*sin((X+Y)/13)")
2922 } else {
2923 format!("128+58*sin((X+N*{sp})/17)+40*sin(Y/29)+20*sin((X-Y)/13)")
2924 };
2925 let source = format!(
2926 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
2927 geq=lum='{lum}',format=yuv420p"
2928 );
2929 let pix_fmt = if bit_depth == 10 {
2930 "yuv420p10le"
2931 } else {
2932 "yuv420p"
2933 };
2934 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2935 .args([
2936 "-v",
2937 "error",
2938 "-f",
2939 "lavfi",
2940 "-i",
2941 &source,
2942 "-t",
2943 &duration.to_string(),
2944 "-pix_fmt",
2945 pix_fmt,
2946 "-strict",
2947 "-1",
2948 "-f",
2949 "yuv4mpegpipe",
2950 "-",
2951 ])
2952 .stdin(Stdio::null())
2953 .stdout(Stdio::piped())
2954 .stderr(Stdio::piped()), None, |c| c.output())
2955 .expect("ffmpeg failed to run");
2956 assert!(
2957 y4m.status.success(),
2958 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
2959 String::from_utf8_lossy(&y4m.stderr)
2960 );
2961 let cq_arg = format!("--cq-level={cq}");
2962 let depth_arg = format!("--bit-depth={bit_depth}");
2963 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
2964 let tile_arg = format!("--tile-columns={tile_cols}");
2965 let args: Vec<&str> = vec![
2966 "--codec=av1",
2967 "--passes=1",
2968 "--end-usage=q",
2969 &cq_arg,
2970 "--cpu-used=0",
2971 "--threads=1",
2972 "--row-mt=0",
2973 "--sb-size=64",
2974 &depth_arg,
2975 &input_depth_arg,
2976 "--enable-restoration=0",
2977 "--enable-palette=0",
2978 "--deltaq-mode=0",
2979 "--enable-filter-intra=0",
2980 "--enable-cfl-intra=0",
2981 "--enable-intrabc=0",
2982 "--lag-in-frames=0",
2983 "--kf-max-dist=9999",
2984 &tile_arg,
2985 // Per-arm overrides go LAST: aomenc keeps the last
2986 // occurrence of a repeated --enable-* flag.
2987 "--enable-rect-partitions=1",
2988 "--enable-ab-partitions=1",
2989 "--enable-1to4-partitions=0",
2990 "--min-partition-size=32",
2991 "--max-partition-size=64",
2992 "--obu",
2993 "-o",
2994 "-",
2995 "-",
2996 ];
2997 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2998 assert!(
2999 out.status.success(),
3000 "aomenc refused the fixture: {}",
3001 String::from_utf8_lossy(&out.stderr)
3002 );
3003 let stream = out.stdout;
3004 let before = decode::sb_ab_inter_hits_by_arm();
3005 let frames = match decode_stream(&stream) {
3006 Err(e) => {
3007 let msg = e.to_string();
3008 assert!(
3009 msg.contains("unsupported"),
3010 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
3011 attempt {attempt}): {msg}"
3012 );
3013 named_refusals += 1;
3014 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
3015 continue;
3016 }
3017 Ok(frames) => frames,
3018 };
3019 let after = decode::sb_ab_inter_hits_by_arm();
3020 let fired: Vec<usize> = (0..4).map(|a| after[a] - before[a]).collect();
3021 let ffmpeg_frames = if bit_depth == 10 {
3022 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
3023 } else {
3024 ffmpeg_decode_sequence(&stream, width, height, frame_count)
3025 };
3026 assert_eq!(frames.len(), frame_count);
3027 let mismatched = frames
3028 .iter()
3029 .zip(&ffmpeg_frames)
3030 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
3031 if fired.iter().sum::<usize>() == 0 {
3032 out_of_scope += 1;
3033 if mismatched {
3034 oos_mismatch += 1;
3035 eprintln!(
3036 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
3037 64-level inter AB partition -- another shape's defect"
3038 );
3039 }
3040 continue;
3041 }
3042 if mismatched {
3043 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3044 let bad: Vec<usize> = (0..got.y.len())
3045 .filter(|&k| got.y[k] != want.y[k])
3046 .collect();
3047 if !bad.is_empty() {
3048 eprintln!(
3049 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
3050 pixels differ, first at ({}, {}), max |delta| {}",
3051 bad.len(),
3052 bad[0] % width,
3053 bad[0] / width,
3054 bad.iter()
3055 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
3056 .max()
3057 .unwrap_or(0)
3058 );
3059 }
3060 }
3061 }
3062 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3063 assert_eq!(
3064 got.y, want.y,
3065 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
3066 );
3067 assert_eq!(
3068 got.u, want.u,
3069 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
3070 );
3071 assert_eq!(
3072 got.v, want.v,
3073 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
3074 );
3075 }
3076 for a in 0..4 {
3077 if fired[a] > 0 {
3078 arms_proved[a] += 1;
3079 arms_total[a] += 1;
3080 }
3081 }
3082 matched += 1;
3083 }
3084 eprintln!(
3085 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
3086 attempts carrying a 64-level inter AB partition, per-arm attempts \
3087 HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \
3088 none ({oos_mismatch} of them mismatched)"
3089 );
3090 assert_eq!(
3091 oos_mismatch, 0,
3092 "{NAME}: {oos_mismatch} attempt(s) with no 64-level inter AB partition decoded \
3093 but mismatched ffmpeg -- a defect of another shape, not a pass"
3094 );
3095 }
3096 assert!(
3097 arms_total.iter().all(|&n| n > 0),
3098 "{NAME}: not every 64-level inter AB arm fired on a pixel-exact attempt \
3099 (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven"
3100 );
3101 }
3102
3103 /// The inter-frame twin of
3104 /// [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`]:
3105 /// deblocking left *on* at a crf high enough that libaom picks a nonzero
3106 /// level, CDEF off, so a pixel mismatch can only come from the loop
3107 /// filter -- and over a real 4-frame INTER sequence, not one key frame.
3108 ///
3109 /// lane-av1skipfix: the attempt-loop shape. The sweep walks cq and seed,
3110 /// REQUIRES at least one attempt to decode, and hard-asserts
3111 /// `decode::deblock_hits` on a pixel-compared attempt; a decode error on
3112 /// every attempt is a hard failure carrying the refusal texts, never a
3113 /// printed SKIP (class `gate-skips-on-its-own-failure`). MEASURED
3114 /// 2026-09-29 on `a21f3680`: cq 55/45/35/63 all decode 4 frames
3115 /// pixel-exact with 208/224/160/208 deblock edges.
3116 #[test]
3117 fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() {
3118 const NAME: &str = "a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact";
3119 let _gate_lock = lock_gate_counters();
3120 if !have_ffmpeg() {
3121 eprintln!("SKIP {NAME}: no ffmpeg");
3122 return;
3123 }
3124 if !have_aomenc() {
3125 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3126 return;
3127 }
3128 let (width, height, frame_count) = (64usize, 64usize, 4usize);
3129 // Two seeds x four quantisers.
3130 const CQS: [u32; 4] = [55, 45, 35, 63];
3131 let mut refusals = Vec::new();
3132 let mut counted_exact = 0u32;
3133 let mut uncounted_exact = 0u32;
3134 'attempts: for round in 0..2u32 {
3135 for cq in CQS {
3136 let source = gradients_source(42 + round, width, height, "duration=0.16:rate=25");
3137 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3138 .args(["-v", "error", "-f", "lavfi", "-i"])
3139 .arg(&source)
3140 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
3141 .stdin(Stdio::null())
3142 .stdout(Stdio::piped())
3143 .stderr(Stdio::piped()), None, |c| c.output())
3144 .expect("ffmpeg failed to run");
3145 assert!(
3146 y4m.status.success(),
3147 "{NAME}: ffmpeg fixture (seed {} cq {cq}): {}",
3148 42 + round,
3149 String::from_utf8_lossy(&y4m.stderr)
3150 );
3151 let cq_arg = format!("--cq-level={cq}");
3152 let out = run_with_stdin(
3153 Command::new(aomenc_path()).args([
3154 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
3155 // occurrence, so overrides go before the base list).
3156 "--loopfilter-control=1",
3157 "--codec=av1",
3158 "--passes=1",
3159 "--end-usage=q",
3160 &cq_arg,
3161 "--cpu-used=0",
3162 "--lag-in-frames=0",
3163 "--auto-alt-ref=0",
3164 "--kf-max-dist=1000",
3165 // Forces `primary_ref_frame = PRIMARY_REF_NONE` on every
3166 // frame (spec 5.9.2): without it a real encoder's inter
3167 // frame loads its initial CDF state from the previous
3168 // frame's *adapted* tables (spec 7.20's `load_cdfs`), which
3169 // this decoder never does -- it always starts each frame's
3170 // `Cdfs` from the spec defaults (`decode.rs`'s
3171 // `Cdfs::new(q_ctx)`, called fresh per frame in
3172 // `decode_stream`). Without this flag the inter frame's
3173 // very first symbol desyncs immediately (traced 2026-08-27:
3174 // no coefficient trace at all before the tile's first
3175 // partition read comes back an out-of-alphabet value). A
3176 // real decoder needs cross-frame CDF forwarding to handle
3177 // that stream; this fixture sidesteps it the same way a
3178 // real broadcast/low-latency encode legitimately can.
3179 "--error-resilient=1",
3180 "--enable-rect-partitions=0",
3181 "--enable-ab-partitions=0",
3182 "--enable-1to4-partitions=0",
3183 "--enable-filter-intra=0",
3184 "--enable-smooth-intra=0",
3185 "--enable-paeth-intra=0",
3186 "--enable-directional-intra=0",
3187 "--enable-angle-delta=0",
3188 "--enable-tx-size-search=0",
3189 "--enable-cdef=0",
3190 // Loop restoration is a named refusal (aomenc's RD picks
3191 // Sgrproj on this kind of content) -- off in every recipe
3192 // whose test targets a different surface.
3193 "--enable-restoration=0",
3194 "--max-partition-size=32",
3195 "--enable-palette=0",
3196 "--enable-intrabc=0",
3197 "--enable-cfl-intra=0",
3198 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
3199 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
3200 "--enable-ref-frame-mvs=0",
3201 "--obu",
3202 "-o",
3203 "-",
3204 "-",
3205 ]),
3206 &y4m.stdout,
3207 );
3208 assert!(
3209 out.status.success(),
3210 "{NAME}: aomenc refused the seed {} cq {cq} fixture: {}",
3211 42 + round,
3212 String::from_utf8_lossy(&out.stderr)
3213 );
3214 let stream = out.stdout;
3215 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
3216 std::fs::write(dump, &stream).expect("dump stream");
3217 }
3218 let before = decode::deblock_hits();
3219 let frames = match decode_stream(&stream) {
3220 Ok(frames) => frames,
3221 Err(e) => {
3222 refusals.push(format!("seed {} cq {cq}: {e}", 42 + round));
3223 continue;
3224 }
3225 };
3226 // A decode that succeeded is ALWAYS pixel-compared; the hit
3227 // counter only decides whether the attempt counts as firing
3228 // (class `counter-from-refused-stream`).
3229 let counted = decode::deblock_hits() != before;
3230 if counted {
3231 counted_exact += 1;
3232 } else {
3233 uncounted_exact += 1;
3234 }
3235 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
3236 assert_eq!(frames.len(), frame_count);
3237 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3238 // gradients' colors ignore its seed, so this gate encodes fresh
3239 // content every run -- a mismatch here may never reproduce.
3240 // Self-pin the stream before panicking so the failure is
3241 // bisectable (replay: EC_AV1_PIN on scratch_isolate_pinned_mismatch).
3242 let ok = got.y == want.y && got.u == want.u && got.v == want.v;
3243 if !ok {
3244 let pin = std::env::temp_dir().join(format!(
3245 "ec-av1-deblocking-gate-fail-s{}-cq{cq}.obu",
3246 42 + round
3247 ));
3248 crate::dumpio::pin("TEST_PIN", &pin, &stream);
3249 panic!(
3250 "frame {i} mismatch vs ffmpeg (seed {} cq {cq}, deblock fired: \
3251 {counted}) -- stream pinned at {}",
3252 42 + round,
3253 pin.display()
3254 );
3255 }
3256 }
3257 if counted_exact >= 2 {
3258 break 'attempts;
3259 }
3260 }
3261 }
3262 gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
3263 assert!(
3264 counted_exact > 0,
3265 "{NAME}: none of {} attempts decoded a sequence with a deblocking edge -- \
3266 apply_deblock is unproven (class gate-blind-to-feature):\n{}",
3267 CQS.len() * 2,
3268 refusals.join("\n")
3269 );
3270 }
3271
3272 /// The decisive cross-frame CDF forwarding test: identical to
3273 /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`]
3274 /// except it drops `--error-resilient=1`, so aomenc codes every inter
3275 /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`)
3276 /// and expects the decoder to resume from the previous frame's *adapted*
3277 /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding,
3278 /// frame 1's very first tile symbol desyncs (an out-of-alphabet
3279 /// partition read); with it, every frame decodes pixel-exact.
3280 #[test]
3281 fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() {
3282 if !have_ffmpeg() {
3283 eprintln!(
3284 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg"
3285 );
3286 return;
3287 }
3288 if !have_aomenc() {
3289 eprintln!(
3290 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}",
3291 aomenc_path().display()
3292 );
3293 return;
3294 }
3295 let (width, height, frame_count) = (64usize, 64usize, 4usize);
3296 // The fixture's content varies run to run (lavfi gradients ignores its
3297 // seed option for the c0..c7 colors -- they default to "random"), so:
3298 // most encodes of this recipe trip one of the decoder's NAMED round-2
3299 // refusals (a reference other than LAST_FRAME, a sub-16 partition --
3300 // genuine coverage gaps, separately documented), and only some produce
3301 // a stream fully inside this decoder's declared support. So: attempt
3302 // several seeds, and the first stream that DECODES must be pixel-exact
3303 // -- that assertion is what guards the forwarded-CDF state (a wrong
3304 // table decodes plausible-but-wrong pixels; the counter-reset bug this
3305 // gate caught did exactly that). Exhausting every attempt on named
3306 // refusals skips loudly, listing them.
3307 let mut refusals = Vec::new();
3308 for attempt in 0..8u32 {
3309 let seed = 42 + attempt;
3310 let source = gradients_source(seed, 64, 64, "duration=0.16:rate=25");
3311 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3312 .args([
3313 "-v",
3314 "error",
3315 "-f",
3316 "lavfi",
3317 "-i",
3318 &source,
3319 "-pix_fmt",
3320 "yuv420p",
3321 "-f",
3322 "yuv4mpegpipe",
3323 "-",
3324 ])
3325 .stdin(Stdio::null())
3326 .stdout(Stdio::piped())
3327 .stderr(Stdio::piped()), None, |c| c.output())
3328 .expect("ffmpeg failed to run");
3329 assert!(
3330 y4m.status.success(),
3331 "ffmpeg fixture: {}",
3332 String::from_utf8_lossy(&y4m.stderr)
3333 );
3334 // lane-cdfflake: hard length check on the y4m fixture itself --
3335 // a truncated/racing ffmpeg write would otherwise surface as a
3336 // downstream pixel mismatch indistinguishable from a real decode
3337 // defect. y4m frames are `FRAME\n` (6 bytes) + raw 4:2:0 payload;
3338 // find the header/frame-data boundary at the first `FRAME` marker
3339 // rather than parsing the header fields (duration/rate can move
3340 // the header text length without moving the frame math).
3341 let marker_at = y4m
3342 .stdout
3343 .windows(5)
3344 .position(|w| w == b"FRAME")
3345 .expect("y4m stream missing FRAME marker");
3346 let frame_420_bytes = width * height * 3 / 2;
3347 assert_eq!(
3348 y4m.stdout.len(),
3349 marker_at + frame_count * (6 + frame_420_bytes),
3350 "y4m fixture length mismatch (seed {seed})"
3351 );
3352 let y4m_hash = fnv1a64(&y4m.stdout);
3353 let out = run_with_stdin(
3354 Command::new(aomenc_path()).args([
3355 "--codec=av1",
3356 "--passes=1",
3357 "--end-usage=q",
3358 "--cq-level=55",
3359 "--cpu-used=0",
3360 "--lag-in-frames=0",
3361 "--auto-alt-ref=0",
3362 "--kf-max-dist=1000",
3363 // `--threads=1` (not the default): a multithreaded RD search
3364 // makes aomenc's screen-content-tools heuristic race (seen
3365 // flaky under `cargo test`'s own parallelism -- the same
3366 // fixture, same seed, occasionally sets
3367 // `allow_screen_content_tools`, a round-2 gap unrelated to
3368 // CDF forwarding), so pin it to one thread for a
3369 // deterministic header.
3370 "--threads=1",
3371 "--row-mt=0",
3372 // `--enable-order-hint=0` kills BWDREF/ALTREF entirely (no
3373 // order hints -> no bidirectional distance weighting) and,
3374 // combined with `--auto-alt-ref=0`/`--lag-in-frames=0`
3375 // above, leaves aomenc's RD search only LAST_FRAME/
3376 // LAST2_FRAME/LAST3_FRAME/GOLDEN_FRAME to pick from --
3377 // GOLDEN itself needs no order hint (it is the keyframe's
3378 // fixed slot, not a distance-weighted reference), so this
3379 // does not suppress GOLDEN selection the way the sibling
3380 // CDF-forwarding gate's own comment worried about; it just
3381 // narrows the pool this gate needs GOLDEN to win out of.
3382 "--enable-order-hint=0",
3383 "--enable-warped-motion=0",
3384 "--enable-obmc=0",
3385 "--enable-masked-comp=0",
3386 "--enable-interintra-comp=0",
3387 "--enable-dist-wtd-comp=0",
3388 "--enable-diff-wtd-comp=0",
3389 "--enable-onesided-comp=0",
3390 "--enable-interintra-wedge=0",
3391 "--enable-smooth-interintra=0",
3392 "--enable-rect-partitions=0",
3393 "--enable-ab-partitions=0",
3394 "--enable-1to4-partitions=0",
3395 "--enable-filter-intra=0",
3396 "--enable-smooth-intra=0",
3397 "--enable-paeth-intra=0",
3398 "--enable-directional-intra=0",
3399 "--enable-angle-delta=0",
3400 "--enable-tx-size-search=0",
3401 "--enable-cdef=0",
3402 // Loop restoration is a named refusal (aomenc's RD picks
3403 // Sgrproj on this kind of content) -- off in every recipe
3404 // whose test targets a different surface.
3405 "--enable-restoration=0",
3406 "--max-partition-size=32",
3407 "--enable-palette=0",
3408 "--enable-intrabc=0",
3409 "--enable-cfl-intra=0",
3410 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
3411 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
3412 "--enable-ref-frame-mvs=0",
3413 "--obu",
3414 "-o",
3415 "-",
3416 "-",
3417 ]),
3418 &y4m.stdout,
3419 );
3420 assert!(
3421 out.status.success(),
3422 "aomenc refused the fixture: {}",
3423 String::from_utf8_lossy(&out.stderr)
3424 );
3425 let stream = out.stdout;
3426 let stream_hash = fnv1a64(&stream);
3427 // A named `unsupported` refusal is a documented coverage gap (each
3428 // one carries its own test debt elsewhere), not a forwarding verdict
3429 // -- try the next seed. Any stream that DECODES must be pixel-exact,
3430 // and any non-refusal error is a hard failure.
3431 let frames = match decode_stream(&stream) {
3432 Err(e) => {
3433 let msg = e.to_string();
3434 assert!(
3435 msg.contains("unsupported"),
3436 "cross-frame CDF forwarding failed outright (seed {seed}): {msg}"
3437 );
3438 refusals.push(format!("seed {seed}: {msg}"));
3439 continue;
3440 }
3441 Ok(frames) => frames,
3442 };
3443 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
3444 assert_eq!(frames.len(), frame_count);
3445 // lane-cdfflake: reconstruct ffmpeg's raw reference bytes (the
3446 // three per-frame slices are contiguous chunks of the raw
3447 // `-f rawvideo` output ffmpeg_decode_sequence sliced, so
3448 // concatenating them back is bit-for-bit the same bytes ffmpeg
3449 // actually produced -- no second ffmpeg invocation needed).
3450 let ffmpeg_raw: Vec<u8> = ffmpeg_frames
3451 .iter()
3452 .flat_map(|p| p.y.iter().chain(&p.u).chain(&p.v).map(|&v| v as u8))
3453 .collect();
3454 let ffmpeg_raw_hash = fnv1a64(&ffmpeg_raw);
3455 eprintln!(
3456 "cdfflake attempt seed={seed}: y4m_hash={y4m_hash:016x} \
3457 stream_hash={stream_hash:016x} ffmpeg_raw_hash={ffmpeg_raw_hash:016x}"
3458 );
3459 // lane-av1golden3: pin the exact raw stream on the first mismatch
3460 // so a flaky-looking gate failure becomes a deterministic, static
3461 // fixture to bisect against -- env-gated, no cost on a normal run.
3462 let mismatched = frames
3463 .iter()
3464 .zip(&ffmpeg_frames)
3465 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
3466 if mismatched {
3467 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
3468 std::fs::write(&path, &stream).expect("writing pinned stream");
3469 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
3470 }
3471 // lane-cdfflake: unconditional pin on mismatch -- the aomenc
3472 // stream AND ffmpeg's raw reference bytes, so a flake caught
3473 // under load names the liar (stream bytes differ from a
3474 // clean rerun -> subprocess instability; reference bytes
3475 // differ -> ffmpeg instability; both stable -> real decode
3476 // defect) without relying on the env var being set.
3477 // The pin goes to `fixtures/`, which outlives the session: an
3478 // earlier version wrote to a session scratchpad, so once tmpfs
3479 // reaped it a real mismatch aborted on the write instead of
3480 // reporting itself. A failed write must not mask the asserts
3481 // below either, so it warns rather than panicking -- lane-av1pinloud
3482 // routed it through `pin_reporting` rather than bare `fs::write`,
3483 // so the warning now carries on-disk-vs-owed byte counts: a
3484 // truncated pin was as silent here as anywhere else, and this
3485 // is the one site where dying on the write is wrong.
3486 let sp = pin_dir();
3487 let stream_pin = sp.join(format!("cdfflake-stream-seed{seed}.bin"));
3488 let ref_pin = sp.join(format!("cdfflake-ffmpeg-raw-seed{seed}.bin"));
3489 for (path, bytes) in [(&stream_pin, &stream), (&ref_pin, &ffmpeg_raw)] {
3490 if let Err(line) = crate::dumpio::pin_reporting("TEST_PIN", path, bytes) {
3491 eprintln!("cdfflake: {line}");
3492 }
3493 }
3494 eprintln!(
3495 "cdfflake MISMATCH seed={seed}: pinned stream + ffmpeg reference to {}",
3496 sp.display()
3497 );
3498 }
3499 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3500 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
3501 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
3502 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
3503 }
3504 return;
3505 }
3506 eprintln!(
3507 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: every \
3508 attempt hit a named refusal:\n{}",
3509 refusals.join("\n")
3510 );
3511 }
3512
3513 /// lane-av1golden3: reproduces the pinned mismatch bytes captured by
3514 /// `EC_AV1_GATE_DUMP=$SP/golden3-pin.obu` off
3515 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
3516 /// (seed 47, frame 1 U). Deterministic and static -- no aomenc/ffmpeg
3517 /// re-encode involved, only re-decodes fixed bytes on disk. What changed
3518 /// under lane-av1pinslive is that the gate is LIVE: the bytes are committed
3519 /// at `crates/ec-av1/fixtures/golden3-pin.obu` instead of a scratchpad that
3520 /// tmpfs reaps, so it runs in the ordinary suite on any runner that has
3521 /// ffmpeg (guarded by `have_ffmpeg()`, so `EC_AV1_REQUIRE_FFMPEG=1` turns
3522 /// its absence into a hard failure rather than a silent skip). It costs
3523 /// ~0.15 s, touches no process-global, and reads no counter -- none of the
3524 /// conditions that make this crate ignore its other manual gates.
3525 ///
3526 /// The original capture (2026-08-28, `bec27414`) is NOT reproducible: it
3527 /// predates `5ae053d3` "route all 20 gradients gate fixtures through
3528 /// seed-derived colours", so `gradients_source` still left c4..c7 to
3529 /// ffmpeg's `random` default then. This is a FRESH capture from the same
3530 /// recipe family at seed 42, which IS byte-reproducible now: the command is
3531 /// in `lanes/av1pins.report.md`, and the stream's FNV-1a-64
3532 /// (`89c4089148d51c04`; 159 bytes; sha256
3533 /// `11c9d5331cffa6614c8265ad5fa685d5ce9155db8439949b48ec4a652ace95cf`) is
3534 /// the `stream_hash` the live
3535 /// `a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`
3536 /// prints for that seed -- which is what proves the recipe is that gate's.
3537 #[test]
3538 fn pinned_golden3_stream_decodes_pixel_exact() {
3539 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
3540 .map(std::path::PathBuf::from)
3541 .unwrap_or_else(|_| crate_pin("golden3-pin.obu"));
3542 let Ok(stream) = std::fs::read(&path) else {
3543 eprintln!(
3544 "SKIP pinned_golden3_stream_decodes_pixel_exact: no pinned bytes at {} \
3545 -- the committed copy is crates/ec-av1/fixtures/golden3-pin.obu",
3546 path.display()
3547 );
3548 return;
3549 };
3550 if !have_ffmpeg() {
3551 eprintln!("SKIP pinned_golden3_stream_decodes_pixel_exact: no ffmpeg");
3552 return;
3553 }
3554 let frames = decode_stream(&stream).expect("pinned stream must decode");
3555 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
3556 assert_eq!(
3557 frames.len(),
3558 ffmpeg_frames.len(),
3559 "pinned stream decoded {} frames, ffmpeg {} -- a length mismatch would \
3560 make the zip below compare a mis-paired set",
3561 frames.len(),
3562 ffmpeg_frames.len()
3563 );
3564 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3565 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
3566 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
3567 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
3568 }
3569 eprintln!(
3570 "pinned_golden3_stream_decodes_pixel_exact: {} frame(s) byte-exact vs ffmpeg \
3571 from {}",
3572 frames.len(),
3573 path.display()
3574 );
3575 }
3576
3577 /// lane-av1golden4: reproduces the pinned mismatch bytes captured by
3578 /// `EC_AV1_GATE_DUMP=$SP/golden4-pin.obu` off
3579 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
3580 /// (seed 43, frame 3 luma) the round the GOLDEN mask lifted. Deterministic
3581 /// and static.
3582 ///
3583 /// LIVE since lane-av1pinslive r3: the bytes are committed at
3584 /// `crates/ec-av1/fixtures/golden4-pin.obu` (137 bytes; sha256
3585 /// `1754023e44e46edaebc2c05065bf1c65db1a41354577cbf71c0e8ebe737ae14a`,
3586 /// recovered byte-for-byte from the runner library), so the old
3587 /// "reads a pinned fixture path outside the repo" reason is false. Costs
3588 /// ~0.10 s, touches no process-global, reads `non_last_ref_hits` for
3589 /// diagnostic output only (never asserted), and calls no aomenc.
3590 #[test]
3591 fn pinned_golden4_stream_decodes_pixel_exact() {
3592 use crate::decode::non_last_ref_hits;
3593 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
3594 .map(std::path::PathBuf::from)
3595 .unwrap_or_else(|_| crate_pin("golden4-pin.obu"));
3596 let stream = require_pin(&path, "golden4-pin.obu");
3597 if !have_ffmpeg() {
3598 eprintln!("SKIP pinned_golden4_stream_decodes_pixel_exact: no ffmpeg");
3599 return;
3600 }
3601 let before = non_last_ref_hits();
3602 let frames = decode_stream(&stream).expect("pinned stream must decode");
3603 eprintln!(
3604 "non_last_ref_hits before={before} after={}",
3605 non_last_ref_hits()
3606 );
3607 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
3608 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3609 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
3610 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
3611 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
3612 }
3613 }
3614
3615 /// lane-av1golden7 round 9: pins the residual GOLDEN_FRAME MC bug found
3616 /// by the forwarding gate once film grain is out of the way (1/20 real
3617 /// aomenc streams, frame 3 luma, apply_grain=false, `non_last_ref_hits`
3618 /// delta=2). `GOLDEN_FRAME` refuses by name until this decodes exact.
3619 ///
3620 /// LIVE since lane-av1pinslive r3. The old shape was the worst of the
3621 /// class: a `concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/...")`
3622 /// literal, which points at the GITIGNORED root and can therefore never be
3623 /// satisfied by a committed pin, combined with a bare `.expect()`. The
3624 /// bytes are now committed at
3625 /// `crates/ec-av1/fixtures/golden7-forwarding-mismatch.obu` (152 bytes;
3626 /// sha256 `81b3bf657a85e95085287b30d97dee93ba5aea0ed1db1e1f4fcd19a06afc17be`,
3627 /// recovered byte-for-byte from the runner library).
3628 #[test]
3629 fn pinned_golden7_stream_decodes_pixel_exact() {
3630 use crate::decode::non_last_ref_hits;
3631 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
3632 .map(std::path::PathBuf::from)
3633 .unwrap_or_else(|_| crate_pin("golden7-forwarding-mismatch.obu"));
3634 let stream = require_pin(&path, "golden7-forwarding-mismatch.obu");
3635 if !have_ffmpeg() {
3636 eprintln!("SKIP pinned_golden7_stream_decodes_pixel_exact: no ffmpeg");
3637 return;
3638 }
3639 let before = non_last_ref_hits();
3640 let frames = decode_stream(&stream).expect("pinned stream must decode");
3641 eprintln!(
3642 "non_last_ref_hits before={before} after={}",
3643 non_last_ref_hits()
3644 );
3645 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
3646 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3647 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
3648 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
3649 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
3650 }
3651 }
3652
3653 /// lane-av1refs's decisive single-non-LAST-reference gate: identical
3654 /// recipe to
3655 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
3656 /// except `--enable-order-hint=0` is DROPPED (that flag's own comment on
3657 /// the sibling test names it as exactly what suppresses aomenc's RD from
3658 /// ever picking `GOLDEN_FRAME`) and the sequence runs 8 frames, not 4 --
3659 /// more chances for the RD search to reach past the first GOP's initial
3660 /// key frame. `--auto-alt-ref=0` stays: this decoder only supports
3661 /// `LAST_FRAME`/`GOLDEN_FRAME` so far, and alt-ref/backward references
3662 /// are still a named refusal, not this gate's target. A stream that
3663 /// decodes without firing [`decode::non_last_ref_hits`] is not a
3664 /// coverage win for this round -- SKIP it as a genuine, named miss
3665 /// rather than pass silently on untested ground.
3666 #[test]
3667 fn a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact() {
3668 if !have_ffmpeg() {
3669 eprintln!(
3670 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no ffmpeg"
3671 );
3672 return;
3673 }
3674 if !have_aomenc() {
3675 eprintln!(
3676 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no aomenc at {}",
3677 aomenc_path().display()
3678 );
3679 return;
3680 }
3681 let (width, height, frame_count) = (64usize, 64usize, 8usize);
3682 let mut refusals = Vec::new();
3683 let mut never_fired = 0u32;
3684 // aomenc's own RD search is nondeterministic run-to-run even at
3685 // `--threads=1` (confirmed live: identical CLI args, identical
3686 // input, two different output byte streams) -- so beyond varying
3687 // the fixture's seed, each attempt is its own independent coin
3688 // flip against every named refusal below. 120 attempts (not 40)
3689 // to give that coin flip enough tries to land on a stream this
3690 // decoder both accepts and that fires GOLDEN_FRAME. `duration=0.32`
3691 // at `rate=25` (not `0.24`) matches every sibling gate's own
3692 // frame-count fixture exactly -- a shorter duration here once
3693 // produced a frame-0 (keyframe, no reference at all) luma mismatch
3694 // against ffmpeg, i.e. a source-frame-count rounding artifact of
3695 // this recipe's own choosing, not a decoder bug.
3696 for attempt in 0..120u32 {
3697 let seed = 42 + attempt % 40;
3698 let source = gradients_source(seed, 64, 64, "duration=0.32:rate=25");
3699 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3700 .args([
3701 "-v",
3702 "error",
3703 "-f",
3704 "lavfi",
3705 "-i",
3706 &source,
3707 "-pix_fmt",
3708 "yuv420p",
3709 "-f",
3710 "yuv4mpegpipe",
3711 "-",
3712 ])
3713 .stdin(Stdio::null())
3714 .stdout(Stdio::piped())
3715 .stderr(Stdio::piped()), None, |c| c.output())
3716 .expect("ffmpeg failed to run");
3717 assert!(
3718 y4m.status.success(),
3719 "ffmpeg fixture: {}",
3720 String::from_utf8_lossy(&y4m.stderr)
3721 );
3722 let out = run_with_stdin(
3723 Command::new(aomenc_path()).args([
3724 "--codec=av1",
3725 "--passes=1",
3726 "--end-usage=q",
3727 "--cq-level=55",
3728 "--cpu-used=0",
3729 "--lag-in-frames=0",
3730 "--auto-alt-ref=0",
3731 "--kf-max-dist=1000",
3732 "--threads=1",
3733 "--row-mt=0",
3734 // Narrows the RD search's reference alphabet toward
3735 // LAST_FRAME/GOLDEN_FRAME -- without this, aomenc's RD is
3736 // just as likely to pick LAST2/LAST3/BWDREF/ALTREF2/
3737 // ALTREF (this decoder's already-documented, still-open
3738 // refusals), starving this gate of the one reference it
3739 // targets.
3740 "--max-reference-frames=3",
3741 "--reduced-reference-set=1",
3742 "--enable-warped-motion=0",
3743 "--enable-obmc=0",
3744 "--enable-masked-comp=0",
3745 "--enable-interintra-comp=0",
3746 "--enable-dist-wtd-comp=0",
3747 "--enable-diff-wtd-comp=0",
3748 "--enable-onesided-comp=0",
3749 "--enable-interintra-wedge=0",
3750 "--enable-smooth-interintra=0",
3751 "--enable-rect-partitions=0",
3752 "--enable-ab-partitions=0",
3753 "--enable-1to4-partitions=0",
3754 "--enable-filter-intra=0",
3755 "--enable-smooth-intra=0",
3756 "--enable-paeth-intra=0",
3757 "--enable-directional-intra=0",
3758 "--enable-angle-delta=0",
3759 "--enable-tx-size-search=0",
3760 "--enable-cdef=0",
3761 "--enable-restoration=0",
3762 // `min == max == 32` forces PARTITION_NONE for every
3763 // 32x32 block, not just biases toward it -- with
3764 // `--min-partition-size=16` alone aomenc's exhaustive
3765 // `cpu-used=0` RD search still occasionally read HORZ/
3766 // VERT/SPLIT partitions below 32x32 despite
3767 // `--enable-rect-partitions=0`/`--enable-ab-partitions=0`/
3768 // `--enable-1to4-partitions=0` all being off (two
3769 // separate, already-documented round-2 gaps: "a
3770 // partition below 16x16", "a partition type this encoder
3771 // never writes"), starving this gate's already-narrow
3772 // seed pool. Locking both bounds to 32 removes any
3773 // partition-depth choice from the search entirely, so
3774 // this gate can isolate GOLDEN_FRAME selection alone.
3775 "--max-partition-size=32",
3776 "--min-partition-size=32",
3777 "--enable-palette=0",
3778 "--enable-intrabc=0",
3779 "--enable-cfl-intra=0",
3780 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
3781 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
3782 "--enable-ref-frame-mvs=0",
3783 // `--tune-content=film` was dropped: on this box it
3784 // makes aomenc emit `apply_grain` almost every attempt
3785 // (lane-av1golden8 round 10 measurement, live: 120/120
3786 // real attempts hit a named refusal, 0 ever fired
3787 // GOLDEN_FRAME -- mostly `apply_grain`, dominated by its
3788 // own recipe flag) -- film grain synthesis has its own
3789 // dedicated refusal test and must not starve this gate
3790 // of the GOLDEN_FRAME draws it exists to prove. Default
3791 // content tuning still occasionally flips
3792 // `allow_screen_content_tools` on for this synthetic
3793 // gradient content (a separate, already-documented open
3794 // refusal), which the 120-attempt coin flip below
3795 // tolerates the same way.
3796 "--obu",
3797 "-o",
3798 "-",
3799 "-",
3800 ]),
3801 &y4m.stdout,
3802 );
3803 assert!(
3804 out.status.success(),
3805 "aomenc refused the fixture: {}",
3806 String::from_utf8_lossy(&out.stderr)
3807 );
3808 let stream = out.stdout;
3809 let before = decode::non_last_ref_hits();
3810 let frames = match decode_stream(&stream) {
3811 Err(e) => {
3812 let msg = e.to_string();
3813 assert!(
3814 msg.contains("unsupported"),
3815 "a golden-reference stream failed outright (seed {seed}): {msg}"
3816 );
3817 refusals.push(format!("seed {seed}: {msg}"));
3818 continue;
3819 }
3820 Ok(frames) => frames,
3821 };
3822 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
3823 // is ALWAYS pixel-compared below; the hit counter only decides whether
3824 // the attempt counts toward the firing total.
3825 // This seed's RD search may never have picked GOLDEN_FRAME -- a
3826 // genuine miss, not a refusal, and not a reason to skip the pixels.
3827 let counted = decode::non_last_ref_hits() != before;
3828 if !counted {
3829 never_fired += 1;
3830 }
3831 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
3832 assert_eq!(frames.len(), frame_count);
3833 // Same pin-on-mismatch pattern as the CDF forwarding gate above:
3834 // env-gated, no cost on a normal run.
3835 let mismatched = frames
3836 .iter()
3837 .zip(&ffmpeg_frames)
3838 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
3839 if mismatched
3840 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
3841 std::fs::write(&path, &stream).expect("writing pinned stream");
3842 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
3843 }
3844 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3845 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
3846 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
3847 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
3848 }
3849 if counted {
3850 eprintln!(
3851 "FIRING seed {seed}: non_last_ref_hits advanced by {}",
3852 decode::non_last_ref_hits() - before
3853 );
3854 gate_buckets(
3855 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
3856 1,
3857 never_fired,
3858 refusals.len(),
3859 );
3860 return;
3861 }
3862 }
3863 gate_buckets(
3864 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
3865 0,
3866 never_fired,
3867 refusals.len(),
3868 );
3869 eprintln!(
3870 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: \
3871 {never_fired} attempts decoded but never fired GOLDEN_FRAME, and every other \
3872 attempt hit a named refusal:\n{}",
3873 refusals.join("\n")
3874 );
3875 }
3876
3877 /// lane-av1comp: proves `reference_select`/`comp_mode` are actually read
3878 /// off a real bitstream rather than only unit-tested in isolation --
3879 /// `--auto-alt-ref=1 --lag-in-frames=16` gives aomenc a backward
3880 /// reference to pick `COMPOUND_REFERENCE` with, `--enable-order-hint=1`
3881 /// is required for it to ever consider compound at all. Three
3882 /// acceptable outcomes: (a) a stream where `reference_select` never
3883 /// actually drove a block to `COMPOUND_REFERENCE` decodes bit-exact end
3884 /// to end (proving the per-block `comp_mode` read did not desync the
3885 /// single-ref blocks around it); (b) a stream that does fire compound
3886 /// is refused by name with [`decode::comp_mode_hits`] having advanced
3887 /// (proving `comp_mode`/`read_compound_ref_frames` consumed the right
3888 /// symbols before refusing, rather than desyncing and refusing for an
3889 /// unrelated reason) -- masked/wedge compound (`comp_group_idx == 1`)
3890 /// and a partition below 16x16 (a real, separately tracked capability
3891 /// gap) are the two refusal arms this can still legitimately name; (c)
3892 /// r13 wired plain `COMPOUND_AVERAGE` MC for real, so as of r15 a
3893 /// stream that fires compound may also decode fully -- accepted only
3894 /// when every output frame is pixel-exact against ffmpeg.
3895 #[test]
3896 fn a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly() {
3897 const NAME: &str = "a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly";
3898 let _gate_lock = lock_gate_counters();
3899 if !have_ffmpeg() {
3900 eprintln!("SKIP {NAME}: no ffmpeg");
3901 return;
3902 }
3903 if !have_aomenc() {
3904 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3905 return;
3906 }
3907 let (width, height, frame_count) = (64usize, 64usize, 20usize);
3908 let mut refusals = Vec::new();
3909 let mut never_fired = 0u32;
3910 for attempt in 0..60u32 {
3911 let seed = 42 + attempt % 40;
3912 let duration = frame_count as f64 / 25.0;
3913 let source =
3914 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
3915 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3916 .args([
3917 "-v",
3918 "error",
3919 "-f",
3920 "lavfi",
3921 "-i",
3922 &source,
3923 "-pix_fmt",
3924 "yuv420p",
3925 "-f",
3926 "yuv4mpegpipe",
3927 "-",
3928 ])
3929 .stdin(Stdio::null())
3930 .stdout(Stdio::piped())
3931 .stderr(Stdio::piped()), None, |c| c.output())
3932 .expect("ffmpeg failed to run");
3933 assert!(
3934 y4m.status.success(),
3935 "ffmpeg fixture: {}",
3936 String::from_utf8_lossy(&y4m.stderr)
3937 );
3938 let args: Vec<&str> = vec![
3939 "--codec=av1",
3940 "--passes=1",
3941 "--end-usage=q",
3942 "--cq-level=45",
3943 "--cpu-used=0",
3944 "--kf-max-dist=1000",
3945 "--threads=1",
3946 "--row-mt=0",
3947 "--auto-alt-ref=1",
3948 "--lag-in-frames=16",
3949 "--enable-order-hint=1",
3950 "--enable-warped-motion=0",
3951 "--enable-obmc=0",
3952 "--enable-masked-comp=0",
3953 "--enable-interintra-comp=0",
3954 "--enable-onesided-comp=0",
3955 "--enable-interintra-wedge=0",
3956 "--enable-smooth-interintra=0",
3957 "--enable-rect-partitions=0",
3958 "--enable-ab-partitions=0",
3959 "--enable-1to4-partitions=0",
3960 "--enable-filter-intra=0",
3961 "--enable-smooth-intra=0",
3962 "--enable-paeth-intra=0",
3963 "--enable-directional-intra=0",
3964 "--enable-angle-delta=0",
3965 "--enable-tx-size-search=0",
3966 "--enable-cdef=0",
3967 "--enable-restoration=0",
3968 "--max-partition-size=32",
3969 "--min-partition-size=32",
3970 "--enable-palette=0",
3971 "--enable-intrabc=0",
3972 "--enable-cfl-intra=0",
3973 "--enable-ref-frame-mvs=0",
3974 "--obu",
3975 "-o",
3976 "-",
3977 "-",
3978 ];
3979 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3980 assert!(
3981 out.status.success(),
3982 "aomenc refused the fixture: {}",
3983 String::from_utf8_lossy(&out.stderr)
3984 );
3985 let stream = out.stdout;
3986 let before = decode::comp_mode_hits();
3987 match decode_stream(&stream) {
3988 Err(e) => {
3989 let msg = e.to_string();
3990 let fired = decode::comp_mode_hits() > before;
3991 assert!(
3992 msg.contains("unsupported"),
3993 "{NAME} failed outright (seed {seed}): {msg}"
3994 );
3995 if fired {
3996 // `comp_mode` firing does not stop the block walk --
3997 // a later, unrelated block in the same tile can
3998 // still hit any other named refusal this decoder
3999 // carries. A partition below 16x16 is a real, open
4000 // capability gap tracked on its own (not a
4001 // COMPOUND_REFERENCE defect); accept it here too
4002 // rather than fail a compound-specific gate on a
4003 // partition-search coincidence. lane-av1blend r7:
4004 // re-swept the wide gate with the plain-average
4005 // blend unmasked (r6/r7's ref_ctx fix alone) and it
4006 // still mismatches on real streams beyond that one
4007 // bug -- re-masked comp_group_idx == 0 too, so this
4008 // stays a legal named refusal.
4009 assert!(
4010 msg.contains("COMPOUND_REFERENCE") || msg.contains("a partition"),
4011 "{NAME}: comp_mode fired (seed {seed}) but the refusal \
4012 was for something else: {msg}"
4013 );
4014 let advanced = decode::comp_mode_hits() - before;
4015 eprintln!(
4016 "{NAME} FIRING seed {seed}: comp_mode hits advanced by \
4017 {advanced}, refused by name as expected: {msg}"
4018 );
4019 return;
4020 }
4021 refusals.push(format!("seed {seed}: {msg}"));
4022 continue;
4023 }
4024 Ok(frames) => {
4025 // class [[gate-skips-on-its-own-failure]]: a decode that
4026 // succeeded is ALWAYS pixel-compared below; the hit counter
4027 // only decides whether the attempt counts as firing.
4028 let counted = decode::comp_mode_hits() != before;
4029 if !counted {
4030 never_fired += 1;
4031 }
4032 // Outcome (c): plain COMPOUND_AVERAGE decoded fully --
4033 // non-negotiable pixel exactness, no tolerance.
4034 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
4035 assert_eq!(frames.len(), frame_count);
4036 let mismatched = frames
4037 .iter()
4038 .zip(&ffmpeg_frames)
4039 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
4040 if mismatched {
4041 let pin =
4042 std::env::temp_dir().join("ec-av1-reference-select-gate-fail.obu");
4043 crate::dumpio::pin("TEST_PIN", &pin, &stream);
4044 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
4045 crate::dumpio::pin("EC_AV1_GATE_DUMP", &path, &stream);
4046 eprintln!(
4047 "EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"
4048 );
4049 }
4050 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4051 assert_eq!(
4052 got.y,
4053 want.y,
4054 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
4055 pin.display()
4056 );
4057 assert_eq!(
4058 got.u,
4059 want.u,
4060 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
4061 pin.display()
4062 );
4063 assert_eq!(
4064 got.v,
4065 want.v,
4066 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
4067 pin.display()
4068 );
4069 }
4070 } else {
4071 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4072 assert_eq!(
4073 got.y, want.y,
4074 "{NAME} frame {i} luma vs ffmpeg (seed {seed})"
4075 );
4076 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
4077 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
4078 }
4079 }
4080 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
4081 // stream again, comparing EVERY decode-order frame -- the hidden
4082 // (show_frame == 0) alt-ref frames the ffmpeg compare above
4083 // cannot see, because both sides of it emit shown frames only.
4084 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
4085 eprintln!(
4086 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
4087 {hidden_n} hidden, all pixel-exact vs the oracle"
4088 );
4089 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
4090 // libaom's temporal alt-ref filter absorbs this recipe's hidden
4091 // frames, so the compare above is vacuous -- re-encode the same
4092 // fixture with --arnr-maxframes=0 and compare THOSE.
4093 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args)
4094 {
4095 eprintln!(
4096 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
4097 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
4098 );
4099 }
4100 if counted {
4101 eprintln!(
4102 "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \
4103 fully and pixel-exact",
4104 decode::comp_mode_hits() - before
4105 );
4106 gate_buckets(NAME, 1, never_fired, refusals.len());
4107 return;
4108 }
4109 }
4110 }
4111 }
4112 gate_buckets(NAME, 0, never_fired, refusals.len());
4113 eprintln!(
4114 "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \
4115 block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \
4116 reached comp_mode:\n{}",
4117 refusals.join("\n")
4118 );
4119 }
4120
4121 /// lane-av1comp round 14's decisive gate for `skip_mode`: same
4122 /// pin-on-mismatch pattern as [`a_real_aomenc_single_ref_gate`], proving
4123 /// [`decode::skip_mode_hits`] actually advanced (a real block picked
4124 /// `skip_mode`, not just that the frame header bit was set) and that the
4125 /// resulting forced-compound `NEAREST_NEARESTMV` decode is still
4126 /// pixel-exact against ffmpeg. `--auto-alt-ref=1 --lag-in-frames=16
4127 /// --enable-fwd-kf=0` (backward references) plus
4128 /// `--enable-ref-frame-mvs=0` (unimplemented temporal MV projection,
4129 /// same as every other gate here) is aomenc's own requirement for
4130 /// `skip_mode_present` to ever be considered at all (spec 5.9.22 needs
4131 /// both a forward and a backward reference candidate).
4132 #[test]
4133 fn a_real_aomenc_stream_with_compound_references_decodes_pixel_exact() {
4134 const NAME: &str = "a_real_aomenc_stream_with_compound_references_decodes_pixel_exact";
4135 let _gate_lock = lock_gate_counters();
4136 if !have_ffmpeg() {
4137 eprintln!("SKIP {NAME}: no ffmpeg");
4138 return;
4139 }
4140 if !have_aomenc() {
4141 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4142 return;
4143 }
4144 let (width, height, frame_count) = (64usize, 64usize, 24usize);
4145 let mut refusals = Vec::new();
4146 let mut never_fired = 0u32;
4147 for attempt in 0..80u32 {
4148 let seed = 42 + attempt % 40;
4149 let duration = frame_count as f64 / 25.0;
4150 let source =
4151 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
4152 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
4153 .args([
4154 "-v",
4155 "error",
4156 "-f",
4157 "lavfi",
4158 "-i",
4159 &source,
4160 "-pix_fmt",
4161 "yuv420p",
4162 "-f",
4163 "yuv4mpegpipe",
4164 "-",
4165 ])
4166 .stdin(Stdio::null())
4167 .stdout(Stdio::piped())
4168 .stderr(Stdio::piped()), None, |c| c.output())
4169 .expect("ffmpeg failed to run");
4170 assert!(
4171 y4m.status.success(),
4172 "ffmpeg fixture: {}",
4173 String::from_utf8_lossy(&y4m.stderr)
4174 );
4175 let args: Vec<&str> = vec![
4176 "--codec=av1",
4177 "--passes=1",
4178 "--end-usage=q",
4179 "--cq-level=45",
4180 "--cpu-used=0",
4181 "--kf-max-dist=1000",
4182 "--threads=1",
4183 "--row-mt=0",
4184 "--auto-alt-ref=1",
4185 "--lag-in-frames=16",
4186 "--enable-fwd-kf=0",
4187 "--enable-order-hint=1",
4188 "--enable-warped-motion=0",
4189 "--enable-obmc=0",
4190 "--enable-masked-comp=0",
4191 "--enable-interintra-comp=0",
4192 "--enable-onesided-comp=0",
4193 "--enable-interintra-wedge=0",
4194 "--enable-smooth-interintra=0",
4195 "--enable-rect-partitions=0",
4196 "--enable-ab-partitions=0",
4197 "--enable-1to4-partitions=0",
4198 "--enable-filter-intra=0",
4199 "--enable-smooth-intra=0",
4200 "--enable-paeth-intra=0",
4201 "--enable-directional-intra=0",
4202 "--enable-angle-delta=0",
4203 "--enable-tx-size-search=0",
4204 "--enable-cdef=0",
4205 "--enable-restoration=0",
4206 "--max-partition-size=32",
4207 "--min-partition-size=32",
4208 "--enable-palette=0",
4209 "--enable-intrabc=0",
4210 "--enable-cfl-intra=0",
4211 "--enable-ref-frame-mvs=0",
4212 "--obu",
4213 "-o",
4214 "-",
4215 "-",
4216 ];
4217 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
4218 assert!(
4219 out.status.success(),
4220 "aomenc refused the fixture: {}",
4221 String::from_utf8_lossy(&out.stderr)
4222 );
4223 let stream = out.stdout;
4224 let before = decode::skip_mode_hits();
4225 let frames = match decode_stream(&stream) {
4226 Err(e) => {
4227 let msg = e.to_string();
4228 assert!(
4229 msg.contains("unsupported"),
4230 "{NAME} failed outright (seed {seed}): {msg}"
4231 );
4232 refusals.push(format!("seed {seed}: {msg}"));
4233 continue;
4234 }
4235 Ok(frames) => frames,
4236 };
4237 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
4238 // is ALWAYS pixel-compared below; the hit counter only decides whether
4239 // the attempt counts toward the firing total.
4240 let counted = decode::skip_mode_hits() != before;
4241 if !counted {
4242 never_fired += 1;
4243 }
4244 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
4245 assert_eq!(frames.len(), frame_count);
4246 let mismatched = frames
4247 .iter()
4248 .zip(&ffmpeg_frames)
4249 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
4250 if mismatched {
4251 let pin = std::env::temp_dir().join("ec-av1-compound-refs-gate-fail.obu");
4252 crate::dumpio::pin("TEST_PIN", &pin, &stream);
4253 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
4254 crate::dumpio::pin("EC_AV1_GATE_DUMP", &path, &stream);
4255 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
4256 }
4257 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4258 assert_eq!(
4259 got.y,
4260 want.y,
4261 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
4262 pin.display()
4263 );
4264 assert_eq!(
4265 got.u,
4266 want.u,
4267 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
4268 pin.display()
4269 );
4270 assert_eq!(
4271 got.v,
4272 want.v,
4273 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
4274 pin.display()
4275 );
4276 }
4277 }
4278 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
4279 // stream again, comparing EVERY decode-order frame -- the hidden
4280 // (show_frame == 0) alt-ref frames the ffmpeg compare above
4281 // cannot see, because both sides of it emit shown frames only.
4282 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
4283 eprintln!(
4284 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
4285 {hidden_n} hidden, all pixel-exact vs the oracle"
4286 );
4287 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
4288 // libaom's temporal alt-ref filter absorbs this recipe's hidden
4289 // frames, so the compare above is vacuous -- re-encode the same
4290 // fixture with --arnr-maxframes=0 and compare THOSE.
4291 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
4292 eprintln!(
4293 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
4294 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
4295 );
4296 }
4297 if counted {
4298 eprintln!(
4299 "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}",
4300 decode::skip_mode_hits() - before
4301 );
4302 gate_buckets(NAME, 1, never_fired, refusals.len());
4303 return;
4304 }
4305 }
4306 gate_buckets(NAME, 0, never_fired, refusals.len());
4307 eprintln!(
4308 "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \
4309 other attempt hit a named refusal:\n{}",
4310 refusals.join("\n")
4311 );
4312 }
4313
4314 /// lane-motionmode round 1: `--enable-obmc=1 --enable-warped-motion=0`
4315 /// on the base recipe (`--auto-alt-ref=1 --lag-in-frames=16
4316 /// --enable-fwd-kf=0 --enable-ref-frame-mvs=0`) -- pixel-exact against
4317 /// ffmpeg, gated on [`decode::obmc_hits`] actually advancing (a real
4318 /// block picked `OBMC_CAUSAL`, not just that the header bit was set).
4319 /// Structure copied from
4320 /// `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`:
4321 /// a seed sweep with a named-refusal escape hatch and an
4322 /// `EC_AV1_GATE_DUMP` pin on mismatch.
4323 #[test]
4324 fn a_real_aomenc_stream_with_obmc_decodes_pixel_exact() {
4325 const NAME: &str = "a_real_aomenc_stream_with_obmc_decodes_pixel_exact";
4326 let _gate_lock = lock_gate_counters();
4327 if !have_ffmpeg() {
4328 eprintln!("SKIP {NAME}: no ffmpeg");
4329 return;
4330 }
4331 if !have_aomenc() {
4332 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4333 return;
4334 }
4335 let (width, height, frame_count) = (64usize, 64usize, 24usize);
4336 let mut refusals = Vec::new();
4337 let mut never_fired = 0u32;
4338 for attempt in 0..80u32 {
4339 let seed = 42 + attempt % 40;
4340 let duration = frame_count as f64 / 25.0;
4341 let source =
4342 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
4343 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
4344 .args([
4345 "-v",
4346 "error",
4347 "-f",
4348 "lavfi",
4349 "-i",
4350 &source,
4351 "-pix_fmt",
4352 "yuv420p",
4353 "-f",
4354 "yuv4mpegpipe",
4355 "-",
4356 ])
4357 .stdin(Stdio::null())
4358 .stdout(Stdio::piped())
4359 .stderr(Stdio::piped()), None, |c| c.output())
4360 .expect("ffmpeg failed to run");
4361 assert!(
4362 y4m.status.success(),
4363 "ffmpeg fixture: {}",
4364 String::from_utf8_lossy(&y4m.stderr)
4365 );
4366 let args: Vec<&str> = vec![
4367 "--codec=av1",
4368 "--passes=1",
4369 "--end-usage=q",
4370 "--cq-level=45",
4371 "--cpu-used=0",
4372 "--kf-max-dist=1000",
4373 "--threads=1",
4374 "--row-mt=0",
4375 "--auto-alt-ref=1",
4376 "--lag-in-frames=16",
4377 "--enable-fwd-kf=0",
4378 "--enable-order-hint=1",
4379 "--enable-warped-motion=0",
4380 "--enable-obmc=1",
4381 "--enable-masked-comp=0",
4382 "--enable-interintra-comp=0",
4383 "--enable-onesided-comp=0",
4384 "--enable-interintra-wedge=0",
4385 "--enable-smooth-interintra=0",
4386 "--enable-rect-partitions=0",
4387 "--enable-ab-partitions=0",
4388 "--enable-1to4-partitions=0",
4389 "--enable-filter-intra=0",
4390 "--enable-smooth-intra=0",
4391 "--enable-paeth-intra=0",
4392 "--enable-directional-intra=0",
4393 "--enable-angle-delta=0",
4394 "--enable-tx-size-search=0",
4395 "--enable-cdef=0",
4396 "--enable-restoration=0",
4397 "--max-partition-size=32",
4398 "--min-partition-size=32",
4399 "--enable-palette=0",
4400 "--enable-intrabc=0",
4401 "--enable-cfl-intra=0",
4402 "--enable-ref-frame-mvs=0",
4403 "--obu",
4404 "-o",
4405 "-",
4406 "-",
4407 ];
4408 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
4409 assert!(
4410 out.status.success(),
4411 "aomenc refused the fixture: {}",
4412 String::from_utf8_lossy(&out.stderr)
4413 );
4414 let stream = out.stdout;
4415 let before = decode::obmc_hits();
4416 let frames = match decode_stream(&stream) {
4417 Err(e) => {
4418 let msg = e.to_string();
4419 assert!(
4420 msg.contains("unsupported"),
4421 "{NAME} failed outright (seed {seed}): {msg}"
4422 );
4423 refusals.push(format!("seed {seed}: {msg}"));
4424 continue;
4425 }
4426 Ok(frames) => frames,
4427 };
4428 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
4429 // is ALWAYS pixel-compared below; the hit counter only decides whether
4430 // the attempt counts toward the firing total.
4431 let counted = decode::obmc_hits() != before;
4432 if !counted {
4433 never_fired += 1;
4434 }
4435 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
4436 assert_eq!(frames.len(), frame_count);
4437 let mismatched = frames
4438 .iter()
4439 .zip(&ffmpeg_frames)
4440 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
4441 if mismatched
4442 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
4443 std::fs::write(&path, &stream).expect("writing pinned stream");
4444 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
4445 }
4446 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4447 assert_eq!(
4448 got.y, want.y,
4449 "{NAME} frame {i} luma vs ffmpeg (seed {seed})"
4450 );
4451 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
4452 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
4453 }
4454 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
4455 // stream again, comparing EVERY decode-order frame -- the hidden
4456 // (show_frame == 0) alt-ref frames the ffmpeg compare above
4457 // cannot see, because both sides of it emit shown frames only.
4458 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
4459 eprintln!(
4460 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
4461 {hidden_n} hidden, all pixel-exact vs the oracle"
4462 );
4463 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
4464 // libaom's temporal alt-ref filter absorbs this recipe's hidden
4465 // frames, so the compare above is vacuous -- re-encode the same
4466 // fixture with --arnr-maxframes=0 and compare THOSE.
4467 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
4468 eprintln!(
4469 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
4470 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
4471 );
4472 }
4473 if counted {
4474 eprintln!(
4475 "{NAME} FIRING seed {seed}: obmc hits advanced by {}",
4476 decode::obmc_hits() - before
4477 );
4478 gate_buckets(NAME, 1, never_fired, refusals.len());
4479 return;
4480 }
4481 }
4482 gate_buckets(NAME, 0, never_fired, refusals.len());
4483 eprintln!(
4484 "SKIP {NAME}: {never_fired} attempts decoded but never fired obmc, and every \
4485 other attempt hit a named refusal:\n{}",
4486 refusals.join("\n")
4487 );
4488 }