forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

t04.rs4516 lines, 207.7 KiBHistoryRawDownload
1use super::*;
2use super::support::*;
3use super::gates_a::*;
4use crate::probe::run_with_stdin;
5use std::process::{Command, Stdio};
6
7 /// The 12-bit WARP witness (lane-av112bitw): the same source and recipe
8 /// with the warp tools ON -- aomenc picks warp models on this content
9 /// (measured pre-lift: the warp model fires at the third frame, and the
10 /// decode refused by name at exactly that block) -- now decodes
11 /// BYTE-EXACT against ffmpeg. The warp filter's shifts are the bumped
12 /// `conv_params->round_0` (`warp::warp_round_0`, 5 at 12 bits, feeding
13 /// `reduce_bits_horiz`, the derived non-compound
14 /// `reduce_bits_vert = 2*FILTER_BITS - round_0` and both `offset_bits`),
15 /// the whole libaom `get_conv_params_no_round` 12-bit bump.
16 ///
17 /// Non-vacuous: the same recipe refused by name before the lift, the
18 /// gate hard-asserts a warp predictor was really resolved (a warpless
19 /// stream would pass the pixel compare and prove nothing), and every
20 /// plane of every frame compares against ffmpeg's decode.
21 #[test]
22 fn a_12bit_warped_motion_stream_decodes_pixel_exact() {
23 const NAME: &str = "a_12bit_warped_motion_stream_decodes_pixel_exact";
24 let _gate_lock = lock_gate_counters();
25 if !have_ffmpeg() {
26 eprintln!("SKIP {NAME}: no ffmpeg");
27 return;
28 }
29 if !have_aomenc() {
30 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
31 return;
32 }
33 let y4m = y4m_12bit_subpel_source(6);
34 // Exactly the recipe measured to refuse at warp pre-lift: warp ON,
35 // global motion NOT spelled (spelling it ON drives a GLOBAL_GLOBALMV
36 // compound block into the compound-warp arm -- see the compound gate
37 // below), six frames -- the warp model fires at the third frame.
38 let stream = encode_12bit(&y4m, 6, &["--enable-warped-motion=1"]);
39 assert_12bit_sequence_header(&stream, NAME);
40 let (before_selected, before_warp8, before_affine) = (
41 decode::warp_selected_hits(),
42 decode::warp_hits_8(),
43 decode::affine_gm_hits(),
44 );
45 let frames = decode_stream(&stream).unwrap_or_else(|e| {
46 panic!("{NAME}: decode_stream refused a real 12-bit warp stream: {e}")
47 });
48 assert_eq!(frames.len(), 6);
49 let (delta_selected, delta_warp8, delta_affine) = (
50 decode::warp_selected_hits() - before_selected,
51 decode::warp_hits_8() - before_warp8,
52 decode::affine_gm_hits() - before_affine,
53 );
54 eprintln!(
55 "{NAME}: warp_engagement selected(16x16+ symbol)={delta_selected} \
56 warped8(usable 8x8 model)={delta_warp8} affine_gm(6-param model)={delta_affine}"
57 );
58 assert!(
59 delta_selected + delta_warp8 + delta_affine > 0,
60 "{NAME}: no warp predictor was resolved -- the stream carries no \
61 warp model and the pixel compare would prove nothing"
62 );
63 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6);
64 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
65 assert_eq!(
66 ours.y, reference.y,
67 "frame {i} luma vs ffmpeg (12-bit warp)"
68 );
69 assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit warp)");
70 assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit warp)");
71 }
72 }
73
74 /// The 12-bit COMPOUND witness (lane-av112bitc): the parent's source
75 /// and recipe with warp pinned OFF -- with six frames LAST diverges
76 /// from GOLDEN from frame 2 on and aomenc codes compound inter blocks
77 /// (pre-lift measurement: the decode refused at the compound mode
78 /// read). Two arms: the default recipe (dist-weighted average
79 /// combines live) and `--enable-dist-wtd-comp=0` (pushes compound AND
80 /// the masked choice harder: 6 diffwtd blends). Both byte-exact
81 /// against ffmpeg; each hard-asserts compound mode symbols and
82 /// masked-diffwtd blends really ran, so the parameterised combine
83 /// rounds (`INTER_POST_ROUND - delta`, diffwtd `+ (bd-8) - delta` at
84 /// 12 bits) and the ffmpeg-pinned pixel path genuinely executed.
85 #[test]
86 fn a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact() {
87 const NAME: &str = "a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact";
88 let _gate_lock = lock_gate_counters();
89 if !have_ffmpeg() {
90 eprintln!("SKIP {NAME}: no ffmpeg");
91 return;
92 }
93 if !have_aomenc() {
94 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
95 return;
96 }
97 let y4m = y4m_12bit_subpel_source(6);
98 for (arm, extra) in [
99 ("dist-wtd", &["--enable-warped-motion=0"][..]),
100 (
101 "plain-masked",
102 &["--enable-warped-motion=0", "--enable-dist-wtd-comp=0"][..],
103 ),
104 ] {
105 let stream = encode_12bit(&y4m, 6, extra);
106 assert_12bit_sequence_header(&stream, NAME);
107 let before_compound = decode::compound_mode_hits();
108 let before_masked = decode::masked_compound_hits();
109 let before_diffwtd = decode::diffwtd_hits();
110 let before_wedge = decode::wedge_hits();
111 let frames = decode_stream(&stream).unwrap_or_else(|e| {
112 panic!("{NAME} [{arm}]: decode_stream refused a real 12-bit compound stream: {e}")
113 });
114 assert_eq!(frames.len(), 6, "{NAME} [{arm}]: frame count");
115 let (comp, masked, diffwtd, wedge) = (
116 decode::compound_mode_hits() - before_compound,
117 decode::masked_compound_hits() - before_masked,
118 decode::diffwtd_hits() - before_diffwtd,
119 decode::wedge_hits() - before_wedge,
120 );
121 eprintln!(
122 "{NAME} [{arm}]: compound blocks={comp} masked={masked} diffwtd={diffwtd} wedge={wedge}"
123 );
124 assert!(
125 comp > 0,
126 "{NAME} [{arm}]: no compound mode symbol was read -- the compound path is unexercised"
127 );
128 assert!(
129 masked > 0,
130 "{NAME} [{arm}]: no masked compound block ran -- the masked combine is unexercised"
131 );
132 assert!(
133 diffwtd > 0,
134 "{NAME} [{arm}]: no diffwtd blend ran -- the diffwtd combine is unexercised"
135 );
136 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6);
137 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
138 assert_eq!(
139 ours.y, reference.y,
140 "{NAME} [{arm}] frame {i} luma vs ffmpeg"
141 );
142 assert_eq!(ours.u, reference.u, "{NAME} [{arm}] frame {i} U vs ffmpeg");
143 assert_eq!(ours.v, reference.v, "{NAME} [{arm}] frame {i} V vs ffmpeg");
144 }
145 }
146 }
147
148 /// lane-av112bitg: the 12-bit film grain witness. A real
149 /// `aomenc --bit-depth=12 --profile=2 --film-grain-test=5` stream -- grain
150 /// params present AND applied (2 luma + 9 cb + 9 cr scaling points,
151 /// overlap blending on, clip-to-restricted-range on; the second frame is
152 /// an INTER frame that inherits the params via `update_grain = 0`) --
153 /// decoded byte-exact against ffmpeg's own 12-bit decode of the identical
154 /// bytes (ffmpeg synthesizes grain by default; no grain-disable flag is
155 /// passed anywhere in this file). Proves the bit-depth-generic grain path
156 /// at 12 bits: `grain_range`'s ±(128 << 4) AR clamp and overlap-blend
157 /// clamp, the `gauss_sec_shift = 12 - bd` Gaussian shift, the 4096-entry
158 /// expanded scaling-LUT interpolation, and the `<< (bit_depth - 8)`
159 /// chroma offsets and legal-range clamps. HARD-asserts the parsed headers
160 /// really carry that coverage and `film_grain::grain_hits()` fired, so
161 /// neither a params-without-apply stream nor a silently-skipped synthesis
162 /// can pass vacuously.
163 #[test]
164 fn a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact() {
165 const NAME: &str = "a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact";
166 let _gate_lock = lock_gate_counters();
167 if !have_ffmpeg() {
168 eprintln!("SKIP {NAME}: no ffmpeg");
169 return;
170 }
171 if !have_aomenc() {
172 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
173 return;
174 }
175 let y4m = y4m_12bit_subpel_source(2);
176 // Warp stays refused at 12 bits (lane-av112bitg lifts GRAIN only), so
177 // the arm pins both motion tools off exactly once each -- aomenc
178 // otherwise picks warped motion on this fixture's sub-pel motion.
179 let stream = encode_12bit(
180 &y4m,
181 2,
182 &[
183 "--film-grain-test=5",
184 "--enable-warped-motion=0",
185 "--enable-global-motion=0",
186 ],
187 );
188 assert_12bit_sequence_header(&stream, NAME);
189 // The arm is only honest if the stream itself carries the coverage:
190 // grain applied on every frame, scaling points on all three planes,
191 // overlap blending and restricted-range clipping on.
192 let mut probe = Av1Parser::new();
193 let mut pos = 0usize;
194 let mut grain_frames = 0usize;
195 while pos < stream.len() {
196 let obu = probe.parse_obu(&stream[pos..]).unwrap();
197 pos += obu.total_size;
198 if let ObuKind::Frame(header, _) = obu.kind {
199 let fg = &header.film_grain;
200 assert!(
201 fg.apply_grain,
202 "{NAME}: frame without apply_grain -- aomenc emitted params it does not apply"
203 );
204 assert!(
205 fg.num_y_points > 0 && fg.num_cb_points > 0 && fg.num_cr_points > 0,
206 "{NAME}: grain without all three planes' scaling points -- the bit-depth \
207 LUT math would not be exercised"
208 );
209 assert!(
210 fg.overlap_flag,
211 "{NAME}: overlap off -- the grain_min/grain_max blend clamp is not exercised"
212 );
213 assert!(
214 fg.clip_to_restricted_range,
215 "{NAME}: clip_to_restricted_range off -- the << (bd - 8) legal-range clamps \
216 are not exercised"
217 );
218 grain_frames += 1;
219 }
220 }
221 assert_eq!(grain_frames, 2, "{NAME}: expected grain on both frames");
222 let before = crate::film_grain::grain_hits();
223 let frames = decode_stream(&stream).unwrap_or_else(|e| {
224 panic!("{NAME}: decode_stream refused a real 12-bit grain stream: {e}")
225 });
226 assert_eq!(frames.len(), 2);
227 assert!(
228 crate::film_grain::grain_hits() > before,
229 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
230 );
231 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2);
232 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
233 assert_eq!(
234 ours.y, theirs.y,
235 "{NAME}: luma vs ffmpeg (12-bit grain, frame {i})"
236 );
237 assert_eq!(
238 ours.u, theirs.u,
239 "{NAME}: U vs ffmpeg (12-bit grain, frame {i})"
240 );
241 assert_eq!(
242 ours.v, theirs.v,
243 "{NAME}: V vs ffmpeg (12-bit grain, frame {i})"
244 );
245 }
246 eprintln!(
247 "{NAME}: byte-exact, grain_hits={}",
248 crate::film_grain::grain_hits()
249 );
250 }
251
252 /// lane-av1screen12: a 12-bit PALETTE screen-content stream, palette on
253 /// and palette-UV on, `allow_intrabc` off.
254 ///
255 /// Recipe: `ffmpeg -f lavfi -i testsrc2=s=160x128:r=25 -pix_fmt
256 /// yuv420p12le -strict -1` (2 frames, 160x128 4:2:0) piped to
257 /// [`encode_12bit`] with `--tune-content=screen --enable-palette=1
258 /// `--enable-intrabc=1`; pin `screen12_palette.obu` (3616 bytes, sha256
259 /// `adfe26c67c08a7e986db2743b914ecc3e214c56dd2abbdfd17ebf99f06de64c8`).
260 ///
261 /// What it replaces: this is the arm the blanket refusal "a 12-bit frame
262 /// with screen content tools" blocked while decoding exactly.
263 #[test]
264 fn a_real_aomenc_12bit_screen_content_palette_stream_decodes_pixel_exact() {
265 const NAME: &str = "a_real_aomenc_12bit_screen_content_palette_stream_decodes_pixel_exact";
266 const PIN: &str = "screen12_palette.obu";
267 let _gate_lock = lock_gate_counters();
268 if !have_ffmpeg() {
269 eprintln!("SKIP {NAME}: no ffmpeg");
270 return;
271 }
272 let y4m = y4m_12bit_screen_source("testsrc2=s=160x128:r=25", false);
273 let live = if have_aomenc() {
274 encode_12bit(
275 &y4m,
276 2,
277 &[
278 "--tune-content=screen",
279 "--enable-palette=1",
280 "--enable-intrabc=1",
281 ],
282 )
283 } else {
284 Vec::new()
285 };
286 assert_12bit_screen_content_arm(
287 NAME,
288 PIN,
289 live,
290 PIN_LEN_PALETTE,
291 PIN_FNV_PALETTE,
292 2,
293 160,
294 128,
295 false,
296 );
297 }
298
299 /// lane-av1screen12: a 12-bit screen-content stream whose KEY frame sets
300 /// `allow_intrabc = 1` and really codes `use_intrabc` blocks.
301 ///
302 /// Recipe: [`screen_intrabc_stream_at_depth`] at depth 12 -- the same
303 /// shape the 8/10-bit intrabc census and the sb128 intrabc witness use:
304 /// `-vf tile=2x2` over `smptebars=size=128x96:rate=25` (256x192),
305 /// `--tune-content=screen --enable-intrabc=1 --enable-palette=1
306 /// --cq-level=30 --enable-tx-size-search=0 --min-partition-size=8
307 /// --max-partition-size=32 --sb-size=64 --kf-max-dist=1 --limit=1`, so
308 /// ONE 12-bit key frame; pin `screen12_intrabc.obu` (482 bytes, sha256
309 /// `a3b6b94cabdd09a12057c4688990d55495826b87a14332c386d319629070382e`).
310 ///
311 /// This arm is the one the old refusal's "nor intrabc" half named, and it
312 /// is why the refusal could be LIFTED rather than narrowed: it decodes
313 /// byte-exact at 12 bits and `intrabc_hits()` proves the blocks really
314 /// reconstructed from the current frame.
315 #[test]
316 fn a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact() {
317 const NAME: &str = "a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact";
318 const PIN: &str = "screen12_intrabc.obu";
319 let _gate_lock = lock_gate_counters();
320 if !have_ffmpeg() {
321 eprintln!("SKIP {NAME}: no ffmpeg");
322 return;
323 }
324 let live = if have_aomenc() {
325 // `--enable-palette=1` LAST (aomenc keeps the last occurrence), so
326 // this 12-bit arm carries BOTH screen-content syntaxes rather than
327 // intra-block copy alone.
328 screen_intrabc_stream_at_depth(
329 "smptebars=size=128x96:rate=25",
330 "30",
331 "0",
332 true,
333 false,
334 12,
335 &["--enable-palette=1"],
336 )
337 } else {
338 Vec::new()
339 };
340 assert_12bit_screen_content_arm(
341 NAME,
342 PIN,
343 live,
344 PIN_LEN_INTRABC,
345 PIN_FNV_INTRABC,
346 1,
347 256,
348 192,
349 true,
350 );
351 }
352
353 /// lane-av1screen12: a 12-bit LOSSLESS screen-content stream with
354 /// palette and palette-UV on.
355 ///
356 /// Recipe: the palette arm's source and flags plus `--lossless=1`, so the
357 /// frame is `CodedLossless` (base_q_idx 0, WHT on every plane) AND
358 /// screen-content -- two 12-bit tile-syntax interactions in one frame;
359 /// pin `screen12_lossless_palette.obu` (11698 bytes, sha256
360 /// `ec7942c96763593e6d8e4b3fb23c03930bba3bb743102d0cf552fe73ae11c203`).
361 #[test]
362 fn a_real_aomenc_12bit_lossless_screen_content_stream_decodes_pixel_exact() {
363 const NAME: &str = "a_real_aomenc_12bit_lossless_screen_content_stream_decodes_pixel_exact";
364 const PIN: &str = "screen12_lossless_palette.obu";
365 let _gate_lock = lock_gate_counters();
366 if !have_ffmpeg() {
367 eprintln!("SKIP {NAME}: no ffmpeg");
368 return;
369 }
370 let y4m = y4m_12bit_screen_source("testsrc2=s=160x128:r=25", false);
371 let live = if have_aomenc() {
372 encode_12bit(
373 &y4m,
374 2,
375 &[
376 "--tune-content=screen",
377 "--enable-palette=1",
378 "--enable-intrabc=1",
379 "--lossless=1",
380 ],
381 )
382 } else {
383 Vec::new()
384 };
385 assert_12bit_screen_content_arm(
386 NAME,
387 PIN,
388 live,
389 PIN_LEN_LOSSLESS,
390 PIN_FNV_LOSSLESS,
391 2,
392 160,
393 128,
394 false,
395 );
396 }
397
398 #[test]
399 fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {
400 const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact";
401 if !have_ffmpeg() {
402 eprintln!("SKIP {NAME}: no ffmpeg");
403 return;
404 }
405 if !have_aomenc() {
406 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
407 return;
408 }
409 let (width, height) = (64usize, 64usize);
410 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
411 .args([
412 "-v",
413 "error",
414 "-f",
415 "lavfi",
416 "-i",
417 &gradients_source(42, width, height, "duration=0.04:rate=25"),
418 "-pix_fmt",
419 "yuv420p10le",
420 "-strict",
421 "-1",
422 "-t",
423 "0.04",
424 "-f",
425 "yuv4mpegpipe",
426 "-",
427 ])
428 .stdin(Stdio::null())
429 .stdout(Stdio::piped())
430 .stderr(Stdio::piped()), None, |c| c.output())
431 .expect("ffmpeg failed to run");
432 assert!(
433 y4m.status.success(),
434 "ffmpeg failed to render the 10-bit fixture: {}",
435 String::from_utf8_lossy(&y4m.stderr)
436 );
437 let out = run_with_stdin(
438 Command::new(aomenc_path()).args([
439 "--codec=av1",
440 "--passes=1",
441 "--end-usage=q",
442 "--cq-level=30",
443 "--cpu-used=0",
444 "--threads=1",
445 "--row-mt=0",
446 "--sb-size=64",
447 "--input-bit-depth=10",
448 "--bit-depth=10",
449 "--limit=1",
450 "--obu",
451 "-o",
452 "-",
453 "-",
454 ]),
455 &y4m.stdout,
456 );
457 assert!(
458 out.status.success(),
459 "aomenc refused the 10-bit fixture: {}",
460 String::from_utf8_lossy(&out.stderr)
461 );
462 let stream = out.stdout;
463 // Confirm the sequence header this stream actually parses to before
464 // trusting any pixel comparison below.
465 let mut probe = Av1Parser::new();
466 let mut pos = 0usize;
467 while pos < stream.len() && probe.sequence_header().is_none() {
468 let obu = probe.parse_obu(&stream[pos..]).unwrap();
469 pos += obu.total_size;
470 }
471 let seq = probe
472 .sequence_header()
473 .expect("stream has a sequence header OBU");
474 assert_eq!(
475 seq.color_config.bit_depth, 10,
476 "{NAME}: aomenc did not actually write a 10-bit sequence header"
477 );
478 let frames = match decode_stream(&stream) {
479 Ok(frames) => frames,
480 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit stream: {e}"),
481 };
482 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
483 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (10-bit)");
484 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (10-bit)");
485 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
486 }
487
488 /// The 10-bit *inter* counterpart of the gate above: a real `aomenc`
489 /// `yuv420p10le` sequence whose non-key frames are plain forward
490 /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0
491 /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate),
492 /// decoded pixel-exact on every frame. 10-bit intra was proven exact by
493 /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated.
494 #[test]
495 fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() {
496 const NAME: &str = "a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact";
497 let _gate_lock = lock_gate_counters();
498 if !have_ffmpeg() {
499 eprintln!("SKIP {NAME}: no ffmpeg");
500 return;
501 }
502 if !have_aomenc() {
503 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
504 return;
505 }
506 let (width, height, frame_count) = (128usize, 64usize, 16usize);
507 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
508 .args([
509 "-v",
510 "error",
511 "-f",
512 "lavfi",
513 "-i",
514 &gradients_source(42, width, height, "duration=0.64:rate=25"),
515 "-pix_fmt",
516 "yuv420p10le",
517 "-strict",
518 "-1",
519 "-t",
520 "0.64",
521 "-f",
522 "yuv4mpegpipe",
523 "-",
524 ])
525 .stdin(Stdio::null())
526 .stdout(Stdio::piped())
527 .stderr(Stdio::piped()), None, |c| c.output())
528 .expect("ffmpeg failed to run");
529 assert!(
530 y4m.status.success(),
531 "ffmpeg failed to render the 10-bit fixture: {}",
532 String::from_utf8_lossy(&y4m.stderr)
533 );
534 let out = run_with_stdin(
535 Command::new(aomenc_path()).args([
536 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
537 // occurrence, so overrides go before the base list).
538 "--loopfilter-control=1",
539 "--codec=av1",
540 "--passes=1",
541 "--end-usage=q",
542 "--cq-level=15",
543 "--cpu-used=0",
544 "--threads=1",
545 "--row-mt=0",
546 "--sb-size=64",
547 "--input-bit-depth=10",
548 "--bit-depth=10",
549 "--lag-in-frames=0",
550 "--auto-alt-ref=0",
551 "--kf-max-dist=1000",
552 "--error-resilient=1",
553 "--aq-mode=0",
554 "--deltaq-mode=0",
555 "--enable-cdef=0",
556 "--enable-rect-partitions=0",
557 "--enable-ab-partitions=0",
558 "--enable-1to4-partitions=0",
559 "--enable-filter-intra=0",
560 "--enable-smooth-intra=0",
561 "--enable-paeth-intra=0",
562 "--enable-directional-intra=0",
563 "--enable-angle-delta=0",
564 "--enable-tx-size-search=0",
565 "--enable-cdef=1",
566 "--enable-restoration=1",
567 "--min-partition-size=16",
568 "--max-partition-size=32",
569 "--enable-palette=0",
570 "--enable-intrabc=0",
571 "--enable-cfl-intra=0",
572 "--enable-ref-frame-mvs=0",
573 "--obu",
574 "-o",
575 "-",
576 "-",
577 ]),
578 &y4m.stdout,
579 );
580 assert!(
581 out.status.success(),
582 "aomenc refused the 10-bit fixture: {}",
583 String::from_utf8_lossy(&out.stderr)
584 );
585 let stream = out.stdout;
586 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
587 std::fs::write(dump, &stream).expect("dump stream");
588 }
589 let mut probe = Av1Parser::new();
590 let mut pos = 0usize;
591 while pos < stream.len() && probe.sequence_header().is_none() {
592 let obu = probe.parse_obu(&stream[pos..]).unwrap();
593 pos += obu.total_size;
594 }
595 assert_eq!(
596 probe
597 .sequence_header()
598 .expect("stream has a sequence header OBU")
599 .color_config
600 .bit_depth,
601 10,
602 "{NAME}: aomenc did not actually write a 10-bit sequence header"
603 );
604 let before_deblock = decode::deblock_hits();
605 let before_inter = decode::inter_pred_hits();
606 let before_lr = crate::restoration::wiener_hits()
607 + crate::restoration::sgrproj_hits()
608 + crate::restoration::switchable_hits();
609 let frames = match decode_stream(&stream) {
610 Ok(frames) => frames,
611 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"),
612 };
613 assert!(
614 decode::inter_pred_hits() > before_inter,
615 "{NAME}: no inter-predicted block decoded -- the gate proves nothing"
616 );
617 assert!(
618 decode::deblock_hits() > before_deblock,
619 "{NAME}: no deblocking edge fired -- raise cq-level"
620 );
621 // Loop restoration is where the 10-bit inter/intra defect lived
622 // (lane-hbdinter r1: the self-guided box sums were never brought back
623 // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened
624 // to pick RESTORE_NONE would pass while proving nothing.
625 assert!(
626 crate::restoration::wiener_hits()
627 + crate::restoration::sgrproj_hits()
628 + crate::restoration::switchable_hits()
629 > before_lr,
630 "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level"
631 );
632 eprintln!(
633 "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}",
634 decode::inter_pred_hits() - before_inter,
635 decode::deblock_hits() - before_deblock,
636 decode::cdef_idx_hits(),
637 crate::restoration::wiener_hits(),
638 crate::restoration::sgrproj_hits(),
639 );
640 assert_eq!(frames.len(), frame_count);
641 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count);
642 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
643 if got.y != want.y || got.u != want.u || got.v != want.v {
644 let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu");
645 crate::dumpio::pin("TEST_PIN", &pin, &stream);
646 let first = |a: &Vec<u16>, b: &Vec<u16>| {
647 a.iter()
648 .zip(b)
649 .enumerate()
650 .find(|(_, (x, y))| x != y)
651 .map(|(k, (x, y))| (k, *x, *y))
652 };
653 panic!(
654 "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}",
655 first(&got.y, &want.y),
656 first(&got.u, &want.u),
657 first(&got.v, &want.v),
658 pin.display()
659 );
660 }
661 }
662 }
663
664 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1`
665 /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the
666 /// identical bytes (ffmpeg synthesizes grain by default -- no
667 /// grain-disable flag is passed anywhere in this file). Proves the
668 /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`,
669 /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather
670 /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed
671 /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a
672 /// silent 8-bit fallback nor a stream aomenc emitted without
673 /// `apply_grain` can make it pass vacuously.
674 #[test]
675 fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() {
676 const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact";
677 if !have_ffmpeg() {
678 eprintln!("SKIP {NAME}: no ffmpeg");
679 return;
680 }
681 if !have_aomenc() {
682 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
683 return;
684 }
685 let (width, height) = (64usize, 64usize);
686 let stream = encode_10bit_gradients(
687 NAME,
688 width,
689 height,
690 1,
691 &["--film-grain-test=1", "--limit=1"],
692 );
693 assert_eq!(
694 parsed_bit_depth(&stream),
695 10,
696 "{NAME}: aomenc did not actually write a 10-bit sequence header"
697 );
698 let mut probe = Av1Parser::new();
699 let mut pos = 0usize;
700 let mut saw_grain = false;
701 while pos < stream.len() {
702 let obu = probe.parse_obu(&stream[pos..]).unwrap();
703 pos += obu.total_size;
704 if let ObuKind::Frame(header, _) = obu.kind
705 && header.film_grain.apply_grain
706 {
707 // A grain block whose scaling LUT is empty would blend a
708 // zero delta into every pixel and let this gate pass without
709 // the bit-depth math mattering at all.
710 assert!(
711 header.film_grain.num_y_points > 0,
712 "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op"
713 );
714 saw_grain = true;
715 }
716 }
717 assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain");
718 let before = crate::film_grain::grain_hits();
719 let frames = match decode_stream(&stream) {
720 Ok(frames) => frames,
721 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
722 };
723 assert!(
724 crate::film_grain::grain_hits() > before,
725 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
726 );
727 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
728 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
729 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
730 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
731 eprintln!(
732 "{NAME}: pixel-exact, grain_hits={}",
733 crate::film_grain::grain_hits()
734 );
735 }
736
737 /// lane-t900 r29: `fixtures/superres_kf_cdef_lr_64x64.obu` is a real
738 /// aomenc key frame (64x64 upscaled from a coded 43x64,
739 /// `--superres-mode=1 --superres-denominator=12 --cpu-used=0 --sb-size=64
740 /// --enable-cdef=1 --enable-restoration=1 --cq-level=32`) -- the first
741 /// stream in this repo that runs BOTH in-loop filters under superres.
742 ///
743 /// The defect it pins: spec 7.16's upscale runs between CDEF and loop
744 /// restoration (libaom `superres_post_decode`, `decodeframe.c`, called
745 /// between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`),
746 /// but this decoder ran the whole filter chain on the DOWNSCALED frame
747 /// and upscaled last, in `stream.rs`. Loop restoration therefore filtered
748 /// downscaled pixels with a unit grid sized from the downscaled width
749 /// (1873 wrong samples, max 7, on this very stream). Class
750 /// `wrong-stage-width`: every plane width in the filter chain is either
751 /// the downscaled one (deblock, CDEF, and the mi grid all three walk) or
752 /// the upscaled one (loop restoration's `av1_get_upsampled_plane_size`
753 /// unit grid, `av1_loop_restoration_corners_in_sb`'s `mi_to_num_x`
754 /// superres arm, and the pixel filters themselves); the sweep is every
755 /// caller of `apply_deblock`/`apply_cdef`/`apply_loop_restoration` plus
756 /// `RestorationGrid::new` and `read_lr`.
757 #[test]
758 fn a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact() {
759 const NAME: &str =
760 "a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact";
761 let _gate_lock = lock_gate_counters();
762 if !have_ffmpeg() {
763 eprintln!("SKIP {NAME}: no ffmpeg");
764 return;
765 }
766 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
767 .join("fixtures/superres_kf_cdef_lr_64x64.obu");
768 let stream = std::fs::read(&path)
769 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
770 let (width, height) = (64usize, 64usize);
771 let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
772 let frames = match decode_stream(&stream) {
773 Ok(frames) => frames,
774 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
775 };
776 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
777 assert_eq!((frames[0].width, frames[0].height), (width, height));
778 // class `gate-blind-to-feature`: the stream must actually upscale and
779 // actually run a real restoration filter, or this gate proves nothing.
780 assert!(
781 crate::superres::superres_hits() > 0,
782 "{NAME}: zero superres_hits -- the frame was never upscaled"
783 );
784 assert!(
785 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
786 "{NAME}: zero restoration units fired -- LR never ran under superres"
787 );
788 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
789 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
790 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
791 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
792 }
793
794 /// lane-av1superhbd (1): 4:4:4 superres at **10 bits**, `--superres-mode=1
795 /// --superres-denominator=12` on all four frames -- coded 171x128 upscaled
796 /// to 256x128 at `denom = 12`.
797 ///
798 /// **What it closes.** Every superres fixture the crate carried parsed
799 /// `bit_depth = 8` (4:2:0 `superres_kf_cdef_lr_64x64.obu`) or was 4:2:0
800 /// (`superres_alltools_sb128_320x180.obu`), and the 4:4:4 superres cells
801 /// were 8-bit. The chroma-format sweep's not-measured list kept "4:4:4
802 /// superres at 10/12 bits" open on that basis. This arm is the 10-bit
803 /// measurement: a 4:4:4 chroma plane upscaled at FULL resolution, where
804 /// the upscaler and the scaled inter predictor both run with a
805 /// 10-bit sample width and the 4:4:4 chroma gather has no subsampling
806 /// halving to hide behind.
807 ///
808 /// **The recipe** (sha256
809 /// `95b49d7aa81843399ee3aa64bdadfec8f4037bcc3f861923c9b2da3bc868b223`,
810 /// 15803 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p10le):
811 /// ```text
812 /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \
813 /// -pix_fmt yuv444p10le -strict -1 -f yuv4mpegpipe - | \
814 /// aomenc --codec=av1 --profile=1 --bit-depth=10 --input-bit-depth=10 \
815 /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \
816 /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \
817 /// --superres-mode=1 --superres-denominator=12 \
818 /// --superres-kf-denominator=12 --obu -o - -
819 /// ```
820 /// `-strict -1` is load-bearing: without it ffmpeg refuses to write
821 /// `yuv444p10le` into a y4m pipe at all (zero bytes out).
822 #[test]
823 fn a_444_lossy_superres_10bit_d12_stream_decodes_pixel_exact() {
824 a_444_hbd_superres_arm(
825 "a_444_lossy_superres_10bit_d12_stream_decodes_pixel_exact",
826 "fixtures/444_lossy_superres_256x128_d12_10bit.obu",
827 15803,
828 0x9fad_3227_6e91_792c,
829 "95b49d7aa81843399ee3aa64bdadfec8f4037bcc3f861923c9b2da3bc868b223",
830 10,
831 (256, 128),
832 &[(12, 171); 4],
833 );
834 }
835
836 /// lane-av1superhbd (2): 4:4:4 superres at **12 bits**,
837 /// `--superres-mode=1 --superres-denominator=12`, coded 171x128 upscaled
838 /// to 256x128.
839 ///
840 /// **Why the source is `mandelbrot` and not `testsrc2`.** The 12-bit
841 /// frame gate refuses a frame carrying `allow_screen_content_tools = 1`
842 /// by name (palette and intrabc have no 12-bit witness). libaom sets
843 /// that bit from its own content detection
844 /// (`av1_set_screen_content_options` -> `encoder_utils.c:1153`, keyed on
845 /// the palette-pixel ratio of the FIRST pass), and `testsrc2` -- flat
846 /// colour bars and hard edges -- trips it at 12 bits while the very same
847 /// recipe at 10 bits does not. `--enable-palette=0 --enable-intrabc=0`
848 /// and `--tune-content=film` do NOT suppress it (measured: all four
849 /// still parse `allow_screen_content_tools = true`), because the
850 /// detection is a property of the CONTENT, not of those flags. A
851 /// photographic source (`mandelbrot`, same geometry and frame count)
852 /// parses `allow_screen_content_tools = false` and decodes. This is a
853 /// source choice, stated so the next lane does not re-derive it.
854 ///
855 /// **The recipe** (sha256
856 /// `973bf374c0185c4e6301509ce834cef01318e6cdb9488fd258118d7ec89bdd04`,
857 /// 11023 bytes, 4 frames, `mandelbrot 256x128 rate=25` yuv444p12le):
858 /// ```text
859 /// ffmpeg -f lavfi -i "mandelbrot=size=256x128:rate=25" -frames:v 4 \
860 /// -pix_fmt yuv444p12le -strict -1 -f yuv4mpegpipe - | \
861 /// aomenc --codec=av1 --profile=1 --bit-depth=12 --input-bit-depth=12 \
862 /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \
863 /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \
864 /// --superres-mode=1 --superres-denominator=12 \
865 /// --superres-kf-denominator=12 --obu -o - -
866 /// ```
867 /// Byte-reproducible: two independent encodes produced the same 11023
868 /// bytes.
869 #[test]
870 fn a_444_lossy_superres_12bit_d12_stream_decodes_pixel_exact() {
871 a_444_hbd_superres_arm(
872 "a_444_lossy_superres_12bit_d12_stream_decodes_pixel_exact",
873 "fixtures/444_lossy_superres_256x128_d12_12bit.obu",
874 11023,
875 0xd6cf_bb83_2b42_8e2d,
876 "973bf374c0185c4e6301509ce834cef01318e6cdb9488fd258118d7ec89bdd04",
877 12,
878 (256, 128),
879 &[(12, 171); 4],
880 );
881 }
882
883 /// lane-av1superhbd (3): 4:4:4 superres at **12 bits** at the WIDEST
884 /// denominator this geometry allows, `--superres-denominator=9` -- coded
885 /// 228x128 upscaled to 256x128, so 28 of the 256 columns are the frame's
886 /// right-edge upscale margin, against 12's 85.
887 ///
888 /// It is a separate gate from the den=12 arm because the margin is
889 /// where a round-trip is most likely to read past the coded picture: a
890 /// decoder that sized the upscale source from `UpscaledWidth` instead of
891 /// `FrameWidth` is exact at den=12 on this content and wrong here. Its
892 /// recipe is the 12-bit one above with `--superres-denominator=9
893 /// --superres-kf-denominator=9` (sha256
894 /// `898c775108495b998cb5ec9b08e194d4656ed0140aa8e7e7236892d468bbad99`,
895 /// 13015 bytes).
896 #[test]
897 fn a_444_lossy_superres_12bit_d9_stream_decodes_pixel_exact() {
898 a_444_hbd_superres_arm(
899 "a_444_lossy_superres_12bit_d9_stream_decodes_pixel_exact",
900 "fixtures/444_lossy_superres_256x128_d9_12bit.obu",
901 13015,
902 0x4110_ce7b_cd85_901b,
903 "898c775108495b998cb5ec9b08e194d4656ed0140aa8e7e7236892d468bbad99",
904 12,
905 (256, 128),
906 &[(9, 228); 4],
907 );
908 }
909
910 /// lane-av1superhbd (4): 4:4:4 superres at **10 bits** under
911 /// `--superres-mode=2` -- the random-denominator arm, where libaom picks
912 /// a DIFFERENT denominator for every frame and IGNORES
913 /// `--superres-denominator` entirely.
914 ///
915 /// This is what keeps the high-bit-depth superres cell from silently
916 /// degenerating into a single-denominator cell: the per-frame parsed
917 /// denominators are 11, 14, 15, 9 -- three of them values no flag on the
918 /// command line ever named -- so a gate that read the flag instead of
919 /// the header would be wrong on three of four frames. The assertion
920 /// below makes that structural rather than incidental, and it is the
921 /// assertion that fails if a future libaom starts honouring the flag
922 /// under mode 2.
923 ///
924 /// **The recipe** (sha256
925 /// `699398aba58fb53b80e05d3d214eb746a3c91945e01da6b47488513f20b55668`,
926 /// 17776 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p10le):
927 /// ```text
928 /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \
929 /// -pix_fmt yuv444p10le -strict -1 -f yuv4mpegpipe - | \
930 /// aomenc --codec=av1 --profile=1 --bit-depth=10 --input-bit-depth=10 \
931 /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \
932 /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \
933 /// --superres-mode=2 --obu -o - -
934 /// ```
935 #[test]
936 fn a_444_lossy_superres_10bit_mode2_random_denom_stream_decodes_pixel_exact() {
937 const NAME: &str =
938 "a_444_lossy_superres_10bit_mode2_random_denom_stream_decodes_pixel_exact";
939 let heads = a_444_hbd_superres_arm(
940 NAME,
941 "fixtures/444_lossy_superres_mode2_256x128_10bit.obu",
942 17776,
943 0x164f_4099_7576_7ae4,
944 "699398aba58fb53b80e05d3d214eb746a3c91945e01da6b47488513f20b55668",
945 10,
946 (256, 128),
947 &[(11, 186), (14, 146), (15, 137), (9, 228)],
948 );
949 // Distinct-denominator assert: the cell must stay a MULTI-denominator
950 // one. A libaom that collapsed mode 2 onto a single denominator (or
951 // stopped scaling) would still decode, and the gate above would still
952 // hold only because the literals would have been re-pinned with it --
953 // so the property is asserted from the parsed headers directly.
954 let denoms: Vec<u8> = heads.iter().map(|h| h.superres_denom).collect();
955 let mut distinct = denoms.clone();
956 distinct.sort_unstable();
957 distinct.dedup();
958 assert!(
959 distinct.len() >= 3,
960 "{NAME}: the stream carries denominators {denoms:?} -- fewer than three distinct \
961 values, so this is no longer the per-frame-denominator cell and the pin has to be \
962 re-derived from the stream"
963 );
964 let flagged = [9u8, 12, 16];
965 assert!(
966 denoms.iter().any(|d| !flagged.contains(d)),
967 "{NAME}: every parsed denominator is one of the flag values {flagged:?} -- mode 2 now \
968 appears to honour --superres-denominator, and this cell stops being the \
969 flag-ignoring one"
970 );
971 }
972
973 /// lane-av1superhbd (5): 4:4:4 superres at **12 bits** under
974 /// `--superres-mode=2` -- the high-bit-depth random-denominator arm, the
975 /// 12-bit twin of the arm above (sha256
976 /// `18aa8b3124ab10672f22577a8eea81e44141a3d0bb506104aee2f950254a2e9f`,
977 /// 14656 bytes, same `mandelbrot` source as the 12-bit fixed-denominator
978 /// arms). Its parsed denominators are again 11/14/15/9 at coded widths
979 /// 186/146/137/228, so the upscaler is handed FOUR coded-to-upscaled
980 /// ratios in one 12-bit decode -- the case a single-denominator gate
981 /// cannot reach at any bit depth.
982 #[test]
983 fn a_444_lossy_superres_12bit_mode2_random_denom_stream_decodes_pixel_exact() {
984 const NAME: &str =
985 "a_444_lossy_superres_12bit_mode2_random_denom_stream_decodes_pixel_exact";
986 let heads = a_444_hbd_superres_arm(
987 NAME,
988 "fixtures/444_lossy_superres_mode2_256x128_12bit.obu",
989 14656,
990 0xef38_3fb7_b284_2166,
991 "18aa8b3124ab10672f22577a8eea81e44141a3d0bb506104aee2f950254a2e9f",
992 12,
993 (256, 128),
994 &[(11, 186), (14, 146), (15, 137), (9, 228)],
995 );
996 let denoms: Vec<u8> = heads.iter().map(|h| h.superres_denom).collect();
997 let mut distinct = denoms.clone();
998 distinct.sort_unstable();
999 distinct.dedup();
1000 assert!(
1001 distinct.len() >= 3,
1002 "{NAME}: the stream carries denominators {denoms:?} -- fewer than three distinct \
1003 values, so this is no longer the per-frame-denominator cell and the pin has to be \
1004 re-derived from the stream"
1005 );
1006 let flagged = [9u8, 12, 16];
1007 assert!(
1008 denoms.iter().any(|d| !flagged.contains(d)),
1009 "{NAME}: every parsed denominator is one of the flag values {flagged:?} -- mode 2 now \
1010 appears to honour --superres-denominator, and this cell stops being the \
1011 flag-ignoring one"
1012 );
1013 }
1014
1015 /// lane-wave1 step (ii): the superblock-row wavefront
1016 /// (`EC_AV1_RECON_THREADS`) reconstructs every output frame byte for
1017 /// byte as the inline path does, on a hidden-ARF 10-bit stream (no-show
1018 /// frames, CfL, 128 superblocks) and on the two screen-content streams
1019 /// whose palette/intrabc blocks READ the current frame's pixels while
1020 /// parsing -- the sites that make the workers barrier.
1021 #[test]
1022 fn a_real_stream_reconstructs_identically_with_one_and_four_recon_threads() {
1023 const NAME: &str = "a_real_stream_reconstructs_identically_with_one_and_four_recon_threads";
1024 let _gate_lock = lock_gate_counters();
1025 for fixture in [
1026 "reelb_arf_witness.obu",
1027 "palette_screen_witness.obu",
1028 "palette_screen_witness_10bit.obu",
1029 // lane-av1wavefront: the 4:4:4 inter witness. The wavefront's
1030 // replay-side chroma (`mv_to_q4(.., ss_x(fctx))` in the deferred
1031 // builds, `exec_intra`'s CfL AC) used to read the worker's fresh
1032 // `FrameCtx` 4:2:0 DEFAULT instead of the frame's subsampling --
1033 // invisible on the three 4:2:0 streams above, chroma-only loss on
1034 // this one (f1 U 17504 / V 3, f2 U 25472 / V 1472 at PREFILT).
1035 "444_sb128rect_lr_witness.obu",
1036 ] {
1037 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1038 .join("fixtures")
1039 .join(fixture);
1040 let stream = std::fs::read(&path)
1041 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1042 crate::par::set_recon_threads(1);
1043 let one = match decode_stream(&stream) {
1044 Ok(frames) => frames,
1045 Err(e) => panic!("{NAME}: {fixture} refused at 1 recon thread: {e}"),
1046 };
1047 crate::par::set_recon_threads(4);
1048 let four = match decode_stream(&stream) {
1049 Ok(frames) => frames,
1050 Err(e) => {
1051 crate::par::set_recon_threads(1);
1052 panic!("{NAME}: {fixture} refused at 4 recon threads: {e}")
1053 }
1054 };
1055 crate::par::set_recon_threads(1);
1056 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
1057 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
1058 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
1059 assert_eq!(
1060 a.y, b.y,
1061 "{NAME}: {fixture} frame {i} luma differs at 4 recon threads"
1062 );
1063 assert_eq!(
1064 a.u, b.u,
1065 "{NAME}: {fixture} frame {i} U differs at 4 recon threads"
1066 );
1067 assert_eq!(
1068 a.v, b.v,
1069 "{NAME}: {fixture} frame {i} V differs at 4 recon threads"
1070 );
1071 }
1072 }
1073 }
1074
1075 /// lane-filt1: `EC_AV1_FILTER_THREADS` splits every in-frame filter stage
1076 /// -- deblock (row bands for the vertical-edge pass, column bands for the
1077 /// horizontal one), CDEF (mi row bands), loop restoration (RU row bands)
1078 /// and film grain (32-pixel block rows) -- across scoped worker threads.
1079 /// A split is only legal if it is BYTE-EXACT, so this gate decodes two
1080 /// real aomenc streams at 1 and at 4 filter threads and compares every
1081 /// output frame's three planes.
1082 ///
1083 /// Between them the fixtures fire all four stages, and the firing
1084 /// counters are asserted rather than assumed (class `gate-blind-to-feature`):
1085 /// `superres_alltools_sb128_320x180.obu` is the 10-bit CDEF + loop
1086 /// restoration stream, `grain_cdef_lr_128x128.obu` a 128x128
1087 /// `--denoise-noise-level=25` stream whose frames carry film grain
1088 /// parameters (small enough that 4 bands is one block row each, which is
1089 /// what exercises the grain band's one-row `prelude` replay).
1090 #[test]
1091 fn a_real_stream_filters_identically_with_one_and_four_filter_threads() {
1092 const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads";
1093 let _gate_lock = lock_gate_counters();
1094 for (fixture, wants_lr, wants_grain) in [
1095 ("superres_alltools_sb128_320x180.obu", true, false),
1096 ("grain_cdef_lr_128x128.obu", false, true),
1097 ] {
1098 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1099 .join("fixtures")
1100 .join(fixture);
1101 let stream = std::fs::read(&path)
1102 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1103 let before = (
1104 crate::decode::deblock_hits(),
1105 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
1106 crate::film_grain::grain_hits(),
1107 );
1108 crate::par::set_filter_threads(1);
1109 let one = match decode_stream(&stream) {
1110 Ok(frames) => frames,
1111 Err(e) => panic!("{NAME}: {fixture} refused at 1 filter thread: {e}"),
1112 };
1113 let after = (
1114 crate::decode::deblock_hits(),
1115 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
1116 crate::film_grain::grain_hits(),
1117 );
1118 crate::par::set_filter_threads(4);
1119 let four = match decode_stream(&stream) {
1120 Ok(frames) => frames,
1121 Err(e) => {
1122 crate::par::set_filter_threads(1);
1123 panic!("{NAME}: {fixture} refused at 4 filter threads: {e}")
1124 }
1125 };
1126 crate::par::set_filter_threads(1);
1127 assert!(
1128 after.0 > before.0,
1129 "{NAME}: {fixture} deblocked no edge at all"
1130 );
1131 if wants_lr {
1132 assert!(
1133 after.1 > before.1,
1134 "{NAME}: {fixture} ran no restoration unit"
1135 );
1136 }
1137 if wants_grain {
1138 assert!(
1139 after.2 > before.2,
1140 "{NAME}: {fixture} applied no film grain"
1141 );
1142 }
1143 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
1144 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
1145 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
1146 assert_eq!(
1147 a.y, b.y,
1148 "{NAME}: {fixture} frame {i} luma differs at 4 filter threads"
1149 );
1150 assert_eq!(
1151 a.u, b.u,
1152 "{NAME}: {fixture} frame {i} U differs at 4 filter threads"
1153 );
1154 assert_eq!(
1155 a.v, b.v,
1156 "{NAME}: {fixture} frame {i} V differs at 4 filter threads"
1157 );
1158 }
1159 }
1160 }
1161
1162 /// lane-t900 r30b: `fixtures/superres_alltools_sb128_320x180.obu` is 10
1163 /// frames of `--cpu-used=4 --sb-size=128 --superres-mode=1
1164 /// --superres-denominator=12 --cq-level=32` with every tool aomenc turns
1165 /// on by default (CDEF, loop restoration, OBMC, compound, warp) -- the
1166 /// first stream here that deblocks CHROMA across a group of 4x4 luma
1167 /// blocks.
1168 ///
1169 /// The defect it pins (fixed at this commit, `decode.rs`'s
1170 /// `plane_to_mi`/`edge_params`): `set_lpf_parameters`
1171 /// (`av1_loopfilter.c:245`) indexes the mi grid for a CHROMA edge at
1172 /// `scale | ((coord << scale) >> MI_SIZE_LOG2)` -- the BOTTOM/RIGHT mi of
1173 /// the co-located 8x8 luma group, the same cell that donates the group's
1174 /// chroma prediction. This decoder dropped that `| 1` and read the
1175 /// group's top-left mi, stepped to the previous cell by one mi instead of
1176 /// `1 << ss`, and priced `pu_edge` by comparing mi origins rather than
1177 /// the edge coordinate against the block size in the FILTERED plane's own
1178 /// pixels (chroma bottoms out at 4). All three are invisible while every
1179 /// block is 8x8 or larger (all four mi of a group carry the same tx size,
1180 /// ref frame, skip flag and delta_lf) and wrong the moment cpu-used=4
1181 /// splits a group into 4x4 blocks: on this stream one U sample of frame 2
1182 /// took a filter level of 12 where libaom's neighbouring 4x4 block gives
1183 /// 8, and the error compounded through the reference chain to 280 U + 331
1184 /// V samples (max 9) by frame 9. Class `context-read-from-one-cell`.
1185 ///
1186 /// Post-deblock, this stream is now byte-exact against the instrumented
1187 /// libaom (`EC_AV1_POSTDEBLOCK_DUMP`) in all 10 frames, and the final
1188 /// output matches ffmpeg's.
1189 #[test]
1190 fn a_superres_all_tools_sb128_stream_decodes_pixel_exact() {
1191 const NAME: &str = "a_superres_all_tools_sb128_stream_decodes_pixel_exact";
1192 let _gate_lock = lock_gate_counters();
1193 if !have_ffmpeg() {
1194 eprintln!("SKIP {NAME}: no ffmpeg");
1195 return;
1196 }
1197 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1198 .join("fixtures/superres_alltools_sb128_320x180.obu");
1199 let stream = std::fs::read(&path)
1200 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1201 let (width, height, count) = (320usize, 180usize, 10usize);
1202 let frames = match decode_stream(&stream) {
1203 Ok(frames) => frames,
1204 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1205 };
1206 assert_eq!(frames.len(), count, "{NAME}: frame count");
1207 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, count);
1208 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1209 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
1210 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
1211 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
1212 }
1213 }
1214
1215 /// lane-golomb r1: THE FILM ITSELF. `crates/ec-av1/fixtures/reelb_head_key_frame.obu`
1216 /// is the first frame of the user's ReelB AV1 release (3840x1608
1217 /// yuv420p10le, `ffmpeg -i <mkv> -c copy -frames:v 1 -f obu`, 147 bytes) --
1218 /// a real 10-bit key frame whose height is NOT a multiple of the 64-pixel
1219 /// superblock, so its last superblock row (mi_row=400 of 402) carries the
1220 /// edge partition symbol this lane fixed: libaom's `ec_read_partition_impl`
1221 /// returns `PARTITION_HORZ` when the gathered `split_or_horz` bit is 0, and
1222 /// this decoder used to READ that bit and throw it away, forcing SPLIT
1223 /// (class `parsed-then-discarded`). The desync surfaced two rows later as
1224 /// "a Golomb tail longer than this decoder reads" -- a refusal naming the
1225 /// symptom, never the cause.
1226 #[test]
1227 fn the_reelb_head_key_frame_decodes_pixel_exact() {
1228 const NAME: &str = "the_reelb_head_key_frame_decodes_pixel_exact";
1229 if !have_ffmpeg() {
1230 eprintln!("SKIP {NAME}: no ffmpeg");
1231 return;
1232 }
1233 let path =
1234 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_head_key_frame.obu");
1235 let stream = std::fs::read(&path)
1236 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1237 let (width, height) = (3840usize, 1608usize);
1238 let frames = match decode_stream(&stream) {
1239 Ok(frames) => frames,
1240 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1241 };
1242 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
1243 assert_eq!((frames[0].width, frames[0].height), (width, height));
1244 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1245 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1246 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
1247 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
1248 }
1249
1250 /// lane-reelckf r2: `crates/ec-av1/fixtures/reelc_kf2700.obu` is a 1920x792
1251 /// 10-bit AV1 key frame taken out of one of the user's own films
1252 /// (`ffmpeg -ss 2700 -c:v copy -f obu`, then truncated to its first temporal
1253 /// unit, 36 kB) -- the ONLY stream in this repo that contains a SKIPPED
1254 /// `UV_CFL_PRED` block. 30 aomenc recipes (r1's 20 plus r2's chroma-correlated
1255 /// `geq` sweep, cq 40..63, cpu-used 0..2, min/max-partition 4..64, 8 and
1256 /// 10 bit) never made the encoder pick one, so the counter can only be
1257 /// hard-asserted against a real film frame. The instrumented oracle agrees:
1258 /// `EC_TRACE_MODE=1 aomdec` prints 5 `EC_IMODE_VAL ... uv_mode=13 skip=1`
1259 /// lines for this frame.
1260 ///
1261 /// The defect it pins (fixed at 29cd53f, `decode.rs:7719`/`:10528`/`:10891`):
1262 /// a skipped intra block must still PREDICT with CfL -- libaom's
1263 /// `predict_and_reconstruct_intra_block` predicts every plane and guards only
1264 /// the residual on `skip_txfm`. Before the fix this frame had 499 wrong
1265 /// chroma samples (U rows 48..79 cols 464..492); after it, zero.
1266 ///
1267 /// The ffmpeg reference is `ffmpeg -f obu -i <fixture> -f rawvideo
1268 /// -pix_fmt yuv420p10le -` (what `ffmpeg_decode_sequence_10bit` runs).
1269 #[test]
1270 fn a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact() {
1271 const NAME: &str = "a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact";
1272 let path =
1273 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelc_kf2700.obu");
1274 let stream = std::fs::read(&path)
1275 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1276 let (width, height) = (1920usize, 792usize);
1277 let before = crate::decode::reelc_chroma_counters();
1278 let frames = match decode_stream(&stream) {
1279 Ok(frames) => frames,
1280 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1281 };
1282 let after = crate::decode::reelc_chroma_counters();
1283 let skip_cfl = after.0 - before.0;
1284 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
1285 assert_eq!((frames[0].width, frames[0].height), (width, height));
1286 // Asserted before the ffmpeg compare so an absent ffmpeg cannot make the
1287 // gate vacuous: the skipped-CfL path is exercised on every run.
1288 assert!(
1289 skip_cfl > 0,
1290 "{NAME}: zero skipped-CfL blocks -- the fixture no longer exercises defect 1"
1291 );
1292 if !have_ffmpeg() {
1293 eprintln!("SKIP {NAME} pixel compare: no ffmpeg (skipped_cfl={skip_cfl})");
1294 return;
1295 }
1296 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1297 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1298 assert_eq!(
1299 frames[0].u, ffmpeg_frames[0].u,
1300 "{NAME}: U vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
1301 );
1302 assert_eq!(
1303 frames[0].v, ffmpeg_frames[0].v,
1304 "{NAME}: V vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
1305 );
1306 eprintln!("{NAME}: pixel-exact, skipped_cfl={skip_cfl}");
1307 }
1308
1309 /// lane-kf1200 r2: the same film's `-ss 300` key frame, pinned because no
1310 /// aomenc recipe reaches its shape -- a SKIPPED sub-8x8 chroma block whose
1311 /// `uv_mode` is `UV_CFL_PRED`. (lane-reelckf r1 burned 20 recipes across cq
1312 /// 40..63 and nine lavfi sources hunting exactly this block and never got
1313 /// one; ledger dead-end "never produced a SKIPPED 1:4 or sub-8x8 CfL
1314 /// block".) Before the fix the two sub-8x8 skip arms passed `None` for the
1315 /// CfL argument, so the block reconstructed as flat DC and 463 bytes of
1316 /// this frame's chroma were wrong. HARD-asserts `skip_cfl_hits` moved, so
1317 /// the fixture cannot silently stop exercising the arm.
1318 #[test]
1319 fn the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact() {
1320 const NAME: &str = "the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact";
1321 if !have_ffmpeg() {
1322 eprintln!("SKIP {NAME}: no ffmpeg");
1323 return;
1324 }
1325 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1326 .join("fixtures/reelb_ss300_key_frame.obu");
1327 let stream = std::fs::read(&path)
1328 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1329 let (width, height) = (3840usize, 1608usize);
1330 let before = crate::decode::skip_cfl_hits();
1331 let frames = match decode_stream(&stream) {
1332 Ok(frames) => frames,
1333 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1334 };
1335 let skipped_cfl = crate::decode::skip_cfl_hits() - before;
1336 assert!(
1337 skipped_cfl > 0,
1338 "{NAME}: zero skipped sub-8x8 CfL blocks -- the fixture no longer \
1339 exercises the arm this test exists for"
1340 );
1341 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
1342 assert_eq!((frames[0].width, frames[0].height), (width, height));
1343 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1344 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1345 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
1346 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
1347 eprintln!("{NAME}: {skipped_cfl} skipped sub-8x8 CfL chroma blocks, frame pixel-exact");
1348 }
1349
1350 /// lane-kf900 r2: the film's key frame at -ss 900, one frame
1351 /// (`crates/ec-av1/fixtures/reelb_kf900.obu`, 484640 bytes, sha256
1352 /// `a273ae99328388be14a1ff8fa1c5a6d391a9948159eaef120e1b50e02015eb83`,
1353 /// extracted twice from independent
1354 /// `ffmpeg -ss 900 -t 2 -i <2160p AV1 HDR10 mkv> -c:v copy -f obu` runs and
1355 /// truncated to the first frame; both extracts hashed identically).
1356 ///
1357 /// This is the ONLY stream that reaches the r1 defect: a SKIPPED 8x8 intra
1358 /// leaf whose `tx_depth` symbol resolved to `TX_4X4` still publishes 4 --
1359 /// not its 8-pixel block side -- to the next block's `get_tx_size_context`
1360 /// (`set_txfm_ctxs(mbmi->tx_size, bw, bh, skip_txfm && is_inter_block(...))`,
1361 /// `decodemv.c`; the skip term is 0 for intra). It fires 15 times here and
1362 /// zero times across 108 measured aomenc recipes, so the counter is
1363 /// asserted against the film rather than against a synthesised stream.
1364 ///
1365 /// LUMA only. U/V still differ (open residue, lane-kf900 r2: 221 U and
1366 /// 47912 V samples, max |d| 23/2, first at chroma (195, 640) -- chroma
1367 /// RESIDUAL, the prediction there is bit-exact against aomdec's
1368 /// `EC_PREDOUT`), so this gate pins what is proven and no more.
1369 #[test]
1370 fn a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact()
1371 {
1372 const NAME: &str = "a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact";
1373 if !have_ffmpeg() {
1374 eprintln!("SKIP {NAME}: no ffmpeg");
1375 return;
1376 }
1377 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_kf900.obu");
1378 let stream = std::fs::read(&path)
1379 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1380 let (width, height) = (3840usize, 1608usize);
1381 crate::decode::reset_skip_split_tx_hits();
1382 let frames = match decode_stream(&stream) {
1383 Ok(frames) => frames,
1384 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1385 };
1386 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
1387 assert_eq!((frames[0].width, frames[0].height), (width, height));
1388 assert!(
1389 crate::decode::skip_split_tx_hits() >= 15,
1390 "{NAME}: skip_split_tx_hits() == {} -- the stream that carries the tx-context \
1391 defect stopped carrying it, so this gate proves nothing",
1392 crate::decode::skip_split_tx_hits()
1393 );
1394 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1395 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1396 }
1397
1398 /// lane-kf1200 r3: the same film's `-ss 600` key frame (3840x1608, one
1399 /// 8-px partial bottom superblock row), pinned because no aomenc recipe
1400 /// reaches its shape -- a SKIPPED 8x8 intra leaf whose `tx_depth` resolved
1401 /// to TX_4X4. (80 recipes swept this round: 4 frame shapes x 2 sources x
1402 /// cq 32..63 x cpu-used 0/3 x 8/10-bit, all with
1403 /// `--enable-tx-size-search=1 --enable-filter-intra=1`; every one came
1404 /// back with `skip_split_tx_hits == 0`, `lanes/kf1200-r3.report.md`.)
1405 /// An intra block reads `tx_depth` whether or not it is skipped, so the
1406 /// leaf must record its resolved 4 -- not its 8x8 side -- in the txfm
1407 /// context; recording 8 gave the NEXT block's `tx_depth` symbol the wrong
1408 /// `tx_size_cdf` row (ctx 2 where libaom reads 1) and desynced the
1409 /// entropy stream at mi (400,46). HARD-asserts `skip_split_tx_hits` moved.
1410 #[test]
1411 fn the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact() {
1412 const NAME: &str = "the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact";
1413 if !have_ffmpeg() {
1414 eprintln!("SKIP {NAME}: no ffmpeg");
1415 return;
1416 }
1417 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1418 .join("fixtures/reelb_ss600_key_frame.obu");
1419 let stream = std::fs::read(&path)
1420 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
1421 let (width, height) = (3840usize, 1608usize);
1422 crate::decode::reset_skip_split_tx_hits();
1423 let frames = match decode_stream(&stream) {
1424 Ok(frames) => frames,
1425 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1426 };
1427 let skipped_split_tx = crate::decode::skip_split_tx_hits();
1428 assert!(
1429 skipped_split_tx > 0,
1430 "{NAME}: zero skipped 8x8 leaves with a split transform -- the fixture no longer \
1431 exercises the arm this test exists for"
1432 );
1433 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
1434 assert_eq!((frames[0].width, frames[0].height), (width, height));
1435 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1436 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1437 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
1438 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
1439 eprintln!("{NAME}: {skipped_split_tx} skipped 8x8 TX_4X4 leaves, frame pixel-exact");
1440 }
1441
1442 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1
1443 /// --superres-denominator=12` key frame, decoded pixel-exact against
1444 /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s
1445 /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit
1446 /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts
1447 /// `bit_depth == 10` and `superres_hits > 0`.
1448 #[test]
1449 fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() {
1450 const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact";
1451 if !have_ffmpeg() {
1452 eprintln!("SKIP {NAME}: no ffmpeg");
1453 return;
1454 }
1455 if !have_aomenc() {
1456 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1457 return;
1458 }
1459 let (width, height) = (64usize, 64usize);
1460 let stream = encode_10bit_gradients(
1461 NAME,
1462 width,
1463 height,
1464 1,
1465 &[
1466 "--limit=1",
1467 "--kf-max-dist=0",
1468 "--superres-mode=1",
1469 "--superres-denominator=12",
1470 "--superres-kf-denominator=12",
1471 "--enable-rect-partitions=0",
1472 "--enable-ab-partitions=0",
1473 "--enable-1to4-partitions=0",
1474 "--enable-filter-intra=0",
1475 "--enable-smooth-intra=0",
1476 "--enable-paeth-intra=0",
1477 "--enable-directional-intra=0",
1478 "--enable-angle-delta=0",
1479 "--enable-tx-size-search=0",
1480 "--enable-cdef=0",
1481 "--enable-restoration=0",
1482 "--max-partition-size=32",
1483 "--min-partition-size=32",
1484 "--enable-palette=0",
1485 "--enable-intrabc=0",
1486 "--enable-cfl-intra=0",
1487 ],
1488 );
1489 assert_eq!(
1490 parsed_bit_depth(&stream),
1491 10,
1492 "{NAME}: aomenc did not actually write a 10-bit sequence header"
1493 );
1494 let before = crate::superres::superres_hits();
1495 let frames = match decode_stream(&stream) {
1496 Ok(frames) => frames,
1497 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1498 };
1499 assert!(
1500 crate::superres::superres_hits() > before,
1501 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
1502 );
1503 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
1504 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
1505 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
1506 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
1507 eprintln!(
1508 "{NAME}: pixel-exact, superres_hits={}",
1509 crate::superres::superres_hits()
1510 );
1511 }
1512
1513 /// lane-hbdgates r1: the four intra tools that had an 8-bit gate and no
1514 /// 10-bit one (`filter-intra`, `smooth-intra`, `paeth-intra`,
1515 /// `intra-edge-filter`) on ONE real 10-bit `aomenc` key frame, each with
1516 /// its own hard-asserted counter. His two films are yuv420p10le, so an
1517 /// 8-bit-only gate for these tools proves nothing about the streams that
1518 /// matter (lane-covbd r1).
1519 #[test]
1520 fn a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact() {
1521 const NAME: &str = "a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact";
1522 if !have_ffmpeg() {
1523 eprintln!("SKIP {NAME}: no ffmpeg");
1524 return;
1525 }
1526 if !have_aomenc() {
1527 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1528 return;
1529 }
1530 ten_bit_tool_gate(
1531 NAME,
1532 64,
1533 64,
1534 1,
1535 &[
1536 "--limit=1",
1537 "--kf-max-dist=0",
1538 "--enable-filter-intra=1",
1539 "--enable-smooth-intra=1",
1540 "--enable-paeth-intra=1",
1541 "--enable-intra-edge-filter=1",
1542 "--enable-directional-intra=1",
1543 "--enable-angle-delta=0",
1544 "--enable-rect-partitions=0",
1545 "--enable-ab-partitions=0",
1546 "--enable-1to4-partitions=0",
1547 "--enable-tx-size-search=0",
1548 "--enable-cdef=0",
1549 "--enable-restoration=0",
1550 "--max-partition-size=32",
1551 "--min-partition-size=16",
1552 "--enable-palette=0",
1553 "--enable-intrabc=0",
1554 "--enable-cfl-intra=0",
1555 "--enable-ref-frame-mvs=0",
1556 ],
1557 &[42, 7, 11, 23, 31, 57],
1558 &[
1559 ("filter_intra_hits", decode::filter_intra_hits),
1560 ("smooth_pred_hits", crate::intra::smooth_pred_hits),
1561 ("paeth_pred_hits", crate::intra::paeth_pred_hits),
1562 (
1563 "intra_edge_filter_hits",
1564 crate::intra::intra_edge_filter_hits,
1565 ),
1566 ],
1567 );
1568 }
1569
1570 /// lane-hbdgates r1: `--enable-restoration=1` at 10 bits. Every earlier
1571 /// bit-depth gate ran `--enable-restoration=0`, which is exactly why two
1572 /// high-bit-depth loop-restoration defects survived to 2026-09-01
1573 /// (SGR box sums unscaled, Wiener clamp at the 8-bit bound). Same recipe
1574 /// as the 8-bit LR gate, at 10 bits.
1575 // Written `#[ignore]`d on lane-hbdgates (the branch lacked lane-hbdinter's
1576 // 10-bit LR fix and failed at seed 42, frame 0, Y index 122: ours 351 vs
1577 // ffmpeg 350). Un-ignored on the merge into main 2026-09-01, where the
1578 // SGR box-sum scaling and the Wiener clamp are fixed: 16/16 attempts
1579 // pixel-exact, lr_hits=28.
1580 #[test]
1581 fn a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact() {
1582 const NAME: &str = "a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact";
1583 if !have_ffmpeg() {
1584 eprintln!("SKIP {NAME}: no ffmpeg");
1585 return;
1586 }
1587 if !have_aomenc() {
1588 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1589 return;
1590 }
1591 // 192x128 = 3x2 superblocks, so `read_lr` is re-entered per SB
1592 // (the 8-bit LR gate's own trap warning); cq-level=15 because
1593 // aomenc's RD only picks a non-RESTORE_NONE frame type at low cq.
1594 ten_bit_tool_gate(
1595 NAME,
1596 192,
1597 128,
1598 1,
1599 &[
1600 "--limit=1",
1601 "--kf-max-dist=0",
1602 "--cq-level=15",
1603 "--enable-restoration=1",
1604 "--enable-cdef=0",
1605 "--enable-rect-partitions=0",
1606 "--enable-ab-partitions=0",
1607 "--enable-1to4-partitions=0",
1608 "--enable-filter-intra=0",
1609 "--enable-smooth-intra=0",
1610 "--enable-paeth-intra=0",
1611 "--enable-tx-size-search=0",
1612 "--max-partition-size=32",
1613 "--min-partition-size=16",
1614 "--enable-palette=0",
1615 "--enable-intrabc=0",
1616 "--enable-cfl-intra=0",
1617 "--enable-ref-frame-mvs=0",
1618 ],
1619 &LR_SEEDS,
1620 &[("lr_hits", ten_bit_lr_hits)],
1621 );
1622 }
1623
1624 /// lane-reelckf2 r1: loop restoration on frame sizes whose LAST stripe is
1625 /// partial, with 128-sample superblocks -- the two stripe shapes whose
1626 /// boundary substitution is special (`filter_restoration_unit`: the first
1627 /// stripe is 8 rows short and takes its above boundary from the frame's
1628 /// own top rows, the last one is truncated and takes its below boundary
1629 /// from the frame's own bottom row) had no gate at all: every earlier LR
1630 /// size (192x128, 160x96) is a whole multiple of 64 rows and ran at
1631 /// `--sb-size=64`. 152 = 2*64+24 and 216 = 3*64+24 both leave a 32-row
1632 /// tail stripe, mirroring the 792-row 10-bit film that made this lane.
1633 /// `lr_stripe0_hits`/`lr_last_stripe_hits` are hard-asserted per attempt
1634 /// by [`ten_bit_tool_gate`], so an RD that picked RESTORE_NONE on either
1635 /// stripe cannot pass.
1636 #[test]
1637 fn a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact() {
1638 const NAME: &str =
1639 "a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact";
1640 if !have_ffmpeg() {
1641 eprintln!("SKIP {NAME}: no ffmpeg");
1642 return;
1643 }
1644 if !have_aomenc() {
1645 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1646 return;
1647 }
1648 // `--sb-size=128` goes in `extra`, which the helper appends AFTER its
1649 // own `--sb-size=64` (aomenc keeps the LAST occurrence of a repeated
1650 // flag, measured 2026-09-02); `--max-partition-size=32` keeps the 128
1651 // root on SPLIT, the only 128-root partition decoded today.
1652 for (width, height, cq) in [
1653 (256usize, 152usize, "15"),
1654 (384, 216, "15"),
1655 (256, 152, "25"),
1656 ] {
1657 ten_bit_tool_gate(
1658 &format!("{NAME} {width}x{height} cq{cq}"),
1659 width,
1660 height,
1661 1,
1662 &[
1663 "--limit=1",
1664 "--kf-max-dist=0",
1665 &format!("--cq-level={cq}"),
1666 "--sb-size=128",
1667 "--enable-restoration=1",
1668 "--enable-cdef=0",
1669 "--enable-rect-partitions=0",
1670 "--enable-ab-partitions=0",
1671 "--enable-1to4-partitions=0",
1672 "--enable-filter-intra=0",
1673 "--enable-smooth-intra=0",
1674 "--enable-paeth-intra=0",
1675 "--enable-tx-size-search=0",
1676 "--max-partition-size=32",
1677 "--min-partition-size=16",
1678 "--enable-palette=0",
1679 "--enable-intrabc=0",
1680 "--enable-cfl-intra=0",
1681 "--enable-ref-frame-mvs=0",
1682 ],
1683 &LR_SEEDS,
1684 &[
1685 ("lr_hits", ten_bit_lr_hits),
1686 ("lr_stripe0_hits", crate::restoration::lr_stripe0_hits),
1687 (
1688 "lr_last_stripe_hits",
1689 crate::restoration::lr_last_stripe_hits,
1690 ),
1691 ],
1692 );
1693 }
1694 }
1695
1696 /// lane-hbdgates r1: `--enable-rect-partitions=1 --enable-ab-partitions=1`
1697 /// at 10 bits, one intra stream, one counter per tool
1698 /// (`rect_partition_hits`, `partab_hits`) so a stream that only fired the
1699 /// rect arms cannot stand in for AB.
1700 #[test]
1701 fn a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact() {
1702 const NAME: &str = "a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact";
1703 if !have_ffmpeg() {
1704 eprintln!("SKIP {NAME}: no ffmpeg");
1705 return;
1706 }
1707 if !have_aomenc() {
1708 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1709 return;
1710 }
1711 // The 8-bit free-partition/AB recipe, verbatim, at 10 bits: AB
1712 // splits are an INTER dispatch here (intra-frame AB is still a named
1713 // refusal), so the stream needs alt-refs and 24 frames, not one key
1714 // frame.
1715 ten_bit_tool_gate(
1716 NAME,
1717 64,
1718 64,
1719 24,
1720 &[
1721 "--cq-level=45",
1722 "--kf-max-dist=1000",
1723 "--auto-alt-ref=1",
1724 "--lag-in-frames=16",
1725 "--enable-fwd-kf=0",
1726 "--enable-order-hint=1",
1727 "--enable-warped-motion=1",
1728 "--enable-obmc=1",
1729 "--tune-content=default",
1730 "--enable-masked-comp=0",
1731 "--enable-interintra-comp=0",
1732 "--enable-onesided-comp=0",
1733 "--enable-interintra-wedge=0",
1734 "--enable-smooth-interintra=0",
1735 "--enable-rect-partitions=1",
1736 "--enable-ab-partitions=1",
1737 "--enable-1to4-partitions=0",
1738 "--enable-filter-intra=0",
1739 "--enable-smooth-intra=0",
1740 "--enable-paeth-intra=0",
1741 "--enable-directional-intra=0",
1742 "--enable-angle-delta=0",
1743 "--enable-tx-size-search=0",
1744 "--enable-cdef=0",
1745 "--enable-restoration=0",
1746 "--max-partition-size=32",
1747 "--min-partition-size=16",
1748 "--enable-palette=0",
1749 "--enable-intrabc=0",
1750 "--enable-cfl-intra=0",
1751 "--enable-ref-frame-mvs=0",
1752 ],
1753 &LR_SEEDS,
1754 &[
1755 ("rect_partition_hits", decode::rect_partition_hits),
1756 ("partab_hits", decode::partab_hits),
1757 ],
1758 );
1759 }
1760
1761 /// lane-obmcrec r1: OBMC whose above/left neighbour is a 4-wide/4-tall
1762 /// 1:4-partition strip -- the shape the three 1080p 10-bit film cuts
1763 /// refused on ("an OBMC neighbour whose switchable interp filter was never
1764 /// recorded"). `overlappable_above`/`_left` snap such a neighbour to the
1765 /// chroma pair's SECOND mi but used to read its interp filter from the
1766 /// FIRST one, a different block whose filter record is the intra
1767 /// `[3, 3]` sentinel whenever that half is intra. `obmc_pair_filter_hits`
1768 /// counts exactly that neighbour shape, so a stream without 1:4 strips
1769 /// next to an OBMC block cannot stand in for it.
1770 #[test]
1771 fn a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact() {
1772 const NAME: &str =
1773 "a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact";
1774 if !have_ffmpeg() {
1775 eprintln!("SKIP {NAME}: no ffmpeg");
1776 return;
1777 }
1778 if !have_aomenc() {
1779 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1780 return;
1781 }
1782 ten_bit_tool_gate(
1783 NAME,
1784 128,
1785 128,
1786 24,
1787 &[
1788 "--ec-fixture-noise",
1789 "--cq-level=45",
1790 "--kf-max-dist=1000",
1791 "--auto-alt-ref=1",
1792 "--lag-in-frames=16",
1793 "--enable-fwd-kf=0",
1794 "--enable-order-hint=1",
1795 "--enable-warped-motion=0",
1796 "--enable-obmc=1",
1797 "--tune-content=default",
1798 "--enable-masked-comp=0",
1799 "--enable-interintra-comp=0",
1800 "--enable-onesided-comp=0",
1801 "--enable-interintra-wedge=0",
1802 "--enable-smooth-interintra=0",
1803 "--enable-rect-partitions=1",
1804 "--enable-ab-partitions=0",
1805 "--enable-1to4-partitions=1",
1806 "--enable-filter-intra=0",
1807 "--enable-smooth-intra=0",
1808 "--enable-paeth-intra=0",
1809 "--enable-directional-intra=0",
1810 "--enable-angle-delta=0",
1811 "--enable-tx-size-search=0",
1812 "--enable-cdef=0",
1813 "--enable-restoration=0",
1814 "--max-partition-size=32",
1815 "--min-partition-size=4",
1816 "--enable-palette=0",
1817 "--enable-intrabc=0",
1818 "--enable-cfl-intra=0",
1819 "--enable-ref-frame-mvs=0",
1820 ],
1821 &OBMC_PAIR_SEEDS,
1822 &[("obmc_pair_filter_hits", decode::obmc_pair_filter_hits)],
1823 );
1824 }
1825
1826 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
1827 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
1828 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
1829 /// which flattened chroma to a single value specifically to avoid
1830 /// exercising this path). Same square-only recipe as the palette-Y gate
1831 /// (`--enable-rect-partitions=0`/`-ab-`/`-1to4-`, fixed 32x32 partition)
1832 /// so a UV palette block never lands inside the still-refused HORZ/VERT
1833 /// screen-content strip. HARD-asserts [`decode::palette_uv_hits`] moved
1834 /// -- a stream that never reads a real UV palette block would decode (or
1835 /// not) by construction without proving this milestone at all
1836 /// ([[gate-blind-to-feature]]).
1837 #[test]
1838 fn a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact() {
1839 const NAME: &str = "a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact";
1840 if !have_ffmpeg() {
1841 eprintln!("SKIP {NAME}: no ffmpeg");
1842 return;
1843 }
1844 if !have_aomenc() {
1845 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1846 return;
1847 }
1848 let source = "testsrc2=size=64x64:rate=25";
1849 fn render(source: &str) -> Vec<u8> {
1850 crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1851 .args([
1852 "-v",
1853 "error",
1854 "-f",
1855 "lavfi",
1856 "-i",
1857 source,
1858 "-pix_fmt",
1859 "yuv420p",
1860 "-t",
1861 "0.16",
1862 "-f",
1863 "yuv4mpegpipe",
1864 "-",
1865 ])
1866 .stdin(Stdio::null())
1867 .stdout(Stdio::piped())
1868 .stderr(Stdio::piped()), None, |c| c.output())
1869 .expect("ffmpeg failed to run")
1870 .stdout
1871 }
1872 let y4m_a = render(source);
1873 let y4m_b = render(source);
1874 assert_eq!(
1875 y4m_a, y4m_b,
1876 "testsrc2 must render byte-identical across two runs"
1877 );
1878 let y4m = y4m_a;
1879 let out = run_with_stdin(
1880 Command::new(aomenc_path()).args([
1881 "--codec=av1",
1882 "--passes=1",
1883 "--end-usage=q",
1884 "--cq-level=30",
1885 "--cpu-used=0",
1886 "--threads=1",
1887 "--row-mt=0",
1888 "--sb-size=64",
1889 "--tune-content=screen",
1890 "--enable-palette=1",
1891 "--enable-intrabc=0",
1892 "--enable-rect-partitions=0",
1893 "--enable-ab-partitions=0",
1894 "--enable-1to4-partitions=0",
1895 "--min-partition-size=32",
1896 "--max-partition-size=32",
1897 "--enable-filter-intra=0",
1898 "--enable-cdef=0",
1899 "--enable-restoration=0",
1900 "--enable-tx-size-search=0",
1901 "--loopfilter-control=0",
1902 "--obu",
1903 "-o",
1904 "-",
1905 "-",
1906 ]),
1907 &y4m,
1908 );
1909 assert!(
1910 out.status.success(),
1911 "aomenc refused the fixture: {}",
1912 String::from_utf8_lossy(&out.stderr)
1913 );
1914 let stream = out.stdout;
1915 let before = decode::palette_uv_hits();
1916 let frames = match decode_stream(&stream) {
1917 Ok(frames) => frames,
1918 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1919 };
1920 assert!(
1921 decode::palette_uv_hits() > before,
1922 "palette_uv_mode never fired decoding this stream -- gate is vacuous"
1923 );
1924 let frame_count = frames.len();
1925 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, frame_count);
1926 for i in 0..frame_count {
1927 assert_eq!(frames[i].y, ffmpeg_frames[i].y, "luma vs ffmpeg, frame {i}");
1928 assert_eq!(frames[i].u, ffmpeg_frames[i].u, "U vs ffmpeg, frame {i}");
1929 assert_eq!(frames[i].v, ffmpeg_frames[i].v, "V vs ffmpeg, frame {i}");
1930 }
1931 }
1932
1933 /// A real `aomenc` fixture that lands palette syntax on a HORZ/VERT
1934 /// intra strip (lane-palette2 r5, gating r4's `read_intra_mode_rect`
1935 /// wiring). `smptebars`/`rgbtestsrc` at plain default settings both hit a
1936 /// SQUARE palette refusal or an unrelated 32x32 `HORZ_A`/`VERT_A`/etc
1937 /// partition FIRST on every size/cq combo probed -- `--enable-ab-
1938 /// partitions=0` measurably does not stop aomenc choosing one at this
1939 /// screen-content tune (byte-identical output with `=0` vs `=1`, same
1940 /// aomenc quirk as `[[lane-sbpart-r2]]`'s SB-level AB). Forcing
1941 /// `--min/max-partition-size=64` sidesteps that whole 32x32-level code
1942 /// path: the only choices left at the (single, key-frame) superblock are
1943 /// NONE/SPLIT/HORZ/VERT/AB/1to4 straight from [`decode_block_rect64`],
1944 /// and a size/cq sweep (measured live this round) reliably lands
1945 /// PARTITION_HORZ/VERT with a real (non-split-tx) palette block on both
1946 /// sources. Drives `decode_stream` directly (below any refusal) and
1947 /// HARD-asserts [`decode::palette_rect_hits`] moved on every attempt that
1948 /// didn't refuse, before comparing pixels ([[gate-blind-to-feature]]) --
1949 /// a decode that never lands a rect palette block is not a match.
1950 #[test]
1951 fn a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact() {
1952 const NAME: &str = "a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact";
1953 let _gate_lock = lock_gate_counters();
1954 if !have_ffmpeg() {
1955 eprintln!("SKIP {NAME}: no ffmpeg");
1956 return;
1957 }
1958 if !have_aomenc() {
1959 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1960 return;
1961 }
1962 let mut matched = 0u32;
1963 let mut uncounted_exact = 0u32;
1964 let mut named_refusals = 0u32;
1965 let mut attempts = 0u32;
1966 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
1967 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
1968 for src_name in ["smptebars", "rgbtestsrc"] {
1969 for (width, height) in sizes {
1970 for cq in cqs {
1971 attempts += 1;
1972 let source = format!("{src_name}=size={width}x{height}:rate=25");
1973 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1974 .args([
1975 "-v",
1976 "error",
1977 "-f",
1978 "lavfi",
1979 "-i",
1980 &source,
1981 "-pix_fmt",
1982 "yuv420p",
1983 "-t",
1984 "0.04",
1985 "-f",
1986 "yuv4mpegpipe",
1987 "-",
1988 ])
1989 .stdin(Stdio::null())
1990 .stdout(Stdio::piped())
1991 .stderr(Stdio::piped()), None, |c| c.output())
1992 .expect("ffmpeg failed to run");
1993 assert!(
1994 y4m.status.success(),
1995 "ffmpeg fixture: {}",
1996 String::from_utf8_lossy(&y4m.stderr)
1997 );
1998 let cq_arg = format!("--cq-level={cq}");
1999 let out = run_with_stdin(
2000 Command::new(aomenc_path()).args([
2001 "--codec=av1",
2002 "--passes=1",
2003 "--end-usage=q",
2004 &cq_arg,
2005 "--cpu-used=4",
2006 "--threads=1",
2007 "--row-mt=0",
2008 "--sb-size=64",
2009 "--enable-palette=1",
2010 "--min-partition-size=16",
2011 "--max-partition-size=64",
2012 "--obu",
2013 "-o",
2014 "-",
2015 "-",
2016 ]),
2017 &y4m.stdout,
2018 );
2019 assert!(
2020 out.status.success(),
2021 "aomenc refused the fixture ({source} cq={cq}): {}",
2022 String::from_utf8_lossy(&out.stderr)
2023 );
2024 let stream = out.stdout;
2025 let before = crate::decode::palette_rect_hits();
2026 let frames = match decode_stream(&stream) {
2027 Err(e) => {
2028 let msg = e.to_string();
2029 assert!(
2030 msg.contains("unsupported"),
2031 "{NAME} failed outright, not a named refusal \
2032 ({source} cq={cq}): {msg}"
2033 );
2034 named_refusals += 1;
2035 eprintln!("{source} cq={cq}: refusal: {msg}");
2036 continue;
2037 }
2038 Ok(frames) => frames,
2039 };
2040 // A successful decode is ALWAYS pixel-compared; the hit
2041 // counter only decides whether the attempt counts toward
2042 // the hit-asserting total (class
2043 // [[gate-skips-on-its-own-failure]]: the old `continue`
2044 // here let 16/70 decoded attempts past without any pixel
2045 // check at all).
2046 let counted = crate::decode::palette_rect_hits() != before;
2047 if !counted {
2048 eprintln!(
2049 "{NAME}: {source} cq={cq} decoded without ever landing a rect \
2050 palette block (palette_rect_hits unchanged) -- pixel-compared, \
2051 not counted toward the hit assertion"
2052 );
2053 }
2054 let frame_count = frames.len();
2055 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2056 if frames
2057 .iter()
2058 .zip(&ffmpeg_frames)
2059 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v)
2060 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
2061 {
2062 std::fs::write(&path, &stream).expect("writing pinned stream");
2063 eprintln!(
2064 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
2065 );
2066 }
2067 for i in 0..frame_count {
2068 assert_eq!(
2069 frames[i].y, ffmpeg_frames[i].y,
2070 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
2071 );
2072 assert_eq!(
2073 frames[i].u, ffmpeg_frames[i].u,
2074 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
2075 );
2076 assert_eq!(
2077 frames[i].v, ffmpeg_frames[i].v,
2078 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
2079 );
2080 }
2081 if counted {
2082 matched += 1;
2083 } else {
2084 uncounted_exact += 1;
2085 }
2086 }
2087 }
2088 }
2089 assert!(
2090 matched > 0,
2091 "{NAME}: no attempt out of {attempts} ever landed a matching rect palette \
2092 block ({named_refusals} named refusals) -- palette_rect_hits never proven \
2093 pixel-exact"
2094 );
2095 eprintln!(
2096 "{NAME}: {matched}/{attempts} attempts matched pixel-exact, \
2097 {uncounted_exact} decoded-and-pixel-exact but uncounted, {named_refusals} \
2098 named refusals, palette_rect_hits={}",
2099 crate::decode::palette_rect_hits()
2100 );
2101 }
2102
2103 /// The BROAD case (lane-palette2 r6, per its charter): a HORZ/VERT intra
2104 /// strip in a screen-content-tools frame that does NOT necessarily use a
2105 /// palette. This is what the refusal r4 removed actually guarded --
2106 /// [`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`] above
2107 /// gates the rarer "and picks a palette" case, which r5 measured RD
2108 /// almost never chooses -- 39/70 of that same sweep DID land here (a
2109 /// clean rect-strip decode with `palette_rect_hits` unchanged), just
2110 /// uncounted by r5's narrower assertion. Same `--min/max-partition-size=64`
2111 /// recipe r5 measured live to dodge the 32x32-level AB-partition quirk
2112 /// ([[lane-sbpart-r2]]), single key frame, size/cq sweep. HARD-asserts
2113 /// [`decode::rect_screen_content_hits`] moved -- proof this stream
2114 /// actually ran [`read_intra_mode_rect`]'s screen-content-tools branch --
2115 /// before comparing pixels.
2116 #[test]
2117 fn a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact() {
2118 const NAME: &str = "a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact";
2119 let _gate_lock = lock_gate_counters();
2120 if !have_ffmpeg() {
2121 eprintln!("SKIP {NAME}: no ffmpeg");
2122 return;
2123 }
2124 if !have_aomenc() {
2125 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2126 return;
2127 }
2128 let mut matched = 0u32;
2129 // Blocks that reconstructed a palette-Y prediction through a SPLIT
2130 // luma transform (lane-palette2 r7's lifted refusal): the same
2131 // screen-content streams exercise it, so this gate proves both.
2132 let mut split_palette_matched = 0u32;
2133 let mut uncounted_exact = 0u32;
2134 let mut named_refusals = 0u32;
2135 let mut attempts = 0u32;
2136 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
2137 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
2138 for src_name in ["smptebars", "rgbtestsrc"] {
2139 for (width, height) in sizes {
2140 for cq in cqs {
2141 attempts += 1;
2142 let source = format!("{src_name}=size={width}x{height}:rate=25");
2143 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2144 .args([
2145 "-v",
2146 "error",
2147 "-f",
2148 "lavfi",
2149 "-i",
2150 &source,
2151 "-pix_fmt",
2152 "yuv420p",
2153 "-t",
2154 "0.04",
2155 "-f",
2156 "yuv4mpegpipe",
2157 "-",
2158 ])
2159 .stdin(Stdio::null())
2160 .stdout(Stdio::piped())
2161 .stderr(Stdio::piped()), None, |c| c.output())
2162 .expect("ffmpeg failed to run");
2163 assert!(
2164 y4m.status.success(),
2165 "ffmpeg fixture: {}",
2166 String::from_utf8_lossy(&y4m.stderr)
2167 );
2168 let cq_arg = format!("--cq-level={cq}");
2169 let out = run_with_stdin(
2170 Command::new(aomenc_path()).args([
2171 "--codec=av1",
2172 "--passes=1",
2173 "--end-usage=q",
2174 &cq_arg,
2175 "--cpu-used=4",
2176 "--threads=1",
2177 "--row-mt=0",
2178 "--sb-size=64",
2179 "--enable-palette=1",
2180 "--min-partition-size=16",
2181 "--max-partition-size=64",
2182 "--obu",
2183 "-o",
2184 "-",
2185 "-",
2186 ]),
2187 &y4m.stdout,
2188 );
2189 assert!(
2190 out.status.success(),
2191 "aomenc refused the fixture ({source} cq={cq}): {}",
2192 String::from_utf8_lossy(&out.stderr)
2193 );
2194 let stream = out.stdout;
2195 let before = crate::decode::rect_screen_content_hits();
2196 let split_before = crate::decode::palette_split_tx_hits();
2197 let frames = match decode_stream(&stream) {
2198 Err(e) => {
2199 let msg = e.to_string();
2200 assert!(
2201 msg.contains("unsupported"),
2202 "{NAME} failed outright, not a named refusal \
2203 ({source} cq={cq}): {msg}"
2204 );
2205 named_refusals += 1;
2206 eprintln!("{source} cq={cq}: refusal: {msg}");
2207 continue;
2208 }
2209 Ok(frames) => frames,
2210 };
2211 // Same integrity rule as the palette gate above: decoded
2212 // means pixel-compared, counter or no counter.
2213 let counted = crate::decode::rect_screen_content_hits() != before;
2214 if !counted {
2215 eprintln!(
2216 "{NAME}: {source} cq={cq} decoded without ever running the rect \
2217 screen-content path (rect_screen_content_hits unchanged) -- \
2218 pixel-compared, not counted toward the hit assertion"
2219 );
2220 }
2221 let frame_count = frames.len();
2222 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2223 if frames
2224 .iter()
2225 .zip(&ffmpeg_frames)
2226 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v)
2227 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
2228 {
2229 std::fs::write(&path, &stream).expect("writing pinned stream");
2230 eprintln!(
2231 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
2232 );
2233 }
2234 for i in 0..frame_count {
2235 assert_eq!(
2236 frames[i].y, ffmpeg_frames[i].y,
2237 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
2238 );
2239 assert_eq!(
2240 frames[i].u, ffmpeg_frames[i].u,
2241 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
2242 );
2243 assert_eq!(
2244 frames[i].v, ffmpeg_frames[i].v,
2245 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
2246 );
2247 }
2248 if counted {
2249 matched += 1;
2250 } else {
2251 uncounted_exact += 1;
2252 }
2253 if counted && crate::decode::palette_split_tx_hits() > split_before {
2254 split_palette_matched += 1;
2255 }
2256 }
2257 }
2258 }
2259 assert!(
2260 split_palette_matched > 0,
2261 "{NAME}: no pixel-exact attempt ever reconstructed a palette block with a \
2262 split luma transform -- the lifted refusal is ungated"
2263 );
2264 assert!(
2265 matched > 0,
2266 "{NAME}: no attempt out of {attempts} ever landed a matching rect \
2267 screen-content block ({named_refusals} named refusals) -- \
2268 rect_screen_content_hits never proven pixel-exact"
2269 );
2270 eprintln!(
2271 "{NAME}: {matched}/{attempts} attempts matched pixel-exact \
2272 ({split_palette_matched} of them through a split-transform palette block), \
2273 {uncounted_exact} decoded-and-pixel-exact but uncounted, \
2274 {named_refusals} named refusals, rect_screen_content_hits={}, \
2275 palette_split_tx_hits={}",
2276 crate::decode::rect_screen_content_hits(),
2277 crate::decode::palette_split_tx_hits()
2278 );
2279 }
2280
2281 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s
2282 /// harness, but with the deblocking filter left *on* (no
2283 /// `--loopfilter-control=0`) at a crf high enough that libaom actually
2284 /// picks a nonzero level -- proves `apply_deblock` itself, not just that
2285 /// this decoder still works when every edge lands on level 0. CDEF
2286 /// stays off so a pixel mismatch can only come from the loop filter.
2287 ///
2288 /// lane-av1skipfix: the attempt-loop shape. The sweep walks cq (which is
2289 /// what decides whether libaom picks a nonzero deblocking level at all)
2290 /// and seed, REQUIRES at least one attempt to decode, and hard-asserts
2291 /// `decode::deblock_hits` on a pixel-compared attempt -- a decode error on
2292 /// every attempt is a hard failure carrying the refusal texts, never a
2293 /// printed SKIP (class `gate-skips-on-its-own-failure`). MEASURED
2294 /// 2026-09-29 on `a21f3680`: cq 55/45/35/63 all decode pixel-exact with
2295 /// 48/64/64/64 deblock edges, so the old single recipe was one lucky
2296 /// point of a cq range that needed no fallback.
2297 #[test]
2298 fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() {
2299 const NAME: &str = "a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact";
2300 let _gate_lock = lock_gate_counters();
2301 if !have_ffmpeg() {
2302 eprintln!("SKIP {NAME}: no ffmpeg");
2303 return;
2304 }
2305 if !have_aomenc() {
2306 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2307 return;
2308 }
2309 let (width, height) = (64usize, 64usize);
2310 // Two seeds x four quantisers.
2311 const CQS: [u32; 4] = [55, 45, 35, 63];
2312 let mut refusals = Vec::new();
2313 let mut counted_exact = 0u32;
2314 let mut uncounted_exact = 0u32;
2315 'attempts: for round in 0..2u32 {
2316 for cq in CQS {
2317 let source = gradients_source(42 + round, width, height, "duration=0.04:rate=25");
2318 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2319 .args(["-v", "error", "-f", "lavfi", "-i"])
2320 .arg(&source)
2321 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
2322 .stdin(Stdio::null())
2323 .stdout(Stdio::piped())
2324 .stderr(Stdio::piped()), None, |c| c.output())
2325 .expect("ffmpeg failed to run");
2326 assert!(
2327 y4m.status.success(),
2328 "{NAME}: ffmpeg fixture (seed {} cq {cq}): {}",
2329 42 + round,
2330 String::from_utf8_lossy(&y4m.stderr)
2331 );
2332 let cq_arg = format!("--cq-level={cq}");
2333 let out = run_with_stdin(
2334 Command::new(aomenc_path()).args([
2335 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
2336 // occurrence, so overrides go before the base list).
2337 "--loopfilter-control=1",
2338 "--codec=av1",
2339 "--passes=1",
2340 "--end-usage=q",
2341 &cq_arg,
2342 "--cpu-used=0",
2343 "--enable-filter-intra=0",
2344 "--enable-smooth-intra=0",
2345 "--enable-paeth-intra=0",
2346 "--enable-directional-intra=0",
2347 "--enable-angle-delta=0",
2348 "--enable-tx-size-search=0",
2349 "--enable-cdef=0",
2350 // Loop restoration is a named refusal (aomenc's RD picks
2351 // Sgrproj on this kind of content) -- off in every recipe
2352 // whose test targets a different surface.
2353 "--enable-restoration=0",
2354 "--max-partition-size=32",
2355 "--enable-palette=0",
2356 "--enable-intrabc=0",
2357 "--enable-cfl-intra=0",
2358 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
2359 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
2360 "--enable-ref-frame-mvs=0",
2361 "--obu",
2362 "-o",
2363 "-",
2364 "-",
2365 ]),
2366 &y4m.stdout,
2367 );
2368 assert!(
2369 out.status.success(),
2370 "{NAME}: aomenc refused the seed {} cq {cq} fixture: {}",
2371 42 + round,
2372 String::from_utf8_lossy(&out.stderr)
2373 );
2374 let stream = out.stdout;
2375 let before = decode::deblock_hits();
2376 let frames = match decode_stream(&stream) {
2377 Ok(frames) => frames,
2378 Err(e) => {
2379 refusals.push(format!("seed {} cq {cq}: {e}", 42 + round));
2380 continue;
2381 }
2382 };
2383 // A decode that succeeded is ALWAYS pixel-compared; the hit
2384 // counter only decides whether the attempt counts as firing
2385 // (class `counter-from-refused-stream`).
2386 let counted = decode::deblock_hits() != before;
2387 if counted {
2388 counted_exact += 1;
2389 } else {
2390 uncounted_exact += 1;
2391 }
2392 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
2393 assert_eq!(
2394 frames[0].y,
2395 ffmpeg_frames[0].y,
2396 "luma vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})",
2397 42 + round
2398 );
2399 assert_eq!(
2400 frames[0].u,
2401 ffmpeg_frames[0].u,
2402 "U vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})",
2403 42 + round
2404 );
2405 assert_eq!(
2406 frames[0].v,
2407 ffmpeg_frames[0].v,
2408 "V vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})",
2409 42 + round
2410 );
2411 if counted_exact >= 2 {
2412 break 'attempts;
2413 }
2414 }
2415 }
2416 gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
2417 assert!(
2418 counted_exact > 0,
2419 "{NAME}: none of {} attempts decoded a stream with a deblocking edge -- \
2420 apply_deblock is unproven (class gate-blind-to-feature):\n{}",
2421 CQS.len() * 2,
2422 refusals.join("\n")
2423 );
2424 }
2425
2426 /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`],
2427 /// but WITHOUT `--enable-tx-size-search=0` -- the one flag every other
2428 /// recipe in this file pins off specifically to keep the stream on
2429 /// `TxMode::Largest`. Dropped, aomenc's RD is free to pick
2430 /// `TxMode::Select` and split some blocks' luma transform below their own
2431 /// side (spec 5.11.16), which is what this test's `tx_depth_hits()`
2432 /// counter proves actually happened -- a stream that resolves every
2433 /// `tx_depth` to 0 would pixel-match by construction (identical to
2434 /// `TxMode::Largest`) without exercising the new split-TU decode path at
2435 /// all. Same multi-seed retry shape as
2436 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]:
2437 /// aomenc's own RD is free (with tx-size search on) to also occasionally
2438 /// pick `allow_screen_content_tools` on this content, a separate,
2439 /// already-named refusal -- try several seeds, and the first stream that
2440 /// both decodes AND actually split a transform must be pixel-exact.
2441 #[test]
2442 fn a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact() {
2443 if !have_ffmpeg() {
2444 eprintln!(
2445 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no ffmpeg"
2446 );
2447 return;
2448 }
2449 if !have_aomenc() {
2450 eprintln!(
2451 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no aomenc at {}",
2452 aomenc_path().display()
2453 );
2454 return;
2455 }
2456 let (width, height) = (64usize, 64usize);
2457 let mut refusals = Vec::new();
2458 let mut uncounted_exact = 0u32;
2459 for attempt in 0..40u32 {
2460 let seed = 42 + attempt;
2461 // A flat gradient never has enough local detail for the RD
2462 // search to prefer a split transform over the block's own full
2463 // size -- `mandelbrot`'s fractal boundary gives every attempt
2464 // (a different `start_scale`) sharp, varied-frequency edges.
2465 // start_scale 5.0 is the proven first try (decodes pixel-exact
2466 // AND reads the seven-symbol set-1 tx_type rows on TX8 TUs);
2467 // later attempts walk down for variety when aomenc's RD flips
2468 // elsewhere.
2469 let source = format!(
2470 "mandelbrot=size=64x64:start_scale={}:rate=25",
2471 5.0 - f64::from(attempt) * 0.06
2472 );
2473 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2474 .args([
2475 "-v",
2476 "error",
2477 "-f",
2478 "lavfi",
2479 "-i",
2480 &source,
2481 // Desaturated: chroma stays flat (constant 128) so
2482 // `uv_mode` always resolves to `DC_PRED` and this
2483 // decoder's still-unsupported directional-chroma round-2
2484 // gap never fires, leaving the luma detail alone to
2485 // drive whether `TxMode::Select`'s RD splits a block.
2486 "-vf",
2487 "hue=s=0",
2488 "-pix_fmt",
2489 "yuv420p",
2490 "-t",
2491 "0.04",
2492 "-f",
2493 "yuv4mpegpipe",
2494 "-",
2495 ])
2496 .stdin(Stdio::null())
2497 .stdout(Stdio::piped())
2498 .stderr(Stdio::piped()), None, |c| c.output())
2499 .expect("ffmpeg failed to run");
2500 assert!(
2501 y4m.status.success(),
2502 "ffmpeg fixture: {}",
2503 String::from_utf8_lossy(&y4m.stderr)
2504 );
2505 let out = run_with_stdin(
2506 Command::new(aomenc_path()).args([
2507 "--codec=av1",
2508 "--passes=1",
2509 "--end-usage=q",
2510 "--cq-level=45",
2511 "--cpu-used=0",
2512 "--enable-rect-partitions=0",
2513 "--enable-ab-partitions=0",
2514 "--enable-1to4-partitions=0",
2515 "--enable-filter-intra=0",
2516 // Every non-DC intra tool off: directional chroma and
2517 // angle deltas are separate round-2 gaps, and DC-only
2518 // residual is exactly what gives the RD search a reason
2519 // to split a transform.
2520 "--enable-smooth-intra=0",
2521 "--enable-paeth-intra=0",
2522 "--enable-directional-intra=0",
2523 "--enable-angle-delta=0",
2524 "--enable-cdef=0",
2525 // Loop restoration is a named refusal (aomenc's RD picks
2526 // Sgrproj on this kind of content) -- off in every recipe
2527 // whose test targets a different surface.
2528 "--enable-restoration=0",
2529 "--max-partition-size=32",
2530 // 16x16 blocks are what split into the TX8 TUs whose
2531 // set-1 tx_type rows this gate exists to prove; some
2532 // scales resolve depth 2 (TX4, a named refusal) and the
2533 // attempt loop just moves on.
2534 "--min-partition-size=16",
2535 "--enable-palette=0",
2536 "--enable-intrabc=0",
2537 "--enable-cfl-intra=0",
2538 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
2539 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
2540 "--enable-ref-frame-mvs=0",
2541 "--obu",
2542 "-o",
2543 "-",
2544 "-",
2545 ]),
2546 &y4m.stdout,
2547 );
2548 assert!(
2549 out.status.success(),
2550 "aomenc refused the fixture: {}",
2551 String::from_utf8_lossy(&out.stderr)
2552 );
2553 let stream = out.stdout;
2554 let before = decode::tx_depth_hits();
2555 let frames = match decode_stream(&stream) {
2556 Ok(frames) => frames,
2557 Err(e) => {
2558 refusals.push(format!("seed {seed}: {e}"));
2559 continue;
2560 }
2561 };
2562 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
2563 // is ALWAYS pixel-compared below; the hit counter only decides whether
2564 // the attempt counts toward the firing total.
2565 let counted = decode::tx_depth_hits() != before;
2566 if !counted {
2567 uncounted_exact += 1;
2568 refusals.push(format!(
2569 "seed {seed}: decoded and pixel-compared, but no block resolved a split \
2570 tx_depth"
2571 ));
2572 }
2573 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
2574 assert_eq!(
2575 frames[0].y, ffmpeg_frames[0].y,
2576 "luma vs ffmpeg (seed {seed})"
2577 );
2578 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
2579 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
2580 if counted {
2581 gate_buckets(
2582 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
2583 1,
2584 uncounted_exact,
2585 refusals.len() - uncounted_exact as usize,
2586 );
2587 return;
2588 }
2589 }
2590 gate_buckets(
2591 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
2592 0,
2593 uncounted_exact,
2594 refusals.len() - uncounted_exact as usize,
2595 );
2596 eprintln!(
2597 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: every attempt \
2598 hit a named refusal or never split a transform:\n{}",
2599 refusals.join("\n")
2600 );
2601 }
2602
2603 /// lane-txselect's decisive gate: a real aomenc INTER sequence WITHOUT
2604 /// `--enable-tx-size-search=0`, the flag every other inter recipe in this
2605 /// file pins off precisely to keep the stream on `TxMode::Largest`.
2606 /// Dropped, aomenc takes its own default (`TX_MODE_SELECT` -- which is
2607 /// what both of the user's real films use), and an inter block's
2608 /// transform size is then the recursive `txfm_split` tree of spec
2609 /// 5.11.17 rather than one whole-block transform. A stream that decoded
2610 /// pixel-exact while every `txfm_split` symbol resolved to "no split"
2611 /// would prove nothing (it is `TxMode::Largest` by another name), so this
2612 /// gate hard-asserts BOTH counters: at least one `txfm_split` symbol read
2613 /// AND at least one split actually taken. Exhausting every attempt is a
2614 /// FAILURE, not a SKIP -- an unfired gate is a vacuous gate.
2615 #[test]
2616 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact() {
2617 tx_select_inter_gate(8);
2618 }
2619
2620 /// The 10-bit arm of the gate above (lane-txselect r2): both of the
2621 /// user's films are `yuv420p10le` and var-tx is exactly the tool they
2622 /// use, so an 8-bit-only proof would not reach them. Same recipe plus
2623 /// `-b 10 --input-bit-depth=10`.
2624 #[test]
2625 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact_10bit() {
2626 tx_select_inter_gate(10);
2627 }
2628
2629 /// lane-intrarect r1's decisive gate: a real aomenc INTER sequence whose
2630 /// hard mid-GOP content cut makes aomenc code INTRA blocks inside inter
2631 /// frames, with rect partitions ON so those intra blocks land on
2632 /// HORZ/VERT strip shapes. Every such block was the named refusal "an
2633 /// intra-coded HORZ/VERT strip needs rectangular intra prediction this
2634 /// decoder does not code yet" until this round; they now decode through
2635 /// the same `decode_rect_split` machinery the key-frame rect paths use.
2636 ///
2637 /// Hard-asserts per-shape counters (`intra_rect_strip_in_inter_hits`:
2638 /// 0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16) summed over the
2639 /// attempts that were actually pixel-compared -- at least TWO of the
2640 /// three shape classes must fire, so a green run cannot come from one
2641 /// lucky size. A decode that succeeds is ALWAYS pixel-compared (class
2642 /// [[gate-skips-on-its-own-failure]]); exhausting every attempt without
2643 /// two shapes is a FAILURE, never a SKIP.
2644 #[test]
2645 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact() {
2646 intra_rect_in_inter_gate(8);
2647 }
2648
2649 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
2650 #[test]
2651 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact_10bit() {
2652 intra_rect_in_inter_gate(10);
2653 }
2654
2655 /// lane-intrainter r1's decisive gate: a real aomenc INTER sequence in
2656 /// which aomenc's RD picks an INTRA block inside an inter frame AND
2657 /// splits that block's luma transform (`tx_depth >= 1`, the intra depth
2658 /// symbol -- not the inter var-tx tree). That block codes one intra
2659 /// prediction plus one coefficient set per transform unit, exactly like a
2660 /// key frame's split block but with the inter frame's CDF state and the
2661 /// inter-frame intra mode syntax; before this lane it was a named
2662 /// refusal. Hard-asserts [`decode::intra_in_inter_split_tx_hits`] per
2663 /// block size: an attempt that never produced such a block proves
2664 /// nothing, and exhausting every attempt is a FAILURE, not a SKIP.
2665 #[test]
2666 fn a_real_aomenc_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
2667 intra_in_inter_split_tx_gate(8);
2668 }
2669
2670 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
2671 #[test]
2672 fn a_real_aomenc_10bit_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
2673 intra_in_inter_split_tx_gate(10);
2674 }
2675
2676 /// lane-fiinter r1 (class [[symbol-consumption-gap]] +
2677 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
2678 /// `--enable-filter-intra=1` (aomenc's own default -- every inter gate
2679 /// recipe before this one pinned it OFF, so nothing ever exercised it) in
2680 /// which the RD picks an INTRA block inside an inter frame and gives it
2681 /// filter intra. `read_intra_block_mode_info` reads `use_filter_intra`
2682 /// there exactly as a key frame does; this decoder read no such symbol at
2683 /// all until this round, so such a stream desynced at that symbol and
2684 /// decoded silently wrong. Hard-asserts
2685 /// [`decode::intra_in_inter_filter_intra_hits`]: an attempt that never
2686 /// produced one proves nothing, and exhausting every attempt is a
2687 /// FAILURE, not a SKIP.
2688 #[test]
2689 fn a_real_aomenc_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact() {
2690 filter_intra_in_inter_gate(8);
2691 }
2692
2693 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
2694 #[test]
2695 fn a_real_aomenc_10bit_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact()
2696 {
2697 filter_intra_in_inter_gate(10);
2698 }
2699
2700 /// lane-angleinter r1 (class [[refusal-strings-are-claims]] +
2701 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
2702 /// `--enable-angle-delta=1` and `--enable-directional-intra=1` (aomenc's
2703 /// own defaults; every inter gate before this one pinned BOTH off) in
2704 /// which the RD gives an INTRA block inside an inter frame a directional
2705 /// luma mode with a nonzero `angle_delta_y`. Both intra-in-inter arms
2706 /// read that symbol and then REFUSED it as "this encoder never writes
2707 /// one" -- the claim is false, `read_intra_angle_info` writes it exactly
2708 /// as a key frame does. Hard-asserts
2709 /// [`decode::intra_in_inter_angle_delta_y_hits`]; an attempt that never
2710 /// produced one proves nothing, and exhausting every attempt is a
2711 /// FAILURE, not a SKIP.
2712 #[test]
2713 fn a_real_aomenc_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
2714 {
2715 angle_delta_in_inter_gate(8, "--min-partition-size=16");
2716 }
2717
2718 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
2719 #[test]
2720 fn a_real_aomenc_10bit_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
2721 {
2722 angle_delta_in_inter_gate(10, "--min-partition-size=16");
2723 }
2724
2725 /// lane-uv8 r1 (classes [[refusal-strings-are-claims]] +
2726 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
2727 /// 8x8 partitions and full chroma intra tooling
2728 /// (`--enable-cfl-intra=1 --enable-smooth-intra=1 --enable-paeth-intra=1
2729 /// --enable-directional-intra=1`), in which the RD gives an INTRA 8x8
2730 /// leaf inside an inter frame a NON-DC `uv_mode`. That leaf
2731 /// ([`decode::decode_inter_block8`]'s intra arm) read the `uv_mode`
2732 /// symbol and refused every value but `DC_PRED` -- "this encoder never
2733 /// writes one" was a claim, and this gate is what contradicts it. Hard-
2734 /// asserts `decode::intra_in_inter8_uv_hits` (directional, smooth/paeth,
2735 /// CfL, counted on THIS leaf only); an attempt that never produced one
2736 /// proves nothing, and exhausting every attempt is a FAILURE, not a SKIP.
2737 #[test]
2738 fn a_real_aomenc_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() {
2739 uv_mode_in_inter8_gate(8, 1);
2740 }
2741
2742 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
2743 #[test]
2744 fn a_real_aomenc_10bit_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact()
2745 {
2746 uv_mode_in_inter8_gate(10, 1);
2747 }
2748
2749 /// The multi-tile arm (class [[new-map-ignores-tile-edge]]): this round
2750 /// stamps a new `uv_mode` band from the 8x8 leaf, whose availability must
2751 /// be tile-relative.
2752 #[test]
2753 fn a_real_aomenc_two_tile_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact()
2754 {
2755 uv_mode_in_inter8_gate(8, 2);
2756 }
2757
2758 /// lane-leaf8tx r1: the refusal this round lifts on an INTRA 8x8 leaf
2759 /// inside an INTER frame -- a nonzero luma `angle_delta_y` on it
2760 /// (`--enable-angle-delta=1`,
2761 /// `av1_use_angle_delta(BLOCK_8X8)`). Both counters are per-attempt
2762 /// deltas on an attempt that decoded to the end and is pixel-compared
2763 /// (class [[counter-from-refused-stream]]); a decode error or a mismatch
2764 /// is a FAILURE, never a SKIP.
2765 #[test]
2766 fn a_real_aomenc_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
2767 tx_split_angle_in_inter8_gate(8);
2768 }
2769
2770 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
2771 #[test]
2772 fn a_real_aomenc_10bit_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
2773 tx_split_angle_in_inter8_gate(10);
2774 }
2775
2776 /// lane-chroma r2 stage 1: a real aomenc key frame with
2777 /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`)
2778 /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still-
2779 /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never
2780 /// fires; smooth *luma* neighbours are exactly what this gate wants to
2781 /// exercise, proving [`decode::smooth_luma_hits`] actually landed a
2782 /// directional block next to a smooth-predicted one and decoded
2783 /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix).
2784 #[test]
2785 fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() {
2786 if !have_ffmpeg() {
2787 eprintln!(
2788 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg"
2789 );
2790 return;
2791 }
2792 if !have_aomenc() {
2793 eprintln!(
2794 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}",
2795 aomenc_path().display()
2796 );
2797 return;
2798 }
2799 let (width, height) = (64usize, 64usize);
2800 let mut refusals = Vec::new();
2801 let mut fired_runs = 0u32;
2802 let mut uncounted_exact = 0u32;
2803 for attempt in 0..40u32 {
2804 let seed = 42 + attempt;
2805 let source = format!(
2806 "mandelbrot=size=64x64:start_scale={}:rate=25",
2807 5.0 - f64::from(attempt) * 0.06
2808 );
2809 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2810 .args([
2811 "-v",
2812 "error",
2813 "-f",
2814 "lavfi",
2815 "-i",
2816 &source,
2817 "-pix_fmt",
2818 "yuv420p",
2819 "-t",
2820 "0.04",
2821 "-f",
2822 "yuv4mpegpipe",
2823 "-",
2824 ])
2825 .stdin(Stdio::null())
2826 .stdout(Stdio::piped())
2827 .stderr(Stdio::piped()), None, |c| c.output())
2828 .expect("ffmpeg failed to run");
2829 assert!(
2830 y4m.status.success(),
2831 "ffmpeg fixture: {}",
2832 String::from_utf8_lossy(&y4m.stderr)
2833 );
2834 let out = run_with_stdin(
2835 Command::new(aomenc_path()).args([
2836 "--codec=av1",
2837 "--passes=1",
2838 "--end-usage=q",
2839 "--cq-level=45",
2840 "--cpu-used=0",
2841 "--enable-rect-partitions=0",
2842 "--enable-ab-partitions=0",
2843 "--enable-1to4-partitions=0",
2844 "--enable-filter-intra=0",
2845 "--enable-smooth-intra=1",
2846 // Smooth/paeth chroma is a still-refused, separate
2847 // round-2 gap -- off so no attempt trips it while this
2848 // gate is purely about luma's edge-filter fix.
2849 "--enable-paeth-intra=0",
2850 "--enable-tx-size-search=0",
2851 "--enable-cdef=0",
2852 "--enable-restoration=0",
2853 "--enable-intra-edge-filter=1",
2854 "--max-partition-size=32",
2855 "--min-partition-size=16",
2856 "--enable-palette=0",
2857 "--enable-intrabc=0",
2858 "--enable-cfl-intra=0",
2859 "--enable-ref-frame-mvs=0",
2860 "--obu",
2861 "-o",
2862 "-",
2863 "-",
2864 ]),
2865 &y4m.stdout,
2866 );
2867 assert!(
2868 out.status.success(),
2869 "aomenc refused the fixture: {}",
2870 String::from_utf8_lossy(&out.stderr)
2871 );
2872 let stream = out.stdout;
2873 let smooth_before = decode::smooth_luma_hits();
2874 let frames = match decode_stream(&stream) {
2875 Ok(frames) => frames,
2876 Err(e) => {
2877 refusals.push(format!("seed {seed}: {e}"));
2878 continue;
2879 }
2880 };
2881 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
2882 // is ALWAYS pixel-compared below; the hit counter only decides whether
2883 // the attempt counts toward the firing total.
2884 let counted = decode::smooth_luma_hits() != smooth_before;
2885 if counted {
2886 fired_runs += 1;
2887 } else {
2888 uncounted_exact += 1;
2889 refusals.push(format!(
2890 "seed {seed}: decoded and pixel-compared, but no smooth-luma-neighbour block \
2891 fired"
2892 ));
2893 }
2894 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
2895 assert_eq!(
2896 frames[0].y, ffmpeg_frames[0].y,
2897 "luma vs ffmpeg (seed {seed})"
2898 );
2899 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
2900 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
2901 if fired_runs >= 4 {
2902 gate_buckets(
2903 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
2904 fired_runs,
2905 uncounted_exact,
2906 refusals.len() - uncounted_exact as usize,
2907 );
2908 return;
2909 }
2910 }
2911 gate_buckets(
2912 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
2913 fired_runs,
2914 uncounted_exact,
2915 refusals.len() - uncounted_exact as usize,
2916 );
2917 assert!(
2918 fired_runs > 0,
2919 "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}",
2920 refusals.join("\n")
2921 );
2922 }
2923
2924 /// The smooth/paeth-chroma gate (lane-chroma r1/r3): a real aomenc key
2925 /// frame with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the
2926 /// opposite of the directional-chroma gate below, which turns these OFF
2927 /// to keep this gap from firing while directional chroma is under test).
2928 /// Some seeds won't pick smooth/paeth for chroma at all -- retry like
2929 /// every other real-encoder gate here, but the first attempt that
2930 /// actually fires [`decode::smooth_uv_hits`] must decode pixel-exact.
2931 #[test]
2932 fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() {
2933 if !have_ffmpeg() {
2934 eprintln!(
2935 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg"
2936 );
2937 return;
2938 }
2939 if !have_aomenc() {
2940 eprintln!(
2941 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}",
2942 aomenc_path().display()
2943 );
2944 return;
2945 }
2946 let (width, height) = (64usize, 64usize);
2947 let mut refusals = Vec::new();
2948 let mut fired_runs = 0u32;
2949 let mut uncounted_exact = 0u32;
2950 for attempt in 0..40u32 {
2951 let seed = 42 + attempt;
2952 let source = format!(
2953 "mandelbrot=size=64x64:start_scale={}:rate=25",
2954 5.0 - f64::from(attempt) * 0.06
2955 );
2956 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2957 .args([
2958 "-v",
2959 "error",
2960 "-f",
2961 "lavfi",
2962 "-i",
2963 &source,
2964 "-pix_fmt",
2965 "yuv420p",
2966 "-t",
2967 "0.04",
2968 "-f",
2969 "yuv4mpegpipe",
2970 "-",
2971 ])
2972 .stdin(Stdio::null())
2973 .stdout(Stdio::piped())
2974 .stderr(Stdio::piped()), None, |c| c.output())
2975 .expect("ffmpeg failed to run");
2976 assert!(
2977 y4m.status.success(),
2978 "ffmpeg fixture: {}",
2979 String::from_utf8_lossy(&y4m.stderr)
2980 );
2981 let out = run_with_stdin(
2982 Command::new(aomenc_path()).args([
2983 "--codec=av1",
2984 "--passes=1",
2985 "--end-usage=q",
2986 "--cq-level=45",
2987 "--cpu-used=0",
2988 "--enable-rect-partitions=0",
2989 "--enable-ab-partitions=0",
2990 "--enable-1to4-partitions=0",
2991 "--enable-filter-intra=0",
2992 "--enable-smooth-intra=1",
2993 "--enable-paeth-intra=1",
2994 "--enable-tx-size-search=0",
2995 "--enable-cdef=0",
2996 "--enable-restoration=0",
2997 "--enable-intra-edge-filter=1",
2998 "--max-partition-size=32",
2999 // 8x8/leaf8 splits are a separate, already-named refusal.
3000 "--min-partition-size=16",
3001 "--enable-palette=0",
3002 "--enable-intrabc=0",
3003 "--enable-cfl-intra=0",
3004 "--enable-ref-frame-mvs=0",
3005 "--obu",
3006 "-o",
3007 "-",
3008 "-",
3009 ]),
3010 &y4m.stdout,
3011 );
3012 assert!(
3013 out.status.success(),
3014 "aomenc refused the fixture: {}",
3015 String::from_utf8_lossy(&out.stderr)
3016 );
3017 let stream = out.stdout;
3018 let smooth_before = decode::smooth_uv_hits();
3019 let frames = match decode_stream(&stream) {
3020 Ok(frames) => frames,
3021 Err(e) => {
3022 refusals.push(format!("seed {seed}: {e}"));
3023 continue;
3024 }
3025 };
3026 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
3027 // is ALWAYS pixel-compared below; the hit counter only decides whether
3028 // the attempt counts toward the firing total.
3029 let counted = decode::smooth_uv_hits() != smooth_before;
3030 if counted {
3031 fired_runs += 1;
3032 } else {
3033 uncounted_exact += 1;
3034 refusals.push(format!(
3035 "seed {seed}: decoded and pixel-compared, but no smooth/paeth uv_mode fired"
3036 ));
3037 }
3038 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3039 assert_eq!(
3040 frames[0].y, ffmpeg_frames[0].y,
3041 "luma vs ffmpeg (seed {seed})"
3042 );
3043 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
3044 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
3045 if fired_runs >= 4 {
3046 gate_buckets(
3047 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
3048 fired_runs,
3049 uncounted_exact,
3050 refusals.len() - uncounted_exact as usize,
3051 );
3052 return;
3053 }
3054 }
3055 gate_buckets(
3056 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
3057 fired_runs,
3058 uncounted_exact,
3059 refusals.len() - uncounted_exact as usize,
3060 );
3061 assert!(
3062 fired_runs > 0,
3063 "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}",
3064 refusals.join("\n")
3065 );
3066 }
3067
3068 /// The directional-chroma/angle-delta gate: a real aomenc key frame with
3069 /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the
3070 /// opposite of every sibling recipe's `=0`, which existed specifically to
3071 /// keep this round-2 gap from firing while a different surface was under
3072 /// test). A colourful, sharp-edged source gives the RD search a reason to
3073 /// pick a directional `uv_mode` and/or a nonzero angle delta -- some
3074 /// seeds still won't, so retry like every other real-encoder gate here,
3075 /// but the first attempt that actually fires either counter must decode
3076 /// pixel-exact.
3077 #[test]
3078 fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() {
3079 if !have_ffmpeg() {
3080 eprintln!(
3081 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg"
3082 );
3083 return;
3084 }
3085 if !have_aomenc() {
3086 eprintln!(
3087 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}",
3088 aomenc_path().display()
3089 );
3090 return;
3091 }
3092 let (width, height) = (64usize, 64usize);
3093 let mut refusals = Vec::new();
3094 let mut fired_runs = 0u32;
3095 let mut uncounted_exact = 0u32;
3096 for attempt in 0..40u32 {
3097 let seed = 42 + attempt;
3098 let source = format!(
3099 "mandelbrot=size=64x64:start_scale={}:rate=25",
3100 5.0 - f64::from(attempt) * 0.06
3101 );
3102 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3103 .args([
3104 "-v",
3105 "error",
3106 "-f",
3107 "lavfi",
3108 "-i",
3109 &source,
3110 "-pix_fmt",
3111 "yuv420p",
3112 "-t",
3113 "0.04",
3114 "-f",
3115 "yuv4mpegpipe",
3116 "-",
3117 ])
3118 .stdin(Stdio::null())
3119 .stdout(Stdio::piped())
3120 .stderr(Stdio::piped()), None, |c| c.output())
3121 .expect("ffmpeg failed to run");
3122 assert!(
3123 y4m.status.success(),
3124 "ffmpeg fixture: {}",
3125 String::from_utf8_lossy(&y4m.stderr)
3126 );
3127 let out = run_with_stdin(
3128 Command::new(aomenc_path()).args([
3129 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
3130 // occurrence, so overrides go before the base list).
3131 "--enable-directional-intra=1",
3132 "--codec=av1",
3133 "--passes=1",
3134 "--end-usage=q",
3135 "--cq-level=45",
3136 "--cpu-used=0",
3137 "--enable-rect-partitions=0",
3138 "--enable-ab-partitions=0",
3139 "--enable-1to4-partitions=0",
3140 "--enable-filter-intra=0",
3141 // Smooth/Paeth chroma is a separate, still-refused round-2
3142 // gap (an unrelated `Edges::build` no-neighbour bug this
3143 // lane does not cover) -- off so the RD search's only
3144 // non-DC/CFL chroma choice left is directional.
3145 "--enable-smooth-intra=0",
3146 "--enable-paeth-intra=0",
3147 "--enable-tx-size-search=0",
3148 "--enable-cdef=0",
3149 "--enable-restoration=0",
3150 // The intra edge filter/upsample (spec 7.11.2.7-2.9) is
3151 // now implemented (`directional()`) -- left ON (aomenc's
3152 // own default) so this gate actually exercises it instead
3153 // of the un-filtered fast path a disabled flag would keep
3154 // testing.
3155 "--enable-intra-edge-filter=1",
3156 "--max-partition-size=32",
3157 // Same reason as the tx-select gate above: 8x8 and other
3158 // sub-16x16 splits are a separate, already-named refusal.
3159 "--min-partition-size=16",
3160 "--enable-palette=0",
3161 "--enable-intrabc=0",
3162 "--enable-cfl-intra=0",
3163 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
3164 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
3165 "--enable-ref-frame-mvs=0",
3166 "--obu",
3167 "-o",
3168 "-",
3169 "-",
3170 ]),
3171 &y4m.stdout,
3172 );
3173 assert!(
3174 out.status.success(),
3175 "aomenc refused the fixture: {}",
3176 String::from_utf8_lossy(&out.stderr)
3177 );
3178 let stream = out.stdout;
3179 let (uv_before, angle_before) =
3180 (decode::directional_uv_hits(), decode::angle_delta_hits());
3181 let frames = match decode_stream(&stream) {
3182 Ok(frames) => frames,
3183 Err(e) => {
3184 refusals.push(format!("seed {seed}: {e}"));
3185 continue;
3186 }
3187 };
3188 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
3189 // is ALWAYS pixel-compared below; the hit counter only decides whether
3190 // the attempt counts toward the firing total.
3191 let counted = decode::directional_uv_hits() != uv_before
3192 || decode::angle_delta_hits() != angle_before;
3193 if counted {
3194 fired_runs += 1;
3195 } else {
3196 uncounted_exact += 1;
3197 refusals.push(format!(
3198 "seed {seed}: decoded and pixel-compared, but neither a directional uv_mode \
3199 nor a nonzero angle delta fired"
3200 ));
3201 }
3202 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3203 assert_eq!(
3204 frames[0].y, ffmpeg_frames[0].y,
3205 "luma vs ffmpeg (seed {seed})"
3206 );
3207 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
3208 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
3209 if fired_runs >= 4 {
3210 gate_buckets(
3211 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
3212 fired_runs,
3213 uncounted_exact,
3214 refusals.len() - uncounted_exact as usize,
3215 );
3216 return;
3217 }
3218 }
3219 gate_buckets(
3220 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
3221 fired_runs,
3222 uncounted_exact,
3223 refusals.len() - uncounted_exact as usize,
3224 );
3225 assert!(
3226 fired_runs > 0,
3227 "every attempt hit a named refusal or never exercised directional chroma:\n{}",
3228 refusals.join("\n")
3229 );
3230 }
3231
3232 #[test]
3233 fn a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
3234 inter_sb_none_gate(
3235 "a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
3236 false,
3237 "32",
3238 "64",
3239 decode::inter_sb_none_hits,
3240 "whole-superblock inter PARTITION_NONE",
3241 &[],
3242 64,
3243 4,
3244 );
3245 }
3246
3247 #[test]
3248 fn a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
3249 inter_sb_none_gate(
3250 "a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
3251 true,
3252 "32",
3253 "64",
3254 decode::inter_sb_none_hits,
3255 "whole-superblock inter PARTITION_NONE",
3256 &[],
3257 64,
3258 4,
3259 );
3260 }
3261
3262 /// lane-inter8 r1: the same recipe with `--min-partition-size=8`, so
3263 /// aomenc's RD may split a 16x16 inter block into four 8x8 leaves. The
3264 /// interior (non-edge-straddling) `PARTITION_SPLIT` at the 16x16 level
3265 /// was refused by name until this round; the straddle path always ran the
3266 /// same loop, so only [`decode::inter_sub16_split_hits`] -- which counts
3267 /// interior splits only -- proves the newly-lifted alphabet value fired.
3268 // lane-inter8 r2: GREEN. The neighbour side bands are mi-granular, every
3269 // leaf stamps its own 2x2-mi span (including the compound-return path
3270 // that used to skip `record_mi` entirely) and the compound
3271 // group/index contexts read the LEAF's mi cell, not its 16x16's corner.
3272 /// lane-inter8 r3, from lane-sub8's verifier finding: the mi-granular
3273 /// inter neighbour bands added in r2 must reset per TILE (above) and per
3274 /// SB row (left) and guard availability tile-relative, so the same recipe
3275 /// runs again at 128x64 with two tile columns -- a leaf on the second
3276 /// tile's first column has no left neighbour and must not read the first
3277 /// tile's band.
3278 // Un-ignored 2026-09-04: the SB-level rect-partition refusal (lane-sbpart's arm at 128x64) that blocked this gate is gone and it passes. The tile-relative audit it was written for
3279 // was done by inspection instead: every reader of the mi bands guards on
3280 // `tile_row0_mi`/`tile_col0_mi` (no `> 0` guard exists in decode.rs),
3281 // `start_tile` resets the above mi bands over the tile's own mi column
3282 // span and `start_row` resets every left mi band.
3283 #[test]
3284 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact()
3285 {
3286 inter_sb_none_gate(
3287 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact",
3288 false,
3289 "8",
3290 "16",
3291 decode::inter_sub16_split_hits,
3292 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
3293 &["--tile-columns=1"],
3294 128,
3295 4,
3296 );
3297 }
3298
3299 /// lane-interp3 r1: the same 8x8-leaf recipe with DUAL FILTER, OBMC and
3300 /// warped motion on. `read_mb_interp_filter` runs for every inter block
3301 /// (libaom `decodemv.c` 1575), compound ones included; the compound 8x8
3302 /// leaf skipped it entirely, so a SWITCHABLE-filter stream lost a symbol
3303 /// per compound leaf and stamped the `[3, 3]` "no filter" sentinel, which
3304 /// made a neighbouring OBMC block's `neighbour_filter` PANIC (a crash on
3305 /// his data, not a named refusal). The three hard asserts prove the flags
3306 /// arrived: a compound 8x8 leaf that really read the filter, a block whose
3307 /// two dual-filter directions DIFFER (impossible with dual filter off),
3308 /// and an 8x8 OBMC blend.
3309 // lane-interp3 r2: the ENTROPY desync r1 measured is CLOSED -- the full
3310 // 16-frame stream now parses end to end and every `EC_MODE`/`EC_MODE_VAL`
3311 // element's msac RANGE matches the instrumented aomdec's line for line
3312 // (570/570 mode elements, 0 diff). Two twin-drift root causes, both in
3313 // `decode_inter_block8`'s compound arm: `read_compound_ref_frames` was
3314 // passed a hard-coded `LAST_FRAME` for every inter neighbour instead of
3315 // the real per-mi band, and the grid stamp cleared both per-slot
3316 // `is_global_mv_block` flags.
3317 // lane-interp3 r3: the luma reconstruction residue r2 left open is CLOSED
3318 // and this gate is GREEN. Third instance of the same twin-drift class:
3319 // libaom applies `allow_warp`'s GLOBAL branch to every
3320 // `is_global_mv_block` reference slot, compound included and independent
3321 // of `motion_mode` (`av1_init_warp_params` inside
3322 // `build_inter_predictors_8x8_and_bigger`'s per-`ref` loop) -- the 16x16+
3323 // compound arm has warped since lane-cwarp r1, the 8x8 leaf's compound arm
3324 // predicted BOTH taps translationally, so a GLOBAL_GLOBALMV 8x8 compound
3325 // leaf under a non-TRANSLATION model drifted a few luma levels, growing
3326 // away from the block origin. It was NOT OBMC: the `EC_OBMC` emitter this
3327 // round added to `decode.rs` diffs 325/325 lines against the instrumented
3328 // aomdec's own rung (position, span, neighbour mv/ref/bsize/filter) with
3329 // zero differences.
3330 #[test]
3331 fn a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact() {
3332 const NAME: &str = "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact";
3333 if !have_ffmpeg() || !have_aomenc() {
3334 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
3335 return;
3336 }
3337 let before_dual = decode::dual_filter_diff_hits();
3338 let before_obmc = decode::obmc_hits_8();
3339 let before_cwarp8 = decode::compound_warp_hits_8();
3340 inter_sb_none_gate(
3341 NAME,
3342 false,
3343 "8",
3344 "16",
3345 decode::compound8_filter_hits,
3346 "a compound 8x8 leaf reading its own switchable interp_filter",
3347 &[
3348 "--enable-dual-filter=1",
3349 "--enable-obmc=1",
3350 "--enable-warped-motion=1",
3351 "--enable-onesided-comp=1",
3352 ],
3353 64,
3354 // Recipe search hook (same shape as EC_OBMC8_ATTEMPTS): a compound
3355 // block needs several coded references, so the sequence is longer
3356 // than the other arms' 4 frames.
3357 std::env::var("EC_INTERP3_FRAMES")
3358 .ok()
3359 .and_then(|v| v.parse().ok())
3360 .unwrap_or(16),
3361 );
3362 assert!(
3363 decode::dual_filter_diff_hits() > before_dual,
3364 "{NAME}: no block read two DIFFERENT dual-filter directions -- \
3365 --enable-dual-filter=1 did not arrive or aomenc declined it"
3366 );
3367 assert!(
3368 decode::obmc_hits_8() > before_obmc,
3369 "{NAME}: no 8x8 OBMC blend fired -- --enable-obmc=1 did not arrive"
3370 );
3371 assert!(
3372 decode::compound_warp_hits_8() > before_cwarp8,
3373 "{NAME}: no 8x8 COMPOUND leaf was predicted through the per-ref GLOBAL \
3374 warp -- the r3 root-cause path never fired, so this stream no longer \
3375 proves it"
3376 );
3377 }
3378
3379 /// lane-av1dualfilter10: the 10-bit arm of the dual-filter witness.
3380 ///
3381 /// `NEVER_EXERCISED_10BIT` kept `enable-dual-filter` listed after the
3382 /// 8-bit entry was retired (lane-av1distwtd r3, gate_coverage.rs), and
3383 /// the reason was structural, not incidental: the only `=1` witness,
3384 /// `a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact`,
3385 /// calls `inter_sb_none_gate(NAME, false, ...)` -- and that `false` IS the
3386 /// `ten_bit` parameter, so it built an 8-bit stream. Its `ten_bit = true`
3387 /// siblings build 10-bit streams but spell no dual-filter flag. This is
3388 /// that missing arm.
3389 ///
3390 /// What makes it a witness and not a spelling: the header is read back
3391 /// from the ENCODED stream (`enable_dual_filter` and `bit_depth` both come
3392 /// from `Av1Parser`, never from the flag or the fixture name), and the
3393 /// arrival assert is a DELTA on `decode::dual_filter_diff_hits()` taken
3394 /// around this arm alone. A stream that merely parsed would not move the
3395 /// counter; the counter moves only when `resolve_interp_filter` reads two
3396 /// DIFFERENT directions for one block, which is the property the entry
3397 /// was claiming no real stream carried.
3398 #[test]
3399 fn a_real_aomenc_10bit_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact() {
3400 const NAME: &str =
3401 "a_real_aomenc_10bit_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact";
3402 if !have_ffmpeg() || !have_aomenc() {
3403 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
3404 return;
3405 }
3406 let before_dual = decode::dual_filter_diff_hits();
3407 let stream = inter_sb_none_gate(
3408 NAME,
3409 // `ten_bit`: this is the whole difference from the 8-bit witness.
3410 true,
3411 "8",
3412 "16",
3413 decode::compound8_filter_hits,
3414 "a compound 8x8 leaf reading its own switchable interp_filter",
3415 &[
3416 "--enable-dual-filter=1",
3417 "--enable-obmc=1",
3418 "--enable-warped-motion=1",
3419 "--enable-onesided-comp=1",
3420 ],
3421 64,
3422 std::env::var("EC_INTERP3_FRAMES")
3423 .ok()
3424 .and_then(|v| v.parse().ok())
3425 .unwrap_or(16),
3426 );
3427 // The ARRIVAL assert comes first on purpose. `dual_filter_diff_hits()`
3428 // moves only inside `resolve_interp_filter` when the header bit is set
3429 // AND the block's two directions differ, so pinning it =0 reds HERE,
3430 // on the tool failing to arrive -- not on some shape or pixel assert
3431 // downstream of it. The two header asserts below corroborate it from
3432 // the encoded bytes; they are not what carries the proof.
3433 assert!(
3434 decode::dual_filter_diff_hits() > before_dual,
3435 "{NAME}: no block read two DIFFERENT dual-filter directions in the 10-bit stream \
3436 -- --enable-dual-filter=1 did not arrive or aomenc declined it"
3437 );
3438 // Both facts from the PARSED header, not from what we asked for: a
3439 // gate that trusted `--bit-depth=10` would pass on a stream aomenc
3440 // silently coded at 8, which is the vacuity this asserts against.
3441 let mut probe = Av1Parser::new();
3442 let mut pos = 0usize;
3443 while pos < stream.len() && probe.sequence_header().is_none() {
3444 let obu = probe.parse_obu(&stream[pos..]).unwrap();
3445 pos += obu.total_size;
3446 }
3447 let seq = probe
3448 .sequence_header()
3449 .expect("stream has a sequence header OBU");
3450 assert_eq!(
3451 seq.color_config.bit_depth, 10,
3452 "{NAME}: aomenc did not write a 10-bit sequence header"
3453 );
3454 assert!(
3455 seq.enable_dual_filter,
3456 "{NAME}: the parsed sequence header says enable_dual_filter = false, so this \
3457 stream cannot carry per-direction interp filters however the pixels compare"
3458 );
3459 }
3460
3461 #[test]
3462 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
3463 inter_sb_none_gate(
3464 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
3465 false,
3466 "8",
3467 "16",
3468 decode::inter_sub16_split_hits,
3469 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
3470 &[],
3471 64,
3472 4,
3473 );
3474 }
3475
3476 #[test]
3477 // Un-ignored 2026-09-04: the desync behind the bogus 32x32 value=9 refusal (class refusal-from-own-desync) is gone and this 10-bit twin decodes pixel-exact.
3478 fn a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
3479 inter_sb_none_gate(
3480 "a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
3481 true,
3482 "8",
3483 "16",
3484 decode::inter_sub16_split_hits,
3485 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
3486 &[],
3487 64,
3488 4,
3489 );
3490 }
3491
3492 #[test]
3493 fn a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
3494 chroma_class1_eob_gate(
3495 "a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
3496 false,
3497 );
3498 }
3499
3500 #[test]
3501 fn a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
3502 chroma_class1_eob_gate(
3503 "a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
3504 true,
3505 );
3506 }
3507
3508 /// lane-inter4 r1: the SUPERBLOCK-level inter `PARTITION_HORZ`/
3509 /// `PARTITION_VERT` pair -- two 64x32 / 32x64 inter strips, the arm the
3510 /// inter tile path refused outright before this lane ("an inter SB-level
3511 /// partition type other than NONE or SPLIT"). `--min-partition-size=32`
3512 /// keeps every 32x32-level rect shape (already coded, and residual-capable
3513 /// only when skip) out of the picture so the counters can only be earned
3514 /// at the superblock level; the noiseless split-motion source (one half
3515 /// translating, the other static, flat inside each half) is what makes
3516 /// aomenc's RD pick a superblock HORZ/VERT whose strips are `skip` --
3517 /// the ONLY inter rect shape this decoder can complete, since rectangular
3518 /// inter residual coding is not ported (see `reject_residual`).
3519 ///
3520 /// Every decoded frame is compared to ffmpeg (Y, U and V); an attempt
3521 /// that refuses by name is counted, never turned into a SKIP; and an
3522 /// attempt that decoded without firing the arm is counted separately and
3523 /// still required to be pixel-exact (class gate-skips-on-its-own-failure).
3524 #[test]
3525 fn a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact() {
3526 const NAME: &str = "a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact";
3527 let _gate_lock = lock_gate_counters();
3528 if !have_ffmpeg() {
3529 eprintln!("SKIP {NAME}: no ffmpeg");
3530 return;
3531 }
3532 if !have_aomenc() {
3533 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3534 return;
3535 }
3536 let (width, height, frame_count) = (192usize, 128usize, 6usize);
3537 // lane-inter4 r1: 8-bit ONLY, and the reason is the lane's own open
3538 // residue, not a tolerance: across all 16 attempts x both depths, every
3539 // 10-bit attempt that reached a superblock-level rect strip found it
3540 // NON-skip, so it stops at "a non-skip rectangular (HORZ/VERT/HORZ_B)
3541 // strip needs rectangular residual coding". The 10-bit twin below is
3542 // `#[ignore]`d with that exact reason rather than deleted or weakened.
3543 // lane-r14 r2 re-measured the 8-bit-only note above: the residual
3544 // refusal it names is GONE (this round codes a 64-px transform axis as
3545 // its truncated low-32 corner), and a 10-bit sweep of this exact
3546 // recipe now reaches the arm -- 2 pixel-exact attempts, 2 64x32 and 2
3547 // 32x64 strips, 2 of them carrying a coded 64-axis residual.
3548 // lane-sbrect10 r1 closed the newly exposed 10-bit defect r14 r2
3549 // parked this arm on (10-bit attempt 14, cq 61, horizontal split,
3550 // motion step 12 -- it mismatched ffmpeg while decoding ZERO rect
3551 // strips): a 64x64 INTRA block inside an inter frame read `uv_mode`
3552 // off the 14-symbol CFL-allowed alphabet, which libaom's
3553 // `is_cfl_allowed` caps at 32x32 -- same DC_PRED value, wrong
3554 // interval narrowing, tile desynced from that block on. Both depths
3555 // run now.
3556 for bit_depth in [8u32, 10u32] {
3557 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
3558 (0u32, 0u32, 0u32, 0u32);
3559 let (mut horz_proved, mut vert_proved) = (0usize, 0usize);
3560 let mut rect64_tus = 0usize;
3561 for attempt in 0..16u32 {
3562 // Two orientations (the transposed pair a one-sided gate could
3563 // never separate) x four quantisers x two motion steps: which
3564 // superblock the RD hands a skip-able rect strip moves with
3565 // the quantiser, and the 10-bit arm needs a different corner
3566 // of the grid from the 8-bit one.
3567 let vertical_split = attempt % 2 == 1;
3568 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
3569 let sp = 8 + (attempt / 8) * 4;
3570 let geq = if vertical_split {
3571 format!("if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), 200)")
3572 } else {
3573 format!("if(lt(X,64), 40+mod(floor((Y+N*{sp})/32)*90,200), 200)")
3574 };
3575 let duration = frame_count as f64 / 25.0;
3576 let source = format!(
3577 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
3578 geq=lum='{geq}',format=yuv420p"
3579 );
3580 let pix_fmt = if bit_depth == 10 {
3581 "yuv420p10le"
3582 } else {
3583 "yuv420p"
3584 };
3585 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3586 .args([
3587 "-v",
3588 "error",
3589 "-f",
3590 "lavfi",
3591 "-i",
3592 &source,
3593 "-t",
3594 &duration.to_string(),
3595 "-pix_fmt",
3596 pix_fmt,
3597 "-strict",
3598 "-1",
3599 "-f",
3600 "yuv4mpegpipe",
3601 "-",
3602 ])
3603 .stdin(Stdio::null())
3604 .stdout(Stdio::piped())
3605 .stderr(Stdio::piped()), None, |c| c.output())
3606 .expect("ffmpeg failed to run");
3607 assert!(
3608 y4m.status.success(),
3609 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
3610 String::from_utf8_lossy(&y4m.stderr)
3611 );
3612 let cq_arg = format!("--cq-level={cq}");
3613 let depth_arg = format!("--bit-depth={bit_depth}");
3614 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
3615 let args: Vec<&str> = vec![
3616 "--codec=av1",
3617 "--passes=1",
3618 "--end-usage=q",
3619 &cq_arg,
3620 "--cpu-used=0",
3621 "--threads=1",
3622 "--row-mt=0",
3623 "--sb-size=64",
3624 &depth_arg,
3625 &input_depth_arg,
3626 "--enable-restoration=0",
3627 "--enable-palette=0",
3628 "--deltaq-mode=0",
3629 "--enable-filter-intra=0",
3630 "--enable-cfl-intra=0",
3631 "--enable-intrabc=0",
3632 "--enable-tx-size-search=0",
3633 "--lag-in-frames=0",
3634 // Per-arm overrides go LAST: aomenc keeps the last
3635 // occurrence of a repeated --enable-* flag.
3636 "--enable-rect-partitions=1",
3637 "--enable-ab-partitions=0",
3638 "--enable-1to4-partitions=1",
3639 "--min-partition-size=32",
3640 "--max-partition-size=64",
3641 "--obu",
3642 "-o",
3643 "-",
3644 "-",
3645 ];
3646 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3647 assert!(
3648 out.status.success(),
3649 "aomenc refused the fixture: {}",
3650 String::from_utf8_lossy(&out.stderr)
3651 );
3652 let stream = out.stdout;
3653 let before = crate::stream::inter_rect_counters();
3654 let rect64_before = crate::stream::rect64_inter_tu_hits();
3655 let frames = match decode_stream(&stream) {
3656 Err(e) => {
3657 let msg = e.to_string();
3658 assert!(
3659 msg.contains("unsupported"),
3660 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
3661 attempt {attempt}): {msg}"
3662 );
3663 named_refusals += 1;
3664 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
3665 continue;
3666 }
3667 Ok(frames) => frames,
3668 };
3669 let after = crate::stream::inter_rect_counters();
3670 let (horz, vert) = (after.2 - before.2, after.3 - before.3);
3671 let rect64 = crate::stream::rect64_inter_tu_hits() - rect64_before;
3672 let ffmpeg_frames = if bit_depth == 10 {
3673 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
3674 } else {
3675 ffmpeg_decode_sequence(&stream, width, height, frame_count)
3676 };
3677 assert_eq!(frames.len(), frame_count);
3678 let mismatched = frames
3679 .iter()
3680 .zip(&ffmpeg_frames)
3681 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
3682 if horz + vert == 0 {
3683 out_of_scope += 1;
3684 if mismatched {
3685 oos_mismatch += 1;
3686 eprintln!(
3687 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
3688 superblock-level inter rect strips -- another shape's defect"
3689 );
3690 }
3691 continue;
3692 }
3693 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3694 assert_eq!(
3695 got.y, want.y,
3696 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
3697 );
3698 assert_eq!(
3699 got.u, want.u,
3700 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
3701 );
3702 assert_eq!(
3703 got.v, want.v,
3704 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
3705 );
3706 }
3707 horz_proved += horz;
3708 vert_proved += vert;
3709 rect64_tus += rect64;
3710 matched += 1;
3711 }
3712 eprintln!(
3713 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
3714 attempts carrying the arm, 64x32 strips={horz_proved}, 32x64 strips={vert_proved}, \
3715 64-axis residual TUs={rect64_tus}, \
3716 {out_of_scope} attempts carried none ({oos_mismatch} of them mismatched)"
3717 );
3718 assert_eq!(
3719 oos_mismatch, 0,
3720 "{NAME}: {oos_mismatch} attempt(s) with no superblock-level inter rect strip \
3721 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
3722 );
3723 // lane-r14 r2: the residual half of the arm -- a strip that is not
3724 // `skip` and codes a real 64-axis transform unit. Without this the
3725 // gate proves only the partition symbol.
3726 assert!(
3727 rect64_tus > 0,
3728 "{NAME} ({bit_depth}-bit): no superblock-level rect strip carried a coded \
3729 64-axis residual transform unit inside a pixel-exact attempt \
3730 (horz={horz_proved}, vert={vert_proved}) -- the residual arm proved nothing"
3731 );
3732 assert!(
3733 horz_proved + vert_proved > 0,
3734 "{NAME} ({bit_depth}-bit): the superblock-level inter rect arm never fired \
3735 inside a pixel-exact attempt (horz={horz_proved}, vert={vert_proved}, \
3736 {named_refusals} refusals, {out_of_scope} out of scope) -- gate proved nothing"
3737 );
3738 }
3739 }
3740
3741 /// lane-r14 r3: a 1:4 inter strip with a 64-px axis (64x16 / 16x64) whose
3742 /// transform SPLITS -- the arm r2 left refused by name ("a split transform
3743 /// on a 1:4 inter strip with a 64-px axis"). libaom's
3744 /// `sub_tx_size_map[TX_64X16] == TX_32X16` (and `[TX_16X64] == TX_16X32`)
3745 /// keeps the sub-transform RECTANGULAR, so the var-tx tree's leaves are
3746 /// 32x16/16x32 units read through [`TxbSet::LumaRect32x16Inter`], each with
3747 /// its own `get_txb_ctx_general` neighbour context (the unit is smaller
3748 /// than its block, so `txb_skip_ctx` is NOT the lone-TU 0).
3749 ///
3750 /// `--enable-1to4-partitions=1 --min-partition-size=16
3751 /// --max-partition-size=64 --enable-tx64=1` (each spelled once, last
3752 /// occurrence wins) is what lets aomenc pick a superblock-level HORZ_4 /
3753 /// VERT_4; the textured translating source is what keeps the strips
3754 /// non-skip so the residual is actually coded. 8-bit AND 10-bit, every
3755 /// decoded frame compared to ffmpeg on Y/U/V, refusals counted (never
3756 /// SKIPped), attempts that carried no rectangular var-tx leaf counted
3757 /// separately and still required pixel-exact.
3758 #[test]
3759 fn real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal()
3760 {
3761 const NAME: &str = "real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal";
3762 let _gate_lock = lock_gate_counters();
3763 if !have_ffmpeg() {
3764 eprintln!("SKIP {NAME}: no ffmpeg");
3765 return;
3766 }
3767 if !have_aomenc() {
3768 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3769 return;
3770 }
3771 let frame_count = 6usize;
3772 for bit_depth in [8u32, 10u32] {
3773 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
3774 (0u32, 0u32, 0u32, 0u32);
3775 let (mut leaf_32x16, mut leaf_16x32) = (0usize, 0usize);
3776 // Leaves decoded on ANY attempt, including one whose stream hits a
3777 // later named refusal: the firing half of this gate, kept apart
3778 // from `leaf_32x16`/`leaf_16x32` (pixel-compared attempts only) so
3779 // a refused stream is never counted as a pixel proof
3780 // (class counter-from-refused-stream).
3781 let (mut fired_32x16, mut fired_16x32) = (0usize, 0usize);
3782 // lane-gaterecipe r1: the firing arms (16-17) are 8-BIT ONLY, and
3783 // this is measured, not a convenience. Their 10-bit twin fires the
3784 // leaves too (32x16=0 16x32=46 on attempt 16) and then MISMATCHES
3785 // ffmpeg at decode-order frame 2 of attempt 17 -- an open DECODE
3786 // defect handed off in lanes/gaterecipe-r1.report.md, never
3787 // silenced inside this loop.
3788 let attempts = if bit_depth == 8 { 18u32 } else { 16u32 };
3789 for attempt in 0..attempts {
3790 // Two orientations (the transposed pair a one-sided gate could
3791 // never separate) x four quantisers x two motion steps.
3792 // lane-r14 r4 recipe hunt (~70 aomenc runs on the merged
3793 // tree: testsrc2 / life / mandelbrot / banded motion, 64x64 up
3794 // to 384x256, cq 20..58): attempts 16-17 carry the only recipe
3795 // found that makes aomenc code a 64-axis 1:4 strip whose
3796 // transform SPLITS -- 384x256, per-16-column band motion,
3797 // cq 32 (16x32 leaves) and cq 38 (32x16 leaves).
3798 let firing = attempt >= 16;
3799 let (width, height) = if firing {
3800 (384usize, 256usize)
3801 } else {
3802 (192usize, 128usize)
3803 };
3804 let vertical = attempt % 2 == 1;
3805 // lane-vartxsplit r2, MEASURED against the oracle
3806 // (`EC_VARTX` histogram, ~40 aomenc runs): at cq 10 this
3807 // source splits NO rectangular transform at all -- aomdec
3808 // reads only TX_8X8/TX_16X16/TX_8X16/TX_16X8 split symbols,
3809 // so the leaves gaterecipe r1 counted here came out of a
3810 // stream our decoder was already desynced on (class
3811 // counter-from-refused-stream). cq 44 and 46 are the two
3812 // quantisers of that sweep whose stream really carries
3813 // `TX_32X8`/`TX_8X32` splits (16x8 and 8x16 rectangular
3814 // var-tx leaves) AND decodes pixel-exact on all six frames.
3815 let cq = if firing {
3816 if attempt == 16 { 44 } else { 46 }
3817 } else {
3818 [30, 36, 44, 52][(attempt / 2 % 4) as usize]
3819 };
3820 let sp = 3 + (attempt / 8) * 3;
3821 // 16-pixel bands, each band translating at its OWN speed
3822 // across the other axis: that is what makes aomenc's RD split
3823 // a 64x64 superblock into four 1:4 strips (`PARTITION_HORZ_4`
3824 // / `VERT_4`) with distinct motion vectors, and the texture
3825 // inside a band is what keeps the strip non-skip and its
3826 // transform split.
3827 let geq = if firing && !vertical {
3828 // lane-gaterecipe r1, MEASURED: the banded translating
3829 // source this arm used until now splits NO transform at
3830 // all -- an aomdec EC_TRACE/EC_TRACE_COEFF histogram of its
3831 // stream reads zero 1:4 partitions and zero rectangular
3832 // sub-transforms, so the leaves the old assert counted came
3833 // out of a stream that stopped at a refusal (class
3834 // counter-from-refused-stream). What DOES split a
3835 // rectangular transform is a high-frequency product texture
3836 // at a fine quantiser with `--min-partition-size=8`: part
3837 // of the block predicts well and part does not, which is
3838 // the RD case for `txfm_partition`.
3839 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
3840 } else if firing {
3841 // lane-vartxsplit r2: BOTH leaf orientations come out of
3842 // this one source (three 16x8 leaves and one 8x16 on
3843 // attempt 16), so the firing pair is the same texture at
3844 // two quantisers. Its transposed twin was measured over
3845 // cq 40..56 and splits no rectangular transform at all;
3846 // at cq 56 it also mismatches ffmpeg from decode-order
3847 // frame 2 with ZERO rect var-tx leaves in it -- an open
3848 // reconstruction defect (8-pixel-wide luma column, see
3849 // lanes/vartxsplit-r2.report.md), not something to hide
3850 // inside this gate's attempt list.
3851 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
3852 } else if vertical {
3853 format!("128+60*sin((Y+N*({sp}+9*mod(floor(X/16),2)))/7)+25*sin(X/11)")
3854 } else {
3855 format!("128+60*sin((X+N*({sp}+9*mod(floor(Y/16),2)))/7)+25*sin(Y/11)")
3856 };
3857 let duration = frame_count as f64 / 25.0;
3858 let source = format!(
3859 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
3860 geq=lum='{geq}',format=yuv420p"
3861 );
3862 let pix_fmt = if bit_depth == 10 {
3863 "yuv420p10le"
3864 } else {
3865 "yuv420p"
3866 };
3867 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3868 .args([
3869 "-v",
3870 "error",
3871 "-f",
3872 "lavfi",
3873 "-i",
3874 &source,
3875 "-t",
3876 &duration.to_string(),
3877 "-pix_fmt",
3878 pix_fmt,
3879 "-strict",
3880 "-1",
3881 "-f",
3882 "yuv4mpegpipe",
3883 "-",
3884 ])
3885 .stdin(Stdio::null())
3886 .stdout(Stdio::piped())
3887 .stderr(Stdio::piped()), None, |c| c.output())
3888 .expect("ffmpeg failed to run");
3889 assert!(
3890 y4m.status.success(),
3891 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
3892 String::from_utf8_lossy(&y4m.stderr)
3893 );
3894 let cq_arg = format!("--cq-level={cq}");
3895 let depth_arg = format!("--bit-depth={bit_depth}");
3896 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
3897 // A rectangular var-tx LEAF needs a block whose max rectangular
3898 // transform can split: `--min-partition-size=8` is what lets
3899 // aomenc's RD reach one (measured); at 16 it never did.
3900 let min_part = if firing {
3901 "--min-partition-size=8"
3902 } else {
3903 "--min-partition-size=16"
3904 };
3905 let args: Vec<&str> = vec![
3906 "--codec=av1",
3907 "--passes=1",
3908 "--end-usage=q",
3909 &cq_arg,
3910 "--cpu-used=0",
3911 "--threads=1",
3912 "--row-mt=0",
3913 "--sb-size=64",
3914 &depth_arg,
3915 &input_depth_arg,
3916 "--enable-restoration=0",
3917 "--enable-palette=0",
3918 "--deltaq-mode=0",
3919 "--enable-filter-intra=0",
3920 "--enable-cfl-intra=0",
3921 "--enable-intrabc=0",
3922 "--lag-in-frames=0",
3923 // Per-arm overrides go LAST: aomenc keeps the last
3924 // occurrence of a repeated --enable-* flag.
3925 "--enable-tx64=1",
3926 "--enable-rect-partitions=1",
3927 "--enable-ab-partitions=0",
3928 "--enable-1to4-partitions=1",
3929 "--enable-dual-filter=0",
3930 "--enable-obmc=0",
3931 "--enable-tx-size-search=1",
3932 min_part,
3933 "--max-partition-size=64",
3934 "--obu",
3935 "-o",
3936 "-",
3937 "-",
3938 ];
3939 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3940 assert!(
3941 out.status.success(),
3942 "aomenc refused the fixture: {}",
3943 String::from_utf8_lossy(&out.stderr)
3944 );
3945 let stream = out.stdout;
3946 let before = crate::stream::vartx_rect_leaf_hits();
3947 let frames = match decode_stream(&stream) {
3948 Err(e) => {
3949 let msg = e.to_string();
3950 assert!(
3951 msg.contains("unsupported"),
3952 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
3953 attempt {attempt}): {msg}"
3954 );
3955 let after = crate::stream::vartx_rect_leaf_hits();
3956 fired_32x16 += after[0] - before[0];
3957 fired_16x32 += after[1] - before[1];
3958 named_refusals += 1;
3959 eprintln!(
3960 "{bit_depth}-bit attempt {attempt} refusal (rect var-tx leaves \
3961 decoded before it: 32x16={}, 16x32={}): {msg}",
3962 after[0] - before[0],
3963 after[1] - before[1]
3964 );
3965 continue;
3966 }
3967 Ok(frames) => frames,
3968 };
3969 let after = crate::stream::vartx_rect_leaf_hits();
3970 let (h32, v32) = (after[0] - before[0], after[1] - before[1]);
3971 fired_32x16 += h32;
3972 fired_16x32 += v32;
3973 let ffmpeg_frames = if bit_depth == 10 {
3974 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
3975 } else {
3976 ffmpeg_decode_sequence(&stream, width, height, frame_count)
3977 };
3978 assert_eq!(frames.len(), frame_count);
3979 let mismatched = frames
3980 .iter()
3981 .zip(&ffmpeg_frames)
3982 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
3983 if h32 + v32 == 0 {
3984 // Counted per ATTEMPT, on a decoded+compared attempt only
3985 // (class counter-from-refused-stream).
3986 out_of_scope += 1;
3987 if mismatched {
3988 oos_mismatch += 1;
3989 eprintln!(
3990 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
3991 rectangular var-tx leaves -- another shape's defect"
3992 );
3993 }
3994 continue;
3995 }
3996 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3997 assert_eq!(
3998 got.y, want.y,
3999 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
4000 );
4001 assert_eq!(
4002 got.u, want.u,
4003 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
4004 );
4005 assert_eq!(
4006 got.v, want.v,
4007 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
4008 );
4009 }
4010 leaf_32x16 += h32;
4011 leaf_16x32 += v32;
4012 compared += 1;
4013 }
4014 eprintln!(
4015 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
4016 pixel-exact attempts carrying the arm, pixel-compared rect var-tx leaves \
4017 32x16={leaf_32x16} 16x32={leaf_16x32}, leaves decoded anywhere in the sweep \
4018 32x16={fired_32x16} 16x32={fired_16x32}, {out_of_scope} attempts carried none \
4019 ({oos_mismatch} of them mismatched)"
4020 );
4021 assert_eq!(
4022 oos_mismatch, 0,
4023 "{NAME}: {oos_mismatch} attempt(s) with no rectangular var-tx leaf decoded \
4024 but mismatched ffmpeg -- a defect of another shape, not a pass"
4025 );
4026 assert!(
4027 compared + out_of_scope > 0,
4028 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
4029 );
4030 // The firing half. lane-vartxsplit r2 re-measured it against
4031 // the oracle: attempts 16/17 (384x256 product texture, cq 44/46,
4032 // `--min-partition-size=8 --enable-tx-size-search=1`) are the only
4033 // recipes of a ~40-run sweep whose stream carries `TX_32X8` /
4034 // `TX_8X32` split symbols, i.e. RECTANGULAR var-tx leaves (16x8
4035 // and 8x16, both orientations out of the same stream). They now
4036 // decode PIXEL-EXACT on all six frames, so the assert is on the
4037 // pixel-compared tally, not on the "decoded anywhere" one --
4038 // `fired_*` stays only to separate a refused stream's leaves from
4039 // a proved one (class counter-from-refused-stream). At 10 bits
4040 // the same sweep either fires nothing or mismatches on a
4041 // reconstruction defect of another shape (report), so the firing
4042 // assert stays 8-bit -- and it is a hard assert, never a print.
4043 if bit_depth == 8 {
4044 assert!(
4045 leaf_32x16 > 0 && leaf_16x32 > 0,
4046 "{NAME}: the rectangular var-tx leaf arm never fired on a pixel-exact \
4047 attempt (pixel-compared 32x16={leaf_32x16}, 16x32={leaf_16x32}, decoded \
4048 anywhere 32x16={fired_32x16} 16x32={fired_16x32}, {named_refusals} \
4049 refusals, {compared} compared) -- the rectangular sub-transform path is \
4050 unproved by this gate"
4051 );
4052 }
4053 }
4054 }
4055
4056 /// lane-rectres r1: a 32x32-level 1:4 INTER strip (32x8 / 8x32) that codes
4057 /// a REAL rectangular residual. THIS is the shape both 10-bit 3840x1608
4058 /// film cuts and every measured 1080p offset stopped on -- six of six
4059 /// `decode_probe` runs refused at "a non-skip rectangular (HORZ/VERT/
4060 /// HORZ_B) strip needs rectangular residual coding" with `w=32 h=8` or
4061 /// `w=8 h=32`, nothing else.
4062 ///
4063 /// `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256 of its
4064 /// positions ([`TxbSet::LumaRect32x8Inter`]: `get_txsize_entropy_ctx` =
4065 /// TX_16X16 so the coefficient tables are the luma-16 ones,
4066 /// `txsize_log2_minus4` = 4 so `eob_pt` is the 256-position alphabet), and
4067 /// unlike the INTRA twin it DOES code a `tx_type`:
4068 /// `av1_get_ext_tx_set_type` at `tx_size_sqr_up == TX_32X32` is
4069 /// `EXT_TX_SET_DCT_IDTX` for inter with or without `reduced_tx_set`, read
4070 /// at the `txsize_sqr_map[TX_32X8] == TX_8X8` CDF row (class
4071 /// table-indexed-by-raw-size: the coefficient tables follow the ADJUSTED
4072 /// size, the `tx_type` row the SQUARE one -- they disagree here).
4073 /// Its chroma pair is one 16x4 / 4x16 unit (`ss_size_lookup[BLOCK_32X8]`
4074 /// = BLOCK_16X4, `Chroma8`'s tables, 64-position `eob_pt`), and a split
4075 /// transform gives 16x8 / 8x16 leaves (`sub_tx_size_map[TX_32X8] ==
4076 /// TX_16X8`) the rect var-tx path already reads.
4077 ///
4078 /// `--enable-1to4-partitions=1 --min-partition-size=8
4079 /// --max-partition-size=32 --enable-tx-size-search=1` (each spelled once,
4080 /// last occurrence wins -- aomenc keeps the LAST `--enable-*`) is what
4081 /// lets aomenc pick a 32x32-level HORZ_4 / VERT_4; the 8-pixel banded
4082 /// translating source is what makes those strips the RD winner and keeps
4083 /// them non-skip so the residual is really coded. Both orientations, 8-bit
4084 /// AND 10-bit, every decode-order frame compared to ffmpeg on Y/U/V,
4085 /// refusals counted (never SKIPped), attempts that carried no 32x8/8x32
4086 /// residual unit counted separately and still required pixel-exact.
4087 #[test]
4088 fn a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual() {
4089 const NAME: &str =
4090 "a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual";
4091 let _gate_lock = lock_gate_counters();
4092 if !have_ffmpeg() {
4093 eprintln!("SKIP {NAME}: no ffmpeg");
4094 return;
4095 }
4096 if !have_aomenc() {
4097 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4098 return;
4099 }
4100 let frame_count = 6usize;
4101 let (mut proved_32x8, mut proved_8x32) = (0usize, 0usize);
4102 let (mut fired_32x8, mut fired_8x32) = (0usize, 0usize);
4103 for bit_depth in [8u32, 10u32] {
4104 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
4105 (0u32, 0u32, 0u32, 0u32);
4106 for attempt in 0..16u32 {
4107 // Two orientations (the transposed pair a one-sided gate could
4108 // never separate) x four quantisers x two motion steps.
4109 let vertical = attempt % 2 == 1;
4110 let (width, height) = (192usize, 128usize);
4111 let cq = [48, 52, 56, 60][(attempt / 2 % 4) as usize];
4112 let sp = 3 + (attempt / 8) * 4;
4113 // 32-pixel bands, each translating at its OWN speed across the
4114 // other axis: that is what makes aomenc's RD split a 32x32
4115 // block into four 32x8 (or 8x32) strips with distinct motion
4116 // vectors, and the texture inside a band is what keeps a strip
4117 // non-skip. MEASURED (72-run recipe sweep, 192x128..256x192,
4118 // cq 24..60, bands 8/16/32/64): only 32-pixel bands at cq >= 48
4119 // make aomenc code a NON-SKIP one -- attempt 0 (cq 48,
4120 // horizontal source) codes an 8x32 residual unit, attempt 7
4121 // (cq 60, the transposed source) five 32x8 ones. Narrower
4122 // bands give the same strips with `skip` set, which proves the
4123 // partition symbol and nothing about the residual.
4124 let geq = if vertical {
4125 format!("128+62*sin((Y+N*({sp}+7*mod(floor(X/32),4)))/6)+28*sin(X/9)")
4126 } else {
4127 format!("128+62*sin((X+N*({sp}+7*mod(floor(Y/32),4)))/6)+28*sin(Y/9)")
4128 };
4129 let duration = frame_count as f64 / 25.0;
4130 let source = format!(
4131 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
4132 geq=lum='{geq}',format=yuv420p"
4133 );
4134 let pix_fmt = if bit_depth == 10 {
4135 "yuv420p10le"
4136 } else {
4137 "yuv420p"
4138 };
4139 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
4140 .args([
4141 "-v",
4142 "error",
4143 "-f",
4144 "lavfi",
4145 "-i",
4146 &source,
4147 "-t",
4148 &duration.to_string(),
4149 "-pix_fmt",
4150 pix_fmt,
4151 "-strict",
4152 "-1",
4153 "-f",
4154 "yuv4mpegpipe",
4155 "-",
4156 ])
4157 .stdin(Stdio::null())
4158 .stdout(Stdio::piped())
4159 .stderr(Stdio::piped()), None, |c| c.output())
4160 .expect("ffmpeg failed to run");
4161 assert!(
4162 y4m.status.success(),
4163 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
4164 String::from_utf8_lossy(&y4m.stderr)
4165 );
4166 let cq_arg = format!("--cq-level={cq}");
4167 let depth_arg = format!("--bit-depth={bit_depth}");
4168 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
4169 let args: Vec<&str> = vec![
4170 "--codec=av1",
4171 "--passes=1",
4172 "--end-usage=q",
4173 &cq_arg,
4174 "--cpu-used=0",
4175 "--threads=1",
4176 "--row-mt=0",
4177 "--sb-size=64",
4178 &depth_arg,
4179 &input_depth_arg,
4180 "--enable-restoration=0",
4181 "--enable-palette=0",
4182 "--deltaq-mode=0",
4183 "--enable-filter-intra=0",
4184 "--enable-cfl-intra=0",
4185 "--enable-intrabc=0",
4186 "--lag-in-frames=0",
4187 // Per-arm overrides go LAST: aomenc keeps the last
4188 // occurrence of a repeated --enable-* flag.
4189 "--enable-tx64=0",
4190 "--enable-rect-partitions=1",
4191 "--enable-ab-partitions=0",
4192 "--enable-1to4-partitions=1",
4193 "--enable-tx-size-search=1",
4194 "--enable-dual-filter=0",
4195 "--enable-obmc=0",
4196 // aomenc's min-partition-size bounds the SMALLER side of a
4197 // 1:4 strip, so 32x8 needs 8 (memory
4198 // aomenc-min-partition-bounds-smaller-side).
4199 "--min-partition-size=8",
4200 "--max-partition-size=32",
4201 "--obu",
4202 "-o",
4203 "-",
4204 "-",
4205 ];
4206 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
4207 assert!(
4208 out.status.success(),
4209 "aomenc refused the fixture: {}",
4210 String::from_utf8_lossy(&out.stderr)
4211 );
4212 let stream = out.stdout;
4213 let before = crate::stream::rect32x8_inter_tu_hits();
4214 let frames = match decode_stream(&stream) {
4215 Err(e) => {
4216 let msg = e.to_string();
4217 assert!(
4218 msg.contains("unsupported"),
4219 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
4220 attempt {attempt}): {msg}"
4221 );
4222 let after = crate::stream::rect32x8_inter_tu_hits();
4223 // Firing counted on a refused stream is kept apart from
4224 // the pixel-proved tally (class
4225 // counter-from-refused-stream).
4226 fired_32x8 += after[0] - before[0];
4227 fired_8x32 += after[1] - before[1];
4228 named_refusals += 1;
4229 eprintln!(
4230 "{NAME} {bit_depth}-bit attempt {attempt} refusal (32x8 residual \
4231 units decoded before it: {}, 8x32: {}): {msg}",
4232 after[0] - before[0],
4233 after[1] - before[1]
4234 );
4235 continue;
4236 }
4237 Ok(frames) => frames,
4238 };
4239 let after = crate::stream::rect32x8_inter_tu_hits();
4240 let (h, v) = (after[0] - before[0], after[1] - before[1]);
4241 fired_32x8 += h;
4242 fired_8x32 += v;
4243 let ffmpeg_frames = if bit_depth == 10 {
4244 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
4245 } else {
4246 ffmpeg_decode_sequence(&stream, width, height, frame_count)
4247 };
4248 assert_eq!(frames.len(), frame_count);
4249 let mismatched = frames
4250 .iter()
4251 .zip(&ffmpeg_frames)
4252 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
4253 if h + v == 0 {
4254 out_of_scope += 1;
4255 if mismatched {
4256 oos_mismatch += 1;
4257 eprintln!(
4258 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
4259 32x8/8x32 inter residual units -- another shape's defect"
4260 );
4261 }
4262 continue;
4263 }
4264 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4265 assert_eq!(
4266 got.y, want.y,
4267 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
4268 );
4269 assert_eq!(
4270 got.u, want.u,
4271 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
4272 );
4273 assert_eq!(
4274 got.v, want.v,
4275 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
4276 );
4277 }
4278 proved_32x8 += h;
4279 proved_8x32 += v;
4280 compared += 1;
4281 }
4282 eprintln!(
4283 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
4284 pixel-exact attempts carrying the arm, {out_of_scope} attempts carried none \
4285 ({oos_mismatch} of them mismatched)"
4286 );
4287 assert_eq!(
4288 oos_mismatch, 0,
4289 "{NAME}: {oos_mismatch} attempt(s) with no 32x8/8x32 inter residual unit \
4290 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
4291 );
4292 assert!(
4293 compared + out_of_scope > 0,
4294 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
4295 );
4296 }
4297 eprintln!(
4298 "{NAME}: pixel-compared 32x32-level 1:4 inter residual units 32x8={proved_32x8} \
4299 8x32={proved_8x32} (decoded anywhere in the sweep 32x8={fired_32x8} \
4300 8x32={fired_8x32})"
4301 );
4302 // The firing half, one assert per lifted shape. Both orientations must
4303 // be PIXEL-PROVED: a transposed table passes one and fails the other
4304 // (class reference-layout-not-spec).
4305 assert!(
4306 proved_32x8 > 0,
4307 "{NAME}: no 32x8 inter residual transform unit was decoded inside a pixel-exact \
4308 attempt (decoded anywhere: {fired_32x8}) -- the lift is unproved"
4309 );
4310 assert!(
4311 proved_8x32 > 0,
4312 "{NAME}: no 8x32 inter residual transform unit was decoded inside a pixel-exact \
4313 attempt (decoded anywhere: {fired_8x32}) -- the lift is unproved"
4314 );
4315 }
4316
4317 /// lane-sbrect10 r1: a 64x64 INTRA block inside an INTER frame, whose
4318 /// `uv_mode` alphabet libaom's `is_cfl_allowed` (`blockd.h`: `wide <= 32
4319 /// && high <= 32`) narrows to the 13-symbol NO-CFL table. Reading the
4320 /// 14-symbol CFL one produced the same `DC_PRED` value with the wrong
4321 /// interval narrowing, so the tile desynced from that block on and the
4322 /// frame decoded silently wrong (class `wrong-alphabet-same-value`; found
4323 /// as the "another shape" mismatch the superblock rect gate above had to
4324 /// park its 10-bit arm on).
4325 ///
4326 /// The counter `nocfl_uv_mode_hits` proves the shape fired in EVERY
4327 /// compared attempt, and every decode-order frame is compared against
4328 /// ffmpeg -- an attempt that mismatches fails, it never SKIPs.
4329 ///
4330 /// lane-sbrect10 r2: with the half-random source below this gate also
4331 /// covers a SECOND defect it exposed at 10-bit cq 58/61 -- the compound
4332 /// MV stack's extension pass zero-filled the `comp_list` tail slots
4333 /// libaom fills with each side's GLOBAL MOTION vector
4334 /// (`combine_compound_candidates`, mvref_common.c:723-729). A compound
4335 /// block with no usable neighbour pair (frame top row, intra block to
4336 /// its left, empty temporal field) then took a `(0, 0)` predictor
4337 /// instead of the frame's translation: 32890/39907 wrong luma samples
4338 /// on decode-order frame 2 with the entropy stream still in sync.
4339 #[test]
4340 fn a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet() {
4341 const NAME: &str =
4342 "a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet";
4343 let _gate_lock = lock_gate_counters();
4344 if !have_ffmpeg() {
4345 eprintln!("SKIP {NAME}: no ffmpeg");
4346 return;
4347 }
4348 if !have_aomenc() {
4349 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4350 return;
4351 }
4352 let (width, height, frame_count) = (192usize, 128usize, 6usize);
4353 for bit_depth in [8u32, 10u32] {
4354 let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
4355 let mut total_hits = 0usize;
4356 for attempt in 0..16u32 {
4357 // The sibling superblock-rect gate's own grid (its 10-bit
4358 // attempt 14 -- cq 61, horizontal split, motion step 12 -- is
4359 // the stream that exposed the defect); which superblock the RD
4360 // hands an intra 64x64 block moves with the quantiser and the
4361 // depth, so both orientations x four quantisers x two motion
4362 // steps run here too.
4363 let vertical_split = attempt % 2 == 1;
4364 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
4365 let sp = 8 + (attempt / 8) * 4;
4366 // Half ramp, half deterministic pseudo-noise: the flat "200"
4367 // half of r1's source made aomenc code the right-hand
4368 // superblocks skip, so at 8 bit no >32 intra block ever
4369 // appeared (probed cq 45/52/58/61/63 = 0 hits). The textured
4370 // half forces intra above 32x32 in an inter frame at BOTH
4371 // depths, so both arms carry the shape.
4372 let geq = if vertical_split {
4373 format!(
4374 "if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
4375 )
4376 } else {
4377 format!(
4378 "if(lt(X,128), 40+mod(floor((Y+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
4379 )
4380 };
4381 let duration = frame_count as f64 / 25.0;
4382 let source = format!(
4383 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
4384 geq=lum='{geq}',format=yuv420p"
4385 );
4386 let pix_fmt = if bit_depth == 10 {
4387 "yuv420p10le"
4388 } else {
4389 "yuv420p"
4390 };
4391 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
4392 .args([
4393 "-v",
4394 "error",
4395 "-f",
4396 "lavfi",
4397 "-i",
4398 &source,
4399 "-t",
4400 &duration.to_string(),
4401 "-pix_fmt",
4402 pix_fmt,
4403 "-strict",
4404 "-1",
4405 "-f",
4406 "yuv4mpegpipe",
4407 "-",
4408 ])
4409 .stdin(Stdio::null())
4410 .stdout(Stdio::piped())
4411 .stderr(Stdio::piped()), None, |c| c.output())
4412 .expect("ffmpeg failed to run");
4413 assert!(
4414 y4m.status.success(),
4415 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
4416 String::from_utf8_lossy(&y4m.stderr)
4417 );
4418 let cq_arg = format!("--cq-level={cq}");
4419 let depth_arg = format!("--bit-depth={bit_depth}");
4420 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
4421 let args: Vec<&str> = vec![
4422 "--codec=av1",
4423 "--passes=1",
4424 "--end-usage=q",
4425 &cq_arg,
4426 "--cpu-used=0",
4427 "--threads=1",
4428 "--row-mt=0",
4429 "--sb-size=64",
4430 &depth_arg,
4431 &input_depth_arg,
4432 "--enable-restoration=0",
4433 "--enable-palette=0",
4434 "--deltaq-mode=0",
4435 "--enable-filter-intra=0",
4436 "--enable-cfl-intra=0",
4437 "--enable-intrabc=0",
4438 "--enable-tx-size-search=0",
4439 "--lag-in-frames=0",
4440 "--enable-rect-partitions=1",
4441 "--enable-ab-partitions=0",
4442 "--enable-1to4-partitions=1",
4443 "--min-partition-size=32",
4444 "--max-partition-size=64",
4445 "--obu",
4446 "-o",
4447 "-",
4448 "-",
4449 ];
4450 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
4451 assert!(
4452 out.status.success(),
4453 "aomenc refused the fixture: {}",
4454 String::from_utf8_lossy(&out.stderr)
4455 );
4456 let stream = out.stdout;
4457 let before = crate::decode::nocfl_uv_mode_hits();
4458 let frames = match decode_stream(&stream) {
4459 Err(e) => {
4460 let msg = e.to_string();
4461 assert!(
4462 msg.contains("unsupported"),
4463 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
4464 attempt {attempt}): {msg}"
4465 );
4466 named_refusals += 1;
4467 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
4468 continue;
4469 }
4470 Ok(frames) => frames,
4471 };
4472 let hits = crate::decode::nocfl_uv_mode_hits() - before;
4473 let ffmpeg_frames = if bit_depth == 10 {
4474 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
4475 } else {
4476 ffmpeg_decode_sequence(&stream, width, height, frame_count)
4477 };
4478 assert_eq!(frames.len(), frame_count);
4479 if hits == 0 {
4480 // No 64-axis intra block in this stream: still compared
4481 // (a mismatch here is a defect, never a pass), just not
4482 // proof of this gate's shape.
4483 carried_none += 1;
4484 }
4485 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4486 assert_eq!(
4487 got.y, want.y,
4488 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
4489 );
4490 assert_eq!(
4491 got.u, want.u,
4492 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
4493 );
4494 assert_eq!(
4495 got.v, want.v,
4496 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
4497 );
4498 }
4499 if hits > 0 {
4500 matched += 1;
4501 total_hits += hits;
4502 }
4503 }
4504 eprintln!(
4505 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
4506 attempts carrying a >32 intra block ({total_hits} no-CFL uv_mode reads), \
4507 {carried_none} attempts carried none"
4508 );
4509 assert!(
4510 matched > 0 && total_hits > 0,
4511 "{NAME} ({bit_depth}-bit): no attempt decoded an intra block above 32x32, so the \
4512 no-CFL uv_mode alphabet was never exercised -- gate proved nothing \
4513 ({named_refusals} refusals, {carried_none} attempts carried none)"
4514 );
4515 }
4516 }