forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

gates_a.rs2841 lines, 126.0 KiBHistoryRawDownload
1use super::*;
2use super::support::*;
3
4 /// Three-bucket gate summary (class [[gate-skips-on-its-own-failure]]):
5 /// every attempt lands in exactly one bucket -- decoded pixel-exact WITH
6 /// the feature counter moving, decoded pixel-exact WITHOUT it, or a named
7 /// refusal -- and the three sum to the attempts made.
8 pub(super) fn gate_buckets(name: &str, counted_exact: u32, uncounted_exact: u32, named_refusals: usize) {
9 eprintln!(
10 "{name}: buckets counted-exact={counted_exact} uncounted-exact={uncounted_exact} \
11 named-refusals={named_refusals} (attempts {})",
12 counted_exact as usize + uncounted_exact as usize + named_refusals
13 );
14 }
15
16 pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
17 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
18 }
19
20 /// The body every 4:4:4 lossy live gate runs: assert the oracle compare
21 /// CANNOT be skipped, assert the decode really is the cell it claims
22 /// (frame count, geometry, full-resolution chroma), assert the 4:4:4-only
23 /// own-extent route really ran, then compare every frame in decode order
24 /// against the oracle aomdec with the length asserted first.
25 ///
26 /// The aomdec arm is a HARD failure, not a skip: these three gates encode
27 /// LIVE, so reaching this point means the oracle aomenc resolved, and
28 /// aomenc and aomdec ship in the same build directory -- an aomdec that is
29 /// missing beside a present aomenc is a broken oracle, not a checkout
30 /// without one. (The older shape, `if aomdec_path().is_file()`, let the
31 /// compare vanish with no env escape at all; that is what
32 /// [`aomdec_available`] replaced for the pinned gates, and it cannot be
33 /// used here because these gates have no stream to compare without one.)
34 pub(super) fn gate_444_lossy_live_exact(name: &str, w: usize, h: usize) {
35 // The ONLY way out without measuring, and it has already printed a
36 // SKIP naming the env var that would turn it into a failure.
37 let Some(stream) = encode_444_lossy_live(name, w, h) else {
38 return;
39 };
40 assert!(
41 aomdec_path().is_file(),
42 "{name}: the oracle aomenc resolved to {} but no aomdec sits beside it at {} -- \
43 the pixel compare would silently skip, which this gate treats as a failure",
44 aomenc_path().display(),
45 aomdec_path().display()
46 );
47
48 let _guard = lock_gate_counters();
49 crate::decode::reset_rect4_inter_own_chroma444_hits();
50 let frames = decode_stream(&stream).unwrap_or_else(|e| {
51 panic!("{name}: the live {w}x{h} 4:4:4 lossy stream was refused: {e}")
52 });
53 let own = crate::decode::rect4_inter_own_chroma444_hits();
54 assert!(
55 own > 0,
56 "{name}: no 4:4:4 1:4 inter strip read its chroma context over its own extent -- \
57 the route this cell is a witness for never ran (measured: 13 at 66x66, 12 at \
58 130x122, 24 at 256x128)"
59 );
60 assert_eq!(
61 frames.len(),
62 4,
63 "{name}: decoded {} frame(s), the recipe encodes 4 -- a short decode would make the \
64 oracle compare cover a prefix of the cell",
65 frames.len()
66 );
67 for (i, f) in frames.iter().enumerate() {
68 assert_eq!(
69 (f.width, f.height),
70 (w, h),
71 "{name}: frame {i} is {}x{}, the cell is {w}x{h}",
72 f.width,
73 f.height
74 );
75 // At 4:4:4 both chroma planes are full resolution. A decoder that
76 // kept a subsampled extent would hand quarter-size planes to the
77 // byte compare; say so here instead of letting the compare
78 // stand in for the shape claim.
79 assert_eq!(
80 f.u.len(),
81 w * h,
82 "{name}: frame {i} U plane is {} samples; at 4:4:4 it must be full resolution \
83 ({w}x{h})",
84 f.u.len()
85 );
86 assert_eq!(
87 f.v.len(),
88 w * h,
89 "{name}: frame {i} V plane is {} samples; at 4:4:4 it must be full resolution \
90 ({w}x{h})",
91 f.v.len()
92 );
93 assert_eq!(
94 f.y.len(),
95 w * h,
96 "{name}: frame {i} luma plane is {} samples, expected {w}x{h}",
97 f.y.len()
98 );
99 }
100 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, name);
101 assert_eq!(
102 decoded, 4,
103 "{name}: the oracle decoded {decoded} frame(s) in decode order, the recipe carries 4 \
104 (so far {hidden} hidden)"
105 );
106 eprintln!(
107 "{name}: {w}x{h} 4:4:4 lossy, {decoded} decode-order frame(s) byte-exact vs aomdec \
108 ({hidden} hidden), {own} own-extent 1:4 chroma gather(s)"
109 );
110 }
111
112 /// lane-av1toolgates: the shared body of the two `enable-rect-tx`
113 /// coverage gates (8-bit and 10-bit).
114 ///
115 /// The aomenc ARGUMENT VECTOR is built by each gate and passed in, never
116 /// assembled here. That is not tidiness: `gate_coverage`'s `gate_bodies()`
117 /// splits `stream.rs` on `\n #[` and keeps a segment only if that
118 /// segment itself contains `--passes=1`, so a flag living in a helper is
119 /// invisible to the coverage derivation. A helper that owns the recipe
120 /// would leave this gate counted at whatever depth the helper's own text
121 /// implies -- which is the blind spot that kept `enable-rect-tx` on the
122 /// `NEVER_EXERCISED` lists after real streams had exercised it.
123 ///
124 /// WHAT THIS GATE IS AND IS NOT. `enable_rect_tx` has no sequence-header
125 /// bit in AV1 -- aom reads it only in `tx_search.c` (`search_tx_size`'s
126 /// `!enable_rect_tx && tx_size_wide != tx_size_high` skip and the
127 /// `tx_size_max_32_square` remap) -- so the flag never reaches a decoder.
128 /// Spelling `--enable-rect-tx=1` proves the ENCODER was ALLOWED the tool
129 /// and nothing more. It is CONTEXT here, not the witness: a gate that
130 /// stopped at the flag would be the `tool-disabled-in-every-gate` defect
131 /// `NEVER_EXERCISED` exists to prevent, in a new costume.
132 ///
133 /// The witness is the PARSED PARTITION SHAPE, the only thing in the
134 /// bitstream that can carry a rect transform:
135 /// [`decode::rect_partition_hits`] counts `PARTITION_HORZ`/`PARTITION_VERT`
136 /// symbols actually read, i.e. a rect partition in the tree this decoder
137 /// walked, and [`decode::rect_coeff_tu_hits`] counts the rectangular
138 /// transform units that then coded coefficients through `read_coeffs_rect`
139 /// (`all_zero == 0`) -- the rect coefficient TABLES being read, not a
140 /// header bit. Both are asserted above zero over the arms that decoded AND
141 /// compared, and every frame is pixel-compared against ffmpeg's own decode
142 /// of the identical bytes.
143 ///
144 /// LIMIT, stated because it bounds what this gate can claim: this
145 /// repository has no INDEPENDENT partition parser to list leaves from --
146 /// `ec-av1-syntax` parses OBU headers and the sequence header only -- and
147 /// `ec_av1::census`'s per-frame `blocks`/`tx` shape maps, the one true
148 /// leaf list, are armed by a process-global `OnceLock` on
149 /// `EC_AV1_BITCENSUS`, so arming them inside a lib test would switch the
150 /// accountant on for every other gate in the process. The partition walk is
151 /// therefore observed through the decoder's own counters, which is weaker
152 /// than a second opinion but is still a shape fact about the stream rather
153 /// than a fact about the flag.
154 ///
155 /// RED-BEFORE: the COUNTERS, one per assert, both measured.
156 /// `--enable-rect-tx=0` is deliberately NOT claimed as the mutation: it
157 /// does NOT zero these counters (39 rect coefficient TUs against 210 on
158 /// the cq20 arm, because `--enable-rect-partitions=1` already forces
159 /// non-square transform sizes regardless), and with every partition shape
160 /// off the flag yields no rect transform at either setting. `=0` does turn
161 /// the gate red, but through the ORACLE -- its `--enable-tx-size-search=0`
162 /// arm is a stream ffmpeg cannot decode past frame 6 of 15 -- so the
163 /// frame-count assert fires first and proves nothing about the tool.
164 pub(super) fn rect_tx_tool_gate(name: &str, ten_bit: bool, args: &[String]) -> (usize, usize) {
165 // A missing tool SKIPs, so the totals the caller sums stay 0 and the
166 // gate's own witness assert fails loudly instead of passing vacuously
167 // on a run that decoded nothing.
168 if !have_ffmpeg() {
169 eprintln!("SKIP {name}: no ffmpeg");
170 return (0, 0);
171 }
172 if !have_aomenc() {
173 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
174 return (0, 0);
175 }
176 let (width, height) = (64usize, 64usize);
177 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
178 .args([
179 "-v",
180 "error",
181 "-f",
182 "lavfi",
183 "-i",
184 "mandelbrot=size=64x64:rate=25",
185 "-pix_fmt",
186 if ten_bit { "yuv420p10le" } else { "yuv420p" },
187 // y4m calls 10-bit an unofficial pixel format (no-op at 8).
188 "-strict",
189 "-1",
190 "-t",
191 "0.60",
192 "-f",
193 "yuv4mpegpipe",
194 "-",
195 ])
196 .stdin(Stdio::null())
197 .stdout(Stdio::piped())
198 .stderr(Stdio::piped()), None, |c| c.output())
199 .expect("ffmpeg failed to run");
200 assert!(
201 y4m.status.success(),
202 "{name}: ffmpeg fixture: {}",
203 String::from_utf8_lossy(&y4m.stderr)
204 );
205 let out = run_with_stdin(Command::new(aomenc_path()).args(args), &y4m.stdout);
206 assert!(
207 out.status.success(),
208 "{name}: aomenc refused the fixture: {}",
209 String::from_utf8_lossy(&out.stderr)
210 );
211 let stream = out.stdout;
212 assert!(!stream.is_empty(), "{name}: aomenc wrote an empty stream");
213 if ten_bit {
214 assert_eq!(
215 parsed_bit_depth(&stream),
216 10,
217 "{name}: aomenc did not write a 10-bit sequence header"
218 );
219 }
220 let parts_before = decode::rect_partition_hits();
221 let tus_before = decode::rect_coeff_tu_hits();
222 let decoded = match decode_stream(&stream) {
223 Ok(frames) => frames,
224 Err(e) => panic!("{name}: decode_stream refused: {e}"),
225 };
226 // Sampled after the decode, before the pixel compare, so a mismatch
227 // report can still say whether the arm fired.
228 let parts = decode::rect_partition_hits() - parts_before;
229 let tus = decode::rect_coeff_tu_hits() - tus_before;
230 // The ENCODE's frame count: the fixture renders `mandelbrot=size=64x64:rate=25`
231 // with `-t "0.60"` (10677-10691) -- 25 x 0.60 = 15 frames -- and the
232 // caller's `args` carry no `--limit` (10823-10853), so every arm's stream
233 // codes all 15. Asserted ABOVE the oracle call, which is the fix for the
234 // misattribution this gate's own doc comment records: the
235 // `--enable-tx-size-search=0` arm is a stream ffmpeg cannot decode past
236 // frame 6 of 15, and with the count taken from our decode the helper's
237 // byte-length assert fires FIRST and reads as an ffmpeg fault. Naming the
238 // 15 here makes the shortfall ours to explain.
239 const ENCODED_FRAMES: usize = 15;
240 assert_eq!(
241 decoded.len(),
242 ENCODED_FRAMES,
243 "{name}: the encode codes {ENCODED_FRAMES} frames, the decode showed {} (rect \
244 partitions {parts}, rect coefficient TUs {tus})",
245 decoded.len()
246 );
247 let reference = if ten_bit {
248 ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len())
249 } else {
250 ffmpeg_decode_sequence(&stream, width, height, decoded.len())
251 };
252 assert_eq!(
253 decoded.len(),
254 reference.len(),
255 "{name}: shown-frame count vs ffmpeg (rect partitions {parts}, rect coefficient \
256 TUs {tus})"
257 );
258 for (i, (ours, theirs)) in decoded.iter().zip(&reference).enumerate() {
259 for (plane, (a, b), w) in [
260 ("Y", (&ours.y, &theirs.y), width),
261 ("U", (&ours.u, &theirs.u), width / 2),
262 ("V", (&ours.v, &theirs.v), width / 2),
263 ] {
264 assert_eq!(a.len(), b.len(), "{name}: frame {i} {plane} plane length");
265 if a != b {
266 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
267 crate::dumpio::pin("TEST_PIN", &pin, &stream);
268 let at = a
269 .iter()
270 .zip(b.iter())
271 .position(|(x, y)| x != y)
272 .unwrap_or(0);
273 panic!(
274 "{name}: frame {i} {plane} mismatch vs ffmpeg at row {}, col {}: {} vs \
275 {} (rect partitions {parts}, rect coefficient TUs {tus}; stream pinned \
276 at {})",
277 at / w,
278 at % w,
279 a[at],
280 b[at],
281 pin.display()
282 );
283 }
284 }
285 }
286 eprintln!(
287 "{name}: {} bit, pixel-exact vs ffmpeg; parsed rect partitions {parts}, rect \
288 coefficient TUs {tus}",
289 if ten_bit { "10" } else { "8" }
290 );
291 (parts, tus)
292 }
293
294 /// lane-hbdgates r1: drive one 10-bit aomenc recipe over `seeds`, decode
295 /// every attempt and pixel-compare every SHOWN frame against ffmpeg's own
296 /// 10-bit decode of the identical bytes. Per-tool firing counters are
297 /// sampled PER ATTEMPT and summed only over attempts that decoded *and*
298 /// compared -- a stream that hit a named refusal contributes nothing
299 /// (class `counter-from-refused-stream`). Named refusals are tolerated
300 /// and reported; a pixel mismatch is a hard failure, never a SKIP.
301 pub(super) fn ten_bit_tool_gate(
302 name: &str,
303 width: usize,
304 height: usize,
305 frames: usize,
306 extra: &[&str],
307 seeds: &[u32],
308 counters: &[(&str, fn() -> usize)],
309 ) {
310 fn first_diff(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
311 ours.iter()
312 .zip(theirs.iter())
313 .position(|(a, b)| a != b)
314 .map(|i| {
315 format!(
316 "first diff at index {i} (row {}, col {}): ours {} vs ffmpeg {}",
317 i / width,
318 i % width,
319 ours[i],
320 theirs[i]
321 )
322 })
323 }
324 let mut totals = vec![0usize; counters.len()];
325 let mut refusals: Vec<String> = Vec::new();
326 let mut compared = 0usize;
327 for &seed in seeds {
328 let stream = encode_10bit_gradients_seed(name, seed, width, height, frames, extra);
329 assert_eq!(
330 parsed_bit_depth(&stream),
331 10,
332 "{name}: aomenc did not write a 10-bit sequence header (seed {seed})"
333 );
334 let before: Vec<usize> = counters.iter().map(|(_, f)| f()).collect();
335 let decoded = match decode_stream(&stream) {
336 Ok(frames) => frames,
337 Err(e) => {
338 refusals.push(format!("seed {seed}: {e}"));
339 continue;
340 }
341 };
342 // Deltas are read BEFORE the pixel compare so a mismatch report
343 // says whether the tool under test actually fired on the failing
344 // stream (a mismatch with a zero delta is some other defect).
345 let deltas: Vec<usize> = counters
346 .iter()
347 .zip(before.iter())
348 .map(|((_, f), b)| f() - b)
349 .collect();
350 let fired: Vec<String> = counters
351 .iter()
352 .zip(deltas.iter())
353 .map(|((label, _), d)| format!("{label}={d}"))
354 .collect();
355 let fired = fired.join(" ");
356 // The ENCODE's frame count, and it is this helper's `frames` PARAMETER
357 // (15446) -- not our decode's length. It is the same value handed to
358 // `encode_10bit_gradients_seed` (15469), which renders
359 // `frames / 25.0` seconds at `rate=25` (15928, 15940) and runs
360 // aomenc with no `--limit` of its own, so the stream codes exactly
361 // `frames` frames: 1 for the single-key-frame callers, 24 for the
362 // `--lag-in-frames=16` inter callers. Asserted ABOVE the oracle call,
363 // so a decode that showed fewer reds naming the encode rather than
364 // handing ffmpeg the same short count.
365 assert_eq!(
366 decoded.len(),
367 frames,
368 "{name}: seed {seed}: the encode codes {frames} frame(s), the decode showed {}",
369 decoded.len()
370 );
371 let reference = ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len());
372 assert_eq!(
373 decoded.len(),
374 reference.len(),
375 "{name}: seed {seed}: shown-frame count vs ffmpeg"
376 );
377 for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() {
378 for (plane, (a, b), w) in [
379 ("Y", (&ours.y, &theirs.y), width),
380 ("U", (&ours.u, &theirs.u), width / 2),
381 ("V", (&ours.v, &theirs.v), width / 2),
382 ] {
383 if let Some(d) = first_diff(a, b, w) {
384 panic!("{name}: seed {seed} frame {i} plane {plane}: {d} [{fired}]");
385 }
386 assert_eq!(
387 a.len(),
388 b.len(),
389 "{name}: seed {seed} frame {i} plane {plane}: ours has {} samples, \
390 ffmpeg's has {} -- a short plane would zip-truncate the walk above \
391 and hide a chroma-span defect",
392 a.len(),
393 b.len()
394 );
395 }
396 }
397 compared += 1;
398 for (i, d) in deltas.iter().enumerate() {
399 totals[i] += d;
400 }
401 }
402 assert!(
403 compared > 0,
404 "{name}: every attempt hit a named refusal:\n{}",
405 refusals.join("\n")
406 );
407 for (i, (label, _)) in counters.iter().enumerate() {
408 assert!(
409 totals[i] > 0,
410 "{name}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
411 the gate would prove nothing about that tool. refusals:\n{}",
412 refusals.join("\n")
413 );
414 }
415 let summary: Vec<String> = counters
416 .iter()
417 .zip(totals.iter())
418 .map(|((label, _), t)| format!("{label}={t}"))
419 .collect();
420 eprintln!(
421 "{name}: {compared}/{} attempts pixel-exact, {}",
422 seeds.len(),
423 summary.join(" ")
424 );
425 }
426
427 pub(super) fn intra_rect_in_inter_gate(bit_depth: u32) {
428 const NAME: &str =
429 "a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact";
430 if !have_ffmpeg() {
431 eprintln!("SKIP {NAME}: no ffmpeg");
432 return;
433 }
434 if !have_aomenc() {
435 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
436 return;
437 }
438 let (width, height, frame_count) = (96usize, 96usize, 8usize);
439 let mut refusals: Vec<String> = Vec::new();
440 let mut uncounted_exact = 0u32;
441 let mut compared = 0u32;
442 let mut shapes = [0usize; 3];
443 for attempt in 0..45u32 {
444 let seed = 42 + attempt;
445 // mandelbrot's fractal detail plus a HARD cut at frame 4: half
446 // the picture becomes a flat white box, which no motion vector
447 // can predict, so aomenc's RD codes those blocks INTRA inside an
448 // inter frame. The box's vertical edge at x=48 is what makes the
449 // partition search reach for HORZ/VERT strips there.
450 // A FAST ZOOM: `end_scale`/`end_pts` make mandelbrot rush
451 // through its own zoom, so consecutive frames share almost no
452 // content and aomenc's RD codes blocks INTRA inside INTER frames
453 // (`--kf-min-dist=1000` forbids a new key frame). That is the
454 // only way a real encoder reaches this decoder's intra-in-inter
455 // arm; a slowly-evolving source codes every rect strip inter.
456 let source = format!(
457 "mandelbrot=size={width}x{height}:start_scale={}:end_scale=0.004:end_pts=8:rate=25",
458 5.0 - f64::from(attempt) * 0.06
459 );
460 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
461 .args([
462 "-v",
463 "error",
464 "-f",
465 "lavfi",
466 "-i",
467 &source,
468 "-vf",
469 "hue=s=0",
470 "-pix_fmt",
471 if bit_depth == 10 {
472 "yuv420p10le"
473 } else {
474 "yuv420p"
475 },
476 "-strict",
477 "-1",
478 "-t",
479 "0.32",
480 "-f",
481 "yuv4mpegpipe",
482 "-strict",
483 "-1",
484 "-",
485 ])
486 .stdin(Stdio::null())
487 .stdout(Stdio::piped())
488 .stderr(Stdio::piped()), None, |c| c.output())
489 .expect("ffmpeg failed to run");
490 assert!(
491 y4m.status.success(),
492 "ffmpeg fixture: {}",
493 String::from_utf8_lossy(&y4m.stderr)
494 );
495 let depth_args: &[&str] = if bit_depth == 10 {
496 &["-b", "10", "--input-bit-depth=10"]
497 } else {
498 &[]
499 };
500 // MEASURED (r1): the speed preset gates the feature (class
501 // [[gate-preset-gates-the-feature]]) -- at `--cpu-used=4` this
502 // content produces no rect partition at all, at `--cpu-used=0`
503 // aomenc emits AB partitions the tile path refuses (it ignores
504 // `--enable-ab-partitions=0`, ledger). So the attempt sweep walks
505 // the preset as well as the seed.
506 let cpu = format!("--cpu-used={}", attempt % 5);
507 // The quantiser drives how finely the RD partitions: the sweep
508 // walks it too, so "no rect strip fired" cannot be an artefact of
509 // one cq.
510 let cq = format!("--cq-level={}", [30u32, 20, 12][(attempt / 5) as usize % 3]);
511 let out = run_with_stdin(
512 Command::new(aomenc_path())
513 .args(depth_args)
514 .arg(&cpu)
515 .arg(&cq)
516 .args([
517 // class [[aomenc-first-flag-wins]]: every flag is spelled
518 // exactly ONCE in this recipe, so there is no override to
519 // order. These four are what this gate is about.
520 "--enable-rect-partitions=1",
521 // MEASURED (r1): the charter's `--min-partition-size=8`
522 // makes 24/24 attempts stop at a sub-16 AB-partition
523 // refusal ("a HORZ_A/HORZ_B/VERT_A partition below 16x16",
524 // "a coded (non-skip) HORZ_B/VERT_B rect strip below
525 // 16x16") before any intra rect strip is reached -- those
526 // are other lanes' surfaces. 16 keeps the 16x8/8x16 shape
527 // reachable (a 16x16 block's own HORZ/VERT children).
528 "--min-partition-size=16",
529 "--max-partition-size=64",
530 // MEASURED (r1): with tx-size search ON, 24/24 attempts stop at
531 // the SQUARE intra-in-inter arm's own refusal ("an intra
532 // block in an inter frame whose tx_depth splits its luma
533 // transform (round 1)", read_block_tx_size) long before a
534 // rect strip is reached -- that arm is another lane's
535 // surface. OFF, no tx-depth symbol is coded at all and
536 // every rect strip here is the unsplit single-transform
537 // case. The SPLIT rect arm (`depth_to_tx_wh` +
538 // decode_rect_split's per-unit walk) is wired but stays
539 // UNGATED on this path until that square refusal lifts.
540 "--enable-tx-size-search=0",
541 "--codec=av1",
542 "--passes=1",
543 "--end-usage=q",
544 "--lag-in-frames=0",
545 "--auto-alt-ref=0",
546 // One key frame at the head: the frames after the cut must
547 // stay INTER frames carrying intra blocks, not become a
548 // new key frame.
549 "--kf-min-dist=1000",
550 "--kf-max-dist=1000",
551 "--threads=1",
552 "--row-mt=0",
553 "--enable-order-hint=0",
554 "--enable-warped-motion=0",
555 "--enable-obmc=0",
556 "--enable-masked-comp=0",
557 "--enable-interintra-comp=0",
558 "--enable-dist-wtd-comp=0",
559 "--enable-diff-wtd-comp=0",
560 "--enable-onesided-comp=0",
561 "--enable-interintra-wedge=0",
562 "--enable-smooth-interintra=0",
563 "--enable-ab-partitions=0",
564 "--enable-1to4-partitions=0",
565 // The intra-in-inter arm reads no `use_filter_intra`
566 // symbol (square OR rect) -- lane-fiinter owns that read.
567 "--enable-filter-intra=0",
568 "--enable-smooth-intra=0",
569 "--enable-paeth-intra=0",
570 "--enable-directional-intra=0",
571 "--enable-angle-delta=0",
572 "--enable-cdef=0",
573 "--enable-restoration=0",
574 "--enable-palette=0",
575 "--enable-intrabc=0",
576 "--enable-cfl-intra=0",
577 "--enable-ref-frame-mvs=0",
578 "--obu",
579 "-o",
580 "-",
581 "-",
582 ]),
583 &y4m.stdout,
584 );
585 assert!(
586 out.status.success(),
587 "aomenc refused the fixture: {}",
588 String::from_utf8_lossy(&out.stderr)
589 );
590 let stream = out.stdout;
591 let before = [
592 decode::intra_rect_strip_in_inter_hits(0),
593 decode::intra_rect_strip_in_inter_hits(1),
594 decode::intra_rect_strip_in_inter_hits(2),
595 ];
596 let kf_rect_before = decode::rect_partition_hits();
597 let frames = match decode_stream(&stream) {
598 Ok(frames) => frames,
599 Err(e) => {
600 let msg = e.to_string();
601 assert!(
602 msg.contains("unsupported"),
603 "intra-rect-in-inter decode failed outright (seed {seed}): {msg}"
604 );
605 refusals.push(format!("seed {seed} {cpu} {cq}: {msg}"));
606 continue;
607 }
608 };
609 let delta = [
610 decode::intra_rect_strip_in_inter_hits(0) - before[0],
611 decode::intra_rect_strip_in_inter_hits(1) - before[1],
612 decode::intra_rect_strip_in_inter_hits(2) - before[2],
613 ];
614 let ffmpeg_frames = if bit_depth == 10 {
615 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
616 } else {
617 ffmpeg_decode_sequence(&stream, width, height, frame_count)
618 };
619 assert_eq!(frames.len(), frame_count);
620 eprintln!(
621 "intrarect gate {bit_depth}-bit seed={seed} {cpu} {cq}: intra rect strips in inter frames \
622 64-level={} 32-level={} 16-level={}, key-frame rect strips this stream={}",
623 delta[0],
624 delta[1],
625 delta[2],
626 decode::rect_partition_hits() - kf_rect_before
627 );
628 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
629 for (plane, (g, w)) in [
630 ("Y", (&got.y, &want.y)),
631 ("U", (&got.u, &want.u)),
632 ("V", (&got.v, &want.v)),
633 ] {
634 let stride = if plane == "Y" { width } else { width / 2 };
635 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
636 eprintln!(
637 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} first \
638 diff at ({}, {}) got {} want {} ({} samples differ)",
639 at % stride,
640 at / stride,
641 g[at],
642 w[at],
643 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
644 );
645 // Magnitude separates a deblock/prediction difference
646 // (all |d| == 1) from an entropy desync (large,
647 // arbitrary): the first thing r2 needs to know.
648 let maxd = g
649 .iter()
650 .zip(w.iter())
651 .map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b)))
652 .max()
653 .unwrap_or(0);
654 let rows: std::collections::BTreeSet<usize> = g
655 .iter()
656 .zip(w.iter())
657 .enumerate()
658 .filter(|(_, (a, b))| a != b)
659 .map(|(k, _)| k / stride)
660 .collect();
661 eprintln!(
662 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} max \
663 |diff|={maxd}, rows {:?}..{:?}",
664 rows.iter().next(),
665 rows.iter().next_back()
666 );
667 }
668 assert_eq!(g, w, "{plane} vs ffmpeg (seed {seed}, frame {i})");
669 }
670 }
671 compared += 1;
672 if delta.iter().all(|d| *d == 0) {
673 uncounted_exact += 1;
674 refusals.push(format!(
675 "seed {seed} {cpu} {cq}: decoded and pixel-compared, but no intra rect strip on the \
676 inter path"
677 ));
678 }
679 for k in 0..3 {
680 shapes[k] += delta[k];
681 }
682 if shapes.iter().filter(|n| **n > 0).count() >= 2 {
683 break;
684 }
685 }
686 gate_buckets(
687 NAME,
688 compared - uncounted_exact,
689 uncounted_exact,
690 refusals.len() - uncounted_exact as usize,
691 );
692 eprintln!(
693 "{NAME} ({bit_depth}-bit): compared {compared} streams, intra rect strips in inter \
694 frames per shape: 64x32/32x64={} 32x16/16x32={} 16x8/8x16={}; refusals:\n{}",
695 shapes[0],
696 shapes[1],
697 shapes[2],
698 refusals.join("\n")
699 );
700 assert!(
701 compared > 0,
702 "{NAME} ({bit_depth}-bit): every attempt hit a named refusal -- nothing was \
703 pixel-compared:\n{}",
704 refusals.join("\n")
705 );
706 // MEASURED (r1, 90 attempts; r2 re-ran the 45-attempt sweep at both
707 // depths): only the 32x16/16x32 class is REACHABLE on this branch --
708 // the inter tile path refuses any SB-level partition other than
709 // NONE/SPLIT, so a 64x32/32x64 intra strip cannot be produced at all,
710 // and every 16x8/8x16 candidate stops at a sub-16 refusal owned by
711 // another lane. So the bar is that class, hard, not "two of three":
712 // a green run still cannot come from a stream that fired nothing.
713 assert!(
714 shapes[1] > 0,
715 "{NAME} ({bit_depth}-bit): no 32x16/16x32 intra rect strip fired over \
716 {compared} compared streams (64-level={} 32-level={} 16-level={})",
717 shapes[0],
718 shapes[1],
719 shapes[2]
720 );
721 }
722
723 pub(super) fn tx_select_inter_gate(bit_depth: u32) {
724 if !have_ffmpeg() {
725 eprintln!(
726 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no ffmpeg"
727 );
728 return;
729 }
730 if !have_aomenc() {
731 eprintln!(
732 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no aomenc at {}",
733 aomenc_path().display()
734 );
735 return;
736 }
737 let (width, height, frame_count) = (64usize, 64usize, 4usize);
738 let mut refusals = Vec::new();
739 let mut uncounted_exact = 0u32;
740 for attempt in 0..40u32 {
741 let seed = 42 + attempt;
742 // Detail is what makes aomenc's RD prefer a split transform; a
743 // flat gradient resolves every `txfm_split` to 0. `mandelbrot`'s
744 // fractal boundary is the same source the sibling intra tx-select
745 // gate uses, at a different `start_scale` per attempt.
746 let source = format!(
747 "mandelbrot=size=64x64:start_scale={}:rate=25",
748 5.0 - f64::from(attempt) * 0.06
749 );
750 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
751 .args([
752 "-v",
753 "error",
754 "-f",
755 "lavfi",
756 "-i",
757 &source,
758 // Desaturated chroma: `uv_mode` stays DC_PRED, so the
759 // still-refused directional-chroma gap never fires and
760 // luma detail alone drives the transform split.
761 "-vf",
762 "hue=s=0",
763 "-pix_fmt",
764 if bit_depth == 10 {
765 "yuv420p10le"
766 } else {
767 "yuv420p"
768 },
769 // y4m carries no official 10-bit tag; ffmpeg writes one
770 // only under `-strict -1` (a no-op at 8 bit).
771 "-strict",
772 "-1",
773 "-t",
774 "0.16",
775 "-f",
776 "yuv4mpegpipe",
777 "-strict",
778 "-1",
779 "-",
780 ])
781 .stdin(Stdio::null())
782 .stdout(Stdio::piped())
783 .stderr(Stdio::piped()), None, |c| c.output())
784 .expect("ffmpeg failed to run");
785 assert!(
786 y4m.status.success(),
787 "ffmpeg fixture: {}",
788 String::from_utf8_lossy(&y4m.stderr)
789 );
790 let depth_args: &[&str] = if bit_depth == 10 {
791 &["-b", "10", "--input-bit-depth=10"]
792 } else {
793 &[]
794 };
795 let out = run_with_stdin(
796 Command::new(aomenc_path()).args(depth_args).args([
797 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
798 // occurrence, so overrides go before the base list).
799 "--enable-tx-size-search=1",
800 "--codec=av1",
801 "--passes=1",
802 "--end-usage=q",
803 "--cq-level=55",
804 "--cpu-used=0",
805 "--lag-in-frames=0",
806 "--auto-alt-ref=0",
807 "--kf-max-dist=1000",
808 "--threads=1",
809 "--row-mt=0",
810 "--enable-order-hint=0",
811 "--enable-warped-motion=0",
812 "--enable-obmc=0",
813 "--enable-masked-comp=0",
814 "--enable-interintra-comp=0",
815 "--enable-dist-wtd-comp=0",
816 "--enable-diff-wtd-comp=0",
817 "--enable-onesided-comp=0",
818 "--enable-interintra-wedge=0",
819 "--enable-smooth-interintra=0",
820 "--enable-rect-partitions=0",
821 "--enable-ab-partitions=0",
822 "--enable-1to4-partitions=0",
823 "--enable-filter-intra=0",
824 "--enable-smooth-intra=0",
825 "--enable-paeth-intra=0",
826 "--enable-directional-intra=0",
827 "--enable-angle-delta=0",
828 // DELIBERATELY ABSENT: --enable-tx-size-search=0.
829 "--enable-cdef=0",
830 "--enable-restoration=0",
831 "--max-partition-size=32",
832 // Sub-16 inter partitions are a separate named refusal
833 // (this decoder codes no inter block below 16x16 through
834 // the square path this gate drives), and detailed content
835 // makes aomenc's RD reach for them on nearly every seed.
836 "--min-partition-size=16",
837 "--enable-palette=0",
838 "--enable-intrabc=0",
839 "--enable-cfl-intra=0",
840 "--enable-ref-frame-mvs=0",
841 "--obu",
842 "-o",
843 "-",
844 "-",
845 ]),
846 &y4m.stdout,
847 );
848 assert!(
849 out.status.success(),
850 "aomenc refused the fixture: {}",
851 String::from_utf8_lossy(&out.stderr)
852 );
853 let stream = out.stdout;
854 let (reads_before, hits_before) =
855 (decode::txfm_split_reads(), decode::txfm_split_hits());
856 let frames = match decode_stream(&stream) {
857 Ok(frames) => frames,
858 Err(e) => {
859 let msg = e.to_string();
860 assert!(
861 msg.contains("unsupported"),
862 "tx-select inter decode failed outright (seed {seed}): {msg}"
863 );
864 refusals.push(format!("seed {seed}: {msg}"));
865 continue;
866 }
867 };
868 let (reads, hits) = (
869 decode::txfm_split_reads() - reads_before,
870 decode::txfm_split_hits() - hits_before,
871 );
872 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
873 // is ALWAYS pixel-compared below; the hit counter only decides whether
874 // the attempt counts toward the firing total.
875 let counted = hits != 0;
876 if !counted {
877 uncounted_exact += 1;
878 refusals.push(format!(
879 "seed {seed}: decoded and pixel-compared, but no block took a txfm_split \
880 ({reads} symbols read)"
881 ));
882 }
883 let ffmpeg_frames = if bit_depth == 10 {
884 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
885 } else {
886 ffmpeg_decode_sequence(&stream, width, height, frame_count)
887 };
888 assert_eq!(frames.len(), frame_count);
889 eprintln!(
890 "txselect gate {bit_depth}-bit seed={seed}: txfm_split reads={reads} splits taken={hits}"
891 );
892 // Name the first differing sample before the assert fires: a
893 // 64x64 plane's `assert_eq!` output is 4096 numbers, useless for
894 // locating a desync.
895 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
896 for (plane, (g, w)) in [
897 ("Y", (&got.y, &want.y)),
898 ("U", (&got.u, &want.u)),
899 ("V", (&got.v, &want.v)),
900 ] {
901 let stride = if plane == "Y" { width } else { width / 2 };
902 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
903 eprintln!(
904 "txselect gate seed={seed}: frame {i} {plane} first diff at \
905 ({}, {}) got {} want {} ({} samples differ)",
906 at % stride,
907 at / stride,
908 g[at],
909 w[at],
910 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
911 );
912 let coords: Vec<String> = g
913 .iter()
914 .zip(w.iter())
915 .enumerate()
916 .filter(|(_, (a, b))| a != b)
917 .take(12)
918 .map(|(k, (a, b))| format!("({},{})={a}/{b}", k % stride, k / stride))
919 .collect();
920 eprintln!("txselect gate seed={seed}: frame {i} {plane} diffs {coords:?}");
921 }
922 }
923 }
924 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
925 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
926 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
927 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
928 }
929 if counted {
930 gate_buckets(
931 &format!("tx_select_inter_gate({bit_depth})"),
932 1,
933 uncounted_exact,
934 refusals.len() - uncounted_exact as usize,
935 );
936 return;
937 }
938 }
939 gate_buckets(
940 &format!("tx_select_inter_gate({bit_depth})"),
941 0,
942 uncounted_exact,
943 refusals.len() - uncounted_exact as usize,
944 );
945 panic!(
946 "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}",
947 refusals.join("\n")
948 );
949 }
950
951 pub(super) fn intra_in_inter_split_tx_gate(bit_depth: u32) {
952 let name = format!("intra_in_inter_split_tx_gate({bit_depth})");
953 if !have_ffmpeg() {
954 eprintln!("SKIP {name}: no ffmpeg");
955 return;
956 }
957 if !have_aomenc() {
958 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
959 return;
960 }
961 let (width, height, frame_count) = (64usize, 64usize, 8usize);
962 let mut refusals = Vec::new();
963 let mut uncounted_exact = 0u32;
964 for attempt in 0..40u32 {
965 let seed = 42 + attempt;
966 // A zooming fractal: every frame moves (so the sequence is
967 // genuinely inter-coded) and keeps sharp new detail entering at
968 // the borders, which is what makes aomenc's RD choose an INTRA
969 // block inside an inter frame -- and then split its transform.
970 // A zooming fractal with a hard CUT halfway (`overlay` switching
971 // a second, unrelated fractal on at frame 4): after the cut every
972 // block is unpredictable from the reference, which is what makes
973 // aomenc code INTRA blocks inside an inter frame -- and at this
974 // cq the RD then splits their transforms.
975 let source = format!(
976 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
977 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
978 [a][b]overlay=enable='gte(n,4)'",
979 5.0 - f64::from(attempt) * 0.06,
980 0.9 + f64::from(attempt) * 0.11
981 );
982 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
983 .args([
984 "-v",
985 "error",
986 "-f",
987 "lavfi",
988 "-i",
989 &source,
990 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
991 // still-refused directional-chroma gaps never fire and
992 // luma detail alone drives the transform split.
993 "-vf",
994 "hue=s=0",
995 "-pix_fmt",
996 if bit_depth == 10 {
997 "yuv420p10le"
998 } else {
999 "yuv420p"
1000 },
1001 "-strict",
1002 "-1",
1003 "-t",
1004 "0.32",
1005 "-f",
1006 "yuv4mpegpipe",
1007 "-strict",
1008 "-1",
1009 "-",
1010 ])
1011 .stdin(Stdio::null())
1012 .stdout(Stdio::piped())
1013 .stderr(Stdio::piped()), None, |c| c.output())
1014 .expect("ffmpeg failed to run");
1015 assert!(
1016 y4m.status.success(),
1017 "ffmpeg fixture: {}",
1018 String::from_utf8_lossy(&y4m.stderr)
1019 );
1020 let depth_args: &[&str] = if bit_depth == 10 {
1021 &["-b", "10", "--input-bit-depth=10"]
1022 } else {
1023 &[]
1024 };
1025 let out = run_with_stdin(
1026 Command::new(aomenc_path()).args(depth_args).args([
1027 "--codec=av1",
1028 "--passes=1",
1029 "--end-usage=q",
1030 "--cq-level=30",
1031 "--cpu-used=0",
1032 "--lag-in-frames=0",
1033 "--auto-alt-ref=0",
1034 // One key frame only: every later frame is an inter frame,
1035 // which is where this gate's intra blocks must sit. The
1036 // MIN distance is what stops aomenc's scene-cut detector
1037 // from inserting a second key frame at the cut this gate's
1038 // source deliberately contains.
1039 "--kf-max-dist=1000",
1040 "--kf-min-dist=1000",
1041 "--threads=1",
1042 "--row-mt=0",
1043 "--enable-order-hint=0",
1044 "--enable-warped-motion=0",
1045 "--enable-obmc=0",
1046 "--enable-masked-comp=0",
1047 "--enable-interintra-comp=0",
1048 "--enable-dist-wtd-comp=0",
1049 "--enable-diff-wtd-comp=0",
1050 "--enable-onesided-comp=0",
1051 "--enable-interintra-wedge=0",
1052 "--enable-smooth-interintra=0",
1053 "--enable-ab-partitions=0",
1054 "--enable-1to4-partitions=0",
1055 "--enable-filter-intra=0",
1056 "--enable-smooth-intra=0",
1057 "--enable-paeth-intra=0",
1058 "--enable-directional-intra=0",
1059 "--enable-angle-delta=0",
1060 "--enable-cdef=0",
1061 "--enable-restoration=0",
1062 "--enable-palette=0",
1063 "--enable-intrabc=0",
1064 "--enable-cfl-intra=0",
1065 "--enable-ref-frame-mvs=0",
1066 // Per-arm overrides go LAST (aomenc keeps the last
1067 // occurrence of a repeated --enable-* flag): the intra
1068 // tx_depth symbol only exists under TX_MODE_SELECT, and
1069 // rect partitions are a separate named refusal.
1070 "--enable-tx-size-search=1",
1071 "--enable-rect-partitions=0",
1072 "--max-partition-size=32",
1073 // Sub-16 inter partitions are a separate named refusal,
1074 // as is the 8x8 intra leaf's own TX_4X4 split.
1075 "--min-partition-size=16",
1076 "--obu",
1077 "-o",
1078 "-",
1079 "-",
1080 ]),
1081 &y4m.stdout,
1082 );
1083 assert!(
1084 out.status.success(),
1085 "aomenc refused the fixture: {}",
1086 String::from_utf8_lossy(&out.stderr)
1087 );
1088 let stream = out.stdout;
1089 let before = decode::intra_in_inter_split_tx_hits();
1090 let frames = match decode_stream(&stream) {
1091 Ok(frames) => frames,
1092 Err(e) => {
1093 let msg = e.to_string();
1094 assert!(
1095 msg.contains("unsupported"),
1096 "{name} decode failed outright (seed {seed}): {msg}"
1097 );
1098 refusals.push(format!("seed {seed}: {msg}"));
1099 continue;
1100 }
1101 };
1102 let after = decode::intra_in_inter_split_tx_hits();
1103 let mut per_size = [0usize; 4];
1104 for i in 0..4 {
1105 per_size[i] = after[i] - before[i];
1106 }
1107 // class [[gate-skips-on-its-own-failure]]: a decode that
1108 // succeeded is ALWAYS pixel-compared below; the counter only
1109 // decides whether the attempt counts as firing.
1110 let counted = per_size.iter().sum::<usize>() != 0;
1111 if !counted {
1112 uncounted_exact += 1;
1113 refusals.push(format!(
1114 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
1115 frame split its transform"
1116 ));
1117 }
1118 let ffmpeg_frames = if bit_depth == 10 {
1119 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1120 } else {
1121 ffmpeg_decode_sequence(&stream, width, height, frame_count)
1122 };
1123 assert_eq!(frames.len(), frame_count);
1124 eprintln!(
1125 "{name} seed={seed}: split intra-in-inter blocks 8x8={} 16x16={} 32x32={} \
1126 64x64={}",
1127 per_size[0], per_size[1], per_size[2], per_size[3]
1128 );
1129 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1130 for (plane, (g, w)) in [
1131 ("Y", (&got.y, &want.y)),
1132 ("U", (&got.u, &want.u)),
1133 ("V", (&got.v, &want.v)),
1134 ] {
1135 let stride = if plane == "Y" { width } else { width / 2 };
1136 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
1137 eprintln!(
1138 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
1139 want {} ({} samples differ)",
1140 at % stride,
1141 at / stride,
1142 g[at],
1143 w[at],
1144 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
1145 );
1146 }
1147 }
1148 }
1149 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1150 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
1151 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
1152 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
1153 }
1154 if counted {
1155 gate_buckets(
1156 &name,
1157 1,
1158 uncounted_exact,
1159 refusals.len() - uncounted_exact as usize,
1160 );
1161 return;
1162 }
1163 }
1164 gate_buckets(
1165 &name,
1166 0,
1167 uncounted_exact,
1168 refusals.len() - uncounted_exact as usize,
1169 );
1170 panic!(
1171 "{name} never observed a split-transform intra block in an inter frame:\n{}",
1172 refusals.join("\n")
1173 );
1174 }
1175
1176 pub(super) fn filter_intra_in_inter_gate(bit_depth: u32) {
1177 let name = format!("filter_intra_in_inter_gate({bit_depth})");
1178 if !have_ffmpeg() {
1179 eprintln!("SKIP {name}: no ffmpeg");
1180 return;
1181 }
1182 if !have_aomenc() {
1183 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1184 return;
1185 }
1186 let (width, height, frame_count) = (64usize, 64usize, 8usize);
1187 let mut refusals = Vec::new();
1188 let mut uncounted_exact = 0u32;
1189 for attempt in 0..40u32 {
1190 let seed = 42 + attempt;
1191 // A zooming fractal: every frame moves (so the sequence is
1192 // genuinely inter-coded) and keeps sharp new detail entering at
1193 // the borders, which is what makes aomenc's RD choose an INTRA
1194 // block inside an inter frame -- and then split its transform.
1195 // A zooming fractal with a hard CUT halfway (`overlay` switching
1196 // a second, unrelated fractal on at frame 4): after the cut every
1197 // block is unpredictable from the reference, which is what makes
1198 // aomenc code INTRA blocks inside an inter frame -- and at this
1199 // cq the RD then splits their transforms.
1200 let source = format!(
1201 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
1202 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
1203 [a][b]overlay=enable='gte(n,4)'",
1204 5.0 - f64::from(attempt) * 0.06,
1205 0.9 + f64::from(attempt) * 0.11
1206 );
1207 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1208 .args([
1209 "-v",
1210 "error",
1211 "-f",
1212 "lavfi",
1213 "-i",
1214 &source,
1215 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
1216 // still-refused directional-chroma gaps never fire and
1217 // luma detail alone drives the transform split.
1218 "-vf",
1219 "hue=s=0",
1220 "-pix_fmt",
1221 if bit_depth == 10 {
1222 "yuv420p10le"
1223 } else {
1224 "yuv420p"
1225 },
1226 "-strict",
1227 "-1",
1228 "-t",
1229 "0.32",
1230 "-f",
1231 "yuv4mpegpipe",
1232 "-strict",
1233 "-1",
1234 "-",
1235 ])
1236 .stdin(Stdio::null())
1237 .stdout(Stdio::piped())
1238 .stderr(Stdio::piped()), None, |c| c.output())
1239 .expect("ffmpeg failed to run");
1240 assert!(
1241 y4m.status.success(),
1242 "ffmpeg fixture: {}",
1243 String::from_utf8_lossy(&y4m.stderr)
1244 );
1245 let depth_args: &[&str] = if bit_depth == 10 {
1246 &["-b", "10", "--input-bit-depth=10"]
1247 } else {
1248 &[]
1249 };
1250 let out = run_with_stdin(
1251 Command::new(aomenc_path()).args(depth_args).args([
1252 "--codec=av1",
1253 "--passes=1",
1254 "--end-usage=q",
1255 "--cq-level=30",
1256 "--cpu-used=0",
1257 "--lag-in-frames=0",
1258 "--auto-alt-ref=0",
1259 // One key frame only: every later frame is an inter frame,
1260 // which is where this gate's intra blocks must sit. The
1261 // MIN distance is what stops aomenc's scene-cut detector
1262 // from inserting a second key frame at the cut this gate's
1263 // source deliberately contains.
1264 "--kf-max-dist=1000",
1265 "--kf-min-dist=1000",
1266 "--threads=1",
1267 "--row-mt=0",
1268 "--enable-order-hint=0",
1269 "--enable-warped-motion=0",
1270 "--enable-obmc=0",
1271 "--enable-masked-comp=0",
1272 "--enable-interintra-comp=0",
1273 "--enable-dist-wtd-comp=0",
1274 "--enable-diff-wtd-comp=0",
1275 "--enable-onesided-comp=0",
1276 "--enable-interintra-wedge=0",
1277 "--enable-smooth-interintra=0",
1278 "--enable-ab-partitions=0",
1279 "--enable-1to4-partitions=0",
1280 "--enable-smooth-intra=0",
1281 "--enable-paeth-intra=0",
1282 "--enable-directional-intra=0",
1283 "--enable-angle-delta=0",
1284 "--enable-cdef=0",
1285 "--enable-restoration=0",
1286 "--enable-palette=0",
1287 "--enable-intrabc=0",
1288 "--enable-cfl-intra=0",
1289 "--enable-ref-frame-mvs=0",
1290 // Per-arm overrides go LAST (aomenc keeps the last
1291 // occurrence of a repeated --enable-* flag): the intra
1292 // tx_depth symbol only exists under TX_MODE_SELECT, and
1293 // rect partitions are a separate named refusal.
1294 "--enable-filter-intra=1",
1295 "--enable-tx-size-search=1",
1296 "--enable-rect-partitions=0",
1297 "--max-partition-size=32",
1298 // Sub-16 inter partitions are a separate named refusal,
1299 // as is the 8x8 intra leaf's own TX_4X4 split.
1300 "--min-partition-size=16",
1301 "--obu",
1302 "-o",
1303 "-",
1304 "-",
1305 ]),
1306 &y4m.stdout,
1307 );
1308 assert!(
1309 out.status.success(),
1310 "aomenc refused the fixture: {}",
1311 String::from_utf8_lossy(&out.stderr)
1312 );
1313 let stream = out.stdout;
1314 let before = decode::intra_in_inter_filter_intra_hits();
1315 let frames = match decode_stream(&stream) {
1316 Ok(frames) => frames,
1317 Err(e) => {
1318 let msg = e.to_string();
1319 assert!(
1320 msg.contains("unsupported"),
1321 "{name} decode failed outright (seed {seed}): {msg}"
1322 );
1323 refusals.push(format!("seed {seed}: {msg}"));
1324 continue;
1325 }
1326 };
1327 let fired = decode::intra_in_inter_filter_intra_hits() - before;
1328 // class [[gate-skips-on-its-own-failure]]: a decode that
1329 // succeeded is ALWAYS pixel-compared below; the counter only
1330 // decides whether the attempt counts as firing.
1331 let counted = fired != 0;
1332 if !counted {
1333 uncounted_exact += 1;
1334 refusals.push(format!(
1335 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
1336 frame used filter intra"
1337 ));
1338 }
1339 let ffmpeg_frames = if bit_depth == 10 {
1340 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1341 } else {
1342 ffmpeg_decode_sequence(&stream, width, height, frame_count)
1343 };
1344 assert_eq!(frames.len(), frame_count);
1345 eprintln!("{name} seed={seed}: filter-intra blocks inside inter frames = {fired}");
1346 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1347 for (plane, (g, w)) in [
1348 ("Y", (&got.y, &want.y)),
1349 ("U", (&got.u, &want.u)),
1350 ("V", (&got.v, &want.v)),
1351 ] {
1352 let stride = if plane == "Y" { width } else { width / 2 };
1353 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
1354 eprintln!(
1355 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
1356 want {} ({} samples differ)",
1357 at % stride,
1358 at / stride,
1359 g[at],
1360 w[at],
1361 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
1362 );
1363 }
1364 }
1365 }
1366 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1367 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
1368 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
1369 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
1370 }
1371 if counted {
1372 gate_buckets(
1373 &name,
1374 1,
1375 uncounted_exact,
1376 refusals.len() - uncounted_exact as usize,
1377 );
1378 return;
1379 }
1380 }
1381 gate_buckets(
1382 &name,
1383 0,
1384 uncounted_exact,
1385 refusals.len() - uncounted_exact as usize,
1386 );
1387 panic!(
1388 "{name} never observed a filter-intra intra block in an inter frame:\n{}",
1389 refusals.join("\n")
1390 );
1391 }
1392
1393 pub(super) fn angle_delta_in_inter_gate(bit_depth: u32, min_partition: &str) {
1394 let name = format!("angle_delta_in_inter_gate({bit_depth}, min={min_partition})");
1395 let leaf8 = min_partition.ends_with('8');
1396 assert!(
1397 !leaf8,
1398 "the 8x8-leaf arm keeps its refusal; see the module note"
1399 );
1400 if !have_ffmpeg() {
1401 eprintln!("SKIP {name}: no ffmpeg");
1402 return;
1403 }
1404 if !have_aomenc() {
1405 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1406 return;
1407 }
1408 let (width, height, frame_count) = (64usize, 64usize, 8usize);
1409 let mut refusals = Vec::new();
1410 let mut uncounted_exact = 0u32;
1411 for attempt in 0..40u32 {
1412 let seed = 42 + attempt;
1413 // A zooming fractal: every frame moves (so the sequence is
1414 // genuinely inter-coded) and keeps sharp new detail entering at
1415 // the borders, which is what makes aomenc's RD choose an INTRA
1416 // block inside an inter frame -- and then split its transform.
1417 // A zooming fractal with a hard CUT halfway (`overlay` switching
1418 // a second, unrelated fractal on at frame 4): after the cut every
1419 // block is unpredictable from the reference, which is what makes
1420 // aomenc code INTRA blocks inside an inter frame -- and at this
1421 // cq the RD then splits their transforms.
1422 let source = format!(
1423 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
1424 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
1425 [a][b]overlay=enable='gte(n,4)'",
1426 5.0 - f64::from(attempt) * 0.06,
1427 0.9 + f64::from(attempt) * 0.11
1428 );
1429 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1430 .args([
1431 "-v",
1432 "error",
1433 "-f",
1434 "lavfi",
1435 "-i",
1436 &source,
1437 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
1438 // still-refused directional-chroma gaps never fire and
1439 // luma detail alone drives the transform split.
1440 "-vf",
1441 "hue=s=0",
1442 "-pix_fmt",
1443 if bit_depth == 10 {
1444 "yuv420p10le"
1445 } else {
1446 "yuv420p"
1447 },
1448 "-strict",
1449 "-1",
1450 "-t",
1451 "0.32",
1452 "-f",
1453 "yuv4mpegpipe",
1454 "-strict",
1455 "-1",
1456 "-",
1457 ])
1458 .stdin(Stdio::null())
1459 .stdout(Stdio::piped())
1460 .stderr(Stdio::piped()), None, |c| c.output())
1461 .expect("ffmpeg failed to run");
1462 assert!(
1463 y4m.status.success(),
1464 "ffmpeg fixture: {}",
1465 String::from_utf8_lossy(&y4m.stderr)
1466 );
1467 // The 8x8-leaf arm is fenced by three sibling refusals (non-DC
1468 // chroma on an 8x8 leaf, its TX_4X4 split, sub-16 rect inter
1469 // leaves), so it sweeps the quantiser as well as the source: a
1470 // coarser q is what pushes the RD to directional intra at 8x8.
1471 let cq = if leaf8 {
1472 format!("--cq-level={}", 20 + (attempt % 5) * 10)
1473 } else {
1474 "--cq-level=30".to_string()
1475 };
1476 let depth_args: &[&str] = if bit_depth == 10 {
1477 &["-b", "10", "--input-bit-depth=10"]
1478 } else {
1479 &[]
1480 };
1481 let out = run_with_stdin(
1482 Command::new(aomenc_path()).args(depth_args).args([
1483 "--codec=av1",
1484 "--passes=1",
1485 "--end-usage=q",
1486 &cq,
1487 "--cpu-used=0",
1488 "--lag-in-frames=0",
1489 "--auto-alt-ref=0",
1490 // One key frame only: every later frame is an inter frame,
1491 // which is where this gate's intra blocks must sit. The
1492 // MIN distance is what stops aomenc's scene-cut detector
1493 // from inserting a second key frame at the cut this gate's
1494 // source deliberately contains.
1495 "--kf-max-dist=1000",
1496 "--kf-min-dist=1000",
1497 "--threads=1",
1498 "--row-mt=0",
1499 "--enable-order-hint=0",
1500 "--enable-warped-motion=0",
1501 "--enable-obmc=0",
1502 "--enable-masked-comp=0",
1503 "--enable-interintra-comp=0",
1504 "--enable-dist-wtd-comp=0",
1505 "--enable-diff-wtd-comp=0",
1506 "--enable-onesided-comp=0",
1507 "--enable-interintra-wedge=0",
1508 "--enable-smooth-interintra=0",
1509 "--enable-ab-partitions=0",
1510 "--enable-1to4-partitions=0",
1511 "--enable-smooth-intra=0",
1512 "--enable-paeth-intra=0",
1513 "--enable-directional-intra=1",
1514 "--enable-angle-delta=1",
1515 "--enable-cdef=0",
1516 "--enable-restoration=0",
1517 "--enable-palette=0",
1518 "--enable-intrabc=0",
1519 "--enable-cfl-intra=0",
1520 "--enable-ref-frame-mvs=0",
1521 // Per-arm overrides go LAST (aomenc keeps the last
1522 // occurrence of a repeated --enable-* flag): the intra
1523 // tx_depth symbol only exists under TX_MODE_SELECT, and
1524 // rect partitions are a separate named refusal.
1525 "--enable-filter-intra=1",
1526 "--enable-tx-size-search=1",
1527 "--enable-rect-partitions=0",
1528 "--max-partition-size=32",
1529 // Sub-16 inter partitions are a separate named refusal,
1530 // as is the 8x8 intra leaf's own TX_4X4 split.
1531 min_partition,
1532 "--obu",
1533 "-o",
1534 "-",
1535 "-",
1536 ]),
1537 &y4m.stdout,
1538 );
1539 assert!(
1540 out.status.success(),
1541 "aomenc refused the fixture: {}",
1542 String::from_utf8_lossy(&out.stderr)
1543 );
1544 let stream = out.stdout;
1545 let before = decode::intra_in_inter_angle_delta_y_hits();
1546 let before_uv = decode::intra_in_inter_angle_delta_uv_hits();
1547 let frames = match decode_stream(&stream) {
1548 Ok(frames) => frames,
1549 Err(e) => {
1550 let msg = e.to_string();
1551 assert!(
1552 msg.contains("unsupported"),
1553 "{name} decode failed outright (seed {seed}): {msg}"
1554 );
1555 refusals.push(format!("seed {seed}: {msg}"));
1556 continue;
1557 }
1558 };
1559 let fired = decode::intra_in_inter_angle_delta_y_hits() - before;
1560 let fired_uv = decode::intra_in_inter_angle_delta_uv_hits() - before_uv;
1561 // class [[gate-skips-on-its-own-failure]]: a decode that
1562 // succeeded is ALWAYS pixel-compared below; the counter only
1563 // decides whether the attempt counts as firing.
1564 let counted = fired != 0;
1565 if !counted {
1566 uncounted_exact += 1;
1567 refusals.push(format!(
1568 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
1569 frame carried a nonzero angle_delta_y"
1570 ));
1571 }
1572 let ffmpeg_frames = if bit_depth == 10 {
1573 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1574 } else {
1575 ffmpeg_decode_sequence(&stream, width, height, frame_count)
1576 };
1577 assert_eq!(frames.len(), frame_count);
1578 eprintln!(
1579 "{name} seed={seed}: intra-in-inter blocks with a nonzero angle_delta_y = \
1580 {fired}, angle_delta_uv = {fired_uv}"
1581 );
1582 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1583 for (plane, (g, w)) in [
1584 ("Y", (&got.y, &want.y)),
1585 ("U", (&got.u, &want.u)),
1586 ("V", (&got.v, &want.v)),
1587 ] {
1588 let stride = if plane == "Y" { width } else { width / 2 };
1589 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
1590 eprintln!(
1591 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
1592 want {} ({} samples differ)",
1593 at % stride,
1594 at / stride,
1595 g[at],
1596 w[at],
1597 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
1598 );
1599 }
1600 }
1601 }
1602 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1603 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
1604 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
1605 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
1606 }
1607 if counted {
1608 gate_buckets(
1609 &name,
1610 1,
1611 uncounted_exact,
1612 refusals.len() - uncounted_exact as usize,
1613 );
1614 return;
1615 }
1616 }
1617 gate_buckets(
1618 &name,
1619 0,
1620 uncounted_exact,
1621 refusals.len() - uncounted_exact as usize,
1622 );
1623 panic!(
1624 "{name} never observed a nonzero angle delta on an intra block in an inter \
1625 frame:\n{}",
1626 refusals.join("\n")
1627 );
1628 }
1629
1630 pub(super) fn uv_mode_in_inter8_gate(bit_depth: u32, tile_columns: u32) {
1631 let name = format!("uv_mode_in_inter8_gate({bit_depth}, tiles={tile_columns})");
1632 if !have_ffmpeg() {
1633 eprintln!("SKIP {name}: no ffmpeg");
1634 return;
1635 }
1636 if !have_aomenc() {
1637 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1638 return;
1639 }
1640 let (width, height, frame_count) = (192usize, 128usize, 8usize);
1641 let mut refusals = Vec::new();
1642 let mut uncounted_exact = 0u32;
1643 let mut totals = (0usize, 0usize, 0usize);
1644 for attempt in 0..30u32 {
1645 let seed = 42 + attempt;
1646 // A zooming fractal with a hard CUT at frame 4 (`overlay`
1647 // switching a second, unrelated fractal on): after the cut a block
1648 // is unpredictable from the reference, which is what makes aomenc
1649 // code INTRA blocks inside an inter frame. Chroma is NOT
1650 // desaturated here (every sibling inter gate passes `hue=s=0`) --
1651 // real chroma detail is exactly what pushes the chroma RD off
1652 // DC_PRED. `noise` carries its own explicit seed (lavfi
1653 // `gradients` ignores its seed; class [[seeded-fixture-not-reproducible]]).
1654 let source = format!(
1655 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
1656 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
1657 [a][b]overlay=enable='gte(n,4)',noise=alls=12:allf=t+u:all_seed={seed}",
1658 5.0 - f64::from(attempt) * 0.06,
1659 0.9 + f64::from(attempt) * 0.11
1660 );
1661 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1662 .args([
1663 "-v",
1664 "error",
1665 "-f",
1666 "lavfi",
1667 "-i",
1668 &source,
1669 "-pix_fmt",
1670 if bit_depth == 10 {
1671 "yuv420p10le"
1672 } else {
1673 "yuv420p"
1674 },
1675 "-strict",
1676 "-1",
1677 "-t",
1678 "0.32",
1679 "-f",
1680 "yuv4mpegpipe",
1681 "-strict",
1682 "-1",
1683 "-",
1684 ])
1685 .stdin(Stdio::null())
1686 .stdout(Stdio::piped())
1687 .stderr(Stdio::piped()), None, |c| c.output())
1688 .expect("ffmpeg failed to run");
1689 assert!(
1690 y4m.status.success(),
1691 "ffmpeg fixture: {}",
1692 String::from_utf8_lossy(&y4m.stderr)
1693 );
1694 // A coarser quantiser is what pushes the chroma RD to a cheap
1695 // non-DC mode on a small block; sweep 12..40 (the low end is what
1696 // lane-cdef's cq12 arm needs).
1697 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
1698 let depth_args: &[&str] = if bit_depth == 10 {
1699 &["-b", "10", "--input-bit-depth=10"]
1700 } else {
1701 &[]
1702 };
1703 let tiles = format!("--tile-columns={}", tile_columns - 1);
1704 // The y4m goes through a FILE, not aomenc's stdin: this gate's
1705 // stream is ~100 KB, bigger than a pipe buffer, so an aomenc that
1706 // is still being fed on stdin blocks writing its stdout and the
1707 // test blocks writing its stdin -- a hard deadlock (measured
1708 // here, 3 min into attempt 0, class [[gate-loader-slurps-whole-file]]).
1709 // The path is PID-keyed (class [[pid-keyed-temp-path]]).
1710 let y4m_path = std::env::temp_dir().join(format!(
1711 "ec-av1-uv8-{}-{bit_depth}-{tile_columns}-{seed}.y4m",
1712 std::process::id()
1713 ));
1714 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
1715 let child = Command::new(aomenc_path())
1716 .args(depth_args)
1717 .args([
1718 "--codec=av1",
1719 "--passes=1",
1720 "--end-usage=q",
1721 &cq,
1722 "--cpu-used=0",
1723 "--lag-in-frames=0",
1724 "--auto-alt-ref=0",
1725 "--kf-max-dist=9999",
1726 "--kf-min-dist=9999",
1727 "--threads=1",
1728 "--row-mt=0",
1729 &tiles,
1730 "--enable-order-hint=0",
1731 "--enable-warped-motion=0",
1732 "--enable-obmc=0",
1733 "--enable-masked-comp=0",
1734 "--enable-interintra-comp=0",
1735 "--enable-dist-wtd-comp=0",
1736 "--enable-diff-wtd-comp=0",
1737 "--enable-onesided-comp=0",
1738 "--enable-interintra-wedge=0",
1739 "--enable-smooth-interintra=0",
1740 "--enable-ab-partitions=0",
1741 "--enable-1to4-partitions=0",
1742 "--enable-cdef=0",
1743 "--enable-restoration=0",
1744 "--enable-palette=0",
1745 "--enable-intrabc=0",
1746 "--enable-ref-frame-mvs=0",
1747 // Per-arm overrides go LAST (aomenc keeps the LAST
1748 // occurrence of a repeated --enable-* flag). The three
1749 // chroma intra tools this gate is about, plus the fences
1750 // that keep the leaf's SIBLING refusals (its TX_4X4
1751 // split, a nonzero angle delta, sub-16 rect inter leaves)
1752 // out of the way.
1753 "--enable-cfl-intra=1",
1754 "--enable-smooth-intra=1",
1755 "--enable-paeth-intra=1",
1756 "--enable-directional-intra=1",
1757 "--enable-angle-delta=0",
1758 "--enable-tx-size-search=0",
1759 "--enable-rect-partitions=0",
1760 "--min-partition-size=8",
1761 "--max-partition-size=32",
1762 "--obu",
1763 "-o",
1764 "-",
1765 ])
1766 .arg(&y4m_path)
1767 .stdin(Stdio::null())
1768 .stdout(Stdio::piped())
1769 .stderr(Stdio::piped())
1770 .spawn()
1771 .expect("aomenc failed to start");
1772 let out = child.wait_with_output().expect("aomenc failed to run");
1773 let _ = std::fs::remove_file(&y4m_path);
1774 assert!(
1775 out.status.success(),
1776 "aomenc refused the fixture: {}",
1777 String::from_utf8_lossy(&out.stderr)
1778 );
1779 let stream = out.stdout;
1780 let before = decode::intra_in_inter8_uv_hits();
1781 let frames = match decode_stream(&stream) {
1782 Ok(frames) => frames,
1783 Err(e) => {
1784 let msg = e.to_string();
1785 assert!(
1786 msg.contains("unsupported"),
1787 "{name} decode failed outright (seed {seed}): {msg}"
1788 );
1789 refusals.push(format!("seed {seed}: {msg}"));
1790 continue;
1791 }
1792 };
1793 let now = decode::intra_in_inter8_uv_hits();
1794 // class [[counter-from-refused-stream]]: per-attempt deltas, and
1795 // only for an attempt that decoded to the end and is pixel-
1796 // compared below.
1797 let fired = (now.0 - before.0, now.1 - before.1, now.2 - before.2);
1798 totals = (totals.0 + fired.0, totals.1 + fired.1, totals.2 + fired.2);
1799 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
1800 // is ALWAYS pixel-compared; the counter only decides whether the
1801 // attempt counts as firing.
1802 // lane-uv8 r3: every one of the three chroma classes this gate
1803 // exists for (directional, smooth/paeth, CfL) must fire on the
1804 // SAME pixel-compared attempt -- a sum-nonzero predicate would
1805 // pass on an attempt that only ever hit DC-adjacent CfL.
1806 let counted = fired.0 > 0 && fired.1 > 0 && fired.2 > 0;
1807 if !counted {
1808 uncounted_exact += 1;
1809 refusals.push(format!(
1810 "seed {seed}: decoded and pixel-compared, but no 8x8 intra leaf in an inter \
1811 frame carried a non-DC uv_mode"
1812 ));
1813 }
1814 let ffmpeg_frames = if bit_depth == 10 {
1815 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1816 } else {
1817 ffmpeg_decode_sequence(&stream, width, height, frame_count)
1818 };
1819 assert_eq!(frames.len(), frame_count);
1820 eprintln!(
1821 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with a non-DC uv_mode -- \
1822 directional {}, smooth/paeth {}, CfL {}",
1823 fired.0, fired.1, fired.2
1824 );
1825 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1826 for (plane, (g, w)) in [
1827 ("Y", (&got.y, &want.y)),
1828 ("U", (&got.u, &want.u)),
1829 ("V", (&got.v, &want.v)),
1830 ] {
1831 let stride = if plane == "Y" { width } else { width / 2 };
1832 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
1833 eprintln!(
1834 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
1835 want {} ({} samples differ)",
1836 at % stride,
1837 at / stride,
1838 g[at],
1839 w[at],
1840 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
1841 );
1842 }
1843 }
1844 }
1845 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1846 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
1847 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
1848 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
1849 }
1850 if counted {
1851 gate_buckets(
1852 &name,
1853 1,
1854 uncounted_exact,
1855 refusals.len() - uncounted_exact as usize,
1856 );
1857 return;
1858 }
1859 }
1860 gate_buckets(
1861 &name,
1862 0,
1863 uncounted_exact,
1864 refusals.len() - uncounted_exact as usize,
1865 );
1866 panic!(
1867 "{name} never observed a non-DC uv_mode on an 8x8 intra leaf in an inter frame \
1868 (totals dir/smooth/cfl {totals:?}):\n{}",
1869 refusals.join("\n")
1870 );
1871 }
1872
1873 pub(super) fn tx_split_angle_in_inter8_gate(bit_depth: u32) {
1874 let name = format!("tx_split_angle_in_inter8_gate({bit_depth})");
1875 if !have_ffmpeg() {
1876 eprintln!("SKIP {name}: no ffmpeg");
1877 return;
1878 }
1879 if !have_aomenc() {
1880 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1881 return;
1882 }
1883 let (width, height, frame_count) = (192usize, 128usize, 6usize);
1884 let mut refusals = Vec::new();
1885 let mut uncounted_exact = 0u32;
1886 let mut counted_exact = 0u32;
1887 let mut totals = (0usize, 0usize);
1888 for attempt in 0..30u32 {
1889 let seed = 42 + attempt;
1890 // Same zoom + hard-cut fractal source the sibling uv_mode gate
1891 // uses (a cut is what makes aomenc code INTRA blocks inside an
1892 // inter frame); `noise` carries an explicit seed (class
1893 // [[seeded-fixture-not-reproducible]]).
1894 let source = format!(
1895 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
1896 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
1897 [a][b]overlay=enable='gte(n,3)',noise=alls=12:allf=t+u:all_seed={seed}",
1898 5.0 - f64::from(attempt) * 0.06,
1899 0.9 + f64::from(attempt) * 0.11
1900 );
1901 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1902 .args([
1903 "-v",
1904 "error",
1905 "-f",
1906 "lavfi",
1907 "-i",
1908 &source,
1909 "-pix_fmt",
1910 if bit_depth == 10 {
1911 "yuv420p10le"
1912 } else {
1913 "yuv420p"
1914 },
1915 "-strict",
1916 "-1",
1917 "-t",
1918 "0.24",
1919 "-f",
1920 "yuv4mpegpipe",
1921 "-strict",
1922 "-1",
1923 "-",
1924 ])
1925 .stdin(Stdio::null())
1926 .stdout(Stdio::piped())
1927 .stderr(Stdio::piped()), None, |c| c.output())
1928 .expect("ffmpeg failed to run");
1929 assert!(
1930 y4m.status.success(),
1931 "ffmpeg fixture: {}",
1932 String::from_utf8_lossy(&y4m.stderr)
1933 );
1934 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
1935 let depth_args: &[&str] = if bit_depth == 10 {
1936 &["-b", "10", "--input-bit-depth=10"]
1937 } else {
1938 &[]
1939 };
1940 // The y4m goes through a PID-keyed FILE, never aomenc's stdin
1941 // (pipe deadlock, class [[gate-loader-slurps-whole-file]]).
1942 let y4m_path = std::env::temp_dir().join(format!(
1943 "ec-av1-leaf8tx-{}-{bit_depth}-{seed}.y4m",
1944 std::process::id()
1945 ));
1946 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
1947 let child = Command::new(aomenc_path())
1948 .args(depth_args)
1949 .args([
1950 "--codec=av1",
1951 "--passes=1",
1952 "--end-usage=q",
1953 &cq,
1954 "--cpu-used=0",
1955 "--lag-in-frames=0",
1956 "--auto-alt-ref=0",
1957 "--kf-max-dist=9999",
1958 "--kf-min-dist=9999",
1959 "--threads=1",
1960 "--row-mt=0",
1961 "--tile-columns=0",
1962 "--enable-order-hint=0",
1963 "--enable-warped-motion=0",
1964 "--enable-obmc=0",
1965 "--enable-masked-comp=0",
1966 "--enable-interintra-comp=0",
1967 "--enable-dist-wtd-comp=0",
1968 "--enable-diff-wtd-comp=0",
1969 "--enable-onesided-comp=0",
1970 "--enable-interintra-wedge=0",
1971 "--enable-smooth-interintra=0",
1972 "--enable-ab-partitions=0",
1973 "--enable-1to4-partitions=0",
1974 "--enable-cdef=0",
1975 "--enable-restoration=0",
1976 "--enable-palette=0",
1977 "--enable-intrabc=0",
1978 "--enable-ref-frame-mvs=0",
1979 // Per-arm overrides LAST (aomenc keeps the last
1980 // occurrence of a repeated --enable-* flag). Rect
1981 // partitions stay off so the leaf's unrelated sub-16 rect
1982 // inter refusal never fires.
1983 "--enable-rect-partitions=0",
1984 "--enable-tx-size-search=1",
1985 "--enable-angle-delta=1",
1986 "--enable-directional-intra=1",
1987 "--min-partition-size=8",
1988 "--max-partition-size=32",
1989 "--obu",
1990 "-o",
1991 "-",
1992 ])
1993 // r1 diagnostic: EC_LEAF8TX_CONTROL=1 turns THIS lane's two
1994 // tools back off (last occurrence of a repeated --enable-*
1995 // wins), so any mismatch that survives is not this lane's.
1996 .args(match std::env::var("EC_LEAF8TX_CONTROL").as_deref() {
1997 Ok("angle") => vec!["--enable-tx-size-search=0", "--enable-angle-delta=1"],
1998 Ok("tx") => vec!["--enable-tx-size-search=1", "--enable-angle-delta=0"],
1999 Ok("tx8") => vec![
2000 "--enable-tx-size-search=1",
2001 "--enable-angle-delta=0",
2002 "--max-partition-size=8",
2003 ],
2004 Ok(_) => vec!["--enable-tx-size-search=0", "--enable-angle-delta=0"],
2005 // Shipped recipe (lane-leaf8tx r4): BOTH of this lane's
2006 // tools on -- the tx_depth split at an 8x8 intra-in-inter
2007 // leaf is what the lifted refusal covers, so
2008 // `--enable-tx-size-search=1` must survive the per-arm
2009 // override (aomenc keeps the LAST occurrence). Odd
2010 // attempts also cap the partition at 8x8, the shape that
2011 // produces the 2x2 TX_4X4 grid most often.
2012 Err(_) => {
2013 if attempt % 2 == 1 {
2014 vec![
2015 "--enable-tx-size-search=1",
2016 "--enable-angle-delta=1",
2017 "--max-partition-size=8",
2018 ]
2019 } else {
2020 vec!["--enable-tx-size-search=1", "--enable-angle-delta=1"]
2021 }
2022 }
2023 })
2024 .arg(&y4m_path)
2025 .stdin(Stdio::null())
2026 .stdout(Stdio::piped())
2027 .stderr(Stdio::piped())
2028 .spawn()
2029 .expect("aomenc failed to start");
2030 let out = child.wait_with_output().expect("aomenc failed to run");
2031 let _ = std::fs::remove_file(&y4m_path);
2032 assert!(
2033 out.status.success(),
2034 "aomenc refused the fixture: {}",
2035 String::from_utf8_lossy(&out.stderr)
2036 );
2037 let stream = out.stdout;
2038 let before = (
2039 decode::intra_in_inter_split_tx_hits()[0],
2040 decode::intra_in_inter8_angle_delta_y_hits(),
2041 );
2042 let frames = match decode_stream(&stream) {
2043 Ok(frames) => frames,
2044 Err(e) => {
2045 let msg = e.to_string();
2046 assert!(
2047 msg.contains("unsupported"),
2048 "{name} decode failed outright (seed {seed}): {msg}"
2049 );
2050 refusals.push(format!("seed {seed}: {msg}"));
2051 continue;
2052 }
2053 };
2054 let now = (
2055 decode::intra_in_inter_split_tx_hits()[0],
2056 decode::intra_in_inter8_angle_delta_y_hits(),
2057 );
2058 let fired = (now.0 - before.0, now.1 - before.1);
2059 totals = (totals.0 + fired.0, totals.1 + fired.1);
2060 // Both lifted capabilities must fire on the SAME pixel-compared
2061 // attempt.
2062 let counted = fired.1 > 0;
2063 if !counted {
2064 uncounted_exact += 1;
2065 refusals.push(format!(
2066 "seed {seed}: decoded and pixel-compared, but split-tx {} / angle-delta {} \
2067 8x8 intra-in-inter leaves",
2068 fired.0, fired.1
2069 ));
2070 }
2071 let ffmpeg_frames = if bit_depth == 10 {
2072 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
2073 } else {
2074 ffmpeg_decode_sequence(&stream, width, height, frame_count)
2075 };
2076 assert_eq!(frames.len(), frame_count);
2077 eprintln!(
2078 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with tx_depth=1 {}, with a \
2079 nonzero angle_delta_y {} (split-tx per size 8/16/32/64 {:?})",
2080 fired.0,
2081 fired.1,
2082 decode::intra_in_inter_split_tx_hits()
2083 );
2084 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2085 for (plane, (g, w)) in [
2086 ("Y", (&got.y, &want.y)),
2087 ("U", (&got.u, &want.u)),
2088 ("V", (&got.v, &want.v)),
2089 ] {
2090 let stride = if plane == "Y" { width } else { width / 2 };
2091 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
2092 eprintln!(
2093 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
2094 want {} ({} samples differ)",
2095 at % stride,
2096 at / stride,
2097 g[at],
2098 w[at],
2099 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
2100 );
2101 }
2102 }
2103 }
2104 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2105 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
2106 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
2107 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
2108 }
2109 if counted {
2110 counted_exact += 1;
2111 }
2112 }
2113 // lane-leaf8tx r4: continue-and-sweep -- every arm is encoded,
2114 // decoded and pixel-compared on every plane of every decode-order
2115 // frame above; the counters are asserted ONCE here. A decode error or
2116 // a mismatch is a failure, never a SKIP, and `uncounted_exact`
2117 // (decoded + compared but neither capability fired) is the
2118 // out-of-scope-mismatch bucket that the sweep tolerates only while at
2119 // least one attempt did fire.
2120 gate_buckets(
2121 &name,
2122 counted_exact,
2123 uncounted_exact,
2124 refusals.len() - uncounted_exact as usize,
2125 );
2126 assert!(
2127 totals.0 > 0,
2128 "{name}: no decoded+compared attempt carried an 8x8 intra-in-inter leaf with \
2129 tx_depth split to 4x4 (split-tx per size {:?}, angle-delta {}):\n{}",
2130 decode::intra_in_inter_split_tx_hits(),
2131 totals.1,
2132 refusals.join("\n")
2133 );
2134 assert!(
2135 totals.1 > 0,
2136 "{name}: no decoded+compared attempt carried a nonzero angle_delta_y on an 8x8 \
2137 intra-in-inter leaf (split-tx {}):\n{}",
2138 totals.0,
2139 refusals.join("\n")
2140 );
2141 }
2142
2143 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
2144 /// --auto-alt-ref=0` keep every non-key frame a simple forward
2145 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this
2146 /// decoder's inter path does not model), `--kf-max-dist` past the clip's
2147 /// own length keeps frame 0 the only key frame.
2148 /// lane-inter8 r1: the inter tile path's SB-level `PARTITION_NONE` -- a
2149 /// whole 64x64 superblock coded as ONE inter block, which is what aomenc
2150 /// picks for static content and which this decoder refused by name
2151 /// ("an inter SB-level partition type other than SPLIT") until this
2152 /// round. HARD-asserts [`decode::inter_sb_none_hits`] moved (the arm
2153 /// really fired, class refusal-lifted-without-a-gate) and every frame is
2154 /// pixel-exact vs ffmpeg; a decode error is a FAILURE here, never a SKIP
2155 /// (class gate-skips-on-its-own-failure).
2156 /// lane-inter8 r1: generalised so the same recipe can target a deeper
2157 /// level of the inter partition tree -- `min_part` is aomenc's
2158 /// `--min-partition-size`, and `hits`/`what` name the counter that proves
2159 /// the arm under test really fired.
2160 #[track_caller]
2161 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
2162 #[allow(clippy::too_many_arguments)]
2163 pub(super) fn inter_sb_none_gate(
2164 name: &str,
2165 ten_bit: bool,
2166 min_part: &str,
2167 max_part: &str,
2168 hits: fn() -> usize,
2169 what: &str,
2170 // lane-inter8 r3: extra aomenc flags + the frame width they need.
2171 // `--tile-columns=1` needs a frame at least two superblocks wide or
2172 // aomenc silently codes one tile column and the arm is vacuous.
2173 extra: &[&str],
2174 width: usize,
2175 // lane-interp3 r1: sequence length -- a compound block needs several
2176 // already-coded references, which a 4-frame sequence never has.
2177 frame_count: usize,
2178 // lane-av1dualfilter10: the encoded stream, so a caller can assert on
2179 // the PARSED sequence header (bit depth, `enable_dual_filter`) rather
2180 // than on the flag it asked for. Empty on the SKIP paths below.
2181 ) -> Vec<u8> {
2182 if !have_ffmpeg() {
2183 eprintln!("SKIP {name}: no ffmpeg");
2184 return Vec::new();
2185 }
2186 if !have_aomenc() {
2187 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
2188 return Vec::new();
2189 }
2190 let height = 64usize;
2191 let duration = format!("{:.2}", frame_count as f64 / 25.0);
2192 // A deterministic synthetic source with real motion (a static source
2193 // codes every inter frame as skip and never exercises the residual
2194 // path); bounded with `-t` (class gate-loader-slurps-whole-file).
2195 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2196 .args([
2197 "-v",
2198 "error",
2199 "-f",
2200 "lavfi",
2201 "-i",
2202 &format!("mandelbrot=size={width}x{height}:rate=25"),
2203 "-t",
2204 &duration,
2205 "-pix_fmt",
2206 if ten_bit { "yuv420p10le" } else { "yuv420p" },
2207 // y4m calls 10-bit unofficial (same as the 10-bit key-frame
2208 // gate's own fixture).
2209 "-strict",
2210 "-1",
2211 "-f",
2212 "yuv4mpegpipe",
2213 "-",
2214 ])
2215 .stdin(Stdio::null())
2216 .stdout(Stdio::piped())
2217 .stderr(Stdio::piped()), None, |c| c.output())
2218 .expect("ffmpeg failed to run");
2219 assert!(
2220 y4m.status.success(),
2221 "{name}: ffmpeg fixture: {}",
2222 String::from_utf8_lossy(&y4m.stderr)
2223 );
2224 let mut args: Vec<String> = [
2225 "--codec=av1",
2226 "--passes=1",
2227 "--end-usage=q",
2228 "--cq-level=40",
2229 "--cpu-used=0",
2230 "--lag-in-frames=0",
2231 "--auto-alt-ref=0",
2232 "--kf-max-dist=1000",
2233 // No cross-frame CDF forwarding in this fixture (see the
2234 // deblocking gate's own note).
2235 "--error-resilient=1",
2236 // This gate targets the SB-level NONE arm only: rect/AB/1-to-4
2237 // partitions and sub-16x16 splits stay off so a failure here
2238 // cannot be another lane's missing arm.
2239 "--enable-rect-partitions=0",
2240 "--enable-ab-partitions=0",
2241 "--enable-1to4-partitions=0",
2242 "--enable-filter-intra=0",
2243 "--enable-smooth-intra=0",
2244 "--enable-paeth-intra=0",
2245 "--enable-directional-intra=0",
2246 "--enable-angle-delta=0",
2247 "--enable-tx-size-search=0",
2248 "--enable-cdef=0",
2249 "--enable-restoration=0",
2250 "--enable-palette=0",
2251 "--enable-intrabc=0",
2252 "--enable-cfl-intra=0",
2253 "--enable-ref-frame-mvs=0",
2254 "--obu",
2255 "-o",
2256 "-",
2257 "-",
2258 ]
2259 .iter()
2260 .map(|s| (*s).to_string())
2261 .collect();
2262 for e in extra {
2263 args.insert(1, (*e).to_string());
2264 }
2265 args.insert(1, format!("--min-partition-size={min_part}"));
2266 args.insert(1, format!("--max-partition-size={max_part}"));
2267 if ten_bit {
2268 args.insert(1, "--input-bit-depth=10".to_string());
2269 args.insert(1, "--bit-depth=10".to_string());
2270 }
2271 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2272 assert!(
2273 out.status.success(),
2274 "{name}: aomenc refused the fixture: {}",
2275 String::from_utf8_lossy(&out.stderr)
2276 );
2277 let stream = out.stdout;
2278 let before = hits();
2279 let frames = match decode_stream(&stream) {
2280 Ok(frames) => frames,
2281 Err(e) => {
2282 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
2283 crate::dumpio::pin("TEST_PIN", &pin, &stream);
2284 panic!(
2285 "{name}: decode_stream refused a real aomenc stream: {e} (pinned at {})",
2286 pin.display()
2287 );
2288 }
2289 };
2290 assert!(
2291 hits() > before,
2292 "{name}: no {what} fired -- this gate proves nothing"
2293 );
2294 let ffmpeg_frames = if ten_bit {
2295 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
2296 } else {
2297 ffmpeg_decode_sequence(&stream, width, height, frame_count)
2298 };
2299 assert_eq!(frames.len(), frame_count, "{name}: frame count");
2300 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2301 if got.y != want.y || got.u != want.u || got.v != want.v {
2302 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
2303 crate::dumpio::pin("TEST_PIN", &pin, &stream);
2304 panic!(
2305 "{name}: frame {i} mismatch vs ffmpeg -- stream pinned at {}",
2306 pin.display()
2307 );
2308 }
2309 }
2310 stream
2311 }
2312
2313 /// lane-eobc1 r1: an INTER sequence whose CHROMA coefficient blocks come
2314 /// off the class-1 (`TX_CLASS_HORIZ`/`VERT`) `eob_pt` row. Chroma codes
2315 /// no `tx_type` symbol of its own -- it inherits the colocated luma type
2316 /// (`av1_get_tx_type`, `blockd.h:1291`) -- so an 8x8 inter leaf whose
2317 /// luma picks `H_*`/`V_*` puts its 4x4 chroma on a CDF row this crate
2318 /// wired for only some sizes until this round (`eob_pt_class1: None` in
2319 /// 9 of 16 `TxbSet` arms, chroma 4x4/8x8 among them).
2320 ///
2321 /// The full tx set stays on (no `--reduced-tx-type-set=1`) and
2322 /// `--enable-flip-idtx=1` is asked for explicitly; the sinusoidal-stripe
2323 /// luma of the `tx_class1` key-frame gate is what actually resolves 1D
2324 /// types, and the temporally-moving chroma ramp keeps chroma out of
2325 /// `all_zero` so it has an `eob` to read at all. Attempts sweep cq and
2326 /// stripe period; a run counts only when
2327 /// [`decode::chroma_eob_class1_hits`] moved, and every shown frame is
2328 /// compared pixel-exact vs ffmpeg (a decode error is a FAILURE, never a
2329 /// SKIP -- class gate-skips-on-its-own-failure).
2330 pub(super) fn chroma_class1_eob_gate(name: &str, ten_bit: bool) {
2331 if !have_ffmpeg() {
2332 eprintln!("SKIP {name}: no ffmpeg");
2333 return;
2334 }
2335 if !have_aomenc() {
2336 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
2337 return;
2338 }
2339 let (width, height, frame_count) = (64usize, 64usize, 4usize);
2340 let mut refusals = Vec::new();
2341 for attempt in 0..12u32 {
2342 let cq = 28 + (attempt % 4) * 10;
2343 let period = [4u32, 6, 8][(attempt as usize / 4) % 3];
2344 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2345 .args([
2346 "-v",
2347 "error",
2348 "-f",
2349 "lavfi",
2350 "-i",
2351 &format!("testsrc2=size={width}x{height}:rate=25"),
2352 "-vf",
2353 &format!(
2354 "geq=lum='128+80*sin(2*PI*Y/{period})':cb='128+60*sin(2*PI*(X+8*T)/{period})':cr='128+60*sin(2*PI*(Y+8*T)/{period})',noise=alls=6:allf=t:all_seed=7"
2355 ),
2356 "-t",
2357 "0.16",
2358 "-pix_fmt",
2359 if ten_bit { "yuv420p10le" } else { "yuv420p" },
2360 "-strict",
2361 "-1",
2362 "-f",
2363 "yuv4mpegpipe",
2364 "-",
2365 ])
2366 .stdin(Stdio::null())
2367 .stdout(Stdio::piped())
2368 .stderr(Stdio::piped()), None, |c| c.output())
2369 .expect("ffmpeg failed to run");
2370 assert!(
2371 y4m.status.success(),
2372 "{name}: ffmpeg fixture: {}",
2373 String::from_utf8_lossy(&y4m.stderr)
2374 );
2375 let mut args: Vec<String> = [
2376 "--codec=av1",
2377 "--passes=1",
2378 "--end-usage=q",
2379 "--cpu-used=0",
2380 "--lag-in-frames=0",
2381 "--auto-alt-ref=0",
2382 "--kf-max-dist=1000",
2383 "--error-resilient=1",
2384 "--enable-flip-idtx=1",
2385 "--reduced-tx-type-set=0",
2386 "--min-partition-size=8",
2387 "--max-partition-size=16",
2388 // Motion tools this decoder refuses by name, kept off so a
2389 // refusal here can only be about the coefficient path.
2390 "--enable-global-motion=0",
2391 "--enable-warped-motion=0",
2392 "--enable-obmc=0",
2393 "--enable-rect-partitions=0",
2394 "--enable-ab-partitions=0",
2395 "--enable-1to4-partitions=0",
2396 "--enable-filter-intra=0",
2397 "--enable-smooth-intra=0",
2398 "--enable-paeth-intra=0",
2399 "--enable-directional-intra=0",
2400 "--enable-angle-delta=0",
2401 "--enable-tx-size-search=0",
2402 "--enable-cdef=0",
2403 "--enable-restoration=0",
2404 "--loopfilter-control=0",
2405 "--enable-palette=0",
2406 "--enable-intrabc=0",
2407 "--enable-cfl-intra=0",
2408 "--enable-ref-frame-mvs=0",
2409 "--obu",
2410 "-o",
2411 "-",
2412 "-",
2413 ]
2414 .iter()
2415 .map(|s| (*s).to_string())
2416 .collect();
2417 args.insert(1, format!("--cq-level={cq}"));
2418 if ten_bit {
2419 args.insert(1, "--input-bit-depth=10".to_string());
2420 args.insert(1, "--bit-depth=10".to_string());
2421 }
2422 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2423 assert!(
2424 out.status.success(),
2425 "{name}: aomenc refused the fixture: {}",
2426 String::from_utf8_lossy(&out.stderr)
2427 );
2428 let stream = out.stdout;
2429 let before = decode::chroma_eob_class1_hits();
2430 let frames = match decode_stream(&stream) {
2431 Ok(frames) => frames,
2432 // A named refusal ("unsupported: ...") is another lane's arm
2433 // and moves this attempt on; anything else is a real decode
2434 // failure and fails the gate on the spot.
2435 Err(e) if e.to_string().contains("unsupported") => {
2436 refusals.push(format!("cq={cq} period={period}: {e}"));
2437 continue;
2438 }
2439 Err(e) => {
2440 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
2441 crate::dumpio::pin("TEST_PIN", &pin, &stream);
2442 panic!(
2443 "{name}: decode_stream failed on a real aomenc stream (cq={cq} period={period}): {e} (pinned at {})",
2444 pin.display()
2445 );
2446 }
2447 };
2448 if decode::chroma_eob_class1_hits() == before {
2449 refusals.push(format!(
2450 "cq={cq} period={period}: decoded, but no chroma block read a class-1 eob_pt row"
2451 ));
2452 continue;
2453 }
2454 let ffmpeg_frames = if ten_bit {
2455 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
2456 } else {
2457 ffmpeg_decode_sequence(&stream, width, height, frame_count)
2458 };
2459 assert_eq!(frames.len(), frame_count, "{name}: frame count");
2460 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2461 if got.y != want.y || got.u != want.u || got.v != want.v {
2462 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
2463 crate::dumpio::pin("TEST_PIN", &pin, &stream);
2464 panic!(
2465 "{name}: frame {i} mismatch vs ffmpeg (cq={cq} period={period}) -- stream pinned at {}",
2466 pin.display()
2467 );
2468 }
2469 }
2470 return;
2471 }
2472 panic!("{name}: no attempt fired a class-1 chroma eob: {refusals:?}");
2473 }
2474
2475 /// lane-av1refs's decisive gate for the 5 references widened past
2476 /// `LAST_FRAME`/`GOLDEN_FRAME`: same envelope and pin-on-mismatch
2477 /// pattern as
2478 /// [`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`],
2479 /// generalised over `(target_ref, extra_args, frame_count)` so each of
2480 /// `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` gets its own attempt pool
2481 /// and its own proof that `decode::ref_hits(target_ref)` -- not just
2482 /// `non_last_ref_hits`, which cannot distinguish one reference from
2483 /// another -- actually advanced. `--max-reference-frames=3
2484 /// --reduced-reference-set=1` (the golden gate's own narrowing) is
2485 /// DROPPED here: both suppress exactly the references this gate needs
2486 /// aomenc's RD to reach.
2487 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
2488 #[allow(clippy::too_many_arguments)]
2489 pub(super) fn a_real_aomenc_single_ref_gate(
2490 gate_name: &str,
2491 target_ref: i8,
2492 target_ref_name: &str,
2493 extra_args: &[&str],
2494 width: usize,
2495 height: usize,
2496 frame_count: usize,
2497 attempts: u32,
2498 ) {
2499 let _gate_lock = lock_gate_counters();
2500 if !have_ffmpeg() {
2501 eprintln!("SKIP {gate_name}: no ffmpeg");
2502 return;
2503 }
2504 if !have_aomenc() {
2505 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
2506 return;
2507 }
2508 let mut refusals = Vec::new();
2509 let mut never_fired = 0u32;
2510 for attempt in 0..attempts {
2511 let seed = 42 + attempt % 40;
2512 let duration = frame_count as f64 / 25.0;
2513 let source =
2514 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
2515 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2516 .args([
2517 "-v",
2518 "error",
2519 "-f",
2520 "lavfi",
2521 "-i",
2522 &source,
2523 "-pix_fmt",
2524 "yuv420p",
2525 "-f",
2526 "yuv4mpegpipe",
2527 "-",
2528 ])
2529 .stdin(Stdio::null())
2530 .stdout(Stdio::piped())
2531 .stderr(Stdio::piped()), None, |c| c.output())
2532 .expect("ffmpeg failed to run");
2533 assert!(
2534 y4m.status.success(),
2535 "ffmpeg fixture: {}",
2536 String::from_utf8_lossy(&y4m.stderr)
2537 );
2538 let mut args: Vec<&str> = vec![
2539 "--codec=av1",
2540 "--passes=1",
2541 "--end-usage=q",
2542 "--cq-level=55",
2543 "--cpu-used=0",
2544 "--kf-max-dist=1000",
2545 "--threads=1",
2546 "--row-mt=0",
2547 "--enable-warped-motion=0",
2548 "--enable-obmc=0",
2549 "--enable-masked-comp=0",
2550 "--enable-interintra-comp=0",
2551 "--enable-dist-wtd-comp=0",
2552 "--enable-diff-wtd-comp=0",
2553 "--enable-onesided-comp=0",
2554 "--enable-interintra-wedge=0",
2555 "--enable-smooth-interintra=0",
2556 "--enable-rect-partitions=0",
2557 "--enable-ab-partitions=0",
2558 "--enable-1to4-partitions=0",
2559 "--enable-filter-intra=0",
2560 "--enable-smooth-intra=0",
2561 "--enable-paeth-intra=0",
2562 "--enable-directional-intra=0",
2563 "--enable-angle-delta=0",
2564 "--enable-tx-size-search=0",
2565 "--enable-cdef=0",
2566 "--enable-restoration=0",
2567 "--max-partition-size=32",
2568 "--min-partition-size=32",
2569 "--enable-palette=0",
2570 "--enable-intrabc=0",
2571 "--enable-cfl-intra=0",
2572 // use_ref_frame_mvs (temporal MV projection) is unimplemented in
2573 // mvstack; leaving it on silently desyncs symbols on inter frames.
2574 "--enable-ref-frame-mvs=0",
2575 "--obu",
2576 "-o",
2577 "-",
2578 "-",
2579 ];
2580 // extra_args goes right before the trailing "-o", "-", "-" triple.
2581 let tail = args.split_off(args.len() - 3);
2582 args.extend_from_slice(extra_args);
2583 args.extend_from_slice(&tail);
2584 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2585 assert!(
2586 out.status.success(),
2587 "aomenc refused the fixture: {}",
2588 String::from_utf8_lossy(&out.stderr)
2589 );
2590 let stream = out.stdout;
2591 let before = decode::ref_hits(target_ref);
2592 let frames = match decode_stream(&stream) {
2593 Err(e) => {
2594 let msg = e.to_string();
2595 assert!(
2596 msg.contains("unsupported"),
2597 "{gate_name} failed outright (seed {seed}): {msg}"
2598 );
2599 refusals.push(format!("seed {seed}: {msg}"));
2600 continue;
2601 }
2602 Ok(frames) => frames,
2603 };
2604 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
2605 // is ALWAYS pixel-compared below; the hit counter only decides whether
2606 // the attempt counts toward the firing total.
2607 let counted = decode::ref_hits(target_ref) != before;
2608 if !counted {
2609 never_fired += 1;
2610 }
2611 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2612 assert_eq!(frames.len(), frame_count);
2613 let mismatched = frames
2614 .iter()
2615 .zip(&ffmpeg_frames)
2616 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2617 if mismatched
2618 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
2619 std::fs::write(&path, &stream).expect("writing pinned stream");
2620 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
2621 }
2622 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2623 assert_eq!(
2624 got.y, want.y,
2625 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
2626 );
2627 assert_eq!(
2628 got.u, want.u,
2629 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
2630 );
2631 assert_eq!(
2632 got.v, want.v,
2633 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
2634 );
2635 }
2636 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
2637 // stream again, comparing EVERY decode-order frame -- the hidden
2638 // (show_frame == 0) alt-ref frames the ffmpeg compare above
2639 // cannot see, because both sides of it emit shown frames only.
2640 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, gate_name);
2641 eprintln!(
2642 "{gate_name} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
2643 {hidden_n} hidden, all pixel-exact vs the oracle"
2644 );
2645 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
2646 // libaom's temporal alt-ref filter absorbs this recipe's hidden
2647 // frames, so the compare above is vacuous -- re-encode the same
2648 // fixture with --arnr-maxframes=0 and compare THOSE.
2649 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(gate_name, &y4m.stdout, &args) {
2650 eprintln!(
2651 "{gate_name} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
2652 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
2653 );
2654 }
2655 if counted {
2656 eprintln!(
2657 "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}",
2658 decode::ref_hits(target_ref) - before
2659 );
2660 gate_buckets(gate_name, 1, never_fired, refusals.len());
2661 return;
2662 }
2663 }
2664 gate_buckets(gate_name, 0, never_fired, refusals.len());
2665 eprintln!(
2666 "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \
2667 and every other attempt hit a named refusal:\n{}",
2668 refusals.join("\n")
2669 );
2670 }
2671
2672 /// lane-gmaffine r1: the two 8x8-LEAF motion gates. `decode_inter_block8`
2673 /// is a separate function from [`decode_inter_block`], and until this
2674 /// round it refused both `GLOBALMV` ("GLOBALMV (round 3)") and
2675 /// `WARPED_CAUSAL` at that size while the 16x16+ leaf had implemented
2676 /// both for rounds. The reason no earlier gate caught it: the existing
2677 /// 8x8 OBMC gate clamps `--max-partition-size=32` and aomenc's RD then
2678 /// never splits down to a clean 8x8 leaf (that gate has never fired in
2679 /// 80 attempts). `--min-partition-size=8 --max-partition-size=8` removes
2680 /// the choice entirely -- every inter leaf in the stream IS an 8x8 one,
2681 /// so the leaf path is exercised by construction rather than by luck.
2682 ///
2683 /// Content is the affine gate's rotating/zooming mandelbrot (global
2684 /// motion the encoder can actually model), and the hit counters
2685 /// (`globalmv_hits_8` / `warp_hits_8`) are 8x8-leaf-specific: a
2686 /// 16x16-leaf GLOBALMV or warp cannot satisfy them.
2687 pub(super) fn run_8x8_leaf_motion_gate(name: &str, global_motion: bool, counter: fn() -> usize) {
2688 // 72x64: `decode_inter_block8` is reached ONLY through the
2689 // true-edge-straddling 16x16 path (an interior 16x16
2690 // PARTITION_SPLIT is still refused by name), so the frame is 8
2691 // luma columns wider than its last whole superblock -- every 16x16
2692 // block in that right-hand strip is cut on ONE axis and decodes as
2693 // four 8x8 leaves by construction. `--min-partition-size=16` keeps
2694 // the interior out of the still-refused sub-16x16 case.
2695 let (width, height, frame_count) = (64usize, 64usize, 24usize);
2696 let duration = frame_count as f64 / 25.0;
2697 // The encoder's own RD still chooses WHICH 8x8 leaf codes GLOBALMV /
2698 // WARPED_CAUSAL, and at some quantisers it picks a rect partition at
2699 // 16x16 (still refused) or a non-LAST reference (still refused at the
2700 // 8x8 leaf) before ever reaching one. So sweep a few quantisers and
2701 // require at least one attempt, at each depth, that BOTH decodes
2702 // pixel-exact AND fires the counter -- a refusing attempt is recorded,
2703 // never a pass (class `gate-skips-on-its-own-failure`).
2704 let mut fired_any = [false; 2];
2705 let mut notes: Vec<String> = Vec::new();
2706 for (di, depth) in [8u32, 10u32].into_iter().enumerate() {
2707 for cq in [32u32, 45, 55] {
2708 let cq_arg = format!("--cq-level={cq}");
2709 let max_part_arg = format!(
2710 "--max-partition-size={}",
2711 std::env::var("EC_8X8_MAXPART").unwrap_or_else(|_| "8".into())
2712 );
2713 let source = format!(
2714 "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\
2715 scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}"
2716 );
2717 let pix_fmt = if depth == 10 {
2718 "yuv420p10le"
2719 } else {
2720 "yuv420p"
2721 };
2722 let mut ff_args: Vec<&str> = vec![
2723 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt,
2724 ];
2725 if depth == 10 {
2726 ff_args.extend(["-strict", "-1"]);
2727 }
2728 let duration_arg = duration.to_string();
2729 ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]);
2730 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2731 .args(&ff_args)
2732 .stdin(Stdio::null())
2733 .stdout(Stdio::piped())
2734 .stderr(Stdio::piped()), None, |c| c.output())
2735 .expect("ffmpeg failed to run");
2736 assert!(
2737 y4m.status.success(),
2738 "ffmpeg fixture: {}",
2739 String::from_utf8_lossy(&y4m.stderr)
2740 );
2741 let bit_depth = format!("--bit-depth={depth}");
2742 let input_bit_depth = format!("--input-bit-depth={depth}");
2743 let gm_arg = format!("--enable-global-motion={}", u8::from(global_motion));
2744 let warp_arg = format!("--enable-warped-motion={}", u8::from(!global_motion));
2745 let args: Vec<&str> = vec![
2746 "--codec=av1",
2747 "--passes=1",
2748 "--end-usage=q",
2749 &cq_arg,
2750 "--cpu-used=0",
2751 "--kf-max-dist=1000",
2752 "--threads=1",
2753 "--row-mt=0",
2754 "--auto-alt-ref=0",
2755 "--lag-in-frames=0",
2756 "--enable-fwd-kf=0",
2757 "--enable-order-hint=1",
2758 &gm_arg,
2759 &warp_arg,
2760 "--enable-obmc=0",
2761 "--tune-content=default",
2762 "--enable-masked-comp=0",
2763 "--enable-interintra-comp=0",
2764 "--enable-onesided-comp=0",
2765 "--enable-rect-partitions=0",
2766 "--enable-ab-partitions=0",
2767 "--enable-1to4-partitions=0",
2768 "--enable-filter-intra=0",
2769 "--enable-smooth-intra=0",
2770 "--enable-paeth-intra=0",
2771 "--enable-directional-intra=0",
2772 "--enable-angle-delta=0",
2773 "--enable-tx-size-search=0",
2774 "--enable-cdef=0",
2775 "--enable-restoration=0",
2776 &max_part_arg,
2777 "--min-partition-size=8",
2778 "--enable-palette=0",
2779 "--enable-intrabc=0",
2780 "--enable-cfl-intra=0",
2781 "--enable-ref-frame-mvs=0",
2782 &bit_depth,
2783 &input_bit_depth,
2784 "--obu",
2785 "-o",
2786 "-",
2787 "-",
2788 ];
2789 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2790 assert!(
2791 out.status.success(),
2792 "aomenc refused the fixture: {}",
2793 String::from_utf8_lossy(&out.stderr)
2794 );
2795 let stream = out.stdout;
2796 let before = counter();
2797 let frames = match decode_stream(&stream) {
2798 Ok(f) => f,
2799 Err(e) => {
2800 let msg = e.to_string();
2801 assert!(
2802 msg.contains("unsupported"),
2803 "{name} ({depth}-bit, cq {cq}) failed outright: {msg}"
2804 );
2805 notes.push(format!("{depth}-bit cq {cq}: {msg}"));
2806 continue;
2807 }
2808 };
2809 let ffmpeg_frames = if depth == 10 {
2810 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
2811 } else {
2812 ffmpeg_decode_sequence(&stream, width, height, frame_count)
2813 };
2814 assert_eq!(frames.len(), frame_count);
2815 let hits = counter() - before;
2816 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2817 assert_eq!(got.y, want.y, "{name} {depth}-bit frame {i} luma vs ffmpeg");
2818 assert_eq!(got.u, want.u, "{name} {depth}-bit frame {i} U vs ffmpeg");
2819 assert_eq!(got.v, want.v, "{name} {depth}-bit frame {i} V vs ffmpeg");
2820 }
2821 if hits == 0 {
2822 notes.push(format!(
2823 "{depth}-bit cq {cq}: {frame_count} frames pixel-exact but 0 8x8-leaf hits"
2824 ));
2825 continue;
2826 }
2827 fired_any[di] = true;
2828 eprintln!(
2829 "{name}: {depth}-bit cq {cq}, {frame_count} frames pixel-exact, 8x8 hits={hits}"
2830 );
2831 }
2832 }
2833 assert!(
2834 fired_any[0] && fired_any[1],
2835 "{name}: no attempt both decoded pixel-exact and fired the 8x8 leaf \
2836 (8-bit fired {}, 10-bit fired {}):\n{}",
2837 fired_any[0],
2838 fired_any[1],
2839 notes.join("\n")
2840 );
2841 }