forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

gates_b.rs2804 lines, 128.9 KiBHistoryRawDownload
1use super::*;
2use super::support::*;
3use super::gates_a::*;
4
5 /// lane-cwarp r1: a real `--enable-global-motion=1 --enable-dist-wtd-comp=1`
6 /// stream over a rotating/zooming source, so a `GLOBAL_GLOBALMV` compound
7 /// block lands under a ROTZOOM/AFFINE model and each of its two references
8 /// is predicted through its OWN global warp
9 /// (`crate::warp::warp_affine_compound`, libaom `av1_warp_plane` with
10 /// `conv_params->is_compound`) rather than translationally. Before r1 that
11 /// path was SILENTLY WRONG -- no refusal named it, both taps went through
12 /// `mc::predict_compound_intermediate`. `compound_warp_hits() > 0` is a
13 /// hard assert: a run where the encoder never emitted one proves nothing.
14 /// A decode error or a pixel mismatch is a FAILURE, never a skip.
15 pub(super) fn run_compound_global_warp_gate(name: &str, bd: u32, min_part: u32, leaf8_assert: bool) {
16 let _gate_lock = lock_gate_counters();
17 assert!(have_ffmpeg(), "{name}: ffmpeg required");
18 assert!(
19 have_aomenc(),
20 "{name}: no aomenc at {}",
21 aomenc_path().display()
22 );
23 let (width, height, frame_count) = (64usize, 64usize, 24usize);
24 let before = crate::decode::compound_warp_hits();
25 let before8 = crate::decode::compound_warp_hits_8();
26 let mut matched = 0u32;
27 let mut named_refusals = 0u32;
28 let mut attempts = 0u32;
29 for cq in [32u32, 45, 55] {
30 for (i, rate) in [0.010f64, 0.022].iter().enumerate() {
31 attempts += 1;
32 let duration = frame_count as f64 / 25.0;
33 // A rotation about the frame centre plus a slow zoom is what
34 // aomenc's global-motion search fits a ROTZOOM/AFFINE model to;
35 // mandelbrot gives it real, non-flat texture to track.
36 let source = format!(
37 "mandelbrot=size={w}x{h}:rate=25:start_x={sx}:start_y=-0.4,\
38 rotate=a={rate}*n:ow={w}:oh={h}:c=black,scale={width}:{height}",
39 w = width * 2,
40 h = height * 2,
41 sx = -0.6 + 0.01 * (i as f64),
42 );
43 let pix_fmt = match bd {
44 8 => "yuv420p",
45 10 => "yuv420p10le",
46 _ => "yuv420p12le",
47 };
48 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
49 .args([
50 "-v",
51 "error",
52 "-f",
53 "lavfi",
54 "-i",
55 &source,
56 "-t",
57 &duration.to_string(),
58 "-pix_fmt",
59 pix_fmt,
60 "-strict",
61 "-1",
62 "-f",
63 "yuv4mpegpipe",
64 "-",
65 ])
66 .stdin(Stdio::null())
67 .stdout(Stdio::piped())
68 .stderr(Stdio::piped()), None, |c| c.output())
69 .expect("ffmpeg failed to run");
70 assert!(
71 y4m.status.success(),
72 "ffmpeg fixture: {}",
73 String::from_utf8_lossy(&y4m.stderr)
74 );
75 let cq_arg = format!("--cq-level={cq}");
76 let (in_depth_arg, depth_arg) = (
77 format!("--input-bit-depth={bd}"),
78 format!("--bit-depth={bd}"),
79 );
80 let mut args: Vec<&str> = vec![
81 "--codec=av1",
82 "--passes=1",
83 "--end-usage=q",
84 &cq_arg,
85 "--cpu-used=0",
86 "--kf-max-dist=1000",
87 "--threads=1",
88 "--row-mt=0",
89 "--auto-alt-ref=1",
90 "--lag-in-frames=25",
91 "--enable-fwd-kf=0",
92 "--enable-order-hint=1",
93 // the two tools this gate exists for
94 "--enable-global-motion=1",
95 "--enable-dist-wtd-comp=1",
96 "--enable-warped-motion=1",
97 "--enable-obmc=1",
98 "--enable-masked-comp=1",
99 "--enable-onesided-comp=0",
100 "--enable-interintra-comp=1",
101 "--enable-interintra-wedge=0",
102 "--enable-smooth-interintra=1",
103 "--tune-content=default",
104 // partition/intra tools this decoder does not code yet --
105 // same exclusion list every compound gate carries.
106 "--enable-rect-partitions=0",
107 "--enable-ab-partitions=0",
108 "--enable-1to4-partitions=0",
109 "--enable-filter-intra=0",
110 "--enable-smooth-intra=0",
111 "--enable-paeth-intra=0",
112 "--enable-directional-intra=0",
113 "--enable-angle-delta=0",
114 "--enable-tx-size-search=0",
115 "--enable-cdef=0",
116 "--enable-restoration=0",
117 "--max-partition-size=32",
118 "--enable-palette=0",
119 "--enable-intrabc=0",
120 "--enable-cfl-intra=0",
121 "--enable-ref-frame-mvs=0",
122 ];
123 let min_part_arg = format!("--min-partition-size={min_part}");
124 args.push(min_part_arg.as_str());
125 if bd != 8 {
126 args.extend_from_slice(&[in_depth_arg.as_str(), depth_arg.as_str()]);
127 }
128 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
129 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
130 assert!(
131 out.status.success(),
132 "aomenc refused the fixture: {}",
133 String::from_utf8_lossy(&out.stderr)
134 );
135 let stream = out.stdout;
136 let frames = match decode_stream(&stream) {
137 Err(e) => {
138 let msg = e.to_string();
139 assert!(
140 msg.contains("unsupported"),
141 "{name} failed outright, not a named refusal (cq {cq}): {msg}"
142 );
143 assert!(
144 !msg.contains("warp"),
145 "{name} refused on warp (cq {cq}) -- warp decode is ported: {msg}"
146 );
147 named_refusals += 1;
148 eprintln!("{name} cq {cq} rate {rate} refusal: {msg}");
149 continue;
150 }
151 Ok(frames) => frames,
152 };
153 let want = match bd {
154 8 => ffmpeg_decode_sequence(&stream, width, height, frame_count),
155 10 => ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count),
156 _ => ffmpeg_decode_sequence_12bit(&stream, width, height, frame_count),
157 };
158 assert_eq!(frames.len(), frame_count);
159 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
160 && frames
161 .iter()
162 .zip(&want)
163 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
164 {
165 std::fs::write(&path, &stream).expect("writing pinned stream");
166 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
167 }
168 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
169 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq})");
170 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq})");
171 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq})");
172 }
173 matched += 1;
174 }
175 }
176 let hits = crate::decode::compound_warp_hits() - before;
177 let hits8 = crate::decode::compound_warp_hits_8() - before8;
178 eprintln!(
179 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
180 compound_warp_hits={hits} compound_warp_hits_8={hits8}"
181 );
182 if leaf8_assert {
183 assert!(
184 hits8 > 0,
185 "{name}: no 8x8 COMPOUND leaf was predicted through a per-ref global \
186 warp ({hits} bigger compound warp blocks, {matched} matches, \
187 {named_refusals} refusals of {attempts}) -- gate vacuous"
188 );
189 } else {
190 assert!(
191 hits > 0,
192 "{name}: no compound block was predicted through a per-ref global warp \
193 ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous"
194 );
195 }
196 assert!(
197 matched > 0,
198 "{name}: every attempt refused -- no pixel comparison ran"
199 );
200 }
201
202 /// lane-fimv r1 (class `wrong-alphabet-same-value`): libaom
203 /// `motion_mode_allowed` (blockd.h ~1484) only returns `WARPED_CAUSAL`
204 /// when `!xd->cur_frame_force_integer_mv`, so on a frame whose header set
205 /// `force_integer_mv` an otherwise warp-eligible block reads the 2-symbol
206 /// `obmc_cdf`, not the 3-symbol `motion_mode_cdf`. This decoder read the
207 /// 3-symbol alphabet there (silent tile desync, no refusal named it).
208 ///
209 /// The fixture is screen content that is mostly static with only
210 /// whole-pixel motion, which is exactly what aomenc's own
211 /// `av1_is_integer_mv` (`encoder_utils.c:1357`, >=80% of blocks matching
212 /// their collocated block) needs to set `cur_frame_force_integer_mv`
213 /// under `--tune-content=screen` (seq `force_integer_mv == 2`, adaptive:
214 /// `encoder.c:4171`). Two hard asserts, both class
215 /// `gate-blind-to-feature`: at least one decoded frame header carried
216 /// `force_integer_mv = 1`, and at least one block took the 2-symbol
217 /// alphabet where `allow_warped_motion = 1` and `num_proj_ref >= 1` would
218 /// have picked the 3-symbol one. A decode error or a pixel mismatch is a
219 /// FAILURE, never a skip.
220 #[track_caller]
221 pub(super) fn run_fimv_motion_mode_gate(name: &str, ten_bit: bool) {
222 let _gate_lock = lock_gate_counters();
223 assert!(have_ffmpeg(), "{name}: ffmpeg required");
224 assert!(
225 have_aomenc(),
226 "{name}: no aomenc at {}",
227 aomenc_path().display()
228 );
229 let (width, height, frame_count) = (64usize, 64usize, 20usize);
230 let fimv_frames_before = crate::decode::fimv_frame_hits();
231 let alphabet_before = crate::decode::fimv_alphabet_hits();
232 let mut matched = 0u32;
233 let mut named_refusals = 0u32;
234 let mut attempts = 0u32;
235 let mut refusals = Vec::new();
236 for cq in [32u32, 45, 55] {
237 for step in [4u32, 8] {
238 attempts += 1;
239 // lane-fimv r1: per-attempt snapshots. The aggregate
240 // assertions below are satisfied by a single lucky cq/step
241 // cell; these prove EVERY attempt that decoded and
242 // pixel-compared really carried the header state and the
243 // forced alphabet under test (class gate-blind-to-feature).
244 let attempt_fimv_before = crate::decode::fimv_frame_hits();
245 let attempt_alphabet_before = crate::decode::fimv_alphabet_hits();
246 let duration = frame_count as f64 / 25.0;
247 // Flat screen-content tiles with hard edges, translating by a
248 // whole number of pixels per frame: static enough for
249 // `av1_is_integer_mv`, moving enough for a real inter block
250 // with overlappable neighbours.
251 let source = format!(
252 "color=c=black:s={width}x{height}:r=25,\
253 drawbox=x='8+{step}*mod(trunc(t*25)\\,3)':y=8:w=20:h=20:color=white:t=fill,\
254 drawbox=x=36:y='6+{step}*mod(trunc(t*25)+1\\,3)':w=16:h=16:color=0x808080:t=fill,\
255 drawbox=x=4:y=44:w=56:h=12:color=0xC0C0C0:t=fill"
256 );
257 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
258 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
259 .args([
260 "-v",
261 "error",
262 "-f",
263 "lavfi",
264 "-i",
265 &source,
266 "-t",
267 &duration.to_string(),
268 "-pix_fmt",
269 pix_fmt,
270 "-strict",
271 "-1",
272 "-f",
273 "yuv4mpegpipe",
274 "-",
275 ])
276 .stdin(Stdio::null())
277 .stdout(Stdio::piped())
278 .stderr(Stdio::piped()), None, |c| c.output())
279 .expect("ffmpeg failed to run");
280 assert!(
281 y4m.status.success(),
282 "ffmpeg fixture: {}",
283 String::from_utf8_lossy(&y4m.stderr)
284 );
285 let cq_arg = format!("--cq-level={cq}");
286 let mut args: Vec<&str> = vec![
287 "--codec=av1",
288 "--passes=1",
289 "--end-usage=q",
290 &cq_arg,
291 "--cpu-used=0",
292 "--kf-max-dist=1000",
293 "--threads=1",
294 "--row-mt=0",
295 // single reference only: the 10-bit compound MC defect
296 // (see `a_real_compound_global_warp_10bit_stream_...`)
297 // is unrelated to this lane and would mask it.
298 "--auto-alt-ref=0",
299 "--lag-in-frames=0",
300 "--enable-fwd-kf=0",
301 "--enable-order-hint=1",
302 // the flag combination this gate exists for: warp allowed
303 // by the header, OBMC available, global motion off (so the
304 // GLOBALMV suppression is not what picks the alphabet).
305 "--tune-content=screen",
306 "--enable-warped-motion=1",
307 "--enable-obmc=1",
308 "--enable-global-motion=0",
309 "--enable-masked-comp=0",
310 "--enable-onesided-comp=0",
311 "--enable-interintra-comp=0",
312 "--enable-interintra-wedge=0",
313 "--enable-smooth-interintra=0",
314 "--enable-dist-wtd-comp=0",
315 // partition/intra tools this decoder does not code yet --
316 // the same exclusion list every inter gate here carries.
317 "--enable-rect-partitions=0",
318 "--enable-ab-partitions=0",
319 "--enable-1to4-partitions=0",
320 "--enable-filter-intra=0",
321 "--enable-smooth-intra=0",
322 "--enable-paeth-intra=0",
323 "--enable-directional-intra=0",
324 "--enable-angle-delta=0",
325 "--enable-tx-size-search=0",
326 "--enable-cdef=0",
327 "--enable-restoration=0",
328 "--max-partition-size=32",
329 "--min-partition-size=32",
330 "--enable-palette=0",
331 "--enable-intrabc=0",
332 "--enable-cfl-intra=0",
333 "--enable-ref-frame-mvs=0",
334 ];
335 if ten_bit {
336 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
337 }
338 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
339 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
340 assert!(
341 out.status.success(),
342 "aomenc refused the fixture: {}",
343 String::from_utf8_lossy(&out.stderr)
344 );
345 let stream = out.stdout;
346 let frames = match decode_stream(&stream) {
347 Err(e) => {
348 let msg = e.to_string();
349 assert!(
350 msg.contains("unsupported"),
351 "{name} failed outright (cq {cq} step {step}): {msg}"
352 );
353 named_refusals += 1;
354 refusals.push(format!("cq {cq} step {step}: {msg}"));
355 continue;
356 }
357 Ok(frames) => frames,
358 };
359 let want = if ten_bit {
360 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
361 } else {
362 ffmpeg_decode_sequence(&stream, width, height, frame_count)
363 };
364 assert_eq!(frames.len(), frame_count);
365 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
366 && frames
367 .iter()
368 .zip(&want)
369 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
370 {
371 std::fs::write(&path, &stream).expect("writing pinned stream");
372 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
373 }
374 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
375 assert_eq!(
376 got.y, want.y,
377 "{name} frame {i} luma vs ffmpeg (cq {cq} step {step})"
378 );
379 assert_eq!(
380 got.u, want.u,
381 "{name} frame {i} U vs ffmpeg (cq {cq} step {step})"
382 );
383 assert_eq!(
384 got.v, want.v,
385 "{name} frame {i} V vs ffmpeg (cq {cq} step {step})"
386 );
387 }
388 assert!(
389 crate::decode::fimv_frame_hits() > attempt_fimv_before,
390 "{name} (cq {cq} step {step}): decoded and compared all \
391 frames but no frame header had force_integer_mv=1 -- \
392 this attempt is vacuous"
393 );
394 assert!(
395 crate::decode::fimv_alphabet_hits() > attempt_alphabet_before,
396 "{name} (cq {cq} step {step}): no block was forced onto the \
397 2-symbol obmc alphabet by force_integer_mv while \
398 allow_warped_motion=1 and num_proj_ref>=1 -- this attempt \
399 is vacuous"
400 );
401 matched += 1;
402 }
403 }
404 let fimv_frames = crate::decode::fimv_frame_hits() - fimv_frames_before;
405 let alphabet = crate::decode::fimv_alphabet_hits() - alphabet_before;
406 eprintln!(
407 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
408 force_integer_mv frames={fimv_frames}, forced-2-symbol blocks={alphabet}\n{}",
409 refusals.join("\n")
410 );
411 assert!(
412 matched > 0,
413 "{name}: every attempt refused -- no pixel comparison ran"
414 );
415 assert!(
416 fimv_frames > 0,
417 "{name}: no decoded frame header had force_integer_mv=1 \
418 ({matched} matches of {attempts}) -- gate vacuous"
419 );
420 assert!(
421 alphabet > 0,
422 "{name}: no block read the 2-symbol obmc alphabet where \
423 allow_warped_motion=1 and num_proj_ref>=1 would have picked the \
424 3-symbol motion_mode alphabet -- gate vacuous"
425 );
426 }
427
428 /// lane-mcomp64 r1: at 64x64 `av1_is_wedge_used` is false
429 /// (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`), so libaom's
430 /// `read_compound_type` codes NO `compound_type` symbol and INFERS
431 /// `COMPOUND_DIFFWTD`; only the 1-bit `mask_type` literal follows. This
432 /// decoder used to refuse such a block by name ("a masked compound 64x64
433 /// inter block..."), because reading the symbol would have desynced.
434 ///
435 /// The recipe pins every block to 64x64 (`--sb-size=64
436 /// --max-partition-size=64 --min-partition-size=64`) with masked compound
437 /// on and distance-weighted compound off, so the only way a
438 /// `comp_group_idx == 1` block can be coded is through the inferred arm.
439 /// `diffwtd_inferred_hits` is snapshotted PER ATTEMPT and only accumulated
440 /// for attempts that decoded AND pixel-compared (class
441 /// `counter-from-refused-stream`), and is hard-asserted at the end. A
442 /// decode error or a pixel mismatch is a FAILURE, never a skip.
443 #[track_caller]
444 pub(super) fn run_diffwtd_inferred_64x64_gate(name: &str, ten_bit: bool) {
445 let _gate_lock = lock_gate_counters();
446 assert!(have_ffmpeg(), "{name}: ffmpeg required");
447 assert!(
448 have_aomenc(),
449 "{name}: no aomenc at {}",
450 aomenc_path().display()
451 );
452 let (width, height, frame_count) = (128usize, 128usize, 16usize);
453 let mut matched = 0u32;
454 let mut named_refusals = 0u32;
455 let mut attempts = 0u32;
456 let mut fired = 0usize;
457 let mut refusals: Vec<String> = Vec::new();
458 for cq in [32u32, 45, 55] {
459 for (i, zoom) in [0.004f64, 0.010].iter().enumerate() {
460 attempts += 1;
461 let attempt_before = crate::decode::diffwtd_inferred_hits();
462 let duration = frame_count as f64 / 25.0;
463 // Hard-edged, moving content: a difference-weighted mask only
464 // wins where the two references genuinely disagree over part
465 // of a 64x64 block (a smooth `gradients` source measured
466 // diffwtd_hits == 0, memory `gate-blind-to-feature`).
467 let source = format!(
468 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y=-0.4:\
469 end_scale=0.3:maxiter=200,\
470 noise=alls=6:allf=t+u:all_seed={seed}",
471 sx = -0.6 + zoom * (i as f64 + 1.0),
472 seed = 1000 + cq,
473 );
474 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
475 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
476 .args([
477 "-v",
478 "error",
479 "-f",
480 "lavfi",
481 "-i",
482 &source,
483 "-t",
484 &duration.to_string(),
485 "-pix_fmt",
486 pix_fmt,
487 "-strict",
488 "-1",
489 "-f",
490 "yuv4mpegpipe",
491 "-",
492 ])
493 .stdin(Stdio::null())
494 .stdout(Stdio::piped())
495 .stderr(Stdio::piped()), None, |c| c.output())
496 .expect("ffmpeg failed to run");
497 assert!(
498 y4m.status.success(),
499 "ffmpeg fixture: {}",
500 String::from_utf8_lossy(&y4m.stderr)
501 );
502 let cq_arg = format!("--cq-level={cq}");
503 let mut args: Vec<&str> = vec![
504 "--codec=av1",
505 "--passes=1",
506 "--end-usage=q",
507 &cq_arg,
508 "--cpu-used=0",
509 "--kf-max-dist=1000",
510 "--threads=1",
511 "--row-mt=0",
512 "--auto-alt-ref=1",
513 "--lag-in-frames=16",
514 "--enable-fwd-kf=0",
515 "--enable-order-hint=1",
516 // the tools this gate exists for: masked compound on, the
517 // difference-weighted arm on, the distance-weighted
518 // competitor off so comp_group_idx==1 is the encoder's
519 // only masked choice at a size where wedge does not exist.
520 "--enable-masked-comp=1",
521 "--enable-diff-wtd-comp=1",
522 "--enable-dist-wtd-comp=0",
523 "--enable-onesided-comp=0",
524 "--enable-interintra-comp=0",
525 "--enable-global-motion=0",
526 "--enable-warped-motion=1",
527 "--enable-obmc=1",
528 "--tune-content=default",
529 // partition/intra tools this decoder does not code yet --
530 // same exclusion list every compound gate carries.
531 "--enable-rect-partitions=0",
532 "--enable-ab-partitions=0",
533 "--enable-1to4-partitions=0",
534 "--enable-filter-intra=0",
535 "--enable-smooth-intra=0",
536 "--enable-paeth-intra=0",
537 "--enable-directional-intra=0",
538 "--enable-angle-delta=0",
539 "--enable-tx-size-search=0",
540 "--enable-cdef=0",
541 "--enable-restoration=0",
542 "--enable-palette=0",
543 "--enable-intrabc=0",
544 "--enable-cfl-intra=0",
545 "--enable-ref-frame-mvs=0",
546 // every block is a whole 64x64 superblock: the ONLY size
547 // where compound_type is inferred rather than coded.
548 "--sb-size=64",
549 "--max-partition-size=64",
550 "--min-partition-size=64",
551 ];
552 if ten_bit {
553 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
554 }
555 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
556 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
557 assert!(
558 out.status.success(),
559 "aomenc refused the fixture: {}",
560 String::from_utf8_lossy(&out.stderr)
561 );
562 let stream = out.stdout;
563 let frames = match decode_stream(&stream) {
564 Err(e) => {
565 let msg = e.to_string();
566 assert!(
567 msg.contains("unsupported"),
568 "{name} failed outright, not a named refusal (cq {cq}): {msg}"
569 );
570 assert!(
571 !msg.contains("masked compound 64x64"),
572 "{name} refused the inferred-DIFFWTD 64x64 block (cq {cq}) -- \
573 that refusal is lifted, this is forbidden: {msg}"
574 );
575 named_refusals += 1;
576 refusals.push(msg.clone());
577 eprintln!("{name} cq {cq} variant {i} refusal: {msg}");
578 continue;
579 }
580 Ok(frames) => frames,
581 };
582 let want = if ten_bit {
583 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
584 } else {
585 ffmpeg_decode_sequence(&stream, width, height, frame_count)
586 };
587 assert_eq!(frames.len(), frame_count);
588 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
589 && frames
590 .iter()
591 .zip(&want)
592 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
593 {
594 std::fs::write(&path, &stream).expect("writing pinned stream");
595 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
596 }
597 for (f, (got, want)) in frames.iter().zip(&want).enumerate() {
598 assert_eq!(got.y, want.y, "{name} frame {f} luma vs ffmpeg (cq {cq})");
599 assert_eq!(got.u, want.u, "{name} frame {f} U vs ffmpeg (cq {cq})");
600 assert_eq!(got.v, want.v, "{name} frame {f} V vs ffmpeg (cq {cq})");
601 }
602 // decoded AND compared: only now does this attempt's own
603 // inferred-DIFFWTD count mean anything.
604 fired += crate::decode::diffwtd_inferred_hits() - attempt_before;
605 matched += 1;
606 }
607 }
608 eprintln!(
609 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
610 diffwtd_inferred_hits (decoded+compared attempts only)={fired}"
611 );
612 assert!(
613 matched > 0,
614 "{name}: every attempt refused ({refusals:?}) -- no pixel compare ran"
615 );
616 assert!(
617 fired > 0,
618 "{name}: no inferred-DIFFWTD 64x64 block fired on a compared attempt \
619 ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous"
620 );
621 }
622
623 pub(super) fn both_axes_cut_sweep(
624 name: &'static str,
625 (arm, frames, kf_arg, limit_arg): (&str, usize, &str, &str),
626 ) {
627 // Kept upper-case so every message string below reads the same as in
628 // the sibling gates.
629 #[allow(non_snake_case)]
630 let NAME = name;
631 let _gate_lock = lock_gate_counters();
632 if !have_ffmpeg() || !have_aomenc() {
633 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
634 return;
635 }
636 let sizes: &[(usize, usize)] = &[(200, 72), (136, 104), (264, 136), (72, 200), (104, 136)];
637 let mut compared = 0u32;
638 let mut refusals: Vec<String> = Vec::new();
639 let mut totals = [0usize; 4];
640 for &(width, height) in sizes {
641 let mut size_compared = 0u32;
642 {
643 for bit_depth in [8u32, 10u32] {
644 // cq 58 is left out on purpose: measured r1, it is where
645 // libaom starts answering the frame-edge gathered symbol
646 // with a rect strip and other lanes' refusals fire first
647 // ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs
648 // rectangular residual coding").
649 for cq in [32u32, 45] {
650 let source = format!("mandelbrot=size={width}x{height}:rate=25");
651 // Feed exactly `frames` frames: --limit=1 makes
652 // aomenc stop reading after the first one and the
653 // y4m write then dies on a broken pipe.
654 let dur = format!("{}", frames as f64 / 25.0);
655 let pix_fmt = if bit_depth == 10 {
656 "yuv420p10le"
657 } else {
658 "yuv420p"
659 };
660 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
661 .args([
662 "-v",
663 "error",
664 "-f",
665 "lavfi",
666 "-i",
667 &source,
668 "-t",
669 &dur,
670 "-pix_fmt",
671 pix_fmt,
672 "-strict",
673 "-1",
674 "-f",
675 "yuv4mpegpipe",
676 "-",
677 ])
678 .stdin(Stdio::null())
679 .stdout(Stdio::piped())
680 .stderr(Stdio::piped()), None, |c| c.output())
681 .expect("ffmpeg failed to run");
682 assert!(
683 y4m.status.success(),
684 "{NAME}: ffmpeg refused the {width}x{height} {bit_depth}-bit \
685 fixture: {}",
686 String::from_utf8_lossy(&y4m.stderr)
687 );
688 let depth_arg = format!("--bit-depth={bit_depth}");
689 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
690 let cq_arg = format!("--cq-level={cq}");
691 let out = run_with_stdin(
692 Command::new(aomenc_path()).args([
693 "--codec=av1",
694 "--passes=1",
695 "--end-usage=q",
696 &cq_arg,
697 // cpu-used >= 1 keeps libaom on 64x64
698 // superblocks at these sizes
699 // (`av1_select_sb_size`).
700 "--cpu-used=4",
701 "--threads=1",
702 "--row-mt=0",
703 // --lag-in-frames=0: no hidden alt-ref, so
704 // decode order == display order and the
705 // compare below covers every frame the stream
706 // carries (class gate-blind-to-hidden-frames).
707 kf_arg,
708 limit_arg,
709 "--lag-in-frames=0",
710 &depth_arg,
711 &input_depth_arg,
712 // Other lanes' named refusals this recipe must
713 // not trip. The both-cut corner is FORCED down
714 // to 8x8 leaves, which is exactly where the
715 // 8x8-intra-leaf-in-an-inter-frame gaps live,
716 // so the intra tool set and tx-size search are
717 // pinned off: without them 30/30 inter
718 // attempts refused (measured r1) on "a nonzero
719 // angle delta on an 8x8 intra leaf in an inter
720 // frame", "a non-DC chroma mode on an 8x8
721 // inter-frame leaf" and "an 8x8 intra leaf in
722 // an inter frame whose tx_depth splits it into
723 // 4x4 transform units".
724 "--enable-rect-partitions=0",
725 "--enable-ab-partitions=0",
726 "--enable-1to4-partitions=0",
727 "--min-partition-size=8",
728 "--max-partition-size=64",
729 "--enable-palette=0",
730 "--enable-intrabc=0",
731 "--enable-warped-motion=0",
732 "--enable-obmc=0",
733 "--enable-masked-comp=0",
734 "--enable-interintra-comp=0",
735 "--enable-onesided-comp=0",
736 "--enable-interintra-wedge=0",
737 "--enable-smooth-interintra=0",
738 "--enable-ref-frame-mvs=0",
739 "--enable-angle-delta=0",
740 "--enable-cfl-intra=0",
741 "--enable-directional-intra=0",
742 "--enable-smooth-intra=0",
743 "--enable-paeth-intra=0",
744 "--enable-filter-intra=0",
745 "--enable-tx-size-search=0",
746 "--obu",
747 "-o",
748 "-",
749 "-",
750 ]),
751 &y4m.stdout,
752 );
753 assert!(
754 out.status.success(),
755 "aomenc refused: {}",
756 String::from_utf8_lossy(&out.stderr)
757 );
758 let stream = out.stdout;
759
760 // Reset, never a delta across attempts: a refused
761 // attempt's hits must not count (class
762 // counter-from-refused-stream).
763 crate::decode::reset_edge_both_cut_hits();
764 let decoded = match decode_stream(&stream) {
765 Ok(f) => f,
766 Err(e) => {
767 let msg = e.to_string();
768 assert!(
769 msg.contains("unsupported"),
770 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
771 failed outright, not a named refusal: {msg}"
772 );
773 eprintln!(
774 " {NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
775 REFUSED {msg}"
776 );
777 refusals.push(msg);
778 continue;
779 }
780 };
781 let hits = crate::decode::edge_both_cut_hits();
782 let reference = if bit_depth == 10 {
783 ffmpeg_decode_sequence_10bit(&stream, width, height, frames)
784 } else {
785 ffmpeg_decode_sequence(&stream, width, height, frames)
786 };
787 assert_eq!(
788 decoded.len(),
789 frames,
790 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} decoded {} \
791 frames, expected {frames}",
792 decoded.len()
793 );
794 assert_eq!(
795 reference.len(),
796 frames,
797 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} reference \
798 frame count"
799 );
800 for (i, (ours, theirs)) in decoded.iter().zip(&reference).enumerate() {
801 let nd = |a: &[u16], b: &[u16]| {
802 a.iter().zip(b).filter(|(x, y)| x != y).count()
803 };
804 // Where a mismatch lands is the whole diagnosis
805 // here (corner block vs elsewhere), so print the
806 // luma bounding box before the assert kills the run.
807 if nd(&ours.y, &theirs.y) > 0 {
808 let (mut r0, mut c0, mut r1, mut c1) =
809 (usize::MAX, usize::MAX, 0usize, 0usize);
810 for row in 0..height {
811 for col in 0..width {
812 if ours.y[row * width + col] != theirs.y[row * width + col]
813 {
814 r0 = r0.min(row);
815 c0 = c0.min(col);
816 r1 = r1.max(row);
817 c1 = c1.max(col);
818 }
819 }
820 }
821 eprintln!(
822 " {NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
823 frame {i} luma diff bbox rows {r0}..={r1} cols {c0}..={c1}"
824 );
825 }
826 assert_eq!(
827 (
828 nd(&ours.y, &theirs.y),
829 nd(&ours.u, &theirs.u),
830 nd(&ours.v, &theirs.v)
831 ),
832 (0, 0, 0),
833 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} frame \
834 {i} differs from ffmpeg"
835 );
836 for (plane, a, b) in [
837 ("Y", &ours.y, &theirs.y),
838 ("U", &ours.u, &theirs.u),
839 ("V", &ours.v, &theirs.v),
840 ] {
841 assert_eq!(
842 a.len(),
843 b.len(),
844 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} \
845 frame {i} plane {plane}: ours has {} samples, ffmpeg's has \
846 {} -- a short plane would zip-truncate the diff count \
847 above and hide a chroma-span defect",
848 a.len(),
849 b.len()
850 );
851 }
852 }
853 // Every compared attempt must carry the case, so no
854 // compared attempt is out of scope and
855 // out_of_scope_mismatch is 0 by construction.
856 assert!(
857 hits[0] > 0,
858 "{NAME}: {width}x{height} {arm} {bit_depth}-bit cq {cq} decoded \
859 pixel-exact but no 16-level both-axes-cut block fired \
860 (hits={hits:?}) -- the recipe no longer reaches the lifted arm"
861 );
862 for l in 0..4 {
863 totals[l] += hits[l];
864 }
865 compared += 1;
866 size_compared += 1;
867 }
868 }
869 }
870 assert!(
871 size_compared > 0,
872 "{NAME}: every {width}x{height} attempt refused -- that size proved nothing"
873 );
874 }
875 assert!(
876 totals[1] > 0 && totals[2] > 0,
877 "{NAME}: no 32-level ({}) or 64-level ({}) both-axes-cut node fired -- 200x72 puts \
878 both in that state, so the sweep stopped reaching them",
879 totals[1],
880 totals[2]
881 );
882 eprintln!(
883 "{NAME}: {compared} attempts pixel-exact over {} sizes ({arm} arm), \
884 out_of_scope_mismatch=0, both_cut hits [16,32,64,128]={totals:?}, {} named refusals",
885 sizes.len(),
886 refusals.len()
887 );
888 }
889
890 /// lane-av1tmvp: the temporal-MV gate -- unlike every `_single_ref_gate`
891 /// attempt above, this one leaves `--enable-ref-frame-mvs` at aomenc's
892 /// own default (on) instead of pinning it off, so `use_ref_frame_mvs`
893 /// actually fires and `decode::tmv_hits()` (this gate's own capability
894 /// proof, not just `non_last_ref_hits`) has to advance for the run to
895 /// count as a real pass rather than a `never_fired` skip.
896 pub(super) fn a_real_aomenc_temporal_mv_gate(seed_base: u32, attempts: u32) {
897 let gate_name = "a_real_aomenc_temporal_mv_gate";
898 let _gate_lock = lock_gate_counters();
899 if !have_ffmpeg() {
900 eprintln!("SKIP {gate_name}: no ffmpeg");
901 return;
902 }
903 if !have_aomenc() {
904 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
905 return;
906 }
907 let (width, height, frame_count) = (64usize, 64usize, 16usize);
908 let mut never_fired = 0u32;
909 let mut refusals = Vec::new();
910 for attempt in 0..attempts {
911 let seed = seed_base + attempt;
912 let duration = frame_count as f64 / 25.0;
913 let source =
914 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
915 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
916 .args([
917 "-v",
918 "error",
919 "-f",
920 "lavfi",
921 "-i",
922 &source,
923 "-pix_fmt",
924 "yuv420p",
925 "-f",
926 "yuv4mpegpipe",
927 "-",
928 ])
929 .stdin(Stdio::null())
930 .stdout(Stdio::piped())
931 .stderr(Stdio::piped()), None, |c| c.output())
932 .expect("ffmpeg failed to run");
933 assert!(
934 y4m.status.success(),
935 "ffmpeg fixture: {}",
936 String::from_utf8_lossy(&y4m.stderr)
937 );
938 // Same envelope as `a_real_aomenc_single_ref_gate`, minus its
939 // `--enable-ref-frame-mvs=0` pin -- everything else this decoder
940 // still cannot code stays refused the same way.
941 let args: Vec<&str> = vec![
942 "--codec=av1",
943 "--passes=1",
944 "--end-usage=q",
945 "--cq-level=55",
946 "--cpu-used=0",
947 "--kf-max-dist=1000",
948 "--threads=1",
949 "--row-mt=0",
950 "--auto-alt-ref=1",
951 "--lag-in-frames=16",
952 "--enable-fwd-kf=0",
953 "--enable-warped-motion=0",
954 "--enable-obmc=0",
955 "--enable-masked-comp=0",
956 "--enable-interintra-comp=0",
957 "--enable-dist-wtd-comp=0",
958 "--enable-diff-wtd-comp=0",
959 "--enable-onesided-comp=0",
960 "--enable-interintra-wedge=0",
961 "--enable-smooth-interintra=0",
962 "--enable-rect-partitions=0",
963 "--enable-ab-partitions=0",
964 "--enable-1to4-partitions=0",
965 "--enable-filter-intra=0",
966 "--enable-smooth-intra=0",
967 "--enable-paeth-intra=0",
968 "--enable-directional-intra=0",
969 "--enable-angle-delta=0",
970 "--enable-tx-size-search=0",
971 "--enable-cdef=0",
972 "--enable-restoration=0",
973 "--max-partition-size=32",
974 "--min-partition-size=32",
975 "--enable-palette=0",
976 "--enable-intrabc=0",
977 "--enable-cfl-intra=0",
978 "--obu",
979 "-o",
980 "-",
981 "-",
982 ];
983 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
984 assert!(
985 out.status.success(),
986 "aomenc refused the fixture: {}",
987 String::from_utf8_lossy(&out.stderr)
988 );
989 let stream = out.stdout;
990 let before = decode::tmv_hits();
991 let frames = match decode_stream(&stream) {
992 Err(e) => {
993 let msg = e.to_string();
994 assert!(
995 msg.contains("unsupported"),
996 "{gate_name} failed outright (seed {seed}): {msg}"
997 );
998 refusals.push(format!("seed {seed}: {msg}"));
999 continue;
1000 }
1001 Ok(frames) => frames,
1002 };
1003 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
1004 // is ALWAYS pixel-compared below; the hit counter only decides whether
1005 // the attempt counts toward the firing total.
1006 let counted = decode::tmv_hits() != before;
1007 if !counted {
1008 never_fired += 1;
1009 }
1010 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
1011 assert_eq!(frames.len(), frame_count);
1012 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
1013 let mismatched = frames
1014 .iter()
1015 .zip(&ffmpeg_frames)
1016 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1017 if mismatched {
1018 std::fs::write(&path, &stream).expect("writing pinned stream");
1019 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
1020 }
1021 }
1022 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1023 assert_eq!(
1024 got.y, want.y,
1025 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
1026 );
1027 assert_eq!(
1028 got.u, want.u,
1029 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
1030 );
1031 assert_eq!(
1032 got.v, want.v,
1033 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
1034 );
1035 }
1036 if counted {
1037 eprintln!(
1038 "{gate_name} FIRING seed {seed}: tmv_hits advanced by {}",
1039 decode::tmv_hits() - before
1040 );
1041 gate_buckets(gate_name, 1, never_fired, refusals.len());
1042 return;
1043 }
1044 }
1045 gate_buckets(gate_name, 0, never_fired, refusals.len());
1046 eprintln!(
1047 "SKIP {gate_name}: {never_fired} attempts decoded but never fired a temporal MV \
1048 candidate, and every other attempt hit a named refusal:\n{}",
1049 refusals.join("\n")
1050 );
1051 }
1052
1053 /// lane-mvtwin r1: the COMPOUND MV-stack gate. Every other compound gate
1054 /// here pins `--enable-ref-frame-mvs=0`, so `find_mv_stack_compound`'s
1055 /// temporal half (the three `tpl_sample_pos` extension samples lane-sb128
1056 /// r3 found missing) and its extension pass have never been exercised by
1057 /// a real encoder. This arm turns ref-frame-mvs ON, gives the encoder a
1058 /// 25-frame lookahead plus alt-refs so `reference_select` really drives
1059 /// blocks to COMPOUND_REFERENCE, and sweeps global motion off/on so the
1060 /// combine step's `gm_mv_candidates` fill (r1 defect 1) is reachable.
1061 ///
1062 /// Firing proof, hard-asserted: `decode::comp_mode_hits` (a real
1063 /// compound block) AND `mvstack::tmv_hits` (a temporal candidate landed
1064 /// in some stack) must BOTH have advanced on an attempt that also
1065 /// decoded pixel-exact -- class [[gate-skips-on-its-own-failure]]: a
1066 /// decode that succeeds is ALWAYS compared, on every decode-order frame,
1067 /// and only the counters decide whether the attempt counts.
1068 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1069 #[allow(clippy::too_many_arguments)]
1070 pub(super) fn a_real_aomenc_compound_mv_stack_gate(
1071 gate_name: &str,
1072 seed_base: u32,
1073 attempts: u32,
1074 bit_depth: u32,
1075 sb_size: u32,
1076 global_motion: u32,
1077 width: usize,
1078 tile_columns: u32,
1079 ) {
1080 let _gate_lock = lock_gate_counters();
1081 if !have_ffmpeg() {
1082 eprintln!("SKIP {gate_name}: no ffmpeg");
1083 return;
1084 }
1085 if !have_aomenc() {
1086 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
1087 return;
1088 }
1089 let (height, frame_count) = (64usize, 16usize);
1090 let mut never_fired = 0u32;
1091 let mut refusals = Vec::new();
1092 for attempt in 0..attempts {
1093 let seed = seed_base + attempt;
1094 let duration = frame_count as f64 / 25.0;
1095 let source =
1096 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
1097 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1098 .args([
1099 "-v",
1100 "error",
1101 "-f",
1102 "lavfi",
1103 "-i",
1104 &source,
1105 "-pix_fmt",
1106 if bit_depth == 10 {
1107 "yuv420p10le"
1108 } else {
1109 "yuv420p"
1110 },
1111 "-strict",
1112 "-1",
1113 "-t",
1114 "0.64",
1115 "-f",
1116 "yuv4mpegpipe",
1117 "-strict",
1118 "-1",
1119 "-",
1120 ])
1121 .stdin(Stdio::null())
1122 .stdout(Stdio::piped())
1123 .stderr(Stdio::piped()), None, |c| c.output())
1124 .expect("ffmpeg failed to run");
1125 assert!(
1126 y4m.status.success(),
1127 "ffmpeg fixture: {}",
1128 String::from_utf8_lossy(&y4m.stderr)
1129 );
1130 let depth_args: &[&str] = if bit_depth == 10 {
1131 &["-b", "10", "--input-bit-depth=10"]
1132 } else {
1133 &[]
1134 };
1135 // The cq sweep: how finely RD partitions decides how often a
1136 // block's stack comes up short enough to reach the extension
1137 // pass at all.
1138 let cq = format!("--cq-level={}", [45u32, 55, 35][(attempt % 3) as usize]);
1139 let sb = format!("--sb-size={sb_size}");
1140 let gm = format!("--enable-global-motion={global_motion}");
1141 // `--tile-columns` is log2: 1 means two tile columns, which is
1142 // what makes every block in the right-hand tile carry a nonzero
1143 // `tile_col0` and so exercise r1 defect 3's reach clamp.
1144 let tiles = format!("--tile-columns={tile_columns}");
1145 // class [[aomenc-last-flag-wins]]: every flag appears exactly
1146 // once below, so there is no override to order.
1147 let out = run_with_stdin(
1148 Command::new(aomenc_path())
1149 .args(depth_args)
1150 .arg(&cq)
1151 .arg(&sb)
1152 .arg(&gm)
1153 .arg(&tiles)
1154 .args([
1155 "--codec=av1",
1156 "--passes=1",
1157 "--end-usage=q",
1158 "--cpu-used=0",
1159 "--kf-max-dist=1000",
1160 "--threads=1",
1161 "--row-mt=0",
1162 // What this gate is about: real compound references
1163 // with a real temporal MV field behind them.
1164 "--enable-ref-frame-mvs=1",
1165 "--enable-order-hint=1",
1166 "--auto-alt-ref=1",
1167 "--lag-in-frames=25",
1168 "--enable-fwd-kf=0",
1169 "--enable-warped-motion=0",
1170 "--enable-obmc=0",
1171 "--enable-masked-comp=0",
1172 "--enable-interintra-comp=0",
1173 "--enable-dist-wtd-comp=0",
1174 "--enable-diff-wtd-comp=0",
1175 "--enable-onesided-comp=0",
1176 "--enable-interintra-wedge=0",
1177 "--enable-smooth-interintra=0",
1178 "--enable-rect-partitions=0",
1179 "--enable-ab-partitions=0",
1180 "--enable-1to4-partitions=0",
1181 "--enable-filter-intra=0",
1182 "--enable-smooth-intra=0",
1183 "--enable-paeth-intra=0",
1184 "--enable-directional-intra=0",
1185 "--enable-angle-delta=0",
1186 "--enable-tx-size-search=0",
1187 "--enable-cdef=0",
1188 "--enable-restoration=0",
1189 "--max-partition-size=32",
1190 "--min-partition-size=32",
1191 "--enable-palette=0",
1192 "--enable-intrabc=0",
1193 "--enable-cfl-intra=0",
1194 "--obu",
1195 "-o",
1196 "-",
1197 "-",
1198 ]),
1199 &y4m.stdout,
1200 );
1201 assert!(
1202 out.status.success(),
1203 "aomenc refused the fixture: {}",
1204 String::from_utf8_lossy(&out.stderr)
1205 );
1206 let stream = out.stdout;
1207 let (before_comp, before_tmv) = (decode::comp_mode_hits(), decode::tmv_hits());
1208 let frames = match decode_stream(&stream) {
1209 Err(e) => {
1210 let msg = e.to_string();
1211 assert!(
1212 msg.contains("unsupported"),
1213 "{gate_name} failed outright (seed {seed}): {msg}"
1214 );
1215 refusals.push(format!("seed {seed}: {msg}"));
1216 continue;
1217 }
1218 Ok(frames) => frames,
1219 };
1220 let counted =
1221 decode::comp_mode_hits() != before_comp && decode::tmv_hits() != before_tmv;
1222 if !counted {
1223 never_fired += 1;
1224 }
1225 let ffmpeg_frames = if bit_depth == 10 {
1226 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1227 } else {
1228 ffmpeg_decode_sequence(&stream, width, height, frame_count)
1229 };
1230 assert_eq!(frames.len(), frame_count);
1231 // Every SHOWN/display frame `decode_stream` returned is compared --
1232 // that is decode_stream's whole output, and nothing else is.
1233 // HIDDEN frames are NOT covered here: they are never emitted as
1234 // pictures, so no ffmpeg picture corresponds to them (class
1235 // [[gate-blind-to-hidden-frames]]).
1236 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1237 assert_eq!(
1238 got.y, want.y,
1239 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
1240 );
1241 assert_eq!(
1242 got.u, want.u,
1243 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
1244 );
1245 assert_eq!(
1246 got.v, want.v,
1247 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
1248 );
1249 }
1250 if counted {
1251 eprintln!(
1252 "{gate_name} FIRING seed {seed}: comp_mode_hits +{}, tmv_hits +{}, \
1253 comp_gm_fill_hits={}, stack_full_drops={}, tile_reach_clips={}",
1254 decode::comp_mode_hits() - before_comp,
1255 decode::tmv_hits() - before_tmv,
1256 crate::mvstack::comp_gm_fill_hits(),
1257 crate::mvstack::stack_full_drops(),
1258 crate::mvstack::tile_reach_clips(),
1259 );
1260 gate_buckets(gate_name, 1, never_fired, refusals.len());
1261 return;
1262 }
1263 }
1264 gate_buckets(gate_name, 0, never_fired, refusals.len());
1265 eprintln!(
1266 "SKIP {gate_name}: {never_fired} attempts decoded but never drove a compound block \
1267 with a temporal MV candidate, and every other attempt hit a named refusal:\n{}",
1268 refusals.join("\n")
1269 );
1270 }
1271
1272 /// lane-seg: a real `aomenc` stream with SEGMENTATION genuinely active.
1273 /// `--aq-mode=1` (variance AQ) / `--aq-mode=2` (complexity AQ) are the two
1274 /// paths libaom uses to switch `segmentation_enabled` on by itself
1275 /// (`av1_vaq_frame_setup`/`av1_setup_in_frame_q_adj`, both of which only
1276 /// ever set `SEG_LVL_ALT_Q`); `--deltaq-mode=0` keeps the per-superblock
1277 /// delta-q reader out of the picture so a mismatch points at the segment
1278 /// map, not at `CurrentQIndex`. Mandelbrot's varying local contrast is
1279 /// what gives variance/complexity AQ different segments to assign --
1280 /// a flat gradient collapses every block onto one segment, which the
1281 /// `segment_ids_seen() >= 2` assert below would catch as a vacuous run.
1282 /// The rest of the recipe is the delta-q gate's own feature-disable
1283 /// envelope, so this gate isolates the segmentation reader.
1284 pub(super) fn run_segmentation_gate(
1285 name: &str,
1286 aq_mode: &str,
1287 bit_depth: usize,
1288 frame_count: usize,
1289 rate_args: &[&str],
1290 ) {
1291 let _gate_lock = lock_gate_counters();
1292 if !have_ffmpeg() {
1293 eprintln!("SKIP {name}: no ffmpeg");
1294 return;
1295 }
1296 if !have_aomenc() {
1297 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1298 return;
1299 }
1300 crate::decode::reset_segment_hits();
1301 let (width, height) = (128usize, 64usize);
1302 let mut named_refusals = 0u32;
1303 let mut matched = 0u32;
1304 let n_attempts: u32 = std::env::var("EC_SEG_GATE_ATTEMPTS")
1305 .ok()
1306 .and_then(|s| s.parse().ok())
1307 .unwrap_or(10);
1308 for attempt in 0..n_attempts {
1309 let seed = 42 + attempt;
1310 let duration = frame_count as f64 / 25.0;
1311 let source = format!(
1312 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
1313 sx = -0.6 + 0.005 * (attempt as f64),
1314 sy = -0.4 + 0.005 * (attempt as f64)
1315 );
1316 let pix_fmt = if bit_depth == 10 {
1317 "yuv420p10le"
1318 } else {
1319 "yuv420p"
1320 };
1321 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1322 .args([
1323 "-v",
1324 "error",
1325 "-f",
1326 "lavfi",
1327 "-i",
1328 &source,
1329 "-t",
1330 &duration.to_string(),
1331 "-pix_fmt",
1332 pix_fmt,
1333 "-strict",
1334 "-1",
1335 "-f",
1336 "yuv4mpegpipe",
1337 "-",
1338 ])
1339 .stdin(Stdio::null())
1340 .stdout(Stdio::piped())
1341 .stderr(Stdio::piped()), None, |c| c.output())
1342 .expect("ffmpeg failed to run");
1343 assert!(
1344 y4m.status.success(),
1345 "ffmpeg fixture: {}",
1346 String::from_utf8_lossy(&y4m.stderr)
1347 );
1348 let depth_args: Vec<String> = if bit_depth == 10 {
1349 vec![
1350 "--input-bit-depth=10".to_owned(),
1351 "--bit-depth=10".to_owned(),
1352 ]
1353 } else {
1354 Vec::new()
1355 };
1356 let aq = format!("--aq-mode={aq_mode}");
1357 let mut args: Vec<&str> = vec![
1358 "--codec=av1",
1359 "--passes=1",
1360 "--cpu-used=4",
1361 &aq,
1362 "--deltaq-mode=0",
1363 "--enable-cdef=0",
1364 "--kf-max-dist=1000",
1365 "--threads=1",
1366 "--row-mt=0",
1367 "--sb-size=64",
1368 "--auto-alt-ref=1",
1369 "--lag-in-frames=16",
1370 "--enable-fwd-kf=0",
1371 "--enable-order-hint=1",
1372 "--enable-warped-motion=1",
1373 "--enable-global-motion=0",
1374 "--enable-obmc=1",
1375 "--tune-content=default",
1376 "--enable-masked-comp=1",
1377 "--enable-dist-wtd-comp=0",
1378 "--enable-interintra-comp=1",
1379 "--enable-onesided-comp=0",
1380 "--enable-interintra-wedge=0",
1381 "--enable-smooth-interintra=1",
1382 "--enable-rect-partitions=0",
1383 "--enable-ab-partitions=0",
1384 "--enable-1to4-partitions=0",
1385 "--enable-filter-intra=0",
1386 "--enable-smooth-intra=0",
1387 "--enable-paeth-intra=0",
1388 "--enable-directional-intra=0",
1389 "--enable-angle-delta=0",
1390 "--enable-tx-size-search=0",
1391 "--enable-cdef=1",
1392 "--enable-restoration=0",
1393 "--max-partition-size=32",
1394 "--min-partition-size=32",
1395 "--enable-palette=0",
1396 "--enable-intrabc=0",
1397 "--enable-cfl-intra=0",
1398 "--enable-ref-frame-mvs=0",
1399 ];
1400 args.extend(rate_args.iter().copied());
1401 args.extend(depth_args.iter().map(String::as_str));
1402 args.extend(["--obu", "-o", "-", "-"]);
1403 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1404 assert!(
1405 out.status.success(),
1406 "aomenc refused the fixture: {}",
1407 String::from_utf8_lossy(&out.stderr)
1408 );
1409 let stream = out.stdout;
1410 // The stream must really carry `segmentation_enabled`, or the
1411 // gate proves nothing about the reader.
1412 let mut seg_frames = 0u32;
1413 {
1414 let mut probe = Av1Parser::new();
1415 let mut pos = 0usize;
1416 while pos < stream.len() {
1417 let obu = probe
1418 .parse_obu(&stream[pos..])
1419 .expect("parsing the gate stream");
1420 pos += obu.total_size;
1421 match &obu.kind {
1422 ObuKind::Frame(h, _) => {
1423 if h.segmentation.enabled {
1424 seg_frames += 1;
1425 }
1426 }
1427 ObuKind::FrameHeader(h)
1428 if h.segmentation.enabled => {
1429 seg_frames += 1;
1430 }
1431 _ => {}
1432 }
1433 }
1434 }
1435 if seg_frames == 0 {
1436 eprintln!(
1437 "seed {seed}: aomenc wrote no segmentation-enabled frame, skipping attempt"
1438 );
1439 continue;
1440 }
1441 let frames = match decode_stream(&stream) {
1442 Err(e) => {
1443 let msg = e.to_string();
1444 assert!(
1445 msg.contains("unsupported"),
1446 "{name} failed outright, not a named refusal (seed {seed}): {msg}"
1447 );
1448 assert!(
1449 !msg.contains("segment_id symbol"),
1450 "{name} refused on the segmentation reader itself (seed {seed}): {msg}"
1451 );
1452 named_refusals += 1;
1453 eprintln!("seed {seed} refusal: {msg}");
1454 continue;
1455 }
1456 Ok(frames) => frames,
1457 };
1458 let ffmpeg_frames = if bit_depth == 10 {
1459 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
1460 } else {
1461 ffmpeg_decode_sequence(&stream, width, height, frame_count)
1462 };
1463 assert_eq!(frames.len(), frame_count);
1464 let mismatched = frames
1465 .iter()
1466 .zip(&ffmpeg_frames)
1467 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1468 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
1469 std::fs::write(&path, &stream).expect("writing pinned stream");
1470 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
1471 }
1472 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1473 assert_eq!(
1474 got.y, want.y,
1475 "{name} frame {i} luma vs ffmpeg (seed {seed})"
1476 );
1477 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (seed {seed})");
1478 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (seed {seed})");
1479 }
1480 matched += 1;
1481 }
1482 assert!(
1483 matched > 0,
1484 "{name}: every attempt refused on other capabilities ({named_refusals} refusals); \
1485 the gate never exercised segmentation"
1486 );
1487 assert!(
1488 crate::decode::segment_id_hits() > 0,
1489 "{name}: {matched} pixel-exact matches but zero segment_id symbols fired -- \
1490 the reader is unexercised"
1491 );
1492 assert!(
1493 crate::decode::segment_ids_seen() >= 2,
1494 "{name}: {matched} pixel-exact matches but only {} distinct segment id(s) -- \
1495 every block landed in one segment, so nothing was actually segmented",
1496 crate::decode::segment_ids_seen()
1497 );
1498 // An inter-frame run must also have exercised the TEMPORAL path
1499 // (`seg_id_predicted` against the primary reference's saved map);
1500 // the key-frame-only run has no previous map by construction.
1501 if frame_count > 1 {
1502 assert!(
1503 crate::decode::segment_pred_hits() > 0,
1504 "{name}: {matched} pixel-exact matches over {frame_count} frames but zero \
1505 seg_id_predicted symbols -- the temporal_update path is unexercised"
1506 );
1507 }
1508 eprintln!(
1509 "{name}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
1510 out of {n_attempts}, segment_id_hits={}, distinct segment ids={}, \
1511 seg_id_predicted symbols={}",
1512 crate::decode::segment_id_hits(),
1513 crate::decode::segment_ids_seen(),
1514 crate::decode::segment_pred_hits()
1515 );
1516 }
1517
1518 pub(super) fn edge32_gate(name: &str, flat_band: bool) {
1519 let _gate_lock = lock_gate_counters();
1520 if !have_ffmpeg() {
1521 eprintln!("SKIP {name}: no ffmpeg");
1522 return;
1523 }
1524 if !have_aomenc() {
1525 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1526 return;
1527 }
1528 // (width, height, frames, ten_bit, tile_columns_log2)
1529 let mut arms: Vec<(usize, usize, usize, bool, u32)> = Vec::new();
1530 for &(w, h) in &[(192usize, 80usize), (80usize, 192usize)] {
1531 arms.push((w, h, 1, false, 0));
1532 arms.push((w, h, 1, true, 0));
1533 }
1534 // The inter arm: >= 4 frames so the 32-level edge path in the INTER
1535 // tile walk is exercised too.
1536 arms.push((192, 80, 5, false, 0));
1537 // lane-golomb r9: the straddling-band arms, only under the ignored
1538 // `a_frame_edge_straddling_band_decodes_pixel_exact` name (they are
1539 // RED -- see that test's own comment for the stage bisection). Naming
1540 // them here rather than in a second copy of this gate keeps the
1541 // recipe, the counters and the refusal handling identical.
1542 if name == "a_frame_edge_straddling_band_decodes_pixel_exact" {
1543 arms.clear();
1544 for &tile_cols in &[0u32, 1] {
1545 arms.push((192, 68, 5, false, tile_cols));
1546 arms.push((192, 68, 5, true, tile_cols));
1547 arms.push((68, 192, 5, false, tile_cols));
1548 arms.push((68, 192, 5, true, tile_cols));
1549 }
1550 }
1551 // lane-golomb r8 MEASURED, arm STILL NOT added (every cq level is
1552 // vacuous, panicking or red -- each measured this round with
1553 // `arms.push((192, 68, 5, false))`, log
1554 // `$HOME/.cache/golomb-gate-r8{b,e,f,g}.log`):
1555 // * the r7 blocker IS fixed -- no attempt refuses "a reference
1556 // picture whose height does not match this frame's own true
1557 // size" any more (`decode.rs`'s comparison now uses the header's
1558 // frame height, per libaom's crop-dimension reference test).
1559 // * cq35 now refuses LATER, by another lane's name: "an inter
1560 // SB-level AB partition (HORZ_A/HORZ_B/VERT_A/VERT_B)" -- so the
1561 // arm compares nothing (class `counter-from-refused-stream`).
1562 // * cq40 PANICS in `decode_inter_block8`
1563 // (`from_switchable_symbol` handed a 4th symbol, `mc.rs:203`) =
1564 // lane-sub8's own open below-8x8 desync; a panic cannot be
1565 // tolerated as a named refusal.
1566 // * cq59 8-bit is RED: `frame 1 plane Y: 217 pixels differ, first
1567 // at row 60 col 170 (ours 172 vs ffmpeg 173)`, and the cq35
1568 // 10-bit twin is RED at `row 56 col 48 (ours 530 vs ffmpeg
1569 // 531)`. Both are +-1 bands in rows 56..63, i.e. the deblock/CDEF
1570 // bleed ABOVE the 4-px straddling row band (64..67) -- the same
1571 // shape as the `(68, 192, 5, false)` column defect below, so the
1572 // two are very likely ONE straddling-band reconstruction defect.
1573 // lane-golomb r7 MEASURED, arm NOT added (it would be vacuous or red):
1574 // a 68-px axis leaves the last superblock straddling by 4 px, the
1575 // shape `read_var_tx_size`'s `blk_row >= max_h_mi || blk_col >=
1576 // max_w_mi` early return exists for. With
1577 // `arms.push((192, 68, 5, false))` all EIGHT cq attempts refuse by
1578 // name -- "a reference picture whose height does not match this
1579 // frame's own true size" -- so the arm compares nothing (class
1580 // `counter-from-refused-stream`). With
1581 // `arms.push((68, 192, 5, false))` the gate goes RED on a real,
1582 // separate defect: `68x192 cq35 frames=5 10bit=false frame 1 plane Y:
1583 // 141 pixels differ, first at row 0 col 64 (ours 167 vs ffmpeg 166)
1584 // [edge32=[0,34,0,0,1,17,0,1]]` -- LUMA, inside the 4-px straddling
1585 // COLUMN. Both are unrelated to this round's chroma tx_type fix.
1586 let cqs: [u32; 8] = [35, 40, 45, 50, 55, 57, 59, 61];
1587 let mut totals = [0usize; 8];
1588 let mut compared = 0usize;
1589 // lane-t900 r15 (class `counter-from-refused-stream`): the aggregate
1590 // `compared` counter is carried by the single-tile arms alone, so the
1591 // `--tile-columns=1` twins were free to refuse every attempt and keep
1592 // the gate green. Counted separately and asserted below.
1593 let mut compared_multi_tile = 0usize;
1594 let mut refusals: Vec<String> = Vec::new();
1595 let straddle = name == "a_frame_edge_straddling_band_decodes_pixel_exact";
1596 let mut straddle_units = 0usize;
1597 for &(width, height, frame_count, ten_bit, tile_cols) in &arms {
1598 for &cq in &cqs {
1599 let duration = frame_count as f64 / 25.0;
1600 // `noise` (explicit seed) both defeats aomenc's
1601 // screen-content detection -- which otherwise refuses every
1602 // attempt at "a HORZ/VERT intra strip in a screen-content
1603 // frame" -- and keeps the RD search off flat NONE blocks.
1604 // Natural content over the whole superblock-aligned area,
1605 // with the 16-px straddling band left FLAT (`pad`): with
1606 // detail in that band aomenc always answers the edge bit with
1607 // SPLIT (measured: 178 edge bits, 178 of them SPLIT, over a
1608 // cq 35..61 sweep), so the HORZ/VERT arm this round guards
1609 // never fired. `noise` on top keeps screen-content detection
1610 // (and its palette-strip refusal) off.
1611 let (cw, ch) = (
1612 if flat_band && width % 64 != 0 {
1613 width - 16
1614 } else {
1615 width
1616 },
1617 if flat_band && height % 64 != 0 {
1618 height - 16
1619 } else {
1620 height
1621 },
1622 );
1623 let pad = if flat_band {
1624 format!("pad={width}:{height}:0:0:gray,")
1625 } else {
1626 String::new()
1627 };
1628 let source = format!(
1629 "testsrc2=size={cw}x{ch}:duration={duration}:rate=25,\
1630 {pad}noise=alls=6:allf=t+u:all_seed={cq}"
1631 );
1632 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
1633 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1634 .args([
1635 "-v",
1636 "error",
1637 "-f",
1638 "lavfi",
1639 "-i",
1640 &source,
1641 "-pix_fmt",
1642 pix,
1643 "-strict",
1644 "-1",
1645 "-t",
1646 &format!("{duration}"),
1647 "-f",
1648 "yuv4mpegpipe",
1649 "-",
1650 ])
1651 .stdin(Stdio::null())
1652 .stdout(Stdio::piped())
1653 .stderr(Stdio::piped()), None, |c| c.output())
1654 .expect("ffmpeg failed to run");
1655 assert!(
1656 y4m.status.success(),
1657 "{name}: ffmpeg fixture: {}",
1658 String::from_utf8_lossy(&y4m.stderr)
1659 );
1660 let cq_arg = format!("--cq-level={cq}");
1661 let mut args: Vec<&str> = vec![
1662 "--codec=av1",
1663 "--passes=1",
1664 "--end-usage=q",
1665 &cq_arg,
1666 "--cpu-used=0",
1667 "--threads=1",
1668 "--row-mt=0",
1669 "--sb-size=64",
1670 "--enable-restoration=0",
1671 "--enable-palette=0",
1672 "--deltaq-mode=0",
1673 "--enable-intrabc=0",
1674 // Per-arm overrides go LAST (aomenc keeps the last
1675 // occurrence of a repeated --enable-* flag).
1676 "--enable-rect-partitions=1",
1677 "--enable-ab-partitions=0",
1678 "--enable-1to4-partitions=0",
1679 // 32, not the charter's 8: at 8 the sub-16 AB and
1680 // split-transform strip arms (still refused by name here)
1681 // fire before the 32-level edge is reached and EVERY
1682 // attempt refuses (measured). At 32 the edge block cannot
1683 // split, so aomenc is forced onto the gathered edge bit's
1684 // HORZ/VERT -- exactly the arm this round guards.
1685 "--min-partition-size=32",
1686 "--tune-content=film",
1687 "--max-partition-size=64",
1688 ];
1689 if ten_bit {
1690 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
1691 }
1692 let tile_arg = format!("--tile-columns={tile_cols}");
1693 if tile_cols > 0 {
1694 args.push(&tile_arg);
1695 }
1696 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
1697 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
1698 assert!(
1699 out.status.success(),
1700 "{name}: aomenc refused the fixture: {}",
1701 String::from_utf8_lossy(&out.stderr)
1702 );
1703 let stream = out.stdout;
1704 if ten_bit {
1705 assert_eq!(
1706 parsed_bit_depth(&stream),
1707 10,
1708 "{name}: aomenc did not write a 10-bit sequence header"
1709 );
1710 }
1711 let tag = format!(
1712 "{width}x{height} cq{cq} frames={frame_count} 10bit={ten_bit} \
1713 tile_cols={tile_cols}"
1714 );
1715 let before = crate::decode::edge32_hits();
1716 let straddle_before = crate::decode::cdef_straddle_units();
1717 // lane-golomb r8: name the attempt BEFORE decoding it -- a
1718 // desync surfaces as a panic deep in mc.rs with no arm in the
1719 // message, and r8 spent a run bisecting arms by hand.
1720 if std::env::var_os("EC_GATE_VERBOSE").is_some() {
1721 eprintln!("{name}: attempting {tag}");
1722 }
1723 let decoded = match decode_stream(&stream) {
1724 Ok(frames) => frames,
1725 Err(e) => {
1726 let msg = e.to_string();
1727 assert!(
1728 msg.contains("unsupported"),
1729 "{name} failed outright, not a named refusal ({tag}): {msg}"
1730 );
1731 refusals.push(format!("{tag}: {msg}"));
1732 continue;
1733 }
1734 };
1735 let after = crate::decode::edge32_hits();
1736 let delta: Vec<usize> = (0..8).map(|i| after[i] - before[i]).collect();
1737 // The ENCODE's frame count, and it is PER ARM: the arm tuple's
1738 // `frame_count` field is what the y4m is built from
1739 // (`duration = frame_count / 25.0`, 38085, rendered with
1740 // `-t {duration}` at 38131) and this gate's aomenc carries no
1741 // `--limit` and no `--lag-in-frames`, so the stream codes exactly
1742 // `frame_count` frames (1 for the intra arms, 5 for the
1743 // inter/straddling ones). Asserted ABOVE the oracle call, so a
1744 // decode that dropped one reds naming the encode.
1745 assert_eq!(
1746 decoded.len(),
1747 frame_count,
1748 "{name}: {tag}: the encode codes {frame_count} frame(s), the decode showed {}",
1749 decoded.len()
1750 );
1751 let reference = if ten_bit {
1752 ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len())
1753 } else {
1754 ffmpeg_decode_sequence(&stream, width, height, decoded.len())
1755 };
1756 assert_eq!(
1757 decoded.len(),
1758 reference.len(),
1759 "{name}: {tag}: shown-frame count vs ffmpeg"
1760 );
1761 for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() {
1762 for (plane, a, b, w) in [
1763 ("Y", &ours.y, &theirs.y, width),
1764 ("U", &ours.u, &theirs.u, width / 2),
1765 ("V", &ours.v, &theirs.v, width / 2),
1766 ] {
1767 if let Some(d) = a.iter().zip(b.iter()).position(|(x, y)| x != y) {
1768 let n = a.iter().zip(b.iter()).filter(|(x, y)| x != y).count();
1769 if std::env::var_os("EC_EDGE32_ROWS").is_some() {
1770 let mut per_row: std::collections::BTreeMap<usize, usize> =
1771 Default::default();
1772 for (k, (x, y)) in a.iter().zip(b.iter()).enumerate() {
1773 if x != y {
1774 *per_row.entry(k / w).or_default() += 1;
1775 }
1776 }
1777 eprintln!("{name}: {tag} plane {plane} diffs per row: {per_row:?}");
1778 }
1779 panic!(
1780 "{name}: {tag} frame {i} plane {plane}: {n} pixels differ, first \
1781 at row {} col {} (ours {} vs ffmpeg {}) [edge32={delta:?}]",
1782 d / w,
1783 d % w,
1784 a[d],
1785 b[d]
1786 );
1787 }
1788 assert_eq!(
1789 a.len(),
1790 b.len(),
1791 "{name}: {tag} frame {i} plane {plane}: ours has {} samples, \
1792 ffmpeg's has {} -- a short plane would zip-truncate the walk above \
1793 and hide a chroma-span defect",
1794 a.len(),
1795 b.len()
1796 );
1797 }
1798 }
1799 compared += 1;
1800 if tile_cols > 0 {
1801 compared_multi_tile += 1;
1802 }
1803 straddle_units += crate::decode::cdef_straddle_units() - straddle_before;
1804 for i in 0..8 {
1805 totals[i] += delta[i];
1806 }
1807 }
1808 }
1809 assert!(
1810 compared > 0,
1811 "{name}: every attempt hit a named refusal:\n{}",
1812 refusals.join("\n")
1813 );
1814 assert!(
1815 !straddle || compared_multi_tile > 0,
1816 "{name}: every `--tile-columns=1` attempt hit a named refusal -- the \
1817 multi-tile twins compared nothing:\n{}",
1818 refusals.join("\n")
1819 );
1820 assert!(
1821 !straddle || straddle_units > 0,
1822 "{name}: no FILTERED 8x8 CDEF unit crossed the cropped frame edge over \
1823 {compared} compared attempts -- the straddling arms proved nothing"
1824 );
1825 assert!(
1826 totals[0] + totals[1] + totals[4] + totals[5] > 0,
1827 "{name}: no frame-edge partition bit was read at all over \
1828 {compared} compared attempts -- the gate proved nothing"
1829 );
1830 // lane-golomb r3: the flat-band arm's ASSERT moved one level up. Until
1831 // r3 the last superblock row was reached through a 32-level edge bit
1832 // only because our own out-of-frame transform units had desynced the
1833 // stream; with that fixed, real aomenc answers a bottom-edge
1834 // superblock with the 64-level `PARTITION_HORZ` (and a right-edge one
1835 // with `PARTITION_VERT`) and the 32-level slots stay 0 on this
1836 // content. Slots 6/7 are the strips actually decoded at the edge.
1837 assert!(
1838 !flat_band || totals[6] > 0,
1839 "{name}: no 64x32 bottom-edge HORZ strip was decoded \
1840 (edge32={totals:?}, {compared} compared attempts)"
1841 );
1842 assert!(
1843 !flat_band || totals[7] > 0,
1844 "{name}: no 32x64 right-edge VERT strip was decoded \
1845 (edge32={totals:?}, {compared} compared attempts)"
1846 );
1847 eprintln!(
1848 "{name}: {compared} pixel-exact attempts, 32-level edge bits \
1849 [horz_or_vert={} split={}] bottom-HORZ={} right-VERT={}, 64-level edge bits \
1850 [horz_or_vert={} split={}] bottom-HORZ={} right-VERT={}, \
1851 {straddle_units} straddling CDEF units, {} named refusals",
1852 totals[0],
1853 totals[1],
1854 totals[2],
1855 totals[3],
1856 totals[4],
1857 totals[5],
1858 totals[6],
1859 totals[7],
1860 refusals.len()
1861 );
1862 for r in &refusals {
1863 eprintln!("{name} refusal: {r}");
1864 }
1865 }
1866
1867 /// lane-tiles r11: every tile gate before this one turns the coding tools
1868 /// OFF (rect/ab partitions, tx-size search, cdef, restoration all `=0`)
1869 /// to isolate the per-tile loop, which is exactly the
1870 /// [[tool-disabled-in-every-gate]] shape -- a tile-edge defect in any of
1871 /// those tools is invisible to all of them. This one runs the BROAD tool
1872 /// set (rect + ab partitions, default tx search, cdef and loop
1873 /// restoration both on, deblocking left at its default so it filters
1874 /// across tile boundaries as the spec requires) over a real 2D tile grid,
1875 /// through `decode_stream` rather than the tile entry point, so it is the
1876 /// same path a caller decoding a file takes.
1877 ///
1878 /// 256x128 is four 64x64 superblocks wide and two tall, so
1879 /// `--tile-columns=1 --tile-rows=1` really yields a 2x2 grid and
1880 /// `--tile-columns=2` really yields 4 columns; both are asserted from the
1881 /// parsed `tile_info` rather than assumed, and the decoded-tile counter
1882 /// (`tile_hits`) is asserted at >= 4 per decoded frame so a stream whose
1883 /// header claims 4 tiles but whose decode only walked one cannot pass.
1884 // `#[track_caller]` so a failing assert names the calling arm's line, and
1885 // so `gate_coverage`'s body split (on `\n #[`) treats this helper's
1886 // recipe as its own gate rather than gluing it onto the preceding one.
1887 #[track_caller]
1888 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1889 #[allow(clippy::too_many_arguments)]
1890 pub(super) fn run_multi_tile_gate(
1891 name: &str,
1892 tile_cols_log2: u32,
1893 tile_rows_log2: u32,
1894 bit_depth: usize,
1895 frame_count: usize,
1896 extra: &[&str],
1897 // lane-tiles r12: the palette arm's own override proof. `true` asserts,
1898 // per attempt, that the arm's `--tune-content=screen --enable-palette=1`
1899 // really reached the encoder (frame header `allow_screen_content_tools`)
1900 // AND that a palette block fired at a TILE's left column -- the exact
1901 // block whose colour cache must not see the previous tile's colours.
1902 require_tile_left_palette: bool,
1903 // `None` = the shared `gradients_source`. The palette arm overrides it
1904 // with `smptebars`, the flat few-colour source the existing palette
1905 // gates use -- gradients never make aomenc pick a palette block.
1906 source_override: Option<&str>,
1907 ) {
1908 let _gate_lock = lock_gate_counters();
1909 if !have_ffmpeg() {
1910 eprintln!("SKIP {name}: no ffmpeg");
1911 return;
1912 }
1913 if !have_aomenc() {
1914 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
1915 return;
1916 }
1917 let (width, height) = (256usize, 128usize);
1918 let expected_tiles = (1usize << tile_cols_log2) * (1usize << tile_rows_log2);
1919 let mut matched = 0u32;
1920 let mut named_refusals = 0u32;
1921 let mut uv_edge_suppressed = 0usize;
1922 let n_attempts: u32 = std::env::var("EC_TILES_GATE_ATTEMPTS")
1923 .ok()
1924 .and_then(|s| s.parse().ok())
1925 .unwrap_or(6);
1926 for attempt in 0..n_attempts {
1927 let seed = 42 + attempt;
1928 let duration = frame_count as f64 / 25.0;
1929 let source = match source_override {
1930 Some(src) => format!("{src}=size={width}x{height}:duration={duration}:rate=25"),
1931 None => {
1932 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
1933 }
1934 };
1935 let pix_fmt = if bit_depth == 10 {
1936 "yuv420p10le"
1937 } else {
1938 "yuv420p"
1939 };
1940 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1941 .args([
1942 "-v",
1943 "error",
1944 "-f",
1945 "lavfi",
1946 "-i",
1947 &source,
1948 "-pix_fmt",
1949 pix_fmt,
1950 "-strict",
1951 "-1",
1952 "-f",
1953 "yuv4mpegpipe",
1954 "-",
1955 ])
1956 .stdin(Stdio::null())
1957 .stdout(Stdio::piped())
1958 .stderr(Stdio::piped()), None, |c| c.output())
1959 .expect("ffmpeg failed to run");
1960 assert!(
1961 y4m.status.success(),
1962 "ffmpeg fixture: {}",
1963 String::from_utf8_lossy(&y4m.stderr)
1964 );
1965 let cols = format!("--tile-columns={tile_cols_log2}");
1966 let rows = format!("--tile-rows={tile_rows_log2}");
1967 let limit = format!("--limit={frame_count}");
1968 let depth_args: Vec<String> = if bit_depth == 10 {
1969 vec![
1970 "--input-bit-depth=10".to_owned(),
1971 "--bit-depth=10".to_owned(),
1972 ]
1973 } else {
1974 Vec::new()
1975 };
1976 let mut args: Vec<&str> = vec![
1977 "--codec=av1",
1978 "--passes=1",
1979 "--end-usage=q",
1980 "--cq-level=40",
1981 "--cpu-used=4",
1982 &limit,
1983 "--kf-max-dist=1000",
1984 "--threads=1",
1985 "--row-mt=0",
1986 // This decoder is 64x64-superblock only, and `--tile-columns`
1987 // splits on superblock boundaries, so 128x128 superblocks
1988 // would leave 256px only two tiles' worth of columns.
1989 "--sb-size=64",
1990 &cols,
1991 &rows,
1992 // The point of this gate: tools ON across tile edges.
1993 "--enable-rect-partitions=1",
1994 "--enable-ab-partitions=1",
1995 "--enable-cdef=1",
1996 "--enable-restoration=1",
1997 // Still off: capabilities this decoder refuses outright, which
1998 // would turn every attempt into a refusal and make the gate
1999 // vacuous rather than proving anything about tiles.
2000 "--enable-1to4-partitions=0",
2001 "--min-partition-size=16",
2002 // Overridable by `extra` (aomenc takes the last occurrence of
2003 // a repeated flag), which the palette arm below relies on.
2004 "--enable-palette=0",
2005 "--enable-intrabc=0",
2006 "--enable-ref-frame-mvs=0",
2007 "--enable-global-motion=0",
2008 ];
2009 args.extend(extra.iter().copied());
2010 args.extend(depth_args.iter().map(String::as_str));
2011 args.extend(["--obu", "-o", "-", "-"]);
2012 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2013 assert!(
2014 out.status.success(),
2015 "aomenc refused the fixture: {}",
2016 String::from_utf8_lossy(&out.stderr)
2017 );
2018 let stream = out.stdout;
2019
2020 // The stream must really carry the tile grid asked for, or the
2021 // gate proves nothing (aomenc silently clamps tile counts that do
2022 // not fit the frame's superblock grid).
2023 {
2024 let mut probe = Av1Parser::new();
2025 let mut pos = 0usize;
2026 let mut checked = false;
2027 while pos < stream.len() {
2028 let obu = probe
2029 .parse_obu(&stream[pos..])
2030 .expect("parsing the gate stream");
2031 pos += obu.total_size;
2032 let header = match &obu.kind {
2033 ObuKind::Frame(h, _) => h,
2034 ObuKind::FrameHeader(h) => h,
2035 // lane-tiles r12: prove the base recipe's tools-on
2036 // flags arrived (a repeated aomenc `--enable-*` keeps
2037 // the LAST occurrence -- measured, see the report --
2038 // so a per-arm override must not silently vanish).
2039 ObuKind::SequenceHeader(seq) => {
2040 assert!(
2041 seq.enable_cdef && seq.enable_restoration,
2042 "{name}: --enable-cdef=1 --enable-restoration=1 did not reach \
2043 aomenc (seq enable_cdef={} enable_restoration={}, seed {seed})",
2044 seq.enable_cdef,
2045 seq.enable_restoration
2046 );
2047 continue;
2048 }
2049 _ => continue,
2050 };
2051 // A `show_existing_frame` header codes no tile info at all
2052 // (spec 5.9.2 returns before `tile_info()`), so its
2053 // `TileInfo` is the parser's 1x1 default -- checking it
2054 // here would fail every inter stream for a header that
2055 // carries no tiling.
2056 if header.show_existing_frame {
2057 continue;
2058 }
2059 if require_tile_left_palette {
2060 assert!(
2061 header.allow_screen_content_tools,
2062 "{name}: --tune-content=screen/--enable-palette=1 did not reach \
2063 aomenc -- allow_screen_content_tools is 0 (seed {seed})"
2064 );
2065 }
2066 assert_eq!(
2067 (header.tile_info.cols * header.tile_info.rows) as usize,
2068 expected_tiles,
2069 "{name}: aomenc wrote {}x{} tiles, not the {expected_tiles} asked for \
2070 (seed {seed})",
2071 header.tile_info.cols,
2072 header.tile_info.rows
2073 );
2074 checked = true;
2075 }
2076 assert!(
2077 checked,
2078 "{name}: no frame header in the stream (seed {seed})"
2079 );
2080 }
2081
2082 let before = crate::decode::tile_hits();
2083 let pal_before = crate::decode::palette_tile_left_hits();
2084 let uv_edge_before = crate::decode::uv_tile_edge_suppressed_hits();
2085 let frames = match decode_stream(&stream) {
2086 Err(e) => {
2087 let msg = e.to_string();
2088 assert!(
2089 msg.contains("unsupported"),
2090 "{name} failed outright, not a named refusal (seed {seed}): {msg}"
2091 );
2092 named_refusals += 1;
2093 eprintln!("seed {seed} refusal: {msg}");
2094 continue;
2095 }
2096 Ok(frames) => frames,
2097 };
2098 let hits = crate::decode::tile_hits() - before;
2099 assert!(
2100 hits >= expected_tiles * frames.len(),
2101 "{name}: tile_hits delta was {hits}, expected >= {} -- every tile of every \
2102 frame must actually decode (seed {seed})",
2103 expected_tiles * frames.len()
2104 );
2105 let ffmpeg_frames = if bit_depth == 10 {
2106 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
2107 } else {
2108 ffmpeg_decode_sequence(&stream, width, height, frames.len())
2109 };
2110 let mismatched = frames
2111 .iter()
2112 .zip(&ffmpeg_frames)
2113 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2114 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
2115 std::fs::write(&path, &stream).expect("writing pinned stream");
2116 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
2117 }
2118 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2119 assert_eq!(
2120 got.y, want.y,
2121 "{name} frame {i} luma vs ffmpeg (seed {seed})"
2122 );
2123 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (seed {seed})");
2124 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (seed {seed})");
2125 }
2126 if require_tile_left_palette {
2127 let pal = crate::decode::palette_tile_left_hits() - pal_before;
2128 assert!(
2129 pal >= 1,
2130 "{name}: this attempt decoded and matched but fired {pal} palette blocks at \
2131 a tile's left column -- the tile-relative palette cache guard is untested \
2132 (seed {seed})"
2133 );
2134 }
2135 // lane-mtfix r1: the chroma edge-filter neighbour of a block on a
2136 // tile's first mi row/column lives in the tile above/left, where
2137 // libaom has no neighbour at all. This counts the reads suppressed
2138 // there whose frame-wide coarse slot held a non-DC mode -- the
2139 // reads that would otherwise pick the wrong chroma edge filter
2140 // strength (they did, before this fix: seed 46 of this gate).
2141 uv_edge_suppressed += crate::decode::uv_tile_edge_suppressed_hits() - uv_edge_before;
2142 matched += 1;
2143 }
2144 assert!(
2145 matched > 0,
2146 "{name}: every attempt refused ({named_refusals}); the gate never decoded a \
2147 multi-tile stream with the coding tools on"
2148 );
2149 eprintln!(
2150 "{name}: {matched} pixel-exact matches, {named_refusals} named refusals, \
2151 {uv_edge_suppressed} chroma edge reads suppressed at a tile edge"
2152 );
2153 }
2154
2155 /// The one recipe both 1:4-in-inter arms run, rewritten by
2156 /// lane-av1recipehunt. What changed, and why the old sweep could not fire:
2157 ///
2158 /// * `--min-partition-size=32` -> **`8`**. This is the flag that was
2159 /// holding the shape off the menu entirely. MEASURED over 96 encodes
2160 /// (10-bit, 192x128 and 256x192, `--cpu-used` 0..5, cq 63/55, this
2161 /// crate's full intra mode set): at `mps=16` the 32-level 1:4 counter is
2162 /// **0 in all 48 attempts**, at `mps=8` it fires in 40 of 48. The old
2163 /// comment's "min size 16 so the 16x16-level 1:4 is out of reach" was
2164 /// protecting against a refusal that no longer fires -- `mps=8` reaches
2165 /// the 8- and 16-level strips too, and on this content the RD takes
2166 /// neither (the `inter16_1to4` and `rect4_32` inter counters confirm the
2167 /// only 1:4 partitions in the stream are the 32-level ones this gate
2168 /// asserts).
2169 /// * the intra mode set: `--enable-smooth-intra/paeth-intra/
2170 /// directional-intra/angle-delta` `0` -> **`1`**. A 8x32 or 32x8 strip
2171 /// has four usable intra modes with these on; with them off the only
2172 /// candidate is DC, and DC never wins a 1:4 strip against inter.
2173 /// * the 40-attempt content/preset/cq seed sweep -> one pinned cell at
2174 /// 256x192, 6 frames, `--cpu-used=2 --cq-level=63`. A sweep hides a
2175 /// recipe that works; a pin makes it a precondition.
2176 ///
2177 /// The 8-bit arm's `hue=s=0` and `-t 0.32` are dropped: they only fixed
2178 /// ffmpeg's own frame count across the sweep, and the frame count is now
2179 /// pinned by `-frames:v 6` (6 decode-order frames, `kf-min-dist=1000`, so
2180 /// frame 0 is the only key frame and every counted strip is in an INTER
2181 /// frame).
2182 ///
2183 /// **The recipe**, exactly (the recorded command lines):
2184 /// ```text
2185 /// ffmpeg -v error -y -f lavfi \
2186 /// -i mandelbrot=size=256x192:start_scale=5.0:end_scale=0.004:end_pts=8:rate=25 \
2187 /// -pix_fmt yuv420p -frames:v 6 -f yuv4mpegpipe - # 10-bit: yuv420p10le + -strict -1
2188 /// aomenc [--cpu-used=2 --input-bit-depth=10 -b 10] --codec=av1 --passes=1 --end-usage=q \
2189 /// --cpu-used=2 --cq-level=63 --threads=1 --row-mt=0 \
2190 /// --enable-rect-partitions=1 --enable-1to4-partitions=1 \
2191 /// --min-partition-size=8 --max-partition-size=64 --enable-tx-size-search=0 \
2192 /// --enable-filter-intra=1 --enable-intra-edge-filter=1 --enable-smooth-intra=1 \
2193 /// --enable-paeth-intra=1 --enable-directional-intra=1 --enable-angle-delta=1 \
2194 /// --lag-in-frames=0 --auto-alt-ref=0 --kf-min-dist=1000 --kf-max-dist=1000 \
2195 /// --enable-order-hint=0 --enable-warped-motion=0 --enable-obmc=0 \
2196 /// --enable-masked-comp=0 --enable-interintra-comp=0 --enable-dist-wtd-comp=0 \
2197 /// --enable-diff-wtd-comp=0 --enable-onesided-comp=0 --enable-interintra-wedge=0 \
2198 /// --enable-smooth-interintra=0 --enable-ab-partitions=0 --enable-cdef=0 \
2199 /// --enable-restoration=0 --enable-palette=0 --enable-intrabc=0 \
2200 /// --enable-cfl-intra=0 --enable-ref-frame-mvs=0 --obu -o - -
2201 /// ```
2202 /// Sources: 8-bit 442462 bytes, sha256
2203 /// `e4b46799b180a0d3e138caa18b2738c035e349219490313db664814a3eae9ec2`;
2204 /// 10-bit 884828 bytes, sha256
2205 /// `b7e0602e0bfc7a7f6813f40bb3989ec7574e5fbbfbf190298b9ab5b625156030`.
2206 /// Outputs, committed with `git add -f` past the `fixtures` gitignore:
2207 /// * `fixtures/intra14_256x192_8bit.obu`, 35179 bytes, sha256
2208 /// `5e50eb6d4492e806a2803988d92bd47f069ca54e02c06344d5500c6b72deb861`
2209 /// (fnv1a64 `0x86f8d1e5a221162a`) -- MEASURED `32x8=8 8x32=11`,
2210 /// `64x16=0 16x64=0`, all 6 frames pixel-exact vs ffmpeg.
2211 /// * `fixtures/intra14_256x192_10bit.obu`, 34727 bytes, sha256
2212 /// `ab6fae0a256af6410e8200f10827a3e965dee7b2d7ab63710e94968bddab23a2`
2213 /// (fnv1a64 `0xecf9455bc20d60f0`) -- MEASURED `32x8=12 8x32=7`,
2214 /// all 6 frames pixel-exact vs ffmpeg.
2215 ///
2216 /// The gate re-encodes live and byte-compares against the pin, so the pin
2217 /// is the expected output and not a second decode path. The control arm
2218 /// re-runs the SAME command line with `--enable-1to4-partitions=0` and
2219 /// requires the counter to stay at 0 -- that single flag is what carries
2220 /// the coverage, and asserting it is also this gate's own red-proof.
2221 pub(super) fn intra_rect4_in_inter_gate(bit_depth: u32) {
2222 const NAME: &str =
2223 "a_real_aomenc_inter_sequence_with_an_intra_1to4_strip_decodes_pixel_exact";
2224 let _gate_lock = lock_gate_counters();
2225 if !have_ffmpeg() {
2226 eprintln!("SKIP {NAME}: no ffmpeg");
2227 return;
2228 }
2229 if !have_aomenc() {
2230 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2231 return;
2232 }
2233 let (width, height, frame_count) = (256usize, 192usize, 6usize);
2234 let (src_len, src_sha, pin_name, pin_len, pin_fnv) = if bit_depth == 10 {
2235 (
2236 884_828usize,
2237 "b7e0602e0bfc7a7f6813f40bb3989ec7574e5fbbfbf190298b9ab5b625156030",
2238 "fixtures/intra14_256x192_10bit.obu",
2239 34_727usize,
2240 0xecf9_455b_c20d_60f0u64,
2241 )
2242 } else {
2243 (
2244 442_462usize,
2245 "e4b46799b180a0d3e138caa18b2738c035e349219490313db664814a3eae9ec2",
2246 "fixtures/intra14_256x192_8bit.obu",
2247 35_179usize,
2248 0x86f8_d1e5_a221_162au64,
2249 )
2250 };
2251 let mut source_args: Vec<&str> = vec![
2252 "-v",
2253 "error",
2254 "-y",
2255 "-f",
2256 "lavfi",
2257 "-i",
2258 "mandelbrot=size=256x192:start_scale=5.0:end_scale=0.004:end_pts=8:rate=25",
2259 "-pix_fmt",
2260 ];
2261 source_args.push(if bit_depth == 10 {
2262 "yuv420p10le"
2263 } else {
2264 "yuv420p"
2265 });
2266 source_args.extend(["-frames:v", "6"]);
2267 if bit_depth == 10 {
2268 // yuv420p10le is not an official yuv4mpegpipe format on this ffmpeg
2269 source_args.extend(["-strict", "-1"]);
2270 }
2271 source_args.extend(["-f", "yuv4mpegpipe", "-"]);
2272 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2273 .args(&source_args)
2274 .stdin(Stdio::null())
2275 .stdout(Stdio::piped())
2276 .stderr(Stdio::piped()), None, |c| c.output())
2277 .expect("ffmpeg failed to run");
2278 assert!(
2279 y4m.status.success(),
2280 "ffmpeg fixture: {}",
2281 String::from_utf8_lossy(&y4m.stderr)
2282 );
2283 assert_eq!(
2284 y4m.stdout.len(),
2285 src_len,
2286 "{NAME} ({bit_depth}-bit): the mandelbrot source is not the pinned 6-frame y4m -- \
2287 `rate=`, `end_pts` and `-frames:v` are all part of this recipe's identity"
2288 );
2289 eprintln!("{NAME} ({bit_depth}-bit): source y4m sha256 {src_sha}");
2290 let mut args: Vec<&str> = Vec::new();
2291 if bit_depth == 10 {
2292 args.extend(["-b", "10", "--input-bit-depth=10"]);
2293 }
2294 // Every flag spelled exactly once (class [[aomenc-last-flag-wins]]).
2295 args.extend([
2296 "--codec=av1",
2297 "--passes=1",
2298 "--end-usage=q",
2299 "--cpu-used=2",
2300 "--cq-level=63",
2301 "--threads=1",
2302 "--row-mt=0",
2303 "--enable-rect-partitions=1",
2304 // The feature this gate is about, and the flag the control arm
2305 // below reverts.
2306 "--enable-1to4-partitions=1",
2307 // 8, not 16 or 32: MEASURED, the 32-level 1:4 counter is 0 in all
2308 // 48 attempts at 16 and fires in 40 of 48 at 8.
2309 "--min-partition-size=8",
2310 "--max-partition-size=64",
2311 "--enable-tx-size-search=0",
2312 // A 1:4 strip needs an intra mode worth coding: with these four
2313 // off the only candidate is DC and it never wins.
2314 "--enable-filter-intra=1",
2315 "--enable-intra-edge-filter=1",
2316 "--enable-smooth-intra=1",
2317 "--enable-paeth-intra=1",
2318 "--enable-directional-intra=1",
2319 "--enable-angle-delta=1",
2320 // Single reference and one key frame, so every counted strip is
2321 // inside an INTER frame.
2322 "--lag-in-frames=0",
2323 "--auto-alt-ref=0",
2324 "--kf-min-dist=1000",
2325 "--kf-max-dist=1000",
2326 "--enable-order-hint=0",
2327 "--enable-warped-motion=0",
2328 "--enable-obmc=0",
2329 "--enable-masked-comp=0",
2330 "--enable-interintra-comp=0",
2331 "--enable-dist-wtd-comp=0",
2332 "--enable-diff-wtd-comp=0",
2333 "--enable-onesided-comp=0",
2334 "--enable-interintra-wedge=0",
2335 "--enable-smooth-interintra=0",
2336 "--enable-ab-partitions=0",
2337 "--enable-cdef=0",
2338 "--enable-restoration=0",
2339 // Ledger dead-end (lane-r14): a NEW gate spelling
2340 // `--enable-cfl-intra=1` retires that tool from
2341 // `NEVER_EXERCISED_8BIT` on the flag alone while no CfL
2342 // hit counter exists to assert -- so it stays 0 here.
2343 // Palette stays 0 for the same class of reason: this arm
2344 // refuses a screen-content frame whole, so a palette flag
2345 // would buy no coverage.
2346 "--enable-palette=0",
2347 "--enable-intrabc=0",
2348 "--enable-cfl-intra=0",
2349 "--enable-ref-frame-mvs=0",
2350 "--obu",
2351 "-o",
2352 "-",
2353 "-",
2354 ]);
2355 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2356 assert!(
2357 out.status.success(),
2358 "aomenc refused the fixture: {}",
2359 String::from_utf8_lossy(&out.stderr)
2360 );
2361 let stream = out.stdout;
2362 assert_eq!(
2363 stream.len(),
2364 pin_len,
2365 "{NAME} ({bit_depth}-bit): encoded size moved"
2366 );
2367 assert_eq!(
2368 fnv1a64(&stream),
2369 pin_fnv,
2370 "{NAME} ({bit_depth}-bit): encoded bytes moved"
2371 );
2372 let pin = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(pin_name);
2373 assert_eq!(
2374 std::fs::read(&pin).unwrap_or_else(|e| panic!("{pin_name} must be committed: {e}")),
2375 stream,
2376 "{NAME} ({bit_depth}-bit): the live encode no longer matches the committed pin"
2377 );
2378
2379 let before: Vec<usize> = (0..4)
2380 .map(decode::intra_rect4_strip_in_inter_hits)
2381 .collect();
2382 let frames = decode_stream(&stream)
2383 .unwrap_or_else(|e| panic!("{NAME} ({bit_depth}-bit): the pin must decode: {e}"));
2384 let delta: Vec<usize> = (0..4)
2385 .map(|k| decode::intra_rect4_strip_in_inter_hits(k) - before[k])
2386 .collect();
2387 let ffmpeg_frames = if bit_depth == 10 {
2388 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
2389 } else {
2390 ffmpeg_decode_sequence(&stream, width, height, frame_count)
2391 };
2392 assert_eq!(frames.len(), frame_count);
2393 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2394 for (plane, (g, w)) in [
2395 ("Y", (&got.y, &want.y)),
2396 ("U", (&got.u, &want.u)),
2397 ("V", (&got.v, &want.v)),
2398 ] {
2399 let stride = if plane == "Y" { width } else { width / 2 };
2400 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
2401 eprintln!(
2402 "{NAME} ({bit_depth}-bit): frame {i} {plane} first diff at ({}, {})",
2403 at % stride,
2404 at / stride
2405 );
2406 }
2407 assert_eq!(g, w, "{plane} vs ffmpeg (frame {i})");
2408 }
2409 }
2410 assert!(
2411 delta[2] + delta[3] > 0,
2412 "{NAME} ({bit_depth}-bit): {frame_count} frames pixel-exact but no 32-level intra 1:4 \
2413 strip (32x8/8x32) fired (64x16={} 16x64={} 32x8={} 8x32={}) -- the recipe stopped \
2414 producing the shape this gate names (class gate-blind-to-feature)",
2415 delta[0],
2416 delta[1],
2417 delta[2],
2418 delta[3]
2419 );
2420
2421 // The control arm: the one flag that is this gate's feature, reverted.
2422 // If it ever fires too, 1:4 is no longer what puts these strips on the
2423 // RD menu and the feature arm above is not the witness it claims to be.
2424 // It is also this gate's own red-proof.
2425 let mut control = args.clone();
2426 let at = control
2427 .iter()
2428 .position(|a| *a == "--enable-1to4-partitions=1")
2429 .expect("the feature flag is in the recipe");
2430 control[at] = "--enable-1to4-partitions=0";
2431 let ctl = run_with_stdin(Command::new(aomenc_path()).args(&control), &y4m.stdout);
2432 assert!(
2433 ctl.status.success(),
2434 "aomenc refused the --enable-1to4-partitions=0 control: {}",
2435 String::from_utf8_lossy(&ctl.stderr)
2436 );
2437 let ctl_before: Vec<usize> = (0..4)
2438 .map(decode::intra_rect4_strip_in_inter_hits)
2439 .collect();
2440 decode_stream(&ctl.stdout)
2441 .unwrap_or_else(|e| panic!("{NAME}: the control stream must decode too: {e}"));
2442 let ctl_delta: Vec<usize> = (0..4)
2443 .map(|k| decode::intra_rect4_strip_in_inter_hits(k) - ctl_before[k])
2444 .collect();
2445 assert_eq!(
2446 ctl_delta, [0; 4],
2447 "{NAME} ({bit_depth}-bit): the --enable-1to4-partitions=0 control fired \
2448 64x16={} 16x64={} 32x8={} 8x32={} -- 1:4 partitions are no longer what produce these \
2449 strips, so the feature arm above is not witnessing what it names",
2450 ctl_delta[0], ctl_delta[1], ctl_delta[2], ctl_delta[3]
2451 );
2452 gate_buckets(NAME, 1, 0, 0);
2453 eprintln!(
2454 "{NAME} ({bit_depth}-bit): {frame_count} frames pixel-exact, intra 1:4 strips in inter \
2455 frames 64x16={} 16x64={} 32x8={} 8x32={} (--enable-1to4-partitions=0 control: \
2456 0/0/0/0), stream {pin_len} B fnv1a64={pin_fnv:016x}",
2457 delta[0], delta[1], delta[2], delta[3]
2458 );
2459 }
2460
2461 pub(super) fn intra_rect_in_inter_split_tx_gate(bit_depth: u32) {
2462 let name = format!("intra_rect_in_inter_split_tx_gate({bit_depth})");
2463 if !have_ffmpeg() {
2464 eprintln!("SKIP {name}: no ffmpeg");
2465 return;
2466 }
2467 if !have_aomenc() {
2468 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
2469 return;
2470 }
2471 // lane-intrasplit r3, MEASURED (probe3, 20 attempts x 2 depths): at
2472 // 192x128 with `--min/--max-partition-size=32` a correctly decoded
2473 // stream contains ZERO intra HORZ/VERT strips in an inter frame -- the
2474 // r1/r2 "firing" counters were read off our own desynced decode (class
2475 // counter-from-refused-stream). The merged unsplit-strip gate's own
2476 // geometry (96x96, min 16 / max 64) is the one that makes aomenc's RD
2477 // pick intra strips here, and at `--enable-tx-size-search=1` it splits
2478 // their transforms: 10-bit attempt 0 = 8 strips, 3 split; 8-bit
2479 // attempt 0 = 5 strips, 1 split.
2480 let (width, height, frame_count) = (96usize, 96usize, 8usize);
2481 let mut refusals = Vec::new();
2482 let mut uncounted_exact = 0u32;
2483 let mut counted_exact = 0u32;
2484 let mut seen = [0usize; 3];
2485 for attempt in 0..40u32 {
2486 let seed = 42 + attempt;
2487 // MEASURED (r1, 40 attempts): the same sweep the merged
2488 // `intra_rect_in_inter_gate` had to make -- at `--cpu-used=0`
2489 // aomenc emits AB partitions regardless of
2490 // `--enable-ab-partitions=0` (ledger), so the preset is swept
2491 // 1..4, and the quantiser with it (a hard-cut overlay source at
2492 // cpu-used=0 stopped 38/40 attempts on other lanes' refusals).
2493 let cpu = attempt % 5;
2494 let cq = [30u32, 20, 12, 4][((attempt / 5) % 4) as usize];
2495 // A FAST ZOOM: consecutive frames share almost no content, so
2496 // aomenc's RD codes blocks INTRA inside INTER frames
2497 // (`--kf-min-dist` forbids a new key frame) -- the only way a
2498 // real encoder reaches this decoder's intra-in-inter arm -- and
2499 // the fractal's fine detail is what then splits their transforms.
2500 let source = format!(
2501 "mandelbrot=size={width}x{height}:start_scale={}:end_scale=0.004:end_pts=8:rate=25",
2502 5.0 - f64::from(attempt) * 0.06
2503 );
2504 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2505 .args([
2506 "-v",
2507 "error",
2508 "-f",
2509 "lavfi",
2510 "-i",
2511 &source,
2512 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
2513 // still-refused directional-chroma gaps never fire and
2514 // luma detail alone drives the transform split.
2515 "-vf",
2516 "hue=s=0",
2517 "-pix_fmt",
2518 if bit_depth == 10 {
2519 "yuv420p10le"
2520 } else {
2521 "yuv420p"
2522 },
2523 "-strict",
2524 "-1",
2525 "-t",
2526 "0.32",
2527 "-f",
2528 "yuv4mpegpipe",
2529 "-strict",
2530 "-1",
2531 "-",
2532 ])
2533 .stdin(Stdio::null())
2534 .stdout(Stdio::piped())
2535 .stderr(Stdio::piped()), None, |c| c.output())
2536 .expect("ffmpeg failed to run");
2537 assert!(
2538 y4m.status.success(),
2539 "ffmpeg fixture: {}",
2540 String::from_utf8_lossy(&y4m.stderr)
2541 );
2542 let depth_args: &[&str] = if bit_depth == 10 {
2543 &["-b", "10", "--input-bit-depth=10"]
2544 } else {
2545 &[]
2546 };
2547 let cq_arg = format!("--cq-level={cq}");
2548 let cpu_arg = format!("--cpu-used={cpu}");
2549 let out = run_with_stdin(
2550 Command::new(aomenc_path()).args(depth_args).args([
2551 "--codec=av1",
2552 "--passes=1",
2553 "--end-usage=q",
2554 &cq_arg,
2555 &cpu_arg,
2556 "--lag-in-frames=0",
2557 "--auto-alt-ref=0",
2558 "--kf-max-dist=9999",
2559 "--kf-min-dist=9999",
2560 "--threads=1",
2561 "--row-mt=0",
2562 "--enable-order-hint=0",
2563 "--enable-warped-motion=0",
2564 "--enable-obmc=0",
2565 "--enable-masked-comp=0",
2566 "--enable-interintra-comp=0",
2567 "--enable-dist-wtd-comp=0",
2568 "--enable-diff-wtd-comp=0",
2569 "--enable-onesided-comp=0",
2570 "--enable-interintra-wedge=0",
2571 "--enable-smooth-interintra=0",
2572 "--enable-ab-partitions=0",
2573 "--enable-1to4-partitions=0",
2574 "--enable-filter-intra=0",
2575 "--enable-smooth-intra=0",
2576 "--enable-paeth-intra=0",
2577 "--enable-directional-intra=0",
2578 "--enable-angle-delta=0",
2579 "--enable-cdef=0",
2580 "--enable-restoration=0",
2581 "--enable-palette=0",
2582 "--enable-intrabc=0",
2583 "--enable-cfl-intra=0",
2584 "--enable-ref-frame-mvs=0",
2585 "--min-partition-size=16",
2586 "--max-partition-size=64",
2587 // Per-arm overrides go LAST (aomenc keeps the last
2588 // occurrence of a repeated --enable-* flag): this gate
2589 // needs the rect partitions the strip lives in and the
2590 // tx_depth symbol, which exists only under TX_MODE_SELECT.
2591 "--enable-rect-partitions=1",
2592 "--enable-tx-size-search=1",
2593 "--obu",
2594 "-o",
2595 "-",
2596 "-",
2597 ]),
2598 &y4m.stdout,
2599 );
2600 assert!(
2601 out.status.success(),
2602 "aomenc refused the fixture: {}",
2603 String::from_utf8_lossy(&out.stderr)
2604 );
2605 let stream = out.stdout;
2606 let before = decode::intra_rect_in_inter_split_tx_hits();
2607 let frames = match decode_stream(&stream) {
2608 Ok(frames) => frames,
2609 Err(e) => {
2610 let msg = e.to_string();
2611 assert!(
2612 msg.contains("unsupported"),
2613 "{name} decode failed outright (seed {seed} cq {cq}): {msg}"
2614 );
2615 refusals.push(format!("seed {seed} cq {cq} cpu {cpu}: {msg}"));
2616 continue;
2617 }
2618 };
2619 let after = decode::intra_rect_in_inter_split_tx_hits();
2620 let mut per_depth = [0usize; 3];
2621 for i in 0..3 {
2622 per_depth[i] = after[i] - before[i];
2623 }
2624 // class [[gate-skips-on-its-own-failure]]: a decode that
2625 // succeeded is ALWAYS pixel-compared below; the counter only
2626 // decides whether the attempt counts as firing.
2627 let counted = per_depth[1] + per_depth[2] != 0;
2628 if !counted {
2629 uncounted_exact += 1;
2630 refusals.push(format!(
2631 "seed {seed} cq {cq} cpu {cpu}: decoded and pixel-compared, but no intra rect strip \
2632 in an inter frame split its transform"
2633 ));
2634 }
2635 let ffmpeg_frames = if bit_depth == 10 {
2636 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
2637 } else {
2638 ffmpeg_decode_sequence(&stream, width, height, frame_count)
2639 };
2640 assert_eq!(frames.len(), frame_count);
2641 eprintln!(
2642 "{name} seed={seed} cq={cq} cpu={cpu}: split intra strips depth1={} depth2={}",
2643 per_depth[1], per_depth[2]
2644 );
2645 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2646 for (plane, (g, w)) in [
2647 ("Y", (&got.y, &want.y)),
2648 ("U", (&got.u, &want.u)),
2649 ("V", (&got.v, &want.v)),
2650 ] {
2651 let stride = if plane == "Y" { width } else { width / 2 };
2652 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
2653 eprintln!(
2654 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
2655 want {} ({} samples differ)",
2656 at % stride,
2657 at / stride,
2658 g[at],
2659 w[at],
2660 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
2661 );
2662 }
2663 }
2664 }
2665 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2666 assert_eq!(
2667 got.y, want.y,
2668 "frame {i} luma vs ffmpeg (seed {seed} cq {cq})"
2669 );
2670 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed} cq {cq})");
2671 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed} cq {cq})");
2672 }
2673 if counted {
2674 counted_exact += 1;
2675 seen[1] += per_depth[1];
2676 seen[2] += per_depth[2];
2677 // Keep sweeping until BOTH reachable depths have been seen in
2678 // a pixel-exact attempt; one firing attempt is the floor.
2679 if seen[1] != 0 && seen[2] != 0 {
2680 break;
2681 }
2682 }
2683 }
2684 gate_buckets(
2685 &name,
2686 counted_exact,
2687 uncounted_exact,
2688 refusals.len() - uncounted_exact as usize,
2689 );
2690 eprintln!(
2691 "{name}: split strips seen depth1={} depth2={}",
2692 seen[1], seen[2]
2693 );
2694 assert!(
2695 seen[1] + seen[2] != 0,
2696 "{name} never observed a split-transform intra strip in an inter frame:\n{}",
2697 refusals.join("\n")
2698 );
2699 }
2700
2701 pub(super) fn screen_rect_intra_palette_syntax_gate(bit_depth: u32) {
2702 let name = format!("screen_rect_intra_palette_syntax_gate({bit_depth})");
2703 if !have_ffmpeg() {
2704 eprintln!("SKIP {name}: no ffmpeg");
2705 return;
2706 }
2707 if !have_aomenc() {
2708 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
2709 return;
2710 }
2711 let (width, height, frame_count) = (256usize, 192usize, 10usize);
2712 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2713 .args([
2714 "-v",
2715 "error",
2716 "-f",
2717 "lavfi",
2718 "-i",
2719 "testsrc2=s=256x192:r=25",
2720 "-t",
2721 "0.4",
2722 "-pix_fmt",
2723 "yuv420p",
2724 "-strict",
2725 "-1",
2726 "-f",
2727 "yuv4mpegpipe",
2728 "-",
2729 ])
2730 .stdin(Stdio::null())
2731 .stdout(Stdio::piped())
2732 .stderr(Stdio::piped()), None, |c| c.output())
2733 .expect("ffmpeg failed to run");
2734 assert!(
2735 y4m.status.success(),
2736 "{name}: ffmpeg fixture: {}",
2737 String::from_utf8_lossy(&y4m.stderr)
2738 );
2739 // The source stays 8-bit for both arms: `--bit-depth=10
2740 // --input-bit-depth=8` is the recipe that was measured to reach the
2741 // refusal, and the arm's point is the coded syntax, not the input.
2742 let depth_arg = format!("--bit-depth={bit_depth}");
2743 let cq_arg = format!("--cq-level={}", if bit_depth == 10 { 45 } else { 40 });
2744 let out = run_with_stdin(
2745 Command::new(aomenc_path())
2746 .args([
2747 "--codec=av1",
2748 "--passes=1",
2749 "--end-usage=q",
2750 "--cpu-used=0",
2751 "--lag-in-frames=0",
2752 "--kf-max-dist=30",
2753 "--limit=10",
2754 "--threads=1",
2755 "--tile-columns=0",
2756 "--enable-rect-partitions=1",
2757 "--enable-1to4-partitions=1",
2758 "--min-partition-size=8",
2759 "--sb-size=64",
2760 "--input-bit-depth=8",
2761 // `allow_screen_content_tools` in every frame header comes
2762 // from here; the two searches below stay off so the KEY frame
2763 // does not stop on a palette/intrabc RECONSTRUCTION refusal
2764 // before an inter frame exists.
2765 "--tune-content=screen",
2766 "--enable-palette=0",
2767 "--enable-intrabc=0",
2768 ])
2769 .args([&depth_arg, &cq_arg])
2770 .args(["--obu", "-o", "-", "-"]),
2771 &y4m.stdout,
2772 );
2773 assert!(
2774 out.status.success(),
2775 "{name}: aomenc refused the fixture: {}",
2776 String::from_utf8_lossy(&out.stderr)
2777 );
2778 let stream = out.stdout;
2779 decode::reset_intra_rect_in_inter_screen_hits();
2780 let frames = decode_stream(&stream).unwrap_or_else(|e| {
2781 panic!("{name}: decode failed -- the case this gate exists for: {e}")
2782 });
2783 let strips = decode::intra_rect_in_inter_screen_hits();
2784 eprintln!(
2785 "{name}: {} frames, {strips} rect intra strip(s) read the palette syntax",
2786 frames.len()
2787 );
2788 assert_eq!(frames.len(), frame_count, "{name}: frame count");
2789 let ffmpeg_frames = if bit_depth == 10 {
2790 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
2791 } else {
2792 ffmpeg_decode_sequence(&stream, width, height, frame_count)
2793 };
2794 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2795 assert_eq!(got.y, want.y, "{name}: frame {i} luma vs ffmpeg");
2796 assert_eq!(got.u, want.u, "{name}: frame {i} U vs ffmpeg");
2797 assert_eq!(got.v, want.v, "{name}: frame {i} V vs ffmpeg");
2798 }
2799 assert!(
2800 strips > 0,
2801 "{name}: no rect intra strip of a screen-content frame read the palette syntax -- \
2802 the gate is vacuous, the recipe stopped producing the shape"
2803 );
2804 }