forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

support.rs4172 lines, 173.2 KiBHistoryRawDownload
1use super::*;
2use super::gates_a::*;
3
4 pub(super) fn test_card(width: usize, height: usize) -> Pic {
5 let mut picture = Pic::grey(width, height);
6 for row in 0..height {
7 for col in 0..width {
8 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
9 }
10 }
11 for row in 0..height / 2 {
12 for col in 0..width / 2 {
13 let i = row * width / 2 + col;
14 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
15 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
16 }
17 }
18 picture
19 }
20
21 pub(super) fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic {
22 let mut picture = Pic::grey(width, height);
23 for y in 0..height {
24 for x in 0..width {
25 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
26 let gradient = sx * 200.0 / width as f64;
27 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
28 }
29 }
30 for y in 0..height / 2 {
31 for x in 0..width / 2 {
32 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
33 let i = y * width / 2 + x;
34 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
35 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
36 }
37 }
38 picture
39 }
40
41 /// One census attempt: encode `frames` frames of `source` with real
42 /// aomenc plus `extra` args, decode with THIS decoder, and return the
43 /// stream's byte length with either the picture count or the refusal (any
44 /// decode error) it produced. A census is about what the encoder emits,
45 /// so a refusal is data here, not a failure.
46 pub(super) fn census_attempt(
47 source: &str,
48 width: usize,
49 height: usize,
50 frames: usize,
51 extra: &[&str],
52 ) -> (usize, std::result::Result<usize, String>) {
53 let duration = format!("{}", frames as f64 / 25.0);
54 let src = format!("{source}=size={width}x{height}:rate=25");
55 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
56 .args([
57 "-v",
58 "error",
59 "-f",
60 "lavfi",
61 "-i",
62 &src,
63 "-t",
64 &duration,
65 "-pix_fmt",
66 "yuv420p",
67 "-strict",
68 "-1",
69 "-f",
70 "yuv4mpegpipe",
71 "-",
72 ])
73 .stdin(Stdio::null())
74 .stdout(Stdio::piped())
75 .stderr(Stdio::piped()), None, |c| c.output())
76 .expect("ffmpeg failed to run");
77 assert!(
78 y4m.status.success(),
79 "ffmpeg refused the {width}x{height} fixture"
80 );
81 let limit = format!("--limit={frames}");
82 let mut args: Vec<String> = [
83 "--codec=av1",
84 "--passes=1",
85 "--end-usage=q",
86 "--threads=1",
87 "--row-mt=0",
88 "--kf-max-dist=9999",
89 "--lag-in-frames=0",
90 ]
91 .iter()
92 .map(|s| (*s).to_owned())
93 .collect();
94 args.push(limit);
95 args.extend(extra.iter().map(|s| (*s).to_owned()));
96 args.extend([
97 "--obu".to_owned(),
98 "-o".to_owned(),
99 "-".to_owned(),
100 "-".to_owned(),
101 ]);
102 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
103 assert!(
104 out.status.success(),
105 "aomenc refused {args:?}: {}",
106 String::from_utf8_lossy(&out.stderr)
107 );
108 let stream = out.stdout;
109 let result = match decode_stream(&stream) {
110 Ok(pictures) => Ok(pictures.len()),
111 Err(e) => Err(e.to_string()),
112 };
113 (stream.len(), result)
114 }
115
116 /// lane-av1seglvl: encode `frames` frames of `source` with real aomenc
117 /// plus `extra` args and return the raw `.obu` bytes -- the census's
118 /// half-sibling of [`census_attempt`] that keeps the STREAM instead of
119 /// only its decode verdict, so the caller can parse the frame headers'
120 /// segmentation tables themselves.
121 pub(super) fn encode_aomenc_stream(
122 source: &str,
123 width: usize,
124 height: usize,
125 frames: usize,
126 extra: &[&str],
127 ) -> Vec<u8> {
128 let duration = format!("{}", frames as f64 / 25.0);
129 let src = format!("{source}=size={width}x{height}:rate=25");
130 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
131 .args([
132 "-v",
133 "error",
134 "-f",
135 "lavfi",
136 "-i",
137 &src,
138 "-t",
139 &duration,
140 "-pix_fmt",
141 "yuv420p",
142 "-strict",
143 "-1",
144 "-f",
145 "yuv4mpegpipe",
146 "-",
147 ])
148 .stdin(Stdio::null())
149 .stdout(Stdio::piped())
150 .stderr(Stdio::piped()), None, |c| c.output())
151 .expect("ffmpeg failed to run");
152 assert!(
153 y4m.status.success(),
154 "ffmpeg refused the {width}x{height} fixture"
155 );
156 let limit = format!("--limit={frames}");
157 let mut args: Vec<String> = [
158 "--codec=av1",
159 "--passes=1",
160 "--end-usage=q",
161 "--threads=1",
162 "--row-mt=0",
163 "--kf-max-dist=9999",
164 "--lag-in-frames=0",
165 ]
166 .iter()
167 .map(|s| (*s).to_owned())
168 .collect();
169 args.push(limit);
170 args.extend(extra.iter().map(|s| (*s).to_owned()));
171 args.extend([
172 "--obu".to_owned(),
173 "-o".to_owned(),
174 "-".to_owned(),
175 "-".to_owned(),
176 ]);
177 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
178 assert!(
179 out.status.success(),
180 "aomenc refused {args:?}: {}",
181 String::from_utf8_lossy(&out.stderr)
182 );
183 out.stdout
184 }
185
186 /// lane-av1seglvl: encode `frames` frames with a real TWO-PASS aomenc
187 /// (pass 1 writes the stats file into the session temp dir, pass 2
188 /// consumes it) and return the `.obu` bytes. This is the only shape that
189 /// reaches libaom's `is_stat_consumption_stage_twopass` segmentation
190 /// setup (`configure_static_seg_features`), so the census is not proven
191 /// over the encoder's whole reachable surface without it.
192 pub(super) fn encode_aomenc_stream_twopass(
193 source: &str,
194 width: usize,
195 height: usize,
196 frames: usize,
197 extra: &[&str],
198 ) -> Vec<u8> {
199 let duration = format!("{}", frames as f64 / 25.0);
200 let src = format!("{source}=size={width}x{height}:rate=25");
201 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
202 .args([
203 "-v",
204 "error",
205 "-f",
206 "lavfi",
207 "-i",
208 &src,
209 "-t",
210 &duration,
211 "-pix_fmt",
212 "yuv420p",
213 "-strict",
214 "-1",
215 "-f",
216 "yuv4mpegpipe",
217 "-",
218 ])
219 .stdin(Stdio::null())
220 .stdout(Stdio::piped())
221 .stderr(Stdio::piped()), None, |c| c.output())
222 .expect("ffmpeg failed to run");
223 assert!(
224 y4m.status.success(),
225 "ffmpeg refused the {width}x{height} fixture"
226 );
227 let limit = format!("--limit={frames}");
228 let fpf =
229 std::env::temp_dir().join(format!("ec-av1-segldapass-{}.fpf", std::process::id()));
230 let mut base: Vec<String> = [
231 "--codec=av1",
232 "--passes=2",
233 "--end-usage=q",
234 "--threads=1",
235 "--row-mt=0",
236 "--kf-max-dist=9999",
237 "--lag-in-frames=0",
238 ]
239 .iter()
240 .map(|s| (*s).to_owned())
241 .collect();
242 base.push(limit);
243 base.extend(extra.iter().map(|s| (*s).to_owned()));
244 let mut pass1 = base.clone();
245 pass1.extend(["--pass=1".to_owned(), format!("--fpf={}", fpf.display())]);
246 pass1.extend([
247 "--obu".to_owned(),
248 "-o".to_owned(),
249 "/dev/null".to_owned(),
250 "-".to_owned(),
251 ]);
252 let out1 = run_with_stdin(Command::new(aomenc_path()).args(&pass1), &y4m.stdout);
253 assert!(
254 out1.status.success(),
255 "aomenc pass 1 refused {pass1:?}: {}",
256 String::from_utf8_lossy(&out1.stderr)
257 );
258 let mut pass2 = base;
259 pass2.extend(["--pass=2".to_owned(), format!("--fpf={}", fpf.display())]);
260 pass2.extend([
261 "--obu".to_owned(),
262 "-o".to_owned(),
263 "-".to_owned(),
264 "-".to_owned(),
265 ]);
266 let out2 = run_with_stdin(Command::new(aomenc_path()).args(&pass2), &y4m.stdout);
267 let _ = std::fs::remove_file(&fpf);
268 assert!(
269 out2.status.success(),
270 "aomenc pass 2 refused {pass2:?}: {}",
271 String::from_utf8_lossy(&out2.stderr)
272 );
273 out2.stdout
274 }
275
276 /// lane-av1seglvl: walk every frame OBU of `stream` and tally which
277 /// `SEG_LVL` features the frame headers actually ENABLE, plus the shape
278 /// counters a census premise is asserted against: frames with
279 /// segmentation on, of which `update_map == 1` (the map is coded) and
280 /// `update_map == 0` (every block's id is INHERITED), and frames whose
281 /// table carries a real `SEG_LVL_ALT_Q` delta.
282 /// The last vector counts per SEGMENT-FEATURE INSTANCE (a frame with
283 /// ALT_Q on all 8 segments contributes 8), which is all the verdict
284 /// needs: only index `SEG_LVL_ALT_Q` may be non-zero.
285 /// Returns `(enabled_frames, update_map_frames, inherited_frames,
286 /// alt_q_frames, feature_instances: [usize; SEG_LVL_MAX])`.
287 #[allow(clippy::type_complexity)]
288 pub(super) fn segmentation_feature_census(
289 stream: &[u8],
290 ) -> (usize, usize, usize, usize, [usize; SEG_LVL_MAX]) {
291 let mut parser = Av1Parser::new();
292 let obus = parser
293 .parse_temporal_unit(stream)
294 .unwrap_or_else(|e| panic!("the census stream does not even parse: {e}"));
295 let mut enabled = 0usize;
296 let mut update_map = 0usize;
297 let mut inherited = 0usize;
298 let mut alt_q = 0usize;
299 let mut feature_frames = [0usize; SEG_LVL_MAX];
300 for obu in &obus {
301 if let ObuKind::Frame(header, _) = &obu.kind {
302 let seg = &header.segmentation;
303 if !seg.enabled {
304 continue;
305 }
306 enabled += 1;
307 if seg.update_map {
308 update_map += 1;
309 } else {
310 inherited += 1;
311 }
312 let mut any_q = false;
313 for segment in 0..MAX_SEGMENTS {
314 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
315 #[allow(clippy::needless_range_loop)]
316 for feature in 0..SEG_LVL_MAX {
317 if seg.feature_enabled[segment][feature] {
318 feature_frames[feature] += 1;
319 if feature == SEG_LVL_ALT_Q {
320 any_q = true;
321 }
322 }
323 }
324 }
325 if any_q {
326 alt_q += 1;
327 }
328 }
329 }
330 (enabled, update_map, inherited, alt_q, feature_frames)
331 }
332
333 /// lane-interedge r1: one attempt of the inter frame-edge half-strip gate --
334 /// encode `width x height` with real aomenc (rect partitions ON, every other
335 /// lane's open tool pinned off), decode it, and return
336 /// `(inter_edge_strip hits, frames whose LUMA differs, frames whose CHROMA
337 /// differs)` against ffmpeg. A refusal or a decode error is a hard failure:
338 /// this recipe reached every size without one (measured r1).
339 pub(super) fn inter_edge_strip_attempt(
340 name: &str,
341 width: usize,
342 height: usize,
343 bit_depth: u32,
344 cq: u32,
345 frames: usize,
346 ) -> ([usize; 6], usize, usize) {
347 let duration = format!("{}", frames as f64 / 25.0);
348 let source = format!("mandelbrot=size={width}x{height}:rate=25");
349 let pix_fmt = if bit_depth == 10 {
350 "yuv420p10le"
351 } else {
352 "yuv420p"
353 };
354 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
355 .args([
356 "-v",
357 "error",
358 "-f",
359 "lavfi",
360 "-i",
361 &source,
362 "-t",
363 &duration,
364 "-pix_fmt",
365 pix_fmt,
366 "-strict",
367 "-1",
368 "-f",
369 "yuv4mpegpipe",
370 "-",
371 ])
372 .stdin(Stdio::null())
373 .stdout(Stdio::piped())
374 .stderr(Stdio::piped()), None, |c| c.output())
375 .expect("ffmpeg failed to run");
376 assert!(
377 y4m.status.success(),
378 "{name}: ffmpeg refused the {width}x{height} {bit_depth}-bit fixture: {}",
379 String::from_utf8_lossy(&y4m.stderr)
380 );
381 let depth_arg = format!("--bit-depth={bit_depth}");
382 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
383 let cq_arg = format!("--cq-level={cq}");
384 let limit_arg = format!("--limit={frames}");
385 let out = run_with_stdin(
386 Command::new(aomenc_path()).args([
387 "--codec=av1",
388 "--passes=1",
389 "--end-usage=q",
390 &cq_arg,
391 // cpu-used >= 1 keeps libaom on 64x64 superblocks at these
392 // sizes (`av1_select_sb_size`).
393 "--cpu-used=4",
394 "--threads=1",
395 "--row-mt=0",
396 "--kf-max-dist=9999",
397 &limit_arg,
398 // decode order == display order, so the compare below covers
399 // every frame the stream carries (class gate-blind-to-hidden-frames).
400 "--lag-in-frames=0",
401 &depth_arg,
402 &input_depth_arg,
403 // Rect partitions stay ON: the frame-edge strip is a FORCED
404 // (gathered) HORZ/VERT, but with rect coding off the encoder
405 // answers that gathered symbol SPLIT every time and no edge
406 // strip ever fires (lane-oddh r2's finding, re-measured r1).
407 "--enable-rect-partitions=1",
408 "--enable-ab-partitions=0",
409 "--enable-1to4-partitions=0",
410 "--min-partition-size=8",
411 "--max-partition-size=64",
412 // Other lanes' open gaps this recipe must not trip.
413 "--enable-palette=0",
414 "--enable-intrabc=0",
415 "--enable-warped-motion=0",
416 "--enable-obmc=0",
417 "--enable-masked-comp=0",
418 "--enable-interintra-comp=0",
419 "--enable-onesided-comp=0",
420 "--enable-interintra-wedge=0",
421 "--enable-smooth-interintra=0",
422 "--enable-ref-frame-mvs=0",
423 "--enable-angle-delta=0",
424 "--enable-cfl-intra=0",
425 "--enable-directional-intra=0",
426 "--enable-smooth-intra=0",
427 "--enable-paeth-intra=0",
428 "--enable-filter-intra=0",
429 "--enable-tx-size-search=0",
430 "--obu",
431 "-o",
432 "-",
433 "-",
434 ]),
435 &y4m.stdout,
436 );
437 assert!(
438 out.status.success(),
439 "aomenc refused: {}",
440 String::from_utf8_lossy(&out.stderr)
441 );
442 let stream = out.stdout;
443
444 // Reset, never a delta: a refused attempt's hits must not leak into the
445 // next one (class counter-from-refused-stream).
446 crate::decode::reset_inter_edge_strip_hits();
447 let decoded = decode_stream(&stream).unwrap_or_else(|e| {
448 panic!("{name}: {width}x{height} {bit_depth}-bit cq {cq} did not decode: {e}")
449 });
450 let hits = crate::decode::inter_edge_strip_hits();
451 let reference = if bit_depth == 10 {
452 ffmpeg_decode_sequence_10bit(&stream, width, height, frames)
453 } else {
454 ffmpeg_decode_sequence(&stream, width, height, frames)
455 };
456 assert_eq!(
457 decoded.len(),
458 reference.len(),
459 "{name}: {width}x{height} {bit_depth}-bit cq {cq} frame count"
460 );
461 assert!(
462 decoded.len() >= frames,
463 "{name}: {width}x{height} {bit_depth}-bit cq {cq} decoded only {} frames",
464 decoded.len()
465 );
466 let (mut luma_bad, mut chroma_bad) = (0usize, 0usize);
467 for (ours, theirs) in decoded.iter().zip(&reference) {
468 if ours.y != theirs.y {
469 luma_bad += 1;
470 }
471 if ours.u != theirs.u || ours.v != theirs.v {
472 chroma_bad += 1;
473 }
474 }
475 (hits, luma_bad, chroma_bad)
476 }
477
478 /// A GOP (key frame plus panned inter frames, so blocks actually take
479 /// motion) decodes bit-exact through `decode_stream` alone, threading its
480 /// own DPB rather than a test-supplied reference.
481 pub(super) fn gop_round_trips(width: usize, height: usize, fctx: &crate::decode::FrameCtx) {
482 let pictures: Vec<_> = (0..4)
483 .map(|i| panned_test_card(width, height, i * 3))
484 .collect();
485 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
486 let decoded = decode_stream(&encoded.stream).unwrap();
487 assert_eq!(decoded.len(), encoded.frames.len());
488 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
489 assert_eq!(
490 got.y, frame.reconstruction.y,
491 "{width}x{height} frame {i} luma"
492 );
493 assert_eq!(
494 got.u, frame.reconstruction.u,
495 "{width}x{height} frame {i} U"
496 );
497 assert_eq!(
498 got.v, frame.reconstruction.v,
499 "{width}x{height} frame {i} V"
500 );
501 }
502 }
503
504 /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`,
505 /// `skip_mode`/compound) all read a process-global atomic counter delta
506 /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to
507 /// prove a real block picked the feature under test, not just that a
508 /// header bit was set. Under `cargo test`'s default parallel run, a
509 /// SIBLING test's own decode bumps the same global counter mid-gate --
510 /// a false "fired" reading pixel-compares an attempt the gate would
511 /// otherwise `continue` past, on top of genuine defects that path may
512 /// still have. Serialising every counter-delta gate behind this one
513 /// mutex makes firing detection honest again (matches the existing
514 /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`).
515 pub(super) static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
516
517 /// lane-cdfflake: a cheap, dependency-free (FNV-1a, not cryptographic --
518 /// this is a load-bearing-identity fingerprint for flake triage, not a
519 /// security digest, so no `sha2` dep is pulled in) fixture fingerprint
520 /// for the cdf-forwarding gate's instrumentation below.
521 /// Reads a pinned fixture, asserting its length and FNV first, so a
522 /// swapped or truncated pin fails loudly instead of silently changing
523 /// what the gate measures.
524 pub(super) fn read_pin(path: &std::path::Path, len: usize, fnv: u64, name: &str) -> Vec<u8> {
525 let bytes = std::fs::read(path).unwrap_or_else(|e| {
526 panic!(
527 "{name}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
528 which is a failure, not a skip",
529 path.display()
530 )
531 });
532 assert_eq!(bytes.len(), len, "{name}: fixture length moved");
533 assert_eq!(fnv1a64(&bytes), fnv, "{name}: fixture bytes moved");
534 bytes
535 }
536
537 /// The bit depth the stream's OWN sequence header declares, read from
538 /// the bytes rather than taken from the gate's name or recipe (class
539 /// `helper-packs-u16-for-an-8-bit-stream`: aomdec's `--rawvideo`
540 /// writes 8 bits per sample for an 8-bit stream and 16 bits LE for a
541 /// high-bitdepth one, so a u16 packer turns every 8-bit compare into a
542 /// raw-SIZE failure that never looks at a sample).
543 pub(super) fn stream_bit_depth(stream: &[u8], name: &str) -> u8 {
544 let mut probe = Av1Parser::new();
545 let mut pos = 0usize;
546 while pos < stream.len() && probe.sequence_header().is_none() {
547 let obu = probe
548 .parse_obu(&stream[pos..])
549 .unwrap_or_else(|e| panic!("{name}: OBU at byte {pos} does not parse: {e:?}"));
550 pos += obu.total_size;
551 }
552 probe
553 .sequence_header()
554 .unwrap_or_else(|| panic!("{name}: the stream carries no sequence header OBU"))
555 .color_config
556 .bit_depth
557 }
558
559 /// The stream's OWN `color_config.subsampling_x/y` (spec 5.5.2), read
560 /// from its bytes the same way [`stream_bit_depth`] reads the depth.
561 pub(super) fn stream_subsampling(stream: &[u8], name: &str) -> (u8, u8) {
562 let mut probe = Av1Parser::new();
563 let mut pos = 0usize;
564 while pos < stream.len() && probe.sequence_header().is_none() {
565 let obu = probe
566 .parse_obu(&stream[pos..])
567 .unwrap_or_else(|e| panic!("{name}: OBU at byte {pos} does not parse: {e:?}"));
568 pos += obu.total_size;
569 }
570 let cc = &probe
571 .sequence_header()
572 .unwrap_or_else(|| panic!("{name}: the stream carries no sequence header OBU"))
573 .color_config;
574 (cc.subsampling_x, cc.subsampling_y)
575 }
576
577 /// The chroma shape a `(subsampling_x, subsampling_y)` pair means.
578 pub(super) fn chroma_shape(sx: u8, sy: u8) -> &'static str {
579 match (sx, sy) {
580 (1, 1) => "4:2:0",
581 (1, 0) => "4:2:2",
582 (0, 0) => "4:4:4",
583 (0, 1) => "4:4:0",
584 _ => "an unassigned subsampling",
585 }
586 }
587
588 /// lane-av1oracleguard: HARD REFUSAL for the 4:2:0 ffmpeg oracle helpers.
589 ///
590 /// `ffmpeg_decode_sequence`, `ffmpeg_decode_sequence_10bit` and
591 /// `ffmpeg_decode_sequence_12bit` ask ffmpeg for `-pix_fmt yuv420p*` and
592 /// size chroma at `width * height / 4`. Those are the 4:2:0 numbers, so
593 /// for a stream that is NOT (1,1) ffmpeg does not fail -- it CONVERTS,
594 /// and the helper then slices a 4:2:0-shaped picture out of it. A 4:2:2
595 /// gate built on one of them compares the wrong planes and passes green:
596 /// the exact failure `lanes/av1subsizesweep.report.md` names. The correct
597 /// siblings (`ffmpeg_decode_sequence_422` / `_422_depth` /
598 /// `ffmpeg_decode_sequence_444`) exist and take the same bytes, so the
599 /// refusal points at them by name rather than leaving the caller to
600 /// rediscover the shape.
601 ///
602 /// Refused by SUBSAMPLING read from the stream's own sequence header, not
603 /// from the caller's `width`/`height` (class
604 /// `helper-assumes-the-shape-the-gate-name-implies`).
605 pub(super) fn assert_420_oracle_stream(stream: &[u8], helper: &str, sibling: &str) {
606 let (sx, sy) = stream_subsampling(stream, helper);
607 assert!(
608 (sx, sy) == (1, 1),
609 "{helper} REFUSED a ({sx},{sy}) stream: this helper asks ffmpeg for a 4:2:0 \
610 pix_fmt, which CONVERTS the stream's real {} chroma down to 4:2:0 instead of \
611 failing, then sizes chroma at `width * height / 4` rather than the {} shape. A \
612 gate built on it would compare converted planes against real ones and pass green. \
613 Use `{sibling}` for a ({sx},{sy}) stream.",
614 chroma_shape(sx, sy),
615 chroma_shape(sx, sy),
616 );
617 }
618
619 /// lane-av1oracleguard: run `f`, return the panic MESSAGE it raised (or
620 /// `None` if it did not panic). The panic hook is silenced so a refusal
621 /// that PASSES its gate prints nothing -- the assertion is the return.
622 pub(super) fn panic_message<F: FnOnce()>(f: F) -> Option<String> {
623 let hook = std::panic::take_hook();
624 std::panic::set_hook(Box::new(|_| {}));
625 let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
626 std::panic::set_hook(hook);
627 match caught {
628 Ok(()) => None,
629 Err(payload) => Some(
630 payload
631 .downcast_ref::<String>()
632 .cloned()
633 .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
634 .unwrap_or_else(|| "<non-string panic payload>".to_string()),
635 ),
636 }
637 }
638
639 /// Packs decoded planes the way `aomdec --rawvideo` writes them for
640 /// `bit_depth`: 1 byte per sample at 8-bit, 2 bytes little-endian at
641 /// 10/12-bit. Plane order is Y, U, V at the frame's own subsampled
642 /// shape, which is exactly what rawvideo emits.
643 pub(super) fn pack_rawvideo(decoded: &[Pic], bit_depth: u8, name: &str) -> Vec<u8> {
644 let mut ours: Vec<u8> = Vec::new();
645 for (fi, f) in decoded.iter().enumerate() {
646 for p in [&f.y, &f.u, &f.v] {
647 if bit_depth == 8 {
648 for &s in p {
649 assert!(
650 s <= 0xff,
651 "{name}: decode-order frame {fi} carries the sample {s}, which an \
652 8-bit stream cannot hold -- the stream is not the one this gate thinks \
653 it is"
654 );
655 ours.push(s as u8);
656 }
657 } else {
658 for &s in p {
659 ours.extend_from_slice(&s.to_le_bytes());
660 }
661 }
662 }
663 }
664 ours
665 }
666
667 /// Decodes `stream` and the oracle's `aomdec --rawvideo` output and
668 /// requires every sample of every frame to agree, in decode order.
669 ///
670 /// `bit_depth` is the depth the CALLER believes the stream has; it is
671 /// asserted against the stream's own sequence header, so a gate that
672 /// hands this an 8-bit stream under a 10-bit label fails here by name
673 /// instead of dying on a raw-size mismatch that reads like a pixel bug.
674 pub(super) fn assert_rawvideo_matches(
675 obu: &std::path::Path,
676 stream: &[u8],
677 name: &str,
678 frames: usize,
679 bit_depth: u8,
680 ) {
681 let actual_depth = stream_bit_depth(stream, name);
682 assert_eq!(
683 actual_depth, bit_depth,
684 "{name}: the stream's sequence header says {actual_depth}-bit, the gate passed \
685 {bit_depth}-bit -- aomdec's --rawvideo writes {actual_depth} bits per sample for it, \
686 so packing for {bit_depth} compares nothing"
687 );
688 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
689 let _ = std::fs::remove_dir_all(&dir);
690 std::fs::create_dir_all(&dir).expect("scratch dir");
691 let raw = dir.join("aomdec.raw");
692 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
693 .args(["--codec=av1", "--rawvideo", "-o"])
694 .arg(&raw)
695 .arg(obu)
696 .stdin(Stdio::null())
697 .stdout(Stdio::piped())
698 .stderr(Stdio::piped()), None, |c| c.output())
699 .expect("aomdec failed to run");
700 assert!(
701 out.status.success(),
702 "{name}: the oracle aomdec refused the stream: {}",
703 String::from_utf8_lossy(&out.stderr)
704 );
705 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
706 let _ = std::fs::remove_dir_all(&dir);
707 let decoded = decode_stream(stream).expect("decode for comparison");
708 let ours = pack_rawvideo(&decoded, bit_depth, name);
709 assert_eq!(
710 ours.len(),
711 ref_raw.len(),
712 "{name}: {bit_depth}-bit raw sizes differ -- ours packs {} bytes ({} samples at \
713 {} bit/sample), aomdec wrote {}",
714 ours.len(),
715 decoded
716 .iter()
717 .map(|f| f.y.len() + f.u.len() + f.v.len())
718 .sum::<usize>(),
719 bit_depth,
720 ref_raw.len()
721 );
722 assert_eq!(decoded.len(), frames, "{name}: frame count");
723 let first = ours
724 .iter()
725 .zip(&ref_raw)
726 .position(|(a, b)| a != b)
727 .unwrap_or(ours.len());
728 assert_eq!(
729 first,
730 ours.len(),
731 "{name}: {} bytes of decoded output differ from aomdec (first at {})",
732 ours.iter().zip(&ref_raw).filter(|(a, b)| a != b).count(),
733 first
734 );
735 }
736
737 pub(super) fn fnv1a64(bytes: &[u8]) -> u64 {
738 let mut hash = 0xcbf29ce484222325u64;
739 for &b in bytes {
740 hash ^= b as u64;
741 hash = hash.wrapping_mul(0x100000001b3);
742 }
743 hash
744 }
745
746 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
747 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
748 /// aomenc gate decodes its stream through ffmpeg and is meaningless
749 /// without it -- turns it into a hard failure. Without this the require
750 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
751 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
752 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
753 pub(super) fn have_ffmpeg() -> bool {
754 let present = Command::new("ffmpeg")
755 .arg("-version")
756 .stdout(Stdio::null())
757 .stderr(Stdio::null())
758 .status()
759 .is_ok_and(|s| s.success());
760 assert!(
761 present
762 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
763 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
764 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
765 );
766 present
767 }
768
769 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
770 /// The frame-count diagnostic shared by the three `ffmpeg_decode_sequence*`
771 /// helpers (lane-av1pins5 r6).
772 ///
773 /// Before this, a caller that passed its OWN decode's length as the expected
774 /// count got `expected N 4:2:0 frames, ffmpeg said: ` -- with an EMPTY tail,
775 /// because ffmpeg ran at `-v error` and succeeded. The message named ffmpeg,
776 /// said nothing about where `N` came from, and sent the next reader hunting
777 /// ffmpeg for a count ffmpeg never chose.
778 ///
779 /// The class is MISATTRIBUTED RED, not silent pass: the helper's
780 /// `out.stdout.len() == frame_bytes * frames` assert fires unconditionally, so
781 /// a wrong count cannot pass -- it just fails while blaming the wrong
782 /// component. (Measured: `ffmpeg_decode_sequence(&s, 192, 128, 0)` panics
783 /// here, not silently.) Naming the real cause is the whole fix; no caller has
784 /// to change to benefit.
785 pub(super) fn frame_count_diagnosis(
786 format: &str,
787 frames: usize,
788 width: usize,
789 height: usize,
790 frame_bytes: usize,
791 got: usize,
792 stderr: &[u8],
793 ) -> String {
794 let actual = got.checked_div(frame_bytes).unwrap_or(0);
795 let leftover = if frame_bytes == 0 {
796 got
797 } else {
798 got % frame_bytes
799 };
800 format!(
801 "FRAME COUNT MISMATCH ({format} {width}x{height}): the caller passed \
802 `frames={frames}`, ffmpeg produced {actual} frame(s) ({got} bytes, \
803 {leftover} byte(s) not a whole frame, at {frame_bytes} B/frame).\n\
804 `frames` is the EXPECTED count the CALLER asserted -- it is NOT measured \
805 from ffmpeg, so it never had ffmpeg's agreement. If it came from our own \
806 decode_stream(), this is OUR decoder disagreeing with ffmpeg about how many \
807 frames the stream holds, and the fix is on OUR side, not ffmpeg's. ffmpeg \
808 itself exited cleanly{}.",
809 if stderr.is_empty() {
810 " with no diagnostics (`-v error`)"
811 } else {
812 ""
813 }
814 )
815 }
816
817 pub(super) fn ffmpeg_decode_sequence(
818 stream: &[u8],
819 width: usize,
820 height: usize,
821 frames: usize,
822 ) -> Vec<Pic> {
823 // lane-av1oracleguard: this helper's numbers are 4:2:0's. A (1,0) or
824 // (0,0) stream would be CONVERTED by ffmpeg rather than refused.
825 assert_420_oracle_stream(
826 stream,
827 "ffmpeg_decode_sequence",
828 "ffmpeg_decode_sequence_422 (4:2:2) or ffmpeg_decode_sequence_444 (4:4:4)",
829 );
830 let out = run_with_stdin(
831 Command::new(ffmpeg_path()).args([
832 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
833 ]),
834 stream,
835 );
836 assert!(
837 out.status.success(),
838 "ffmpeg refused the stream: {}",
839 String::from_utf8_lossy(&out.stderr)
840 );
841 let (luma, chroma) = (width * height, width * height / 4);
842 let frame_bytes = luma + 2 * chroma;
843 assert_eq!(
844 out.stdout.len(),
845 frame_bytes * frames,
846 "{}",
847 frame_count_diagnosis(
848 "4:2:0",
849 frames,
850 width,
851 height,
852 frame_bytes,
853 out.stdout.len(),
854 &out.stderr
855 )
856 );
857 (0..frames)
858 .map(|i| {
859 let base = i * frame_bytes;
860 Pic {
861 width,
862 height,
863 y: out.stdout[base..base + luma]
864 .iter()
865 .map(|&v| u16::from(v))
866 .collect(),
867 u: out.stdout[base + luma..base + luma + chroma]
868 .iter()
869 .map(|&v| u16::from(v))
870 .collect(),
871 v: out.stdout[base + luma + chroma..base + frame_bytes]
872 .iter()
873 .map(|&v| u16::from(v))
874 .collect(),
875 }
876 })
877 .collect()
878 }
879
880 /// As [`ffmpeg_decode_sequence`], for a MONOCHROME stream: one 8-bit luma
881 /// plane per frame, exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes
882 /// (lane-av1mono). Fed through [`run_with_stdin`] for the reason its doc
883 /// records.
884 pub(super) fn ffmpeg_decode_gray_sequence(
885 stream: &[u8],
886 width: usize,
887 height: usize,
888 frames: usize,
889 ) -> Vec<u8> {
890 let out = run_with_stdin(
891 Command::new(ffmpeg_path()).args([
892 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "gray", "-",
893 ]),
894 stream,
895 );
896 assert!(
897 out.status.success(),
898 "ffmpeg refused the monochrome stream: {}",
899 String::from_utf8_lossy(&out.stderr)
900 );
901 assert_eq!(
902 out.stdout.len(),
903 width * height * frames,
904 "expected {frames} monochrome frames, ffmpeg said: {}",
905 String::from_utf8_lossy(&out.stderr)
906 );
907 out.stdout
908 }
909
910 /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples
911 /// are 2-byte little-endian, one full 16-bit range regardless of the
912 /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the
913 /// bit depth). The 8-bit helper above stays untouched -- every existing
914 /// gate depends on it.
915 ///
916 /// lane-av1oracledepth: the stream's OWN sequence header must parse
917 /// 10-bit, the same way `assert_12bit_sequence_header` covers the 12-bit
918 /// gates. A wrong-depth stream handed here would otherwise CONVERT
919 /// silently -- ffmpeg re-scales 8-bit samples into the 16-bit container
920 /// and sizes no plane differently -- so a gate could compare ffmpeg's
921 /// rescaled 8-bit planes against our 10-bit decode and read exact (class
922 /// `helper-assumes-the-shape-the-gate-name-implies`, the depth axis).
923 pub(super) fn ffmpeg_decode_sequence_10bit(
924 stream: &[u8],
925 width: usize,
926 height: usize,
927 frames: usize,
928 ) -> Vec<Pic> {
929 assert_420_oracle_stream(
930 stream,
931 "ffmpeg_decode_sequence_10bit",
932 "ffmpeg_decode_sequence_422_depth(.., 10, \"yuv422p10le\") (4:2:2); \
933 ffmpeg_decode_sequence_444_depth(.., 10, \"yuv444p10le\") (4:4:4)",
934 );
935 assert_eq!(
936 stream_bit_depth(stream, "ffmpeg_decode_sequence_10bit"),
937 10,
938 "ffmpeg_decode_sequence_10bit REFUSED a stream whose own sequence header is not \
939 10-bit -- ffmpeg converts it to yuv420p10le instead of failing, and the comparison \
940 would read a converted reference"
941 );
942 let out = run_with_stdin(
943 Command::new(ffmpeg_path()).args([
944 "-v",
945 "error",
946 "-f",
947 "obu",
948 "-i",
949 "-",
950 "-f",
951 "rawvideo",
952 "-pix_fmt",
953 "yuv420p10le",
954 "-",
955 ]),
956 stream,
957 );
958 assert!(
959 out.status.success(),
960 "ffmpeg refused the stream: {}",
961 String::from_utf8_lossy(&out.stderr)
962 );
963 let (luma, chroma) = (width * height, width * height / 4);
964 let frame_samples = luma + 2 * chroma;
965 let frame_bytes = frame_samples * 2;
966 assert_eq!(
967 out.stdout.len(),
968 frame_bytes * frames,
969 "{}",
970 frame_count_diagnosis(
971 "4:2:0 10-bit",
972 frames,
973 width,
974 height,
975 frame_bytes,
976 out.stdout.len(),
977 &out.stderr
978 )
979 );
980 fn le16(bytes: &[u8]) -> Vec<u16> {
981 bytes
982 .as_chunks::<2>().0.iter()
983 .map(|c| u16::from_le_bytes([c[0], c[1]]))
984 .collect()
985 }
986 (0..frames)
987 .map(|i| {
988 let base = i * frame_bytes;
989 Pic {
990 width,
991 height,
992 y: le16(&out.stdout[base..base + luma * 2]),
993 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
994 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
995 }
996 })
997 .collect()
998 }
999
1000 /// Builds a `gradients` lavfi source string with colours derived from
1001 /// `seed`, not left to the filter's own default.
1002 ///
1003 /// Measured (lane-fixdet r1): ffmpeg's `gradients` source IGNORES its
1004 /// `seed=` parameter for colour selection -- five encodes of an
1005 /// identical command line (same `seed=`, same everything) produced five
1006 /// different fixtures, because the unset `c0..c9` stops are randomized
1007 /// from something other than that seed. Every one of this file's ~20
1008 /// gate fixtures built a `gradients` source this way, so none of them
1009 /// had a reproducible input: a pin captured from one run could not be
1010 /// regenerated, and "attempt N failed" was as likely to be a different
1011 /// fixture as a different decode outcome.
1012 ///
1013 /// Freezing the colours outright (as the earliest four gates below do,
1014 /// hand-picking `c0=red:c1=blue:c2=green`) fixes reproducibility but
1015 /// throws away the per-attempt content variety the sweep gates need to
1016 /// make features (OBMC, warp, wedge, ...) fire at all -- this repo's own
1017 /// `sampler-decorrelated-gate` class. So: derive `c0..c3` deterministically
1018 /// FROM the seed with a plain integer hash, and keep passing `seed=`
1019 /// itself too, so a future ffmpeg that actually honours it only adds
1020 /// more variety, never removes the determinism this buys.
1021 pub(super) fn gradients_source(seed: u32, width: usize, height: usize, tail: &str) -> String {
1022 fn hash_color(seed: u32, salt: u32) -> String {
1023 let h = seed
1024 .wrapping_mul(2_654_435_761)
1025 .wrapping_add(salt.wrapping_mul(0x9E37_79B9))
1026 ^ (seed.rotate_left(13));
1027 format!("0x{:06x}", h & 0x00ff_ffff)
1028 }
1029 let (c0, c1, c2, c3) = (
1030 hash_color(seed, 0),
1031 hash_color(seed, 1),
1032 hash_color(seed, 2),
1033 hash_color(seed, 3),
1034 );
1035 format!(
1036 "gradients=size={width}x{height}:c0={c0}:c1={c1}:c2={c2}:c3={c3}:seed={seed}:{tail}"
1037 )
1038 }
1039
1040 /// Encodes a real libaom-av1 stream (via ffmpeg's own encoder, not this
1041 /// crate's) with the same reduced-partition flags lane-av1adst's r6
1042 /// probe found still select `ADST_ADST`/`ADST_DCT`/`DCT_ADST` on
1043 /// gradient content (TX_SET_INTRA_2), and decodes it with
1044 /// [`decode_stream`] -- lifting the round-2 refusal is only real if it
1045 /// gets past an encoder this crate never wrote a byte of.
1046 pub(super) fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {
1047 libaom_encode_with(lavfi, width, height, crf, &[])
1048 }
1049
1050 /// As [`libaom_encode`], with extra encoder args appended -- used to pin
1051 /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8`
1052 /// RD search is not otherwise stable run-to-run on this box, and lavfi
1053 /// `gradients` needs its own `seed=` for the same reason) and to gate
1054 /// individual feature flags (`-enable-cdef 0`) a given fixture needs off.
1055 pub(super) fn libaom_encode_with(
1056 lavfi: &str,
1057 width: usize,
1058 height: usize,
1059 crf: u32,
1060 extra: &[&str],
1061 ) -> Option<Vec<u8>> {
1062 let mut args = vec![
1063 "-v",
1064 "error",
1065 "-f",
1066 "lavfi",
1067 "-i",
1068 lavfi,
1069 "-frames:v",
1070 "1",
1071 "-pix_fmt",
1072 "yuv420p",
1073 "-c:v",
1074 "libaom-av1",
1075 ];
1076 let crf_str = crf.to_string();
1077 args.extend(["-crf", &crf_str]);
1078 args.extend([
1079 "-cpu-used",
1080 "8",
1081 "-enable-rect-partitions",
1082 "0",
1083 "-enable-ab-partitions",
1084 "0",
1085 "-enable-1to4-partitions",
1086 "0",
1087 "-enable-angle-delta",
1088 "0",
1089 "-enable-cfl-intra",
1090 "0",
1091 ]);
1092 args.extend(extra.iter().copied());
1093 args.extend(["-f", "obu", "-"]);
1094 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1095 .args(&args)
1096 .stdin(Stdio::null())
1097 .stdout(Stdio::piped())
1098 .stderr(Stdio::piped()), None, |c| c.output())
1099 .expect("ffmpeg failed to run");
1100 if !out.status.success() {
1101 eprintln!(
1102 "ffmpeg refused to encode {lavfi} at {width}x{height}: {}",
1103 String::from_utf8_lossy(&out.stderr)
1104 );
1105 return None;
1106 }
1107 Some(out.stdout)
1108 }
1109
1110 /// As [`ffmpeg_decode_sequence`], for a 4:4:4 stream: chroma planes are
1111 /// FULL resolution (`yuv444p` rawvideo), the shape lane-av1-llinter's
1112 /// lossless profile-1 fixture codes.
1113 pub(super) fn ffmpeg_decode_sequence_444(
1114 stream: &[u8],
1115 width: usize,
1116 height: usize,
1117 frames: usize,
1118 ) -> Vec<Pic> {
1119 ffmpeg_decode_sequence_444_depth(stream, width, height, frames, 8, "yuv444p")
1120 }
1121
1122 /// lane-av1oracledepth: the depth-generic 4:4:4 oracle comparator -- the
1123 /// [`ffmpeg_decode_sequence_422_depth`] twin for full-resolution chroma.
1124 /// `yuv444p`, `yuv444p10le` or `yuv444p12le`, with the container width
1125 /// taken from `depth` itself (8 -> one byte per sample; 10/12 -> a 16-bit
1126 /// LE container on BOTH sides, so ours and ffmpeg's are directly
1127 /// comparable sample for sample and nothing narrows). Until this helper
1128 /// existed a 10/12-bit 4:4:4 gate had to fall back to the 8-bit
1129 /// `ffmpeg_decode_sequence_444`, which ffmpeg converts at `yuv444p`
1130 /// instead of refusing, or to a raw hand-rolled spawn (class
1131 /// `helper-assumes-the-shape-the-gate-name-implies`, the depth axis).
1132 ///
1133 /// Refused by SHAPE read from the stream's own sequence header, like its
1134 /// 4:2:0 siblings: `(0,0)` only, so a 4:2:2 or 4:2:0 stream handed here
1135 /// cannot have ffmpeg silently convert it.
1136 pub(super) fn ffmpeg_decode_sequence_444_depth(
1137 stream: &[u8],
1138 width: usize,
1139 height: usize,
1140 frames: usize,
1141 depth: u8,
1142 pix_fmt: &str,
1143 ) -> Vec<Pic> {
1144 assert!(
1145 matches!(depth, 8 | 10 | 12),
1146 "lane-av1oracledepth: ffmpeg_decode_sequence_444_depth takes 8, 10 or 12, got {depth}"
1147 );
1148 let (sx, sy) = stream_subsampling(stream, "ffmpeg_decode_sequence_444_depth");
1149 assert!(
1150 (sx, sy) == (0, 0),
1151 "ffmpeg_decode_sequence_444_depth REFUSED a ({sx},{sy}) stream: this helper asks \
1152 ffmpeg for a 4:4:4 pix_fmt, which CONVERTS the stream's real {} chroma instead of \
1153 failing, then slices full-resolution planes from converted bytes. \
1154 ffmpeg_decode_sequence_422_depth handles (1,0); ffmpeg_decode_sequence handles \
1155 (1,1).",
1156 chroma_shape(sx, sy)
1157 );
1158 assert_eq!(
1159 stream_bit_depth(stream, "ffmpeg_decode_sequence_444_depth"),
1160 depth,
1161 "ffmpeg_decode_sequence_444_depth REFUSED a stream whose own sequence header is \
1162 not {depth}-bit -- ffmpeg would convert it to {pix_fmt} instead of failing"
1163 );
1164 let out = run_with_stdin(
1165 Command::new(ffmpeg_path()).args([
1166 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-",
1167 ]),
1168 stream,
1169 );
1170 assert!(
1171 out.status.success(),
1172 "ffmpeg refused the 4:4:4 stream ({pix_fmt}): {}",
1173 String::from_utf8_lossy(&out.stderr)
1174 );
1175 let plane = width * height;
1176 let bps = if depth == 8 { 1 } else { 2 };
1177 let frame_bytes = 3 * plane * bps;
1178 assert_eq!(
1179 out.stdout.len(),
1180 frame_bytes * frames,
1181 "{}",
1182 frame_count_diagnosis(
1183 if depth == 8 {
1184 "4:4:4"
1185 } else {
1186 "4:4:4 high depth"
1187 },
1188 frames,
1189 width,
1190 height,
1191 frame_bytes,
1192 out.stdout.len(),
1193 &out.stderr
1194 )
1195 );
1196 (0..frames)
1197 .map(|i| {
1198 let base = i * frame_bytes;
1199 let samples = |off: usize| -> Vec<u16> {
1200 let slice = &out.stdout[base + off..base + off + plane * bps];
1201 if bps == 1 {
1202 slice.iter().map(|&v| u16::from(v)).collect()
1203 } else {
1204 slice
1205 .as_chunks::<2>().0.iter()
1206 .map(|c| u16::from_le_bytes([c[0], c[1]]))
1207 .collect()
1208 }
1209 };
1210 Pic {
1211 width,
1212 height,
1213 y: samples(0),
1214 u: samples(plane * bps),
1215 v: samples(2 * plane * bps),
1216 }
1217 })
1218 .collect()
1219 }
1220
1221 /// lane-av1422lift: as [`ffmpeg_decode_sequence`] (4:2:0 8-bit) and
1222 /// [`ffmpeg_decode_sequence_444`], for a 4:2:2 stream: `yuv422p`
1223 /// rawvideo, whose chroma planes are HALF WIDTH and FULL HEIGHT -- the
1224 /// `w/2 * h` shape the whole per-axis port exists to produce. A helper
1225 /// that computed the chroma span 4:2:0-style would make every 4:2:2
1226 /// gate compare half the oracle's bytes and pass, so the span is
1227 /// asserted against the byte count below, not assumed.
1228 pub(super) fn ffmpeg_decode_sequence_422(
1229 stream: &[u8],
1230 width: usize,
1231 height: usize,
1232 frames: usize,
1233 ) -> Vec<Pic> {
1234 ffmpeg_decode_sequence_422_depth(stream, width, height, frames, 8, "yuv422p")
1235 }
1236
1237 /// lane-av1422lift: the depth-generic 4:2:2 oracle comparator --
1238 /// `yuv422p`, `yuv422p10le` or `yuv422p12le`, with the container width
1239 /// taken from `depth` itself (8 -> one byte per sample; 10/12 -> a
1240 /// 16-bit LE container on BOTH sides, so ours and ffmpeg's are directly
1241 /// comparable sample for sample and nothing narrows).
1242 pub(super) fn ffmpeg_decode_sequence_422_depth(
1243 stream: &[u8],
1244 width: usize,
1245 height: usize,
1246 frames: usize,
1247 depth: u8,
1248 pix_fmt: &str,
1249 ) -> Vec<Pic> {
1250 assert!(
1251 matches!(depth, 8 | 10 | 12),
1252 "lane-av1422lift: ffmpeg_decode_sequence_422_depth takes 8, 10 or 12, got {depth}"
1253 );
1254 let out = run_with_stdin(
1255 Command::new("ffmpeg").args([
1256 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-",
1257 ]),
1258 stream,
1259 );
1260 assert!(
1261 out.status.success(),
1262 "ffmpeg refused the 4:2:2 stream ({pix_fmt}): {}",
1263 String::from_utf8_lossy(&out.stderr)
1264 );
1265 let (luma, chroma) = (width * height, width.div_ceil(2) * height);
1266 let bps = if depth == 8 { 1 } else { 2 };
1267 let frame_bytes = (luma + 2 * chroma) * bps;
1268 assert_eq!(
1269 out.stdout.len(),
1270 frame_bytes * frames,
1271 "{}",
1272 frame_count_diagnosis(
1273 "4:2:2",
1274 frames,
1275 width,
1276 height,
1277 frame_bytes,
1278 out.stdout.len(),
1279 &out.stderr
1280 )
1281 );
1282 (0..frames)
1283 .map(|i| {
1284 let base = i * frame_bytes;
1285 let samples = |off: usize, n: usize| -> Vec<u16> {
1286 let slice = &out.stdout[base + off..base + off + n * bps];
1287 if bps == 1 {
1288 slice.iter().map(|&v| u16::from(v)).collect()
1289 } else {
1290 slice
1291 .as_chunks::<2>().0.iter()
1292 .map(|c| u16::from_le_bytes([c[0], c[1]]))
1293 .collect()
1294 }
1295 };
1296 Pic {
1297 width,
1298 height,
1299 y: samples(0, luma),
1300 u: samples(luma * bps, chroma),
1301 v: samples((luma + chroma) * bps, chroma),
1302 }
1303 })
1304 .collect()
1305 }
1306
1307 /// lane-av1422lift: the shared body of every 4:2:2 exactness gate this
1308 /// lane adds, and the answer to "a byte-exact 4:2:2 gate can still be
1309 /// vacuous".
1310 ///
1311 /// Before lane-av1422census422 the per-plane coefficient-unit census was
1312 /// armed at `ss_x == 0 && ss_y == 0` only, so on a 4:2:2 stream
1313 /// `census_nonsub_units()` read `[0, 0, 0]` BY CONSTRUCTION -- a gate
1314 /// could have been green while the decode walked nothing at all. The
1315 /// census is now armed for `(ss_x == 0 || ss_y == 0)`, so the delta
1316 /// asserted here is a real measurement of the walk this stream caused:
1317 /// every plane must show a non-zero number of transform units AND of
1318 /// units that coded at least one coefficient.
1319 ///
1320 /// Four things are asserted per frame, in this order:
1321 ///
1322 /// 1. the decoded frame's dimensions, and that its chroma planes are
1323 /// `round_ss(w, 1) * round_ss(h, 0)` -- half width, FULL height. A
1324 /// decoder that kept 4:2:0 plane allocation while walking 4:2:2
1325 /// entropy would pass a per-sample compare against a 4:2:0-sized
1326 /// oracle; this is the shape assertion that closes that hole, and it
1327 /// is asserted against the DECODED frame, never against the gate's
1328 /// own name.
1329 /// 2. the depth, read out of the stream's own sequence header.
1330 /// 3. per-plane, per-frame byte-exactness against ffmpeg's rawvideo of
1331 /// the same bytes at the depth-correct pixel format. Frame N of ours
1332 /// against frame N of ffmpeg's: `decode_stream` returns DISPLAY order
1333 /// and so does ffmpeg's rawvideo muxer, so a hidden alt-ref does not
1334 /// shift the pairing (the decode-order-vs-display-order trap the
1335 /// out-of-process corpus comparator has to solve separately).
1336 /// 4. the census delta, asserted once for the whole stream rather than
1337 /// per frame, because the counters are cumulative per thread.
1338 ///
1339 /// `require_coded` is false ONLY for a cell whose identity IS that it
1340 /// codes nothing -- `422_allskip_2f.obu`, whose whole point is that
1341 /// the inter frame reads no residual and the pre-port decoder read
1342 /// PHANTOM units there. Demanding coded units on it would be
1343 /// demanding the defect; its caller asserts the all-skip property
1344 /// directly instead.
1345 pub(super) fn assert_422_stream_pixel_exact(
1346 name: &str,
1347 stream: &[u8],
1348 width: usize,
1349 height: usize,
1350 frames: usize,
1351 depth: u8,
1352 require_coded: bool,
1353 ) -> ([usize; 3], [usize; 3]) {
1354 let _gate_lock = lock_gate_counters();
1355 assert_eq!(
1356 stream_bit_depth(stream, name),
1357 depth,
1358 "{name}: the stream's OWN sequence header does not say {depth} bit"
1359 );
1360 let before = crate::decode::census_nonsub_units();
1361 let before_coded = crate::decode::census_nonsub_coded();
1362 let ours = decode_stream(stream)
1363 .unwrap_or_else(|e| panic!("{name}: decode_stream refused a real 4:2:2 stream: {e}"));
1364 assert_eq!(ours.len(), frames, "{name}: decoded frame count");
1365 for (i, f) in ours.iter().enumerate() {
1366 assert_eq!(
1367 (f.width, f.height),
1368 (width, height),
1369 "{name}: frame {i} dimensions"
1370 );
1371 assert_eq!(
1372 (f.u.len(), f.v.len()),
1373 (width.div_ceil(2) * height, width.div_ceil(2) * height),
1374 "{name}: frame {i} chroma planes are {}/{} samples -- 4:2:2 is HALF WIDTH and \
1375 FULL HEIGHT ({width}/2 x {height}); a quarter-height plane means the decode kept \
1376 a 4:2:0 allocation",
1377 f.u.len(),
1378 f.v.len()
1379 );
1380 }
1381 let pix_fmt = match depth {
1382 8 => "yuv422p",
1383 10 => "yuv422p10le",
1384 12 => "yuv422p12le",
1385 other => panic!("{name}: no ffmpeg pixel format mapped for depth {other}"),
1386 };
1387 let theirs =
1388 ffmpeg_decode_sequence_422_depth(stream, width, height, frames, depth, pix_fmt);
1389 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1390 for (plane, ours_plane, theirs_plane) in
1391 [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)]
1392 {
1393 assert_eq!(
1394 ours_plane.len(),
1395 theirs_plane.len(),
1396 "{name}: {plane} plane {i} is {} samples against ffmpeg's {} -- the 4:2:2 chroma \
1397 span is wrong on one of the two sides",
1398 ours_plane.len(),
1399 theirs_plane.len()
1400 );
1401 if let Some(bad) = ours_plane
1402 .iter()
1403 .zip(theirs_plane)
1404 .position(|(x, y)| x != y)
1405 {
1406 panic!(
1407 "{name}: {plane} differs from ffmpeg at frame {i} sample {bad} ({} vs {}; \
1408 {} of {} samples differ)",
1409 ours_plane[bad],
1410 theirs_plane[bad],
1411 ours_plane
1412 .iter()
1413 .zip(theirs_plane)
1414 .filter(|(x, y)| x != y)
1415 .count(),
1416 ours_plane.len()
1417 );
1418 }
1419 }
1420 }
1421 let units = crate::decode::census_nonsub_units();
1422 let coded = crate::decode::census_nonsub_coded();
1423 let delta: [usize; 3] = std::array::from_fn(|p| units[p] - before[p]);
1424 let coded_delta: [usize; 3] = std::array::from_fn(|p| coded[p] - before_coded[p]);
1425 for (p, plane) in ["luma", "U", "V"].into_iter().enumerate() {
1426 assert!(
1427 delta[p] > 0,
1428 "{name}: the {plane} plane read ZERO coefficient units across the whole stream -- \
1429 this byte-exact compare is vacuous with respect to 4:2:2 (class \
1430 gate-blind-to-feature)"
1431 );
1432 if require_coded {
1433 assert!(
1434 coded_delta[p] > 0,
1435 "{name}: the {plane} plane coded ZERO coefficient units across the whole \
1436 stream -- every unit took the all-zero early return, so no coefficient path \
1437 was exercised"
1438 );
1439 }
1440 }
1441 eprintln!(
1442 "{name}: byte-exact vs ffmpeg ({pix_fmt}, {frames} frames); census delta \
1443 units=[{}, {}, {}] coded=[{}, {}, {}]",
1444 delta[0], delta[1], delta[2], coded_delta[0], coded_delta[1], coded_delta[2]
1445 );
1446 (delta, coded_delta)
1447 }
1448
1449 /// `(subsampling_x, subsampling_y, bit_depth)` out of the stream's OWN
1450 /// sequence header. A gate that claims to exercise a subsampling-specific
1451 /// path must assert this from the parsed header, not from the recipe that
1452 /// produced the fixture: the recipe can drift (or a wrong `--pix_fmt`
1453 /// argument can silently produce a different subsampling) and every other
1454 /// assertion would then pass vacuously.
1455 pub(super) fn subsampled_header_shape(stream: &[u8], name: &str) -> (u8, u8, usize) {
1456 let mut parser = Av1Parser::new();
1457 let mut pos = 0usize;
1458 let mut shape = None;
1459 while pos < stream.len() {
1460 let obu = parser
1461 .parse_obu(&stream[pos..])
1462 .unwrap_or_else(|e| panic!("{name}: OBU does not parse: {e:?}"));
1463 if obu.total_size == 0 {
1464 break;
1465 }
1466 pos += obu.total_size;
1467 if let ObuKind::SequenceHeader(seq) = obu.kind {
1468 shape = Some((
1469 seq.color_config.subsampling_x,
1470 seq.color_config.subsampling_y,
1471 seq.color_config.bit_depth as usize,
1472 ));
1473 }
1474 }
1475 shape.unwrap_or_else(|| panic!("{name}: no sequence header parsed"))
1476 }
1477
1478 /// lane-av1gates444: the live 4:4:4 LOSSY cell the chroma-format sweep
1479 /// measured EXACT 4/4 and left unpinned. The recipe is the sweep's own
1480 /// §6.2 encode, reproduced LIVE against the oracle `aomenc` rather than
1481 /// from a pin, because the claim these three gates carry is a property
1482 /// of the *decoder* at a geometry, not of a blob:
1483 /// ```text
1484 /// ffmpeg -f lavfi -i "testsrc2=size=<W>x<H>:rate=25" -frames:v 4 \
1485 /// -pix_fmt yuv444p -f yuv4mpegpipe - | \
1486 /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=20 \
1487 /// --cpu-used=2 --threads=1 --row-mt=0 --lag-in-frames=0 \
1488 /// --kf-max-dist=100 --limit=4 --obu -o - -
1489 /// ```
1490 /// `rate=25` is load-bearing (testsrc2's pattern is time-parameterised)
1491 /// and `--limit=4` is the sweep's frame count: at `--limit=6` the same
1492 /// recipe emits 7674 / 11465 / 19121 bytes instead of the sweep's
1493 /// 5938 / 8945 / 15239, i.e. a different stream than the one measured.
1494 /// `--profile=1` is what makes the source 4:4:4 at all.
1495 ///
1496 /// Every assertion here is a non-vacuity assertion first and a pixel
1497 /// compare second. The frame count, the per-frame geometry and the
1498 /// FULL-RESOLUTION chroma plane length are asserted because a truncated
1499 /// or 4:2:0-shaped decode can pass a lenient compare; the
1500 /// `rect4_inter_own_chroma444_hits()` reach assert is there because the
1501 /// class these cells belong to is the 4:4:4-only own-chroma-extent route
1502 /// in [`decode_inter_block`]'s `around_c` (a 4:2:0 stream of the same
1503 /// content leaves it at 0), and a counter at 0 would mean the gate
1504 /// measured a different route than it names.
1505 /// The guard is [`have_aomenc`], which probes first and asserts LAST with
1506 /// the env escape: with `EC_AV1_REQUIRE_AOMENC` set, a missing oracle is
1507 /// a hard failure naming the path it looked for, and a batch run cannot
1508 /// report green off three skipped gates. With it unset the `None` below is
1509 /// a developer-only convenience for a checkout without an oracle -- it is
1510 /// the ONLY way this gate can return without measuring, and it announces
1511 /// itself on stderr naming the env var that would make it a failure.
1512 /// (It used to return an empty `Vec` that the caller turned into a silent
1513 /// early `return`: the same green, reached through a second exit nobody
1514 /// was reading.)
1515 pub(super) fn encode_444_lossy_live(name: &str, w: usize, h: usize) -> Option<Vec<u8>> {
1516 if !have_aomenc() {
1517 eprintln!(
1518 "SKIP {name}: no aomenc oracle at {} -- set EC_AV1_REQUIRE_AOMENC=1 to make this \
1519 a failure, or run scripts/build-aom-oracle.sh",
1520 aomenc_path().display()
1521 );
1522 return None;
1523 }
1524 let source = format!("testsrc2=size={w}x{h}:rate=25");
1525 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1526 .args([
1527 "-v",
1528 "error",
1529 "-f",
1530 "lavfi",
1531 "-i",
1532 &source,
1533 "-frames:v",
1534 "4",
1535 "-pix_fmt",
1536 "yuv444p",
1537 "-f",
1538 "yuv4mpegpipe",
1539 "-",
1540 ])
1541 .stdin(Stdio::null())
1542 .stdout(Stdio::piped())
1543 .stderr(Stdio::piped()), None, |c| c.output())
1544 .expect("ffmpeg failed to run");
1545 assert!(
1546 y4m.status.success(),
1547 "{name}: ffmpeg refused the {w}x{h} 4:4:4 source: {}",
1548 String::from_utf8_lossy(&y4m.stderr)
1549 );
1550 let out = run_with_stdin(
1551 Command::new(aomenc_path()).args([
1552 "--codec=av1",
1553 "--profile=1",
1554 "--passes=1",
1555 "--end-usage=q",
1556 "--cq-level=20",
1557 "--cpu-used=2",
1558 "--threads=1",
1559 "--row-mt=0",
1560 "--lag-in-frames=0",
1561 "--kf-max-dist=100",
1562 "--limit=4",
1563 "--obu",
1564 "-o",
1565 "-",
1566 "-",
1567 ]),
1568 &y4m.stdout,
1569 );
1570 assert!(
1571 out.status.success(),
1572 "{name}: aomenc refused the {w}x{h} 4:4:4 lossy recipe: {}",
1573 String::from_utf8_lossy(&out.stderr)
1574 );
1575 assert!(
1576 !out.stdout.is_empty(),
1577 "{name}: aomenc produced no OBU for {w}x{h} -- a zero-length stream would \
1578 decode to nothing and the compare below would compare nothing"
1579 );
1580 Some(out.stdout)
1581 }
1582
1583 /// lane-av1-loss64: the generator for the two gates below -- a deterministic
1584 /// 1-frame lossless superblock-128 aomenc stream of `testsrc2`. `extra`
1585 /// flags land last (aomenc keeps the LAST occurrence of a repeated flag).
1586 /// The recipe is the one lanes/av1rect14.report.md section 2 measured
1587 /// (`--lossless=1 --sb-size=128 --enable-1to4-partitions=1`); the
1588 /// `--min-partition-size` override is what steers the bottom superblock
1589 /// row's RD into overhanging 64x64 `NONE` blocks (the shape the first fix
1590 /// clips) or, at 8, keeps sub-8x8 partitions out of the second gate's
1591 /// stream so the whole frame is decodable.
1592 pub(super) fn lossless_sb128_testsrc2(width: usize, height: usize, extra: &[&str]) -> Vec<u8> {
1593 let mut ff = Command::new("ffmpeg");
1594 let out = crate::tool_cache::cached_output_io(ff
1595 .args(["-v", "error", "-f", "lavfi", "-i"])
1596 .arg(format!("testsrc2=s={width}x{height}:r=25"))
1597 .args([
1598 "-frames:v",
1599 "1",
1600 "-pix_fmt",
1601 "yuv420p",
1602 "-strict",
1603 "-1",
1604 "-f",
1605 "yuv4mpegpipe",
1606 "-",
1607 ])
1608 .stdin(Stdio::null())
1609 .stdout(Stdio::piped())
1610 .stderr(Stdio::piped()), None, |c| c.output())
1611 .expect("ffmpeg failed to run");
1612 assert!(
1613 out.status.success(),
1614 "ffmpeg failed for testsrc2 {width}x{height}"
1615 );
1616 let y4m = out.stdout;
1617 let out = run_with_stdin(
1618 Command::new(aomenc_path())
1619 .args(["--codec=av1", "--bit-depth=8", "--input-bit-depth=8"])
1620 .args([
1621 "--passes=1",
1622 "--cpu-used=0",
1623 "--lag-in-frames=0",
1624 "--kf-max-dist=1",
1625 "--limit=1",
1626 "--threads=1",
1627 "--tile-columns=0",
1628 "--lossless=1",
1629 "--sb-size=128",
1630 "--enable-1to4-partitions=1",
1631 ])
1632 .args(extra)
1633 .args(["--obu", "-o", "-", "-"]),
1634 &y4m,
1635 );
1636 assert!(
1637 out.status.success(),
1638 "aomenc failed: {}",
1639 String::from_utf8_lossy(&out.stderr)
1640 );
1641 out.stdout
1642 }
1643
1644 /// Path to a real `aomenc` build carrying the reference options this
1645 /// fixture needs (`--max-partition-size`, `--enable-tx-size-search`,
1646 /// `--loopfilter-control`) -- this box's `ffmpeg` links a libaom too old
1647 /// to expose `enable-tx-size-search`/`loopfilter-control` through its
1648 /// own `-aom-params` passthrough (probed live: "Cannot find aom
1649 /// option"), so [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]
1650 /// shells out to the standalone binary instead of ffmpeg's libaom-av1
1651 /// wrapper every other test here uses. `EC_AV1_AOMENC` overrides the
1652 /// default dev-build path; the test skips (not fails) when neither this
1653 /// nor `ffmpeg` is present.
1654 pub(super) fn aomenc_path() -> std::path::PathBuf {
1655 if let Some(p) = std::env::var_os("EC_AV1_AOMENC") {
1656 return std::path::PathBuf::from(p);
1657 }
1658 // The oracle used to live only under `/tmp`, which this box's tmpfs
1659 // guard reclaims -- when it did, all 20 aomenc gates below went
1660 // silently vacuous (SKIP, suite still green). The durable location
1661 // is provisioned by `scripts/build-aom-oracle.sh`; the `/tmp` path
1662 // stays last as a legacy fallback.
1663 let mut candidates = Vec::new();
1664 if let Some(home) = std::env::var_os("HOME") {
1665 candidates.push(std::path::PathBuf::from(&home).join(".cache/aom-oracle/build/aomenc"));
1666 }
1667 candidates.push("/tmp/libaom-src/build/encoder/aomenc".into());
1668 candidates
1669 .iter()
1670 .find(|p| p.is_file())
1671 .cloned()
1672 .unwrap_or_else(|| candidates.remove(0))
1673 }
1674
1675 /// Whether the aomenc oracle is present. Absence normally SKIPs (a
1676 /// checkout without the oracle should still run the rest of the suite),
1677 /// but `EC_AV1_REQUIRE_AOMENC=1` turns it into a hard failure so a batch
1678 /// run cannot report green off 20 skipped gates.
1679 /// Where a pinned stream lives. `fixtures/` is a symlink to a durable
1680 /// directory outside the repo, so a pin captured in one session is still
1681 /// there in the next; a session scratchpad is not (tmpfs reaps it, and
1682 /// four pins were silently dead because of that).
1683 pub(super) fn pin_dir() -> std::path::PathBuf {
1684 if let Some(p) = std::env::var_os("EC_AV1_PIN_DIR") {
1685 return std::path::PathBuf::from(p);
1686 }
1687 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1688 .join("../../fixtures")
1689 .canonicalize()
1690 .unwrap_or_else(|_| std::path::PathBuf::from("fixtures"))
1691 }
1692
1693 /// A COMMITTED pin: `crates/ec-av1/fixtures/<name>`, which travels in the
1694 /// tarball and is therefore present on every runner. `pin_dir()` resolves
1695 /// to the gitignored root `fixtures/`, so a pin written there is lost when
1696 /// the machine's scratchpad is reaped -- three gates sat at `rc=0` having
1697 /// tested nothing for exactly that reason (lane-av1pins). Falls back to
1698 /// `pin_dir()` so a locally re-captured stream still overrides.
1699 /// Read a pin that a gate cannot proceed without. A missing pin is a
1700 /// HARD failure naming the path and the generator, never a raw io panic
1701 /// and never a silent skip: `EC_AV1_GATE_DUMP_PIN` points the gate at a
1702 /// freshly captured stream, and a runner without the committed copy must
1703 /// say so instead of reporting green having tested nothing.
1704 pub(super) fn require_pin(path: &std::path::Path, name: &str) -> Vec<u8> {
1705 std::fs::read(path).unwrap_or_else(|e| {
1706 panic!(
1707 "no pinned bytes at {} ({e}) -- set EC_AV1_GATE_DUMP_PIN to a freshly \
1708 captured stream, or restore the committed copy at \
1709 crates/ec-av1/fixtures/{name}",
1710 path.display()
1711 )
1712 })
1713 }
1714
1715 pub(super) fn crate_pin(name: &str) -> std::path::PathBuf {
1716 let in_crate = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1717 .join("fixtures")
1718 .join(name);
1719 if in_crate.is_file() {
1720 in_crate
1721 } else {
1722 pin_dir().join(name)
1723 }
1724 }
1725
1726 pub(super) fn have_aomenc() -> bool {
1727 let present = aomenc_path().is_file();
1728 assert!(
1729 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
1730 "EC_AV1_REQUIRE_AOMENC is set but no aomenc at {} -- run scripts/build-aom-oracle.sh",
1731 aomenc_path().display()
1732 );
1733 present
1734 }
1735
1736 /// lane-av1oracleskip: the probe for the ORACLE COMPARER, in the same
1737 /// shape as [`have_ffmpeg`] -- probe first, then `assert!` LAST, with the
1738 /// env escape -- and it prints its own SKIP so a caller cannot skip the
1739 /// compare silently.
1740 ///
1741 /// Why this exists: thirteen gates wrapped their oracle arm in a bare
1742 /// `if aomdec_path().is_file()`, and that shape had NO env escape at all.
1743 /// An oracle build with `aomenc` but no `aomdec` beside it (or an
1744 /// `EC_AV1_AOMDEC` override pointing at a moved path) made the gate
1745 /// encode, decode, assert its geometry and its counters, and then quietly
1746 /// never compare -- green having measured nothing, with no line in the
1747 /// output to notice. Nine of the thirteen printed a SKIP in an `else` and
1748 /// four printed nothing at all; both are the same defect, and both are
1749 /// closed by one probe.
1750 ///
1751 /// With `EC_AV1_REQUIRE_AOMENC` (or the aomdec-specific
1752 /// `EC_AV1_REQUIRE_AOMDEC`) set, the absence is a HARD failure naming the
1753 /// path that was looked for -- that is the batch-run guarantee, and it is
1754 /// what the bare `is_file()` could not give. With it unset the SKIP below
1755 /// is printed and the gate still passes: that remains a developer-only
1756 /// convenience for a checkout without an oracle, never evidence.
1757 pub(super) fn aomdec_available(name: &str) -> bool {
1758 let present = aomdec_path().is_file();
1759 let require = std::env::var_os("EC_AV1_REQUIRE_AOMDEC").is_some()
1760 || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_some();
1761 assert!(
1762 present || !require,
1763 "{name}: no oracle aomdec at {} -- the pixel compare this gate exists for would be \
1764 skipped, and EC_AV1_REQUIRE_AOMDEC/EC_AV1_REQUIRE_AOMENC is set. Build the oracle \
1765 with scripts/build-aom-oracle.sh, or point EC_AV1_AOMDEC at a real aomdec.",
1766 aomdec_path().display()
1767 );
1768 if !present {
1769 eprintln!(
1770 "SKIP {name}: no oracle aomdec at {} -- the pixel compare is NOT running (set \
1771 EC_AV1_REQUIRE_AOMDEC=1 to make this a failure)",
1772 aomdec_path().display()
1773 );
1774 }
1775 present
1776 }
1777
1778 // lane-av1cmpaudit2: this thread's oracle override, set by
1779 // `set_oracle_path` and consulted by `aomdec_path` ahead of the env var.
1780 //
1781 // It is thread-local for the same reason `FINAL_DUMP_PREFIX` is: the
1782 // control test `every_oracle_comparator_reds_on_a_one_byte_wrong_oracle`
1783 // has to hand the helpers a DELIBERATELY WRONG oracle, and a
1784 // process-global `std::env::set_var` could not do that safely -- the
1785 // crate forbids `unsafe_code`, and even where it did not, one test's
1786 // tampered oracle would leak into every sibling test's comparison
1787 // running on another thread. A thread-local override confines the wrong
1788 // oracle to the one thread that asked for it.
1789 thread_local! {
1790 static ORACLE_PATH: std::cell::RefCell<Option<std::path::PathBuf>> =
1791 const { std::cell::RefCell::new(None) };
1792 }
1793
1794 /// Points this thread's oracle helpers at `path`. `None` restores the
1795 /// real `aomdec`.
1796 pub(super) fn set_oracle_path(path: Option<std::path::PathBuf>) {
1797 ORACLE_PATH.with(|c| *c.borrow_mut() = path);
1798 }
1799
1800 // lane-film10fix: this thread's ffmpeg override, set by
1801 // `set_ffmpeg_path` and consulted by `ffmpeg_path` ahead of the bare
1802 // name. Same shape and same reason as `ORACLE_PATH` above: the control
1803 // test `every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg` has
1804 // to hand the `ffmpeg_decode_sequence*` helpers a DELIBERATELY WRONG
1805 // reference, and a process-global PATH edit would leak that wrong
1806 // reference into every sibling test decoding on another thread. The
1807 // crate forbids `unsafe_code`, so `std::env::set_var` is not available
1808 // either; a thread-local confines the tamper to the one thread.
1809 thread_local! {
1810 static FFMPEG_PATH: std::cell::RefCell<Option<std::path::PathBuf>> =
1811 const { std::cell::RefCell::new(None) };
1812 }
1813
1814 /// Points this thread's `ffmpeg_decode_sequence*` helpers at `path`.
1815 /// `None` restores the real `ffmpeg` on PATH.
1816 pub(super) fn set_ffmpeg_path(path: Option<std::path::PathBuf>) {
1817 FFMPEG_PATH.with(|c| *c.borrow_mut() = path);
1818 }
1819
1820 /// The `ffmpeg` every reference helper in this module spawns.
1821 pub(super) fn ffmpeg_path() -> std::path::PathBuf {
1822 if let Some(p) = FFMPEG_PATH.with(|c| c.borrow().clone()) {
1823 return p;
1824 }
1825 std::path::PathBuf::from("ffmpeg")
1826 }
1827
1828 /// The instrumented `aomdec` beside the `aomenc` oracle
1829 /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`).
1830 pub(super) fn aomdec_path() -> std::path::PathBuf {
1831 if let Some(p) = ORACLE_PATH.with(|c| c.borrow().clone()) {
1832 return p;
1833 }
1834 if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") {
1835 return std::path::PathBuf::from(p);
1836 }
1837 aomenc_path().with_file_name("aomdec")
1838 }
1839
1840 /// Decodes `stream` with both this decoder and the instrumented oracle
1841 /// `aomdec`, and compares EVERY decoded frame in DECODE order --
1842 /// including the hidden (`show_frame == 0`) alt-ref frames no other gate
1843 /// in this repo can see, because `decode_stream` only pushes shown
1844 /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames
1845 /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces
1846 /// only as drift on some later shown frame, if at all).
1847 ///
1848 /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it
1849 /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in
1850 /// `decode_stream`, the oracle's in rung 12 of
1851 /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as
1852 /// u16 LE. Returns `(frames_decoded, hidden_frames)`.
1853 pub(super) fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) {
1854 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
1855 let _ = std::fs::remove_dir_all(&dir);
1856 std::fs::create_dir_all(&dir).expect("scratch dir");
1857 let obu = dir.join("in.obu");
1858 std::fs::write(&obu, stream).expect("writing the stream");
1859 let aom_prefix = dir.join("aom");
1860 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
1861 .args(["--codec=av1", "-o"])
1862 .arg(dir.join("out.y4m"))
1863 .arg(&obu)
1864 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
1865 .stdin(Stdio::null())
1866 .stdout(Stdio::piped())
1867 .stderr(Stdio::piped()), None, |c| c.output())
1868 .expect("aomdec failed to run");
1869 assert!(
1870 out.status.success(),
1871 "{name}: the oracle aomdec refused the stream: {}",
1872 String::from_utf8_lossy(&out.stderr)
1873 );
1874 let count_dumps = |prefix: &std::path::Path| -> usize {
1875 let mut n = 0usize;
1876 while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() {
1877 n += 1;
1878 }
1879 n
1880 };
1881 let oracle_frames = count_dumps(&aom_prefix);
1882 assert!(
1883 oracle_frames > 0,
1884 "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \
1885 scripts/instrument-aom-oracle.sh is missing from {}",
1886 aomdec_path().display()
1887 );
1888 let ours_prefix = dir.join("ours");
1889 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
1890 let decoded = decode_stream(stream);
1891 set_final_dump_prefix(None);
1892 let shown = decoded
1893 .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}"))
1894 .len();
1895 let our_frames = count_dumps(&ours_prefix);
1896 assert_eq!(
1897 our_frames, oracle_frames,
1898 "{name}: decoded {our_frames} frames in decode order, the oracle decoded \
1899 {oracle_frames}"
1900 );
1901 for i in 0..oracle_frames {
1902 let want =
1903 std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
1904 let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
1905 assert_eq!(
1906 got.len(),
1907 want.len(),
1908 "{name}: decode-order frame {i} is {} bytes, the oracle's is {}",
1909 got.len(),
1910 want.len()
1911 );
1912 if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) {
1913 let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count();
1914 panic!(
1915 "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \
1916 hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \
1917 bytes differ -- stream pinned at {}",
1918 oracle_frames - shown,
1919 got[at],
1920 want[at],
1921 obu.display()
1922 );
1923 }
1924 }
1925 let hidden = oracle_frames - shown;
1926 let _ = std::fs::remove_dir_all(&dir);
1927 (oracle_frames, hidden)
1928 }
1929
1930 /// lane-av1422anom: a COUNTING oracle comparison.
1931 ///
1932 /// [`assert_rawvideo_matches`] is the right tool for "these must be equal"
1933 /// and the wrong tool for a lane that has to classify many cells: it
1934 /// panics on the first differing byte, so it answers one cell per process
1935 /// and cannot report a magnitude. This returns the count instead.
1936 ///
1937 /// It exists because the previous lane's per-cell counter was tautological:
1938 /// it packed our own decoded samples into `ours` and then compared `ours`
1939 /// against the same samples, never touching the oracle's bytes, so it
1940 /// reported "0 wrong" on every cell including one that differs from
1941 /// `aomdec` in 1612 samples. [`the_counting_oracle_diff_reports_a_real_difference`]
1942 /// below is the test that keeps that mistake from recurring.
1943 ///
1944 /// Returns `(wrong_y, wrong_u, wrong_v, frames_total, frames_exact)`, or
1945 /// `None` when the two sides are not byte-comparable at all (a size
1946 /// mismatch, which is a different failure and must not read as "exact").
1947 /// `flip` flips ONE bit of the ORACLE's own bytes before comparing, so
1948 /// [`the_counting_oracle_diff_detects_one_flipped_oracle_byte`] can prove
1949 /// the comparison still reads the oracle on a stream that is now exact.
1950 pub(super) fn count_rawvideo_diffs(
1951 stream: &[u8],
1952 name: &str,
1953 flip: Option<usize>,
1954 ) -> Option<(usize, usize, usize, usize, usize)> {
1955 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
1956 let _ = std::fs::remove_dir_all(&dir);
1957 std::fs::create_dir_all(&dir).expect("scratch dir");
1958 let obu = dir.join("in.obu");
1959 std::fs::write(&obu, stream).expect("writing the stream");
1960 let raw = dir.join("aomdec.raw");
1961 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
1962 .args(["--codec=av1", "--rawvideo", "-o"])
1963 .arg(&raw)
1964 .arg(&obu)
1965 .stdin(Stdio::null())
1966 .stdout(Stdio::piped())
1967 .stderr(Stdio::piped()), None, |c| c.output())
1968 .expect("aomdec failed to run");
1969 assert!(
1970 out.status.success(),
1971 "{name}: the oracle aomdec refused the stream: {}",
1972 String::from_utf8_lossy(&out.stderr)
1973 );
1974 let mut want = std::fs::read(&raw).expect("aomdec rawvideo output");
1975 if let Some(i) = flip {
1976 assert!(
1977 i < want.len(),
1978 "{name}: flip index {i} is past the oracle's {} bytes",
1979 want.len()
1980 );
1981 want[i] ^= 0x01;
1982 }
1983 let _ = std::fs::remove_dir_all(&dir);
1984 let bit_depth = stream_bit_depth(stream, name);
1985 let decoded = decode_stream(stream).expect("decode for comparison");
1986 let ours = pack_rawvideo(&decoded, bit_depth, name);
1987 if ours.len() != want.len() {
1988 return None;
1989 }
1990 let bpp = if bit_depth == 8 { 1 } else { 2 };
1991 // lane-av1cmpframe: the plane split is PER FRAME and comes from each
1992 // decoded frame's OWN plane lengths -- never from a formula, and
1993 // never from the first picture.
1994 //
1995 // The first-picture form was wrong on every multi-frame stream: it
1996 // compared a byte index against frame 0's thresholds forever, so
1997 // every sample after frame 0's luma was attributed to the LAST
1998 // plane. On `420_oddheight_320x236` (16 frames of 320x236
1999 // 4:2:0, whose frame is 113 280 bytes and whose V plane therefore
2000 // holds 302 080 bytes in total) it reported `wrong_v = 330 673` --
2001 // more wrong V bytes than exist. The per-frame byte totals and the
2002 // frame-exact count were sound; only the per-plane attribution was
2003 // not, and a wrong attribution is the one thing a per-plane report
2004 // is read for.
2005 //
2006 // `pack_rawvideo` already lays the bytes out per frame from the same
2007 // plane lengths, so this table is exactly the layout it produced.
2008 let mut spans: Vec<[usize; 4]> = Vec::with_capacity(decoded.len());
2009 let mut off = 0usize;
2010 for f in &decoded {
2011 let (y, u, v) = (f.y.len() * bpp, f.u.len() * bpp, f.v.len() * bpp);
2012 spans.push([off, off + y, off + y + u, off + y + u + v]);
2013 off += y + u + v;
2014 }
2015 assert_eq!(
2016 off,
2017 ours.len(),
2018 "{name}: the per-frame plane table covers {off} bytes but the packed output is {}",
2019 ours.len()
2020 );
2021 let mut wrong = [0usize; 3];
2022 let mut frame = 0usize;
2023 for (i, (&a, &b)) in ours.iter().zip(&want).enumerate() {
2024 while frame + 1 < spans.len() && i >= spans[frame][3] {
2025 frame += 1;
2026 }
2027 if a == b {
2028 continue;
2029 }
2030 let s = spans[frame];
2031 let pi = if i < s[1] {
2032 0
2033 } else if i < s[2] {
2034 1
2035 } else {
2036 2
2037 };
2038 wrong[pi] += 1;
2039 }
2040 let frames = decoded.len();
2041 let exact = spans
2042 .iter()
2043 .filter(|s| ours[s[0]..s[3]] == want[s[0]..s[3]])
2044 .count();
2045 Some((wrong[0], wrong[1], wrong[2], frames, exact))
2046 }
2047
2048 /// lane-hidden r2: the `--arnr-maxframes=0` SECOND ARM of an existing
2049 /// gate -- the gate's own recipe is never changed, this re-encodes the
2050 /// same fixture with libaom's temporal alt-ref filter switched off and
2051 /// runs [`decode_all_frames_vs_oracle`] on the result. Measured: with
2052 /// the filter at its default EVERY alt-ref recipe in this file emits
2053 /// ZERO hidden frames (the candidates are filtered away), so the
2054 /// hidden-frame compare on the gate's own stream is vacuous; this arm
2055 /// is what actually puts `show_frame == 0` frames on the wire.
2056 ///
2057 /// Runs at most once per gate name per process (the loop gates sweep
2058 /// dozens of attempts and each arm costs a full encode + two decodes).
2059 /// A stream this decoder refuses BY NAME skips the arm -- the arm is
2060 /// about hidden frames, not about that capability gap -- while a pixel
2061 /// mismatch is a hard failure raised inside the compare.
2062 pub(super) fn hidden_arnr_arm(name: &str, y4m: &[u8], args: &[&str]) -> Option<(usize, usize)> {
2063 static ARMED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
2064 std::sync::OnceLock::new();
2065 if !ARMED
2066 .get_or_init(Default::default)
2067 .lock()
2068 .unwrap()
2069 .insert(name.to_string())
2070 {
2071 return None;
2072 }
2073 let mut arm: Vec<&str> = vec!["--arnr-maxframes=0"];
2074 arm.extend_from_slice(args);
2075 let out = run_with_stdin(Command::new(aomenc_path()).args(&arm), y4m);
2076 assert!(
2077 out.status.success(),
2078 "{name} HIDDEN-ARM: aomenc refused its own recipe plus --arnr-maxframes=0: {}",
2079 String::from_utf8_lossy(&out.stderr)
2080 );
2081 let stream = out.stdout;
2082 match decode_stream(&stream) {
2083 Err(e) => {
2084 let msg = e.to_string();
2085 assert!(
2086 msg.contains("unsupported"),
2087 "{name} HIDDEN-ARM failed outright: {msg}"
2088 );
2089 eprintln!("{name} HIDDEN-ARM: skipped on a named refusal: {msg}");
2090 None
2091 }
2092 Ok(_) => Some(decode_all_frames_vs_oracle(
2093 &stream,
2094 &format!("{name}-arnr0"),
2095 )),
2096 }
2097 }
2098
2099 /// lane-av1toolgates: the gate-level WITNESS, summed over the arms that
2100 /// decoded AND compared. It cannot be asserted per arm: the cq20 /
2101 /// tx-size-search=1 arm reaches a rect transform through the var-tx
2102 /// search on a SQUARE block (a nonzero rect coefficient count with zero
2103 /// rect partitions read -- the purest form of what `--enable-rect-tx`
2104 /// buys), while the rect PARTITION only shows up on the
2105 /// tx-size-search=0 arm. Either fact alone would let a stream through on
2106 /// which the tool was allowed and unused, which is the defect this
2107 /// coverage entry was written for; together they are the parsed-shape
2108 /// evidence the entry asked for.
2109 #[track_caller]
2110 pub(super) fn assert_rect_tx_witness(name: &str, parts: usize, tus: usize) {
2111 assert!(
2112 parts > 0,
2113 "{name}: no PARTITION_HORZ/PARTITION_VERT symbol was read on any pixel-exact decode \
2114 -- the parsed partition tree never yielded a rect leaf, so `--enable-rect-tx=1` \
2115 was allowed and unused"
2116 );
2117 assert!(
2118 tus > 0,
2119 "{name}: no rectangular transform unit coded coefficients through read_coeffs_rect \
2120 ({parts} rect partitions read) -- the rect coefficient path was never taken"
2121 );
2122 }
2123
2124 /// lane-t900 r31: builds one `--tune-content=screen --enable-intrabc=1`
2125 /// key frame, 256x192 8-bit, from a deterministic lavfi source. `tiled`
2126 /// renders a 2x2 tiling of a 128x96 pattern -- exact spatial repetition,
2127 /// the content intra block copy exists for; `square_only` turns the rect
2128 /// and 1:4 partitions off so an intrabc block lands on a SQUARE block
2129 /// instead of stopping on the rect-strip intrabc refusal first.
2130 pub(super) fn screen_intrabc_stream(
2131 src: &str,
2132 cq: &str,
2133 txs: &str,
2134 tiled: bool,
2135 square_only: bool,
2136 ) -> Vec<u8> {
2137 screen_intrabc_stream_with(src, cq, txs, tiled, square_only, &[])
2138 }
2139
2140 /// [`screen_intrabc_stream`] with per-arm flags appended AFTER the base
2141 /// recipe -- aomenc keeps the LAST occurrence of a repeated flag, so an
2142 /// arm can override `--sb-size` / `--min-partition-size` here.
2143 pub(super) fn screen_intrabc_stream_with(
2144 src: &str,
2145 cq: &str,
2146 txs: &str,
2147 tiled: bool,
2148 square_only: bool,
2149 extra: &[&str],
2150 ) -> Vec<u8> {
2151 screen_intrabc_stream_at_depth(src, cq, txs, tiled, square_only, 8, extra)
2152 }
2153
2154 /// [`screen_intrabc_stream_with`] at an explicit bit depth (8 or 10): the
2155 /// lavfi source is rendered straight to that depth's yuv4mpegpipe pixel
2156 /// format and aomenc is told to encode at the matching
2157 /// `--bit-depth`/`--input-bit-depth`, so a 10-bit arm produces a genuine
2158 /// high-bit-depth stream rather than an 8-bit one in disguise.
2159 pub(super) fn screen_intrabc_stream_at_depth(
2160 src: &str,
2161 cq: &str,
2162 txs: &str,
2163 tiled: bool,
2164 square_only: bool,
2165 depth: usize,
2166 extra: &[&str],
2167 ) -> Vec<u8> {
2168 // lane-av1screen12: depth 12 joins 8 and 10. The SAME recipe (`-vf
2169 // tile=2x2` over `smptebars=size=128x96:rate=25`,
2170 // `--tune-content=screen --enable-intrabc=1`, cq30,
2171 // `--enable-tx-size-search=0`) that keeps `allow_intrabc` at 8 and 10
2172 // bits keeps it at 12 bits too -- measured, and pinned by
2173 // `a_real_aomenc_12bit_intrabc_screen_stream_decodes_pixel_exact`.
2174 // That is why "neither palette nor intrabc has a 12-bit witness" was
2175 // false: the intrabc half WAS producible, `--tune-content=screen`
2176 // alone just is not what decides the frame-header bit (libaom's
2177 // content detector is).
2178 assert!(
2179 depth == 8 || depth == 10 || depth == 12,
2180 "unsupported bit depth {depth}"
2181 );
2182 // `if depth == 10` is SPELLED, not matched, because
2183 // `gate_coverage::covers_both_depths` recognises this two-depth
2184 // helper by that literal (the lane-defon/reelckf blind spot with
2185 // `depth` spelled instead of `bit_depth`).
2186 let pix_fmt = if depth == 10 {
2187 "yuv420p10le"
2188 } else if depth == 12 {
2189 "yuv420p12le"
2190 } else {
2191 "yuv420p"
2192 };
2193 let mut ff = Command::new("ffmpeg");
2194 ff.args(["-v", "error", "-f", "lavfi", "-i", src, "-t", "0.2"]);
2195 if tiled {
2196 ff.args(["-vf", "tile=2x2"]);
2197 }
2198 let out = crate::tool_cache::cached_output_io(ff
2199 .args([
2200 "-pix_fmt",
2201 pix_fmt,
2202 "-strict",
2203 "-1",
2204 "-f",
2205 "yuv4mpegpipe",
2206 "-",
2207 ])
2208 .stdin(Stdio::null())
2209 .stdout(Stdio::piped())
2210 .stderr(Stdio::piped()), None, |c| c.output())
2211 .expect("ffmpeg failed to run");
2212 assert!(out.status.success(), "ffmpeg failed for {src}");
2213 let y4m = out.stdout;
2214 let enc = run_with_stdin(
2215 Command::new(aomenc_path())
2216 .args(["--codec=av1"])
2217 .args([
2218 format!("--bit-depth={depth}"),
2219 format!("--input-bit-depth={depth}"),
2220 ])
2221 .args([
2222 "--passes=1",
2223 "--end-usage=q",
2224 "--cpu-used=0",
2225 "--lag-in-frames=0",
2226 "--kf-max-dist=1",
2227 "--limit=1",
2228 "--threads=1",
2229 "--tile-columns=0",
2230 "--min-partition-size=8",
2231 "--max-partition-size=32",
2232 "--sb-size=64",
2233 "--tune-content=screen",
2234 "--enable-intrabc=1",
2235 "--enable-palette=0",
2236 ])
2237 .args([
2238 format!("--cq-level={cq}"),
2239 format!("--enable-tx-size-search={txs}"),
2240 ])
2241 // aomenc keeps the LAST occurrence of a repeated flag.
2242 .args(if square_only {
2243 &["--enable-rect-partitions=0", "--enable-1to4-partitions=0"][..]
2244 } else {
2245 &[][..]
2246 })
2247 .args(extra)
2248 .args(["--obu", "-o", "-", "-"]),
2249 &y4m,
2250 );
2251 assert!(
2252 enc.status.success(),
2253 "aomenc refused {src} cq={cq}: {}",
2254 String::from_utf8_lossy(&enc.stderr)
2255 );
2256 enc.stdout
2257 }
2258
2259 /// The sequence header's `use_128x128_superblock`, and how many frames of
2260 /// `stream` keep `allow_intrabc` -- the two bits the refusal "intrabc
2261 /// under a 128x128 superblock" is the conjunction of, read out of the
2262 /// headers rather than assumed from the flags handed to the encoder.
2263 pub(super) fn sb128_and_intrabc_frames(stream: &[u8]) -> (bool, u32) {
2264 let mut parser = Av1Parser::new();
2265 let mut pos = 0usize;
2266 let (mut sb128, mut intrabc) = (false, 0u32);
2267 while pos < stream.len() {
2268 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
2269 break;
2270 };
2271 pos += obu.total_size.max(1);
2272 if let Some(seq) = parser.sequence_header() {
2273 sb128 = seq.use_128x128_superblock;
2274 }
2275 let header = match &obu.kind {
2276 ObuKind::Frame(h, _) => Some(&**h),
2277 ObuKind::FrameHeader(h) => Some(&**h),
2278 _ => None,
2279 };
2280 if header.is_some_and(|h| h.allow_intrabc) {
2281 intrabc += 1;
2282 }
2283 }
2284 (sb128, intrabc)
2285 }
2286
2287 /// How many frames of `stream` carry `tx_mode == Select`, and how many of
2288 /// those also keep `allow_intrabc` -- the frame-level premise of the
2289 /// refusal "an intrabc block under TxMode::Select", read out of the
2290 /// headers rather than assumed from the flags handed to the encoder
2291 /// (libaom clears `allow_intrabc` again when no block picked it,
2292 /// encodeframe.c:2336).
2293 pub(super) fn tx_select_and_intrabc_frames(stream: &[u8]) -> (u32, u32) {
2294 let (mut select, mut premise) = (0u32, 0u32);
2295 let mut p = Av1Parser::new();
2296 let mut pos = 0usize;
2297 while pos < stream.len() {
2298 let obu = p.parse_obu(&stream[pos..]).expect("parse");
2299 pos += obu.total_size;
2300 let header = match &obu.kind {
2301 ObuKind::Frame(h, _) => Some(&**h),
2302 ObuKind::FrameHeader(h) => Some(&**h),
2303 _ => None,
2304 };
2305 if let Some(h) = header
2306 && h.tx_mode == TxMode::Select {
2307 select += 1;
2308 if h.allow_intrabc {
2309 premise += 1;
2310 }
2311 }
2312 }
2313 (select, premise)
2314 }
2315
2316 // /// lane-hbd r5: a real `aomenc --bit-depth=10` stream, decoded through
2317 // /// this crate's own 10-bit planes (`Picture` widened to `u16` in an
2318 // /// earlier round) and checked pixel-exact against ffmpeg's own decode of
2319 // /// the identical bytes via [`ffmpeg_decode_sequence_10bit`]. Confirms
2320 // /// (hard-asserts, not just trusts) the sequence header this stream
2321 // /// actually parses to says `bit_depth == 10` before trusting any pixel
2322 // /// match -- a stream that silently fell back to 8-bit would still
2323 // /// "match" trivially.
2324 // -------------------------------------------------------------------
2325 // lane-av112bit: the 12-bit gate battery. The blanket refusal is lifted
2326 // for what these gates witness byte-exact against ffmpeg on real
2327 // `aomenc --bit-depth=12 --profile=2` streams: the full intra stack,
2328 // dequant/transforms at the 12-bit dequant tables, deblock, CDEF, loop
2329 // restoration (Wiener AND SGR), and translational subpel motion
2330 // compensation through the bit-depth-parameterised `round_0`/`round_1`
2331 // (libaom `convolve.h:81..86`). Everything else stays refused by name:
2332 // warp and screen content tools (palette/intrabc) at the frame level,
2333 // each with its own real-stream refusal gate below.
2334 // lane-av112bitc: compound joined the witnessed set (refusal gate became
2335 // the six-frame compound witness).
2336 // lane-av112bitg: film grain joined the witnessed set (refusal gate became
2337 // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
2338 // -------------------------------------------------------------------
2339 /// The 12-bit witness source, byte-identical to the lane's committed
2340 /// fixture recipe: 160x128 C420p12, a gradient + fine-texture base with a
2341 /// 24x20 box that travels 1.25 px/frame horizontally and 0.75 px/frame
2342 /// vertically with linear edge coverage -- sub-pixel true motion, so an
2343 /// inter frame over it cannot be coded whole-pel-only.
2344 pub(super) fn y4m_12bit_subpel_source(frames: usize) -> Vec<u8> {
2345 const W: usize = 160;
2346 const H: usize = 128;
2347 let cov = |a: f64, b: f64, i: i64| (b.min(i as f64 + 1.0) - a.max(i as f64)).max(0.0);
2348 let mut y4m = format!("YUV4MPEG2 W{W} H{H} F30:1 Ip A1:1 C420p12\n").into_bytes();
2349 for t in 0..frames {
2350 let (ax, ay) = (12.0 + 1.25 * t as f64, 10.0 + 0.75 * t as f64);
2351 let (bx, by) = (ax + 24.0, ay + 20.0);
2352 y4m.extend_from_slice(b"FRAME\n");
2353 for j in 0..H as i64 {
2354 for i in 0..W as i64 {
2355 let g = (i * 190) / W as i64 + (j * 150) / H as i64;
2356 let mut v = (g * 12
2357 + if (i * 5 + j * 3 + t as i64) % 7 < 3 {
2358 90
2359 } else {
2360 220
2361 }
2362 + if (60..110).contains(&i) && (70..110).contains(&j) {
2363 640
2364 } else {
2365 0
2366 }) as f64;
2367 let c = cov(ax, bx, i) * cov(ay, by, j);
2368 if c > 0.0 {
2369 v = v * (1.0 - c) + 3500.0 * c;
2370 }
2371 y4m.extend_from_slice(&(v.min(4095.0) as u16).to_le_bytes());
2372 }
2373 }
2374 for (base, fx) in [(1900usize, 0usize), (2100, 1)] {
2375 for j in 0..H / 2 {
2376 for i in 0..W / 2 {
2377 let v = if fx == 0 {
2378 base + (((i / 5 + t * 2) % 7) * 120 + (j * 60) / H)
2379 } else {
2380 base + (((j / 4 + t) % 5) * 140 + (i * 40) / W)
2381 };
2382 y4m.extend_from_slice(&(v.min(4095) as u16).to_le_bytes());
2383 }
2384 }
2385 }
2386 }
2387 y4m
2388 }
2389
2390 /// lane-av1gwarp12 fixture: rotating + uniformly zooming mandelbrot as a
2391 /// C420p12 y4m. Rotation composed with a UNIFORM scale is a similarity
2392 /// transform -- exactly the family a 4-parameter ROTZOOM global model
2393 /// expresses (the affine gate needs the anisotropic stretch to force
2394 /// 6 parameters; this lane needs the model vanilla aomenc actually
2395 /// searches, ROTZOOM).
2396 pub(super) fn y4m_12bit_rotzoom_gm_source(frames: usize) -> Vec<u8> {
2397 const W: usize = 128;
2398 const H: usize = 128;
2399 let source = format!(
2400 "mandelbrot=size=192x192:rate=25,rotate=a=0.12*t:c=black,\
2401 scale=w='ceil(192*(1+0.04*n)/2)*2':h='ceil(192*(1+0.04*n)/2)*2':eval=frame,\
2402 crop={W}:{H}"
2403 );
2404 let duration = (frames as f64 / 25.0).to_string();
2405 let ff_args: Vec<&str> = vec![
2406 "-v",
2407 "error",
2408 "-f",
2409 "lavfi",
2410 "-i",
2411 &source,
2412 "-pix_fmt",
2413 "yuv420p12le",
2414 // y4m has no official 12-bit tag, same as the 10-bit gate.
2415 "-strict",
2416 "-1",
2417 "-t",
2418 &duration,
2419 "-f",
2420 "yuv4mpegpipe",
2421 "-",
2422 ];
2423 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2424 .args(&ff_args)
2425 .stdin(Stdio::null())
2426 .stdout(Stdio::piped())
2427 .stderr(Stdio::piped()), None, |c| c.output())
2428 .expect("ffmpeg failed to run");
2429 assert!(
2430 out.status.success(),
2431 "ffmpeg fixture: {}",
2432 String::from_utf8_lossy(&out.stderr)
2433 );
2434 out.stdout
2435 }
2436
2437 /// The 12-bit coding recipe shared by the witness gates (cpu-used=0 so
2438 /// every search runs; explicit CDEF/restoration ON). Warp/global-motion
2439 /// are deliberately NOT spelled here: this aomenc honours the LAST
2440 /// occurrence of these flags (measured), so a base pin plus an override
2441 /// would silently take the base value -- each gate spells what it needs
2442 /// exactly once.
2443 pub(super) fn encode_12bit(y4m: &[u8], frames: usize, extra: &[&str]) -> Vec<u8> {
2444 let limit = format!("--limit={frames}");
2445 let mut args: Vec<&str> = vec![
2446 "--codec=av1",
2447 "--profile=2",
2448 "--passes=1",
2449 "--end-usage=q",
2450 "--cq-level=20",
2451 "--cpu-used=0",
2452 "--threads=1",
2453 "--row-mt=0",
2454 "--sb-size=64",
2455 "--lag-in-frames=0",
2456 "--auto-alt-ref=0",
2457 "--kf-max-dist=1000",
2458 "--input-bit-depth=12",
2459 "--bit-depth=12",
2460 "--enable-cdef=1",
2461 "--enable-restoration=1",
2462 "--obu",
2463 "-o",
2464 "-",
2465 "-",
2466 &limit,
2467 ];
2468 // AOMENC FLAG PRECEDENCE (COMMON): aomenc keeps the FIRST occurrence
2469 // of a flag, so the per-arm override goes BEFORE the base list.
2470 args.splice(1..1, extra.iter().copied());
2471 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m);
2472 assert!(
2473 out.status.success(),
2474 "aomenc refused the 12-bit fixture: {}",
2475 String::from_utf8_lossy(&out.stderr)
2476 );
2477 out.stdout
2478 }
2479
2480 /// Asserts the stream's sequence header really says 12-bit before any
2481 /// pixel comparison is trusted.
2482 pub(super) fn assert_12bit_sequence_header(stream: &[u8], name: &str) {
2483 let mut probe = Av1Parser::new();
2484 let mut pos = 0usize;
2485 while pos < stream.len() && probe.sequence_header().is_none() {
2486 let obu = probe.parse_obu(&stream[pos..]).unwrap();
2487 pos += obu.total_size;
2488 }
2489 let seq = probe
2490 .sequence_header()
2491 .expect("stream has a sequence header OBU");
2492 assert_eq!(
2493 seq.color_config.bit_depth, 12,
2494 "{name}: aomenc did not actually write a 12-bit sequence header"
2495 );
2496 }
2497
2498 pub(super) fn ffmpeg_decode_sequence_12bit(
2499 stream: &[u8],
2500 width: usize,
2501 height: usize,
2502 frames: usize,
2503 ) -> Vec<Pic> {
2504 assert_420_oracle_stream(
2505 stream,
2506 "ffmpeg_decode_sequence_12bit",
2507 "ffmpeg_decode_sequence_422_depth(.., 12, \"yuv422p12le\") (4:2:2); \
2508 ffmpeg_decode_sequence_444_depth(.., 12, \"yuv444p12le\") (4:4:4)",
2509 );
2510 let out = run_with_stdin(
2511 Command::new("ffmpeg").args([
2512 "-v",
2513 "error",
2514 "-f",
2515 "obu",
2516 "-i",
2517 "-",
2518 "-f",
2519 "rawvideo",
2520 "-pix_fmt",
2521 "yuv420p12le",
2522 "-",
2523 ]),
2524 stream,
2525 );
2526 assert!(
2527 out.status.success(),
2528 "ffmpeg refused the 12-bit stream: {}",
2529 String::from_utf8_lossy(&out.stderr)
2530 );
2531 let (luma, chroma) = (width * height, width * height / 4);
2532 let frame_bytes = (luma + 2 * chroma) * 2;
2533 assert_eq!(
2534 out.stdout.len(),
2535 frame_bytes * frames,
2536 "expected {frames} 4:2:0 12-bit frames, ffmpeg said: {}",
2537 String::from_utf8_lossy(&out.stderr)
2538 );
2539 fn le16(bytes: &[u8]) -> Vec<u16> {
2540 bytes
2541 .as_chunks::<2>().0.iter()
2542 .map(|c| u16::from_le_bytes([c[0], c[1]]))
2543 .collect()
2544 }
2545 (0..frames)
2546 .map(|i| {
2547 let base = i * frame_bytes;
2548 Pic {
2549 width,
2550 height,
2551 y: le16(&out.stdout[base..base + luma * 2]),
2552 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
2553 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
2554 }
2555 })
2556 .collect()
2557 }
2558
2559 /// lane-av1screen12: how many frames of `stream` carry
2560 /// `allow_screen_content_tools`, and how many of THOSE carry
2561 /// `allow_intrabc`. Both are read out of the frame headers this crate
2562 /// parsed, never taken from the flags handed to the encoder (class
2563 /// `tool-disabled-in-every-gate`): on this oracle build
2564 /// `--tune-content=screen` does NOT by itself decide the frame-header
2565 /// `allow_intrabc` bit -- an untiled `smptebars=size=128x96` source reads
2566 /// `false` with and without the flag, while the 256x192 `tile=2x2` source
2567 /// the intrabc census uses reads `true` with and without it (measured;
2568 /// libaom's content detector, `encoder.c:2404`, is what decides it).
2569 pub(super) fn screen_and_intrabc_frame_counts(stream: &[u8]) -> (u32, u32) {
2570 let mut parser = Av1Parser::new();
2571 let mut pos = 0usize;
2572 let (mut screen, mut intrabc) = (0u32, 0u32);
2573 while pos < stream.len() {
2574 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
2575 break;
2576 };
2577 pos += obu.total_size.max(1);
2578 let header = match &obu.kind {
2579 ObuKind::Frame(h, _) => Some(&**h),
2580 ObuKind::FrameHeader(h) => Some(&**h),
2581 _ => None,
2582 };
2583 if let Some(h) = header
2584 && h.allow_screen_content_tools
2585 {
2586 screen += 1;
2587 if h.allow_intrabc {
2588 intrabc += 1;
2589 }
2590 }
2591 }
2592 (screen, intrabc)
2593 }
2594
2595 /// The three committed 12-bit screen-content witnesses, by literal name
2596 /// (a pin name built from a loop variable leaves the pin census
2597 /// unproven), with the length and `fnv1a64` each gate asserts. sha256,
2598 /// recorded in the gates' doc comments and in
2599 /// `lanes/av1screen12.report.md`:
2600 ///
2601 /// * `screen12_palette.obu` 3616 bytes,
2602 /// `adfe26c67c08a7e986db2743b914ecc3e214c56dd2abbdfd17ebf99f06de64c8`
2603 /// * `screen12_intrabc.obu` 482 bytes,
2604 /// `a3b6b94cabdd09a12057c4688990d55495826b87a14332c386d319629070382e`
2605 /// * `screen12_lossless_palette.obu` 11698 bytes,
2606 /// `ec7942c96763593e6d8e4b3fb23c03930bba3bb743102d0cf552fe73ae11c203`
2607 pub(super) const PIN_LEN_PALETTE: usize = 3616;
2608
2609 pub(super) const PIN_FNV_PALETTE: u64 = 0xf9bb_d408_61d6_f0da;
2610
2611 pub(super) const PIN_LEN_INTRABC: usize = 482;
2612
2613 pub(super) const PIN_FNV_INTRABC: u64 = 0xae83_3eb7_9380_263b;
2614
2615 pub(super) const PIN_LEN_LOSSLESS: usize = 11698;
2616
2617 pub(super) const PIN_FNV_LOSSLESS: u64 = 0x6e28_41c7_7b0a_f9db;
2618
2619 /// lane-av1screen12: the shared body of the three 12-bit screen-content
2620 /// gates. Every assertion a "this arm really is 12-bit screen content,
2621 /// and this decoder reproduces it" claim needs, in one place:
2622 ///
2623 /// 1. the committed PIN is the witness -- its length and fnv1a64 are
2624 /// pinned, and `require_pin` HARD-fails on a missing copy rather than
2625 /// testing nothing;
2626 /// 2. the live recipe reproduces that pin byte for byte (aomenc present),
2627 /// so the recipe in the doc comment is not decoration;
2628 /// 3. the stream's OWN sequence header says 12-bit and its frame headers
2629 /// say `allow_screen_content_tools` (and `allow_intrabc` for the arm
2630 /// that wants it);
2631 /// 4. the decode ENGAGED the feature -- `palette_hits()` /
2632 /// `palette_uv_hits()` / `intrabc_hits()` deltas are hard-asserted,
2633 /// because a stream that merely carries the header bit would leave the
2634 /// arm it claims to witness untested (class `gate-blind-to-feature`);
2635 /// 5. every sample of every frame matches the instrumented `aomdec
2636 /// --rawvideo` (`assert_rawvideo_matches`), and independently ffmpeg;
2637 /// 6. THE CONTROL: the same counting comparator, run twice -- clean it
2638 /// must report zero wrong samples in all three planes, and with ONE
2639 /// bit flipped in the ORACLE's own frame-0 luma high byte it must
2640 /// report exactly one wrong luma byte and one fewer exact frame. That
2641 /// is the proof the comparator READS the oracle side: a comparator
2642 /// that compared our samples with themselves would report 0 both
2643 /// times (class `oracle-diff-counter-tautology`).
2644 ///
2645 /// Flip index 1 is the high byte of the first luma sample of frame 0.
2646 /// A 12-bit sample's high byte holds bits 8..15 only, so flipping its low
2647 /// bit can never carry into another byte: the move is exactly +1 wrong
2648 /// byte in the Y plane, which is what makes "+1 in the right plane and
2649 /// frame" a real statement rather than a hope.
2650 #[allow(clippy::too_many_arguments)]
2651 pub(super) fn assert_12bit_screen_content_arm(
2652 name: &str,
2653 pin: &'static str,
2654 live: Vec<u8>,
2655 pin_len: usize,
2656 pin_fnv: u64,
2657 frames: usize,
2658 width: usize,
2659 height: usize,
2660 want_intrabc: bool,
2661 ) {
2662 let path = crate_pin(pin);
2663 let stream = require_pin(&path, pin);
2664 assert_eq!(
2665 stream.len(),
2666 pin_len,
2667 "{name}: the committed pin {pin} is {} bytes, this gate names {pin_len}",
2668 stream.len()
2669 );
2670 assert_eq!(
2671 fnv1a64(&stream),
2672 pin_fnv,
2673 "{name}: the committed pin {pin} moved"
2674 );
2675 if have_aomenc() {
2676 assert_eq!(
2677 live.len(),
2678 pin_len,
2679 "{name}: the live recipe produced {} bytes, the committed pin {pin} is \
2680 {pin_len} -- aomenc changed, re-pin it",
2681 live.len()
2682 );
2683 assert_eq!(
2684 fnv1a64(&live),
2685 pin_fnv,
2686 "{name}: the live recipe no longer reproduces the committed pin {pin}"
2687 );
2688 }
2689 assert_12bit_sequence_header(&stream, name);
2690 let (screen_frames, intrabc_frames) = screen_and_intrabc_frame_counts(&stream);
2691 assert!(
2692 screen_frames > 0,
2693 "{name}: no frame carries allow_screen_content_tools -- this is not a \
2694 screen-content stream and the arm would prove nothing"
2695 );
2696 assert_eq!(
2697 intrabc_frames > 0,
2698 want_intrabc,
2699 "{name}: {intrabc_frames} frame(s) carry allow_intrabc, the gate wants {}",
2700 u32::from(want_intrabc)
2701 );
2702
2703 let pal_before = crate::decode::palette_hits();
2704 let paluv_before = crate::decode::palette_uv_hits();
2705 let ibc_before = crate::decode::intrabc_hits();
2706 let decoded = decode_stream(&stream).unwrap_or_else(|e| panic!("{name}: {e}"));
2707 assert_eq!(decoded.len(), frames, "{name}: frame count");
2708 let palette = crate::decode::palette_hits() - pal_before;
2709 let palette_uv = crate::decode::palette_uv_hits() - paluv_before;
2710 let intrabc = crate::decode::intrabc_hits() - ibc_before;
2711 assert!(
2712 palette > 0,
2713 "{name}: the stream decoded no palette block -- the 12-bit palette syntax \
2714 would be untested (class gate-blind-to-feature)"
2715 );
2716 assert!(
2717 palette_uv > 0,
2718 "{name}: the stream decoded no chroma palette block -- the 12-bit palette-UV \
2719 syntax would be untested (class gate-blind-to-feature)"
2720 );
2721 if want_intrabc {
2722 assert!(
2723 intrabc > 0,
2724 "{name}: allow_intrabc is set but no block decoded use_intrabc=1 -- the \
2725 12-bit intra-block-copy syntax would be untested (class \
2726 gate-blind-to-feature)"
2727 );
2728 }
2729
2730 if aomdec_available(name) {
2731 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-arm"));
2732 let _ = std::fs::remove_dir_all(&dir);
2733 std::fs::create_dir_all(&dir).expect("scratch dir");
2734 let obu = dir.join("in.obu");
2735 std::fs::write(&obu, &stream).expect("writing the stream");
2736 assert_rawvideo_matches(&obu, &stream, name, frames, 12);
2737 let _ = std::fs::remove_dir_all(&dir);
2738 // The +1 control (part 6): clean is all-zero, one flipped oracle
2739 // byte is exactly +1 luma byte and one fewer exact frame.
2740 let clean = count_rawvideo_diffs(&stream, name, None).unwrap_or_else(|| {
2741 panic!("{name}: our packed output and the oracle's rawvideo differ in SIZE")
2742 });
2743 assert_eq!(
2744 clean,
2745 (0, 0, 0, frames, frames),
2746 "{name}: {frames} frame(s) must be byte-exact against the oracle before the \
2747 control arm means anything"
2748 );
2749 let flipped = count_rawvideo_diffs(&stream, name, Some(1))
2750 .unwrap_or_else(|| panic!("{name}: the control arm lost the size check"));
2751 assert_eq!(
2752 flipped,
2753 (1, 0, 0, frames, frames - 1),
2754 "{name}: flipping bit 0 of the ORACLE's frame-0 luma high byte must move the \
2755 count by exactly +1 luma byte and cost exactly one exact frame -- if this \
2756 reports 0 the comparator never read the oracle (class \
2757 oracle-diff-counter-tautology)"
2758 );
2759 }
2760 if have_ffmpeg() {
2761 let theirs = ffmpeg_decode_sequence_12bit(&stream, width, height, frames);
2762 assert_eq!(theirs.len(), frames, "{name}: ffmpeg frame count");
2763 for (i, (ours, want)) in decoded.iter().zip(&theirs).enumerate() {
2764 assert_eq!(ours.y, want.y, "{name}: 12-bit luma vs ffmpeg (frame {i})");
2765 assert_eq!(ours.u, want.u, "{name}: 12-bit U vs ffmpeg (frame {i})");
2766 assert_eq!(ours.v, want.v, "{name}: 12-bit V vs ffmpeg (frame {i})");
2767 }
2768 }
2769 eprintln!(
2770 "{name}: {frames} 12-bit frame(s) byte-exact vs aomdec --rawvideo and ffmpeg, \
2771 {screen_frames} screen frame(s), {intrabc_frames} allow_intrabc, {palette} palette \
2772 + {palette_uv} palette-UV + {intrabc} intrabc block(s)"
2773 );
2774 }
2775
2776 /// Renders a 12-bit y4m for the 12-bit screen-content gates. `tiled`
2777 /// applies `-vf tile=2x2`, which is what takes the source from 128x96 to
2778 /// the 256x192 shape libaom's content detector clears the (stricter)
2779 /// IntraBC threshold on.
2780 pub(super) fn y4m_12bit_screen_source(src: &str, tiled: bool) -> Vec<u8> {
2781 let mut ff = Command::new("ffmpeg");
2782 ff.args(["-v", "error", "-f", "lavfi", "-i", src, "-t", "0.2"]);
2783 if tiled {
2784 ff.args(["-vf", "tile=2x2"]);
2785 }
2786 let out = crate::tool_cache::cached_output_io(ff
2787 .args([
2788 "-pix_fmt",
2789 "yuv420p12le",
2790 "-strict",
2791 "-1",
2792 "-f",
2793 "yuv4mpegpipe",
2794 "-",
2795 ])
2796 .stdin(Stdio::null())
2797 .stdout(Stdio::piped())
2798 .stderr(Stdio::piped()), None, |c| c.output())
2799 .expect("ffmpeg failed to run");
2800 assert!(
2801 out.status.success(),
2802 "ffmpeg failed for the 12-bit screen source {src}: {}",
2803 String::from_utf8_lossy(&out.stderr)
2804 );
2805 out.stdout
2806 }
2807
2808 /// Shared body for the lane-av1superhbd HIGH-BIT-DEPTH 4:4:4 superres
2809 /// arms: 10-bit and 12-bit, `--superres-mode=1` at a fixed denominator
2810 /// and `--superres-mode=2` (a per-frame denominator libaom picks itself).
2811 ///
2812 /// Everything the 8-bit 4:4:4 superres cell is non-vacuous by, repeated
2813 /// here, plus the one thing that only matters above 8 bits: the gate
2814 /// asserts the PARSED `bit_depth` equals the depth it names, because a
2815 /// 10-bit recipe whose flags were mistyped still decodes -- it just
2816 /// decodes a DIFFERENT cell than the gate claims, which is the same
2817 /// "phantom cell" trap lane-av1444edge r3 recorded for
2818 /// `use_superres=false`.
2819 ///
2820 /// The per-frame table is `(denominator, coded_width)` in DECODE order.
2821 /// The coded width is re-derived as `(UpscaledWidth*8 + denom/2)/denom`
2822 /// from that frame's OWN parsed denominator rather than only compared to
2823 /// a literal, so a re-pinned fixture cannot satisfy the literals while
2824 /// the scaled-size arithmetic moves under them. `superres_hits` and
2825 /// `predict_scaled_hits` are asserted as DELTAS (both are process-wide
2826 /// counters with no reset).
2827 #[allow(clippy::too_many_arguments)]
2828 pub(super) fn a_444_hbd_superres_arm(
2829 name: &str,
2830 fixture: &str,
2831 fixture_len: usize,
2832 fixture_fnv: u64,
2833 fixture_sha: &str,
2834 bit_depth: u8,
2835 upscaled: (usize, usize),
2836 per_frame: &[(u8, usize)],
2837 ) -> Vec<FrameHeader> {
2838 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(fixture);
2839 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
2840 panic!(
2841 "{name}: pinned fixture {fixture} is missing ({e}) -- the gate cannot run, \
2842 which is a failure, not a skip"
2843 )
2844 });
2845 assert_eq!(stream.len(), fixture_len, "{name}: fixture length moved");
2846 assert_eq!(fnv1a64(&stream), fixture_fnv, "{name}: fixture bytes moved");
2847
2848 // --- the header facts the CELL depends on, parsed not assumed ------
2849 let mut parser = Av1Parser::new();
2850 let mut pos = 0usize;
2851 let mut seq = None;
2852 let mut heads: Vec<FrameHeader> = Vec::new();
2853 while pos < stream.len() {
2854 let parsed = parser
2855 .parse_obu(&stream[pos..])
2856 .unwrap_or_else(|e| panic!("{name}: aomenc OBU does not parse: {e:?}"));
2857 if parsed.total_size == 0 {
2858 break;
2859 }
2860 pos += parsed.total_size;
2861 match parsed.kind {
2862 ObuKind::SequenceHeader(s) => seq = Some(s),
2863 ObuKind::FrameHeader(h) => heads.push(*h),
2864 ObuKind::Frame(h, _) => heads.push(*h),
2865 _ => {}
2866 }
2867 }
2868 let seq = seq.unwrap_or_else(|| panic!("{name}: the stream carries no sequence header"));
2869 assert_eq!(
2870 (
2871 seq.color_config.subsampling_x,
2872 seq.color_config.subsampling_y
2873 ),
2874 (0, 0),
2875 "{name}: the stream is not 4:4:4 (ss = ({}, {}))",
2876 seq.color_config.subsampling_x,
2877 seq.color_config.subsampling_y
2878 );
2879 // The high-bit-depth claim itself. A `--bit-depth` flag that silently
2880 // did not take effect still produces a decodable 4:4:4 superres
2881 // stream -- at 8 bits -- and every other assertion below would pass.
2882 assert_eq!(
2883 seq.color_config.bit_depth, bit_depth,
2884 "{name}: the sequence header parses bit_depth {}, not the {bit_depth} this gate \
2885 names -- the encoder flags did not take effect and this is a different cell",
2886 seq.color_config.bit_depth
2887 );
2888 assert!(
2889 seq.enable_superres,
2890 "{name}: the sequence header does not enable superres at all"
2891 );
2892 assert_eq!(
2893 heads.len(),
2894 per_frame.len(),
2895 "{name}: {} frame headers, expected {}",
2896 heads.len(),
2897 per_frame.len()
2898 );
2899 for (i, (h, (denom, coded))) in heads.iter().zip(per_frame).enumerate() {
2900 assert!(
2901 h.use_superres,
2902 "{name}: frame {i} has use_superres = false -- this is an UNSCALED stream and \
2903 the gate would measure something other than the cell it names (class \
2904 gate-blind-to-feature)"
2905 );
2906 assert_eq!(
2907 h.superres_denom, *denom,
2908 "{name}: frame {i} PARSED denominator moved from {denom} -- read the header, \
2909 never the encoder flag (mode 2 chooses its own)"
2910 );
2911 assert_eq!(
2912 (h.upscaled_width as usize, h.frame_height as usize),
2913 upscaled,
2914 "{name}: frame {i} upscaled size moved"
2915 );
2916 assert_eq!(
2917 (h.frame_width as usize, h.frame_height as usize),
2918 (*coded, upscaled.1),
2919 "{name}: frame {i} CODED size moved -- this is the scaled half of the cell and \
2920 the part an unsized stream gets wrong"
2921 );
2922 let d = u32::from(*denom);
2923 assert_eq!(
2924 (h.upscaled_width * 8 + d / 2) / d,
2925 h.frame_width,
2926 "{name}: frame {i}: FrameWidth is not (UpscaledWidth*8 + denom/2)/denom -- the \
2927 scaled size the cell rests on is not the spec's"
2928 );
2929 }
2930
2931 // --- the pixels -----------------------------------------------------
2932 let _guard = lock_gate_counters();
2933 let before_sr = crate::superres::superres_hits();
2934 let before_scaled = crate::mc::predict_scaled_hits();
2935 let frames = decode_stream(&stream).unwrap_or_else(|e| {
2936 panic!("{name}: the pinned {bit_depth}-bit 4:4:4 superres stream was refused: {e}")
2937 });
2938 let scaled_up = crate::superres::superres_hits() - before_sr;
2939 let scaled_mc = crate::mc::predict_scaled_hits() - before_scaled;
2940 assert!(
2941 scaled_up > 0,
2942 "{name}: zero superres_hits -- the upscaler never ran (class gate-blind-to-feature)"
2943 );
2944 assert!(
2945 scaled_mc > 0,
2946 "{name}: zero predict_scaled_hits -- no inter block read a scaled reference, so the \
2947 scaled-PREDICTION half of the cell is unexercised (class gate-blind-to-feature)"
2948 );
2949 assert_eq!(frames.len(), per_frame.len(), "{name}: decoded frame count");
2950 let max = (1u32 << bit_depth) - 1;
2951 for (i, f) in frames.iter().enumerate() {
2952 assert_eq!(
2953 (f.width, f.height),
2954 upscaled,
2955 "{name}: frame {i} came back {}x{}, not the UPSCALED {}x{}",
2956 f.width,
2957 f.height,
2958 upscaled.0,
2959 upscaled.1
2960 );
2961 for (plane, samples) in [("Y", &f.y), ("U", &f.u), ("V", &f.v)] {
2962 assert_eq!(
2963 samples.len(),
2964 upscaled.0 * upscaled.1,
2965 "{name}: frame {i} {plane} plane is {} samples; at 4:4:4 upscaled it must be \
2966 full resolution ({}x{})",
2967 samples.len(),
2968 upscaled.0,
2969 upscaled.1
2970 );
2971 // The depth claim, on the pixels: a decoder that lost the
2972 // high bits (or produced 8-bit values padded into a u16
2973 // plane) would satisfy every length and geometry assert above
2974 // and only be caught here.
2975 assert!(
2976 samples.iter().all(|&s| u32::from(s) <= max),
2977 "{name}: frame {i} {plane} carries a sample above the {bit_depth}-bit \
2978 maximum {max} -- the bit depth of the OUTPUT does not match the header"
2979 );
2980 }
2981 }
2982 if aomdec_available(name) {
2983 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, name);
2984 eprintln!(
2985 "{name}: {decoded} decode-order frame(s) ({hidden} hidden) byte-exact vs aomdec \
2986 at {bit_depth}-bit {upscaled:?} upscaled from {per_frame:?} (denominator, coded \
2987 width) per frame, {scaled_up} upscale(s), {scaled_mc} scaled MC block(s); \
2988 fixture sha256 {fixture_sha}"
2989 );
2990 }
2991 heads
2992 }
2993
2994 /// Seeds swept by the 10-bit LR gate (the 8-bit gate needs ~40 attempts
2995 /// to land a non-RESTORE_NONE frame; every attempt here still has to
2996 /// decode pixel-exact).
2997 /// lane-obmcrec r1: the `LR_SEEDS` members whose 1:4-partition stream both
2998 /// fires `obmc_pair_filter_hits` and decodes every frame pixel-exact.
2999 /// Measured over seeds 42..=73 (32 encodes): 43/46/47/65/66 fire and are
3000 /// exact; 70 and 73 fire and mismatch, but mismatch IDENTICALLY with
3001 /// `--enable-obmc=0` (seed 73 frame 1 luma, seed 70 frame 16), so their
3002 /// defect is in the `--min-partition-size=4` recipe, not in OBMC -- kept
3003 /// out of this gate rather than papered over, and reported as open.
3004 pub(super) const OBMC_PAIR_SEEDS: [u32; 5] = [43, 46, 47, 65, 66];
3005
3006 pub(super) const LR_SEEDS: [u32; 16] = [
3007 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
3008 ];
3009
3010 /// Wiener + SGR + switchable loop-restoration firings, summed.
3011 pub(super) fn ten_bit_lr_hits() -> usize {
3012 crate::restoration::wiener_hits()
3013 + crate::restoration::sgrproj_hits()
3014 + crate::restoration::switchable_hits()
3015 }
3016
3017 /// `bit_depth` of the first sequence header in `stream`.
3018 pub(super) fn parsed_bit_depth(stream: &[u8]) -> u8 {
3019 let mut probe = Av1Parser::new();
3020 let mut pos = 0usize;
3021 while pos < stream.len() && probe.sequence_header().is_none() {
3022 let obu = probe.parse_obu(&stream[pos..]).unwrap();
3023 pos += obu.total_size;
3024 }
3025 probe
3026 .sequence_header()
3027 .expect("stream has a sequence header OBU")
3028 .color_config
3029 .bit_depth
3030 }
3031
3032 /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and
3033 /// encode it with a real 10-bit `aomenc`, returning the OBU stream.
3034 /// `extra` carries the tool flags under test.
3035 pub(super) fn encode_10bit_gradients(
3036 name: &str,
3037 width: usize,
3038 height: usize,
3039 frames: usize,
3040 extra: &[&str],
3041 ) -> Vec<u8> {
3042 encode_10bit_gradients_seed(name, 42, width, height, frames, extra)
3043 }
3044
3045 /// As [`encode_10bit_gradients`], but with the fixture seed exposed --
3046 /// lane-hbdgates r1 sweeps seeds so a tool that aomenc's RD declines on
3047 /// one fixture still gets a firing stream.
3048 pub(super) fn encode_10bit_gradients_seed(
3049 name: &str,
3050 seed: u32,
3051 width: usize,
3052 height: usize,
3053 frames: usize,
3054 extra: &[&str],
3055 ) -> Vec<u8> {
3056 let duration = frames as f64 / 25.0;
3057 // lane-ab32 r1: `--ec-fixture-noise` is not an aomenc flag -- it is a
3058 // fixture request, consumed (and stripped) here: the smooth gradients
3059 // source codes as PARTITION_NONE everywhere, so a partition gate needs
3060 // seeded noise on top of it to give the RD a reason to split.
3061 let noisy = extra.contains(&"--ec-fixture-noise");
3062 let stripped: Vec<&str> = extra
3063 .iter()
3064 .copied()
3065 .filter(|a| *a != "--ec-fixture-noise")
3066 .collect();
3067 let extra: &[&str] = &stripped;
3068 let base = gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
3069 let source = if noisy {
3070 format!("{base},noise=alls=40:all_seed={seed}")
3071 } else {
3072 base
3073 };
3074 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3075 .args([
3076 "-v",
3077 "error",
3078 "-f",
3079 "lavfi",
3080 "-i",
3081 &source,
3082 "-pix_fmt",
3083 "yuv420p10le",
3084 "-strict",
3085 "-1",
3086 "-t",
3087 &format!("{duration}"),
3088 "-f",
3089 "yuv4mpegpipe",
3090 "-",
3091 ])
3092 .stdin(Stdio::null())
3093 .stdout(Stdio::piped())
3094 .stderr(Stdio::piped()), None, |c| c.output())
3095 .expect("ffmpeg failed to run");
3096 assert!(
3097 y4m.status.success(),
3098 "{name}: ffmpeg failed to render the 10-bit fixture: {}",
3099 String::from_utf8_lossy(&y4m.stderr)
3100 );
3101 let mut args: Vec<&str> = vec!["--codec=av1", "--passes=1", "--end-usage=q"];
3102 // lane-hbdgates r1: a caller-supplied `--cq-level` REPLACES the
3103 // default rather than being appended after it -- two `--cq-level`
3104 // flags on one aomenc line is a coin flip on which one lands.
3105 if !extra.iter().any(|a| a.starts_with("--cq-level=")) {
3106 args.push("--cq-level=30");
3107 }
3108 args.extend_from_slice(&[
3109 "--cpu-used=0",
3110 "--threads=1",
3111 "--row-mt=0",
3112 "--sb-size=64",
3113 "--input-bit-depth=10",
3114 "--bit-depth=10",
3115 ]);
3116 args.extend_from_slice(extra);
3117 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
3118 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3119 assert!(
3120 out.status.success(),
3121 "{name}: aomenc refused the 10-bit fixture: {}",
3122 String::from_utf8_lossy(&out.stderr)
3123 );
3124 out.stdout
3125 }
3126
3127 /// The affine-capable encoder (`scripts/build-aom-affine-oracle.sh`),
3128 /// separate from the shared oracle because stock libaom's global-motion
3129 /// model search is pinned to ROTZOOM and can never emit AFFINE.
3130 pub(super) fn affine_aomenc_path() -> std::path::PathBuf {
3131 if let Some(p) = std::env::var_os("EC_AV1_AFFINE_AOMENC") {
3132 return std::path::PathBuf::from(p);
3133 }
3134 let home = std::env::var_os("HOME").unwrap_or_default();
3135 std::path::PathBuf::from(home).join(".cache/aom-affine/build/aomenc")
3136 }
3137
3138 pub(super) fn have_affine_aomenc() -> bool {
3139 let present = affine_aomenc_path().is_file();
3140 assert!(
3141 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
3142 "EC_AV1_REQUIRE_AOMENC is set but no affine-capable aomenc at {} -- run \
3143 scripts/build-aom-affine-oracle.sh",
3144 affine_aomenc_path().display()
3145 );
3146 present
3147 }
3148
3149 pub(super) fn check_pinned_warp_stream(path: &std::path::Path) {
3150 use crate::decode::warp_selected_hits;
3151 let name = path
3152 .file_name()
3153 .map(|n| n.to_string_lossy().into_owned())
3154 .unwrap_or_default();
3155 let stream = require_pin(path, &name);
3156 let before = warp_selected_hits();
3157 let frames = decode_stream(&stream).expect("pinned stream must decode");
3158 eprintln!(
3159 "warp_selected_hits before={before} after={}",
3160 warp_selected_hits()
3161 );
3162 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 24);
3163 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3164 if got.y != want.y {
3165 for row in 0..64 {
3166 let mut line = String::new();
3167 for col in 0..64 {
3168 let d = got.y[row * 64 + col] as i32 - want.y[row * 64 + col] as i32;
3169 line.push(if d == 0 {
3170 '.'
3171 } else if d.abs() < 4 {
3172 'o'
3173 } else {
3174 'X'
3175 });
3176 }
3177 eprintln!("{line}");
3178 }
3179 }
3180 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
3181 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
3182 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
3183 }
3184 }
3185
3186 /// Which of the four 128-root AB shapes the gate above MEASURED aomenc
3187 /// picking (lane-sb128c r9). An arm that is `false` is not reachable from
3188 /// this sweep's recipes and stays unasserted rather than weakening the
3189 /// asserts of the ones that are.
3190 pub(super) const AB_ARMS_REACHED: [bool; 4] = [true, true, true, true];
3191
3192 /// lane-av1muchunk422b: read a pinned 4:2:2 128-root mu-chunk fixture,
3193 /// asserting its byte length and FNV-1a64 -- a missing fixture is a
3194 /// failure, not a skip.
3195 pub(super) fn read_pinned_muchunk_fixture(name: &str, len: usize, fnv: u64, gate: &str) -> Vec<u8> {
3196 let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3197 .join("fixtures")
3198 .join(name);
3199 let bytes = std::fs::read(&path).unwrap_or_else(|e| {
3200 panic!(
3201 "{gate}: pinned fixture {} is missing ({e}) -- the gate cannot run, which is a \
3202 failure, not a skip",
3203 path.display()
3204 )
3205 });
3206 assert_eq!(bytes.len(), len, "{gate}: {name} length moved");
3207 assert_eq!(fnv1a64(&bytes), fnv, "{gate}: {name} bytes moved");
3208 bytes
3209 }
3210
3211 /// lane-av1muchunk422b: `(use_128x128_superblock, ss_x, ss_y, mono_chrome)`
3212 /// of an OBU stream's sequence header. Shape first: a stream that came back
3213 /// 4:2:0 would leave the `side > 64` mu-chunk walk unexercised while every
3214 /// counter assert below still passed.
3215 pub(super) fn obu_stream_shape(stream: &[u8]) -> Option<(bool, u8, u8, bool)> {
3216 let mut parser = ec_av1_syntax::Av1Parser::new();
3217 let mut pos = 0usize;
3218 while let Ok(obu) = parser.parse_obu(&stream[pos..]) {
3219 pos += obu.total_size;
3220 if pos >= stream.len() {
3221 break;
3222 }
3223 }
3224 parser.sequence_header().map(|q| {
3225 (
3226 q.use_128x128_superblock,
3227 q.color_config.subsampling_x,
3228 q.color_config.subsampling_y,
3229 q.color_config.mono_chrome,
3230 )
3231 })
3232 }
3233
3234 /// The chroma-rect gate's fixture + aomenc recipe for one attempt, shared
3235 /// with the seed-46 pin test below so the pin cannot drift from the gate.
3236 pub(super) fn rectchroma_stream(
3237 bit_depth: u32,
3238 cq: u32,
3239 attempt: u32,
3240 width: usize,
3241 height: usize,
3242 ) -> Vec<u8> {
3243 const NAME: &str = "rectchroma_stream";
3244 let seed = 42 + attempt;
3245 let pix_fmt = if bit_depth == 10 {
3246 "yuv420p10le"
3247 } else {
3248 "yuv420p"
3249 };
3250 // `gradients_source`, the content the sibling split-transform
3251 // superblock gate uses. A band/noise `geq` fixture was tried
3252 // first (r1) and gave 12/12 pixel-exact streams carrying ZERO
3253 // 1:4 strips -- vacuous. Odd attempts render it transposed so
3254 // HORZ_4 and VERT_4 both appear (class scan-weights-cross-axis).
3255 let bands = format!(
3256 "geq=lum='mod(floor(Y/16),2)*160+48':cb=128:cr=128,noise=alls=10:all_seed={seed}"
3257 );
3258 let source = if attempt.is_multiple_of(2) {
3259 format!("color=c=black:size={width}x{height}:duration=0.04:rate=25,{bands}")
3260 } else {
3261 format!("color=c=black:size={height}x{width}:duration=0.04:rate=25,{bands},transpose=1")
3262 };
3263 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3264 .args([
3265 "-v",
3266 "error",
3267 "-f",
3268 "lavfi",
3269 "-i",
3270 &source,
3271 "-t",
3272 "0.04",
3273 "-pix_fmt",
3274 pix_fmt,
3275 "-strict",
3276 "-1",
3277 "-f",
3278 "yuv4mpegpipe",
3279 "-",
3280 ])
3281 .stdin(Stdio::null())
3282 .stdout(Stdio::piped())
3283 .stderr(Stdio::piped()), None, |c| c.output())
3284 .expect("ffmpeg failed to run");
3285 assert!(
3286 y4m.status.success(),
3287 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
3288 String::from_utf8_lossy(&y4m.stderr)
3289 );
3290 let cq_arg = format!("--cq-level={cq}");
3291 let depth_arg = format!("--bit-depth={bit_depth}");
3292 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
3293 let out = run_with_stdin(
3294 Command::new(aomenc_path()).args([
3295 "--codec=av1",
3296 "--passes=1",
3297 "--end-usage=q",
3298 &cq_arg,
3299 "--cpu-used=0",
3300 "--threads=1",
3301 "--row-mt=0",
3302 "--sb-size=64",
3303 &depth_arg,
3304 &input_depth_arg,
3305 "--enable-rect-partitions=1",
3306 // AB off: it competes with 1:4 in the RD search (with
3307 // AB on, 0 superblock 1:4 strips appeared in 16
3308 // compared streams), and AB below 16x16 is another
3309 // lane's refusal.
3310 "--enable-ab-partitions=0",
3311 "--enable-1to4-partitions=1",
3312 // 16, not 8: with 8 every seed of this recipe stops
3313 // at a 32x32-level PARTITION_HORZ_4/VERT_4 (partition
3314 // values 8/9, 32x8/8x32 luma strips), a shape this
3315 // decoder does not code at all yet -- 12/12 attempts
3316 // refused before a pixel was compared (measured r1).
3317 // At 16 the 1:4 split happens at the superblock, the
3318 // 64x16/16x64 strips whose chroma half is 32x8/8x32.
3319 "--min-partition-size=16",
3320 "--max-partition-size=64",
3321 "--enable-restoration=0",
3322 "--enable-palette=0",
3323 "--deltaq-mode=0",
3324 "--enable-cdef=0",
3325 "--enable-filter-intra=0",
3326 "--enable-cfl-intra=0",
3327 "--enable-intrabc=0",
3328 "--obu",
3329 "-o",
3330 "-",
3331 "-",
3332 ]),
3333 &y4m.stdout,
3334 );
3335 assert!(
3336 out.status.success(),
3337 "{NAME}: aomenc refused the fixture: {}",
3338 String::from_utf8_lossy(&out.stderr)
3339 );
3340 out.stdout
3341 }
3342
3343 /// Runs the census child on `fixture` and returns the `GRAINCENSUS` line's
3344 /// `(unwritten, scanned)` -- the POST-grain pair, over the picture
3345 /// `apply_grain` returns.
3346 pub(super) fn grain_census(fixture: &str) -> (usize, usize) {
3347 const NAME: &str =
3348 "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample";
3349 let exe = std::env::current_exe().expect("test binary path");
3350 let out = std::process::Command::new(exe)
3351 .args([
3352 "--exact",
3353 "stream::tests::t09::uwdep_child_unwritten_census",
3354 "--nocapture",
3355 ])
3356 .env("UWDEP_CENSUS_FIXTURE", fixture)
3357 .env("EC_AV1_PLANE_SENTINEL", "1")
3358 .output()
3359 .expect("running the census child");
3360 let text = format!(
3361 "{}{}",
3362 String::from_utf8_lossy(&out.stdout),
3363 String::from_utf8_lossy(&out.stderr),
3364 );
3365 text.lines()
3366 .find_map(|l| l.strip_prefix("GRAINCENSUS "))
3367 .and_then(parse_census_line)
3368 .unwrap_or_else(|| {
3369 panic!(
3370 "{NAME}: the census child reported no grained count for {fixture} \
3371 (child said: {:?})",
3372 text.trim()
3373 )
3374 })
3375 }
3376
3377 /// The synthetic non-vacuity control for the grained census: the child with
3378 /// `UWDEP_CENSUS_FIXTURE` UNSET hands [`census_unwritten_grained`] planes
3379 /// carrying 5 sentinel samples and reports what it counted. Function-level,
3380 /// so no fixture's decode behaviour can change it.
3381 pub(super) fn grain_census_synthetic() -> (usize, usize) {
3382 const NAME: &str =
3383 "the_grained_picture_the_caller_receives_carries_no_unwritten_plane_sample";
3384 let exe = std::env::current_exe().expect("test binary path");
3385 let out = std::process::Command::new(exe)
3386 .args([
3387 "--exact",
3388 "stream::tests::t09::uwdep_child_unwritten_census",
3389 "--nocapture",
3390 ])
3391 .env("EC_AV1_PLANE_SENTINEL", "1")
3392 .env("UWDEP_CENSUS_SYNTHETIC", "1")
3393 .env_remove("UWDEP_CENSUS_FIXTURE")
3394 .output()
3395 .expect("running the census child");
3396 let text = format!(
3397 "{}{}",
3398 String::from_utf8_lossy(&out.stdout),
3399 String::from_utf8_lossy(&out.stderr),
3400 );
3401 text.lines()
3402 .find_map(|l| l.strip_prefix("GRAINCENSUS "))
3403 .and_then(parse_census_line)
3404 .unwrap_or_else(|| {
3405 panic!(
3406 "{NAME}: the census child reported no synthetic grained count (child said: \
3407 {:?})",
3408 text.trim()
3409 )
3410 })
3411 }
3412
3413 /// Parses the child's `UWDEP_CENSUS <unwritten> frames=<n> scanned=<n>` line
3414 /// into `(unwritten, scanned)`. The scanned count is what makes the fixture
3415 /// arms meaningful: `unwritten == 0` is also what a build with the census call
3416 /// deleted reports, and only a non-zero scanned count distinguishes "scanned
3417 /// and found nothing" from "never scanned".
3418 pub(super) fn parse_census_line(v: &str) -> Option<(usize, usize)> {
3419 let mut parts = v.split_whitespace();
3420 let unwritten = parts.next()?.parse().ok()?;
3421 let scanned = parts
3422 .find_map(|p| p.strip_prefix("scanned="))?
3423 .parse()
3424 .ok()?;
3425 Some((unwritten, scanned))
3426 }
3427
3428 /// Runs the census child with `UWDEP_CENSUS_FIXTURE` UNSET, which makes it
3429 /// take the synthetic-positive path: hand [`census_unwritten_final`] planes
3430 /// with a known number of `PLANE_SENTINEL` values and report what it counted.
3431 /// This is the non-vacuity control, and it is a direct function-level check
3432 /// rather than a decode, so no fixture's decode behaviour can change it.
3433 pub(super) fn census_synthetic() -> (usize, usize) {
3434 const NAME: &str = "the_frame_the_caller_receives_carries_no_unwritten_plane_sample";
3435 let exe = std::env::current_exe().expect("test binary path");
3436 let out = std::process::Command::new(exe)
3437 .args([
3438 "--exact",
3439 "stream::tests::t09::uwdep_child_unwritten_census",
3440 "--nocapture",
3441 ])
3442 .env("EC_AV1_PLANE_SENTINEL", "1")
3443 .env("UWDEP_CENSUS_SYNTHETIC", "1")
3444 .env_remove("UWDEP_CENSUS_FIXTURE")
3445 .output()
3446 .expect("running the census child");
3447 let text = format!(
3448 "{}{}",
3449 String::from_utf8_lossy(&out.stdout),
3450 String::from_utf8_lossy(&out.stderr),
3451 );
3452 text.lines()
3453 .find_map(|l| l.strip_prefix("UWDEP_CENSUS "))
3454 .and_then(parse_census_line)
3455 .unwrap_or_else(|| {
3456 panic!(
3457 "{NAME}: the census child reported no synthetic count (child said: {:?})",
3458 text.trim()
3459 )
3460 })
3461 }
3462
3463 /// Runs [`allocdet_child_decode`] in a fresh process and parses its
3464 /// `ALLOCDET <fixture> frames=<n> hash=<hex>` lines into
3465 /// `(fixture, frames, hash)` in FIXTURES order.
3466 pub(super) fn allocdet_child(
3467 fixtures: &[&str],
3468 poison: Option<&str>,
3469 alloc: &str,
3470 ) -> Vec<(String, usize, u64)> {
3471 const NAME: &str = "the_frame_does_not_depend_on_the_plane_buffers_initial_content";
3472 let exe = std::env::current_exe().expect("test binary path");
3473 let mut cmd = std::process::Command::new(exe);
3474 cmd.args([
3475 "--exact",
3476 "stream::tests::t09::allocdet_child_decode",
3477 "--nocapture",
3478 ])
3479 .env("ALLOCDET_FIXTURES", fixtures.join(","))
3480 .env("EC_AV1_PLANE_ALLOC", alloc)
3481 .env_remove("ALLOCDET_SYNTHETIC");
3482 match poison {
3483 Some(p) => cmd.env("EC_AV1_PLANE_SENTINEL", p),
3484 None => cmd.env_remove("EC_AV1_PLANE_SENTINEL"),
3485 };
3486 let out = cmd.output().expect("running the allocdet child");
3487 let text = format!(
3488 "{}{}",
3489 String::from_utf8_lossy(&out.stdout),
3490 String::from_utf8_lossy(&out.stderr),
3491 );
3492 let mut rows = Vec::new();
3493 for f in fixtures {
3494 let line = text
3495 .lines()
3496 .find(|l| l.starts_with(&format!("ALLOCDET {f} ")))
3497 .unwrap_or_else(|| {
3498 panic!(
3499 "{NAME}: the child reported nothing for {f} (child said: {:?})",
3500 text.trim()
3501 )
3502 });
3503 let mut parts = line.split_whitespace();
3504 assert_eq!(parts.next(), Some("ALLOCDET"));
3505 assert_eq!(parts.next(), Some(*f));
3506 let frames = parts
3507 .find_map(|p| p.strip_prefix("frames="))
3508 .and_then(|v| v.parse().ok())
3509 .unwrap_or_else(|| panic!("{NAME}: no frame count in {line:?}"));
3510 let hash = parts
3511 .find_map(|p| p.strip_prefix("hash="))
3512 .and_then(|v| u64::from_str_radix(v, 16).ok())
3513 .unwrap_or_else(|| panic!("{NAME}: no hash in {line:?}"));
3514 rows.push(((*f).to_string(), frames, hash));
3515 }
3516 rows
3517 }
3518
3519 /// Two pictures identical except for ONE sample of ONE plane, hashed by the
3520 /// same FNV-1a the child uses. Equal values here would make the gate's
3521 /// equalities vacuous, so it is asserted to differ.
3522 pub(super) fn allocdet_synthetic() -> (u64, u64) {
3523 const P: u64 = 0x0000_0100_0000_01b3;
3524 let hash = |mut h: u64, samples: &[u16]| {
3525 for &s in samples {
3526 for b in s.to_le_bytes() {
3527 h ^= u64::from(b);
3528 h = h.wrapping_mul(P);
3529 }
3530 }
3531 h
3532 };
3533 let a = vec![128u16; 4096];
3534 let mut b = a.clone();
3535 b[2048] = 129;
3536 (
3537 hash(0xcbf2_9ce4_8422_2325, &a),
3538 hash(0xcbf2_9ce4_8422_2325, &b),
3539 )
3540 }
3541
3542 /// lane-av1formatsweep: encodes the odd-dimension arm's fixture --
3543 /// `testsrc2` (or the smoothed `mandelbrot` source at 12 bits, which
3544 /// keeps `allow_screen_content_tools` off) as `y4m`, then hands the pipe
3545 /// to `aomenc`. The child deadline comes from `run_with_stdin`
3546 /// (`EC_AV1_CHILD_TIMEOUT_SECS`), so a wedged encoder fails loudly.
3547 pub(super) fn odd_dim_stream(
3548 width: usize,
3549 height: usize,
3550 pix_fmt: &str,
3551 bit_depth: usize,
3552 smooth: bool,
3553 ) -> Vec<u8> {
3554 let source = if smooth {
3555 format!("mandelbrot=size={width}x{height}:rate=25")
3556 } else {
3557 format!("testsrc2=size={width}x{height}:rate=25")
3558 };
3559 let mut ffmpeg_args: Vec<String> = vec![
3560 "-v".into(),
3561 "error".into(),
3562 "-f".into(),
3563 "lavfi".into(),
3564 "-i".into(),
3565 source,
3566 ];
3567 if smooth {
3568 ffmpeg_args.extend(["-vf".into(), "gblur=sigma=6".into()]);
3569 }
3570 ffmpeg_args.extend([
3571 "-frames:v".into(),
3572 "4".into(),
3573 "-pix_fmt".into(),
3574 pix_fmt.into(),
3575 "-strict".into(),
3576 "-1".into(),
3577 "-f".into(),
3578 "yuv4mpegpipe".into(),
3579 "-".into(),
3580 ]);
3581 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3582 .args(&ffmpeg_args)
3583 .stdin(Stdio::null())
3584 .stdout(Stdio::piped())
3585 .stderr(Stdio::piped()), None, |c| c.output())
3586 .expect("ffmpeg failed to run");
3587 assert!(
3588 y4m.status.success(),
3589 "ffmpeg refused the {width}x{height} {pix_fmt} source: {}",
3590 String::from_utf8_lossy(&y4m.stderr)
3591 );
3592 let mut args: Vec<String> = [
3593 "--codec=av1",
3594 "--passes=1",
3595 "--end-usage=q",
3596 "--cq-level=20",
3597 "--cpu-used=2",
3598 "--threads=1",
3599 "--row-mt=0",
3600 "--lag-in-frames=0",
3601 "--kf-max-dist=100",
3602 "--limit=4",
3603 ]
3604 .iter()
3605 .map(|s| (*s).to_owned())
3606 .collect();
3607 if bit_depth > 8 {
3608 args.push(format!("--input-bit-depth={bit_depth}"));
3609 args.push(format!("--bit-depth={bit_depth}"));
3610 }
3611 args.extend(["--obu".into(), "-o".into(), "-".into(), "-".into()]);
3612 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3613 assert!(
3614 out.status.success(),
3615 "aomenc refused {args:?}: {}",
3616 String::from_utf8_lossy(&out.stderr)
3617 );
3618 out.stdout
3619 }
3620
3621 /// Reads `(mi_cols, mi_rows)` out of a stream's first frame header, and
3622 /// asserts the sequence header says the bit depth the caller asked for.
3623 pub(super) fn odd_dim_header_mi_grid(stream: &[u8], name: &str, bit_depth: usize) -> (usize, usize) {
3624 let mut parser = Av1Parser::new();
3625 let mut pos = 0usize;
3626 let mut seen_depth = None;
3627 let mut grid = None;
3628 while pos < stream.len() {
3629 let obu = parser
3630 .parse_obu(&stream[pos..])
3631 .unwrap_or_else(|e| panic!("{name}: aomenc OBU does not parse: {e:?}"));
3632 if obu.total_size == 0 {
3633 break;
3634 }
3635 pos += obu.total_size;
3636 match obu.kind {
3637 ObuKind::SequenceHeader(seq) => {
3638 assert_eq!(
3639 seq.color_config.bit_depth as usize, bit_depth,
3640 "{name}: the stream is not {bit_depth}-bit"
3641 );
3642 assert_eq!(
3643 (
3644 seq.color_config.subsampling_x,
3645 seq.color_config.subsampling_y
3646 ),
3647 (1, 1),
3648 "{name}: not a 4:2:0 stream"
3649 );
3650 seen_depth = Some(seq.color_config.bit_depth);
3651 }
3652 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => {
3653 grid = Some((
3654 (h.frame_width as usize).div_ceil(8),
3655 (h.frame_height as usize).div_ceil(8),
3656 ));
3657 }
3658 _ => {}
3659 }
3660 }
3661 assert!(seen_depth.is_some(), "{name}: no sequence header parsed");
3662 grid.expect("the stream carries no frame header")
3663 }
3664
3665 /// lane-av1formatsweep: a `testsrc2`/`mandelbrot` source rendered to
3666 /// `pix_fmt` as y4m and piped to `aomenc` at `bit_depth`, with `extra`
3667 /// aomenc flags. `smooth` selects the gblur'd `mandelbrot` source (1) or
3668 /// `testsrc2` (0). The child deadline comes from `run_with_stdin`
3669 /// (`EC_AV1_CHILD_TIMEOUT_SECS`), so a wedged encoder fails loudly.
3670 pub(super) fn chroma_format_stream(
3671 width: usize,
3672 height: usize,
3673 pix_fmt: &str,
3674 bit_depth: usize,
3675 frames: usize,
3676 extra: &[&str],
3677 smooth: u8,
3678 ) -> Vec<u8> {
3679 let source = if smooth == 1 {
3680 format!("mandelbrot=size={width}x{height}:rate=25")
3681 } else {
3682 format!("testsrc2=size={width}x{height}:rate=25")
3683 };
3684 let mut ffmpeg_args: Vec<String> = vec![
3685 "-v".into(),
3686 "error".into(),
3687 "-f".into(),
3688 "lavfi".into(),
3689 "-i".into(),
3690 source,
3691 ];
3692 if smooth == 1 {
3693 ffmpeg_args.extend(["-vf".into(), "gblur=sigma=6".into()]);
3694 }
3695 ffmpeg_args.extend([
3696 "-frames:v".into(),
3697 frames.to_string(),
3698 "-pix_fmt".into(),
3699 pix_fmt.into(),
3700 "-strict".into(),
3701 "-1".into(),
3702 "-f".into(),
3703 "yuv4mpegpipe".into(),
3704 "-".into(),
3705 ]);
3706 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3707 .args(&ffmpeg_args)
3708 .stdin(Stdio::null())
3709 .stdout(Stdio::piped())
3710 .stderr(Stdio::piped()), None, |c| c.output())
3711 .expect("ffmpeg failed to run");
3712 assert!(
3713 y4m.status.success(),
3714 "ffmpeg refused the {width}x{height} {pix_fmt} source: {}",
3715 String::from_utf8_lossy(&y4m.stderr)
3716 );
3717 // AOMENC FLAG PRECEDENCE (COMMON): aomenc keeps the FIRST occurrence
3718 // of a flag, so the per-arm override goes BEFORE the base list.
3719 let limit = format!("--limit={frames}");
3720 let mut args: Vec<String> = extra.iter().map(|s| (*s).to_owned()).collect();
3721 args.extend(
3722 [
3723 "--codec=av1",
3724 "--passes=1",
3725 "--end-usage=q",
3726 "--threads=1",
3727 "--row-mt=0",
3728 "--lag-in-frames=0",
3729 "--kf-max-dist=100",
3730 limit.as_str(),
3731 ]
3732 .iter()
3733 .map(|s| (*s).to_owned()),
3734 );
3735 if bit_depth > 8 {
3736 args.push(format!("--input-bit-depth={bit_depth}"));
3737 args.push(format!("--bit-depth={bit_depth}"));
3738 }
3739 args.extend(["--obu".into(), "-o".into(), "-".into(), "-".into()]);
3740 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3741 assert!(
3742 out.status.success(),
3743 "aomenc refused {args:?}: {}",
3744 String::from_utf8_lossy(&out.stderr)
3745 );
3746 out.stdout
3747 }
3748
3749 /// Asserts the stream's sequence header really is 4:4:4 (`ss 0,0`) at
3750 /// `bit_depth` before any pixel comparison is trusted (class
3751 /// `arrival-not-intent`: a recipe that silently produced 4:2:0 would
3752 /// make the whole gate a no-op for its own subject).
3753 pub(super) fn assert_444_header(stream: &[u8], name: &str, bit_depth: usize) {
3754 let mut parser = Av1Parser::new();
3755 let mut pos = 0usize;
3756 let mut seen = false;
3757 while pos < stream.len() {
3758 let obu = parser
3759 .parse_obu(&stream[pos..])
3760 .unwrap_or_else(|e| panic!("{name}: aomenc OBU does not parse: {e:?}"));
3761 if obu.total_size == 0 {
3762 break;
3763 }
3764 pos += obu.total_size;
3765 if let ObuKind::SequenceHeader(seq) = obu.kind {
3766 let cc = &seq.color_config;
3767 assert_eq!(
3768 (cc.subsampling_x, cc.subsampling_y),
3769 (0, 0),
3770 "{name}: the stream is not 4:4:4 (ss {}x{})",
3771 cc.subsampling_x,
3772 cc.subsampling_y
3773 );
3774 assert_eq!(
3775 cc.bit_depth as usize, bit_depth,
3776 "{name}: the stream is {}-bit, not {bit_depth}-bit",
3777 cc.bit_depth
3778 );
3779 seen = true;
3780 }
3781 }
3782 assert!(seen, "{name}: no sequence header parsed");
3783 }
3784
3785 /// lane-av1tilemeasure: the per-frame facts a tiling / superres / odd-size
3786 /// cell's OWN claim needs, read off the parsed stream.
3787 ///
3788 /// Every gate below asserts its cell through this, never through the
3789 /// aomenc flag that was supposed to produce it. `lanes/av1formatsweep.
3790 /// report.md` trap 2 is exactly that failure: `--tile-rows=1` below 256px
3791 /// high at `--sb-size=128` leaves the stream byte-identical, so a gate
3792 /// that trusted the flag would report an untiled decode as a tile-row
3793 /// decode (and the sweep's own 10/12-bit "tile rows" numbers were that).
3794 #[derive(Debug, Clone, Copy)]
3795 pub(super) struct FrameFacts {
3796 pub(super) tile_cols: u32,
3797 pub(super) tile_rows: u32,
3798 pub(super) use_superres: bool,
3799 pub(super) coded_w: u32,
3800 pub(super) coded_h: u32,
3801 pub(super) upscaled_w: u32,
3802 pub(super) mi_cols: u32,
3803 pub(super) mi_rows: u32,
3804 }
3805
3806 pub(super) fn frame_facts(stream: &[u8], name: &str) -> Vec<FrameFacts> {
3807 let mut parser = Av1Parser::new();
3808 let mut pos = 0usize;
3809 let mut out: Vec<FrameFacts> = Vec::new();
3810 while pos < stream.len() {
3811 let obu = parser
3812 .parse_obu(&stream[pos..])
3813 .unwrap_or_else(|e| panic!("{name}: aomenc OBU does not parse: {e:?}"));
3814 if obu.total_size == 0 {
3815 break;
3816 }
3817 pos += obu.total_size;
3818 if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = obu.kind {
3819 out.push(FrameFacts {
3820 tile_cols: h.tile_info.cols,
3821 tile_rows: h.tile_info.rows,
3822 use_superres: h.use_superres,
3823 coded_w: h.frame_width,
3824 coded_h: h.frame_height,
3825 upscaled_w: h.upscaled_width,
3826 mi_cols: h.mi_cols,
3827 mi_rows: h.mi_rows,
3828 });
3829 }
3830 }
3831 assert!(
3832 !out.is_empty(),
3833 "{name}: the stream carries no frame header"
3834 );
3835 out
3836 }
3837
3838 /// Decode-order frame 0 only, against the oracle's own
3839 /// `EC_AV1_FINAL_DUMP` for that frame: how many SAMPLES differ, and the
3840 /// first one as `(plane, x, y, ours, oracle)`.
3841 ///
3842 /// lane-av1loss444kf: the 4:4:4 lossless 256x256 cell's inter frames carry a
3843 /// SEPARATE, already-diagnosed walk defect (the per-mu-chunk lossless
3844 /// chroma span, `lanes/av1loss444mm.report.md` r1), so a whole-stream
3845 /// byte-exactness assert cannot name this one. `aomdec --limit=1` stops
3846 /// after the key frame, which is exactly the frame the reach fix moves.
3847 #[allow(clippy::type_complexity)]
3848 pub(super) fn key_frame_diffs(
3849 stream: &[u8],
3850 name: &str,
3851 ) -> (usize, Option<(usize, usize, usize, u8, u8)>) {
3852 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-kf-{}", std::process::id()));
3853 let _ = std::fs::remove_dir_all(&dir);
3854 std::fs::create_dir_all(&dir).expect("scratch dir");
3855 let obu = dir.join("in.obu");
3856 std::fs::write(&obu, stream).expect("writing the stream");
3857 let aom_prefix = dir.join("aomkf");
3858 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
3859 .args(["--codec=av1", "--limit=1", "-o"])
3860 .arg(dir.join("out.y4m"))
3861 .arg(&obu)
3862 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
3863 .stdin(Stdio::null())
3864 .stdout(Stdio::piped())
3865 .stderr(Stdio::piped()), None, |c| c.output())
3866 .expect("aomdec failed to run");
3867 assert!(
3868 out.status.success(),
3869 "{name}: the oracle aomdec refused the stream: {}",
3870 String::from_utf8_lossy(&out.stderr)
3871 );
3872 let ours_prefix = dir.join("ourskf");
3873 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
3874 let decoded = decode_stream(stream);
3875 set_final_dump_prefix(None);
3876 decoded.unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}"));
3877 let want = std::fs::read(format!("{}.f0", aom_prefix.display())).expect(
3878 "the oracle wrote no decode-order frame 0 -- rung 12 of \
3879 scripts/instrument-aom-oracle.sh is missing",
3880 );
3881 let got = std::fs::read(format!("{}.f0", ours_prefix.display()))
3882 .expect("this decoder wrote no decode-order frame 0");
3883 assert_eq!(
3884 got.len(),
3885 want.len(),
3886 "{name}: our key frame is {} bytes, the oracle's is {}",
3887 got.len(),
3888 want.len()
3889 );
3890 let side = (want.len() / 3).isqrt();
3891 let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count();
3892 let first = got.iter().zip(&want).position(|(a, b)| a != b).map(|at| {
3893 // the dump is plane after plane (Y, U, V), so the in-plane
3894 // offset is what carries the x/y split
3895 let plane = at / (side * side);
3896 let in_plane = at % (side * side);
3897 (plane, in_plane % side, in_plane / side, got[at], want[at])
3898 });
3899 let _ = std::fs::remove_dir_all(&dir);
3900 (differing, first)
3901 }
3902
3903 /// lane-av1cfl: per-plane sample-mismatch counts between this decoder's
3904 /// final stored frames and the instrumented oracle's, summed over every
3905 /// decode-order frame. Returns `[Y, U, V]`.
3906 ///
3907 /// [`decode_all_frames_vs_oracle`] panics on the first differing byte,
3908 /// which names an offset but not WHICH PLANE the offset falls in -- and
3909 /// for a chroma-scoped defect the plane split is the whole diagnosis
3910 /// (luma byte-exact while U and V both diverge is the chroma-sizing
3911 /// signature; all three diverging is not).
3912 ///
3913 /// `plane_samples` is each plane's own sample count in DECODE order
3914 /// (`[Y, U, V]`) and is read off this decoder's own frame rather than
3915 /// derived from the dimensions: at 4:2:0 the chroma planes are half-size
3916 /// and at 4:4:4 full-size, and a helper that assumed one layout would
3917 /// report every chroma byte as a luma byte. 8-bit only: the dump is one
3918 /// byte per sample at 8-bit and two at 10/12.
3919 pub(super) fn oracle_plane_diffs(stream: &[u8], name: &str, plane_samples: [usize; 3]) -> [usize; 3] {
3920 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-planes-{}", std::process::id()));
3921 let _ = std::fs::remove_dir_all(&dir);
3922 std::fs::create_dir_all(&dir).expect("scratch dir");
3923 let obu = dir.join("in.obu");
3924 std::fs::write(&obu, stream).expect("writing the stream");
3925 let aom_prefix = dir.join("aom");
3926 let out = crate::tool_cache::cached_output_io(Command::new(aomdec_path())
3927 .args(["--codec=av1", "-o"])
3928 .arg(dir.join("out.y4m"))
3929 .arg(&obu)
3930 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
3931 .stdin(Stdio::null())
3932 .stdout(Stdio::piped())
3933 .stderr(Stdio::piped()), None, |c| c.output())
3934 .expect("aomdec failed to run");
3935 assert!(
3936 out.status.success(),
3937 "{name}: the oracle aomdec refused the stream: {}",
3938 String::from_utf8_lossy(&out.stderr)
3939 );
3940 let mut oracle_frames = 0usize;
3941 while std::path::PathBuf::from(format!("{}.f{oracle_frames}", aom_prefix.display()))
3942 .is_file()
3943 {
3944 oracle_frames += 1;
3945 }
3946 assert!(
3947 oracle_frames > 0,
3948 "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \
3949 scripts/instrument-aom-oracle.sh is missing from {}",
3950 aomdec_path().display()
3951 );
3952 let ours_prefix = dir.join("ours");
3953 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
3954 let decoded = decode_stream(stream);
3955 set_final_dump_prefix(None);
3956 let _ = decoded.expect("the caller already decoded this stream cleanly");
3957 let total: usize = plane_samples.iter().sum();
3958 // Plane boundaries in the concatenated dump, in DECODE order.
3959 let mut starts = [0usize; 3];
3960 for p in 1..3 {
3961 starts[p] = starts[p - 1] + plane_samples[p - 1];
3962 }
3963 let mut per_plane = [0usize; 3];
3964 for i in 0..oracle_frames {
3965 let want =
3966 std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
3967 let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
3968 assert_eq!(
3969 got.len(),
3970 total,
3971 "{name}: decode-order frame {i} is {} bytes, expected {plane_samples:?} at 8-bit",
3972 got.len()
3973 );
3974 for p in 0..3 {
3975 let (a, b) = (starts[p], starts[p] + plane_samples[p]);
3976 per_plane[p] += got[a..b]
3977 .iter()
3978 .zip(&want[a..b])
3979 .filter(|(x, y)| x != y)
3980 .count();
3981 }
3982 }
3983 let _ = std::fs::remove_dir_all(&dir);
3984 per_plane
3985 }
3986
3987 /// Shared body for the lane-av1superpin 4:4:4 superres arms. It is the
3988 /// body of [`a_444_lossy_superres_stream_decodes_pixel_exact`] with the
3989 /// single `(denominator, coded_width)` constant generalised to a PER-FRAME
3990 /// table, which is what the mode-2 cell needs: libaom picks a different
3991 /// denominator for each frame there, so a single constant would either
3992 /// describe frame 0 only or be a literal the arithmetic below could not
3993 /// hold.
3994 ///
3995 /// Everything that makes the den=12 cell non-vacuous is here, unchanged:
3996 /// the pinned bytes (length + FNV-1a), 4:4:4 / 8-bit / superres-enabled
3997 /// from the sequence header, `use_superres` on every parsed frame header,
3998 /// the per-frame parsed denominator and coded size, and the coded width
3999 /// RE-DERIVED as `(UpscaledWidth*8 + denom/2)/denom` from that frame's OWN
4000 /// parsed denominator rather than compared to a literal alone -- so a
4001 /// re-pinned fixture cannot satisfy the literals while the scaled-size
4002 /// arithmetic moves under them. Then `superres_hits` and
4003 /// `predict_scaled_hits` as DELTAS (both counters are process-wide with no
4004 /// reset, so absolute values would pass on residue from another stream),
4005 /// the returned frames at the UPSCALED width with full-resolution 4:4:4
4006 /// chroma planes, and every decode-order frame byte-exact against the
4007 /// instrumented aomdec.
4008 #[allow(clippy::too_many_arguments)]
4009 pub(super) fn a_444_superres_arm(
4010 name: &str,
4011 fixture: &str,
4012 fixture_len: usize,
4013 fixture_fnv: u64,
4014 fixture_sha: &str,
4015 upscaled: (usize, usize),
4016 // `(denominator, coded_width)` per DECODE-ORDER frame.
4017 per_frame: &[(u8, usize)],
4018 ) -> Vec<ec_av1_syntax::FrameHeader> {
4019 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(fixture);
4020 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
4021 panic!(
4022 "{name}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
4023 which is a failure, not a skip",
4024 obu.display()
4025 )
4026 });
4027 assert_eq!(stream.len(), fixture_len, "{name}: fixture length moved");
4028 assert_eq!(fnv1a64(&stream), fixture_fnv, "{name}: fixture bytes moved");
4029
4030 // --- the header facts the CELL depends on, parsed not assumed ------
4031 let mut parser = Av1Parser::new();
4032 let mut pos = 0usize;
4033 let mut seq = None;
4034 let mut heads: Vec<FrameHeader> = Vec::new();
4035 while pos < stream.len() {
4036 let obu = parser
4037 .parse_obu(&stream[pos..])
4038 .unwrap_or_else(|e| panic!("{name}: aomenc OBU does not parse: {e:?}"));
4039 if obu.total_size == 0 {
4040 break;
4041 }
4042 pos += obu.total_size;
4043 match obu.kind {
4044 ObuKind::SequenceHeader(s) => seq = Some(s),
4045 ObuKind::FrameHeader(h) => heads.push(*h),
4046 ObuKind::Frame(h, _) => heads.push(*h),
4047 _ => {}
4048 }
4049 }
4050 let seq = seq.unwrap_or_else(|| panic!("{name}: the stream carries no sequence header"));
4051 assert_eq!(
4052 (
4053 seq.color_config.subsampling_x,
4054 seq.color_config.subsampling_y
4055 ),
4056 (0, 0),
4057 "{name}: the stream is not 4:4:4 (ss = ({}, {}))",
4058 seq.color_config.subsampling_x,
4059 seq.color_config.subsampling_y
4060 );
4061 assert_eq!(
4062 seq.color_config.bit_depth, 8,
4063 "{name}: not the 8-bit cell this gate names"
4064 );
4065 assert!(
4066 seq.enable_superres,
4067 "{name}: the sequence header does not enable superres at all"
4068 );
4069 assert_eq!(
4070 heads.len(),
4071 per_frame.len(),
4072 "{name}: {} frame headers, expected {}",
4073 heads.len(),
4074 per_frame.len()
4075 );
4076 for (i, (h, (denom, coded))) in heads.iter().zip(per_frame).enumerate() {
4077 // The assertion the phantom cell failed. Without a denominator
4078 // flag aomenc picks 8 and this is false while the stream still
4079 // decodes, which is how a whole sweep cell ends up mislabelled.
4080 assert!(
4081 h.use_superres,
4082 "{name}: frame {i} has use_superres = false -- this is an UNSCALED \
4083 stream and the gate would be measuring something other than the \
4084 cell it names (class gate-blind-to-feature)"
4085 );
4086 assert_eq!(
4087 h.superres_denom, *denom,
4088 "{name}: frame {i} PARSED denominator moved from {denom} -- read the \
4089 header, never the encoder flag (mode 2 chooses its own)"
4090 );
4091 assert_eq!(
4092 (h.upscaled_width as usize, h.frame_height as usize),
4093 upscaled,
4094 "{name}: frame {i} upscaled size moved"
4095 );
4096 assert_eq!(
4097 (h.frame_width as usize, h.frame_height as usize),
4098 (*coded, upscaled.1),
4099 "{name}: frame {i} CODED size moved -- this is the scaled half of \
4100 the cell and the part an unsized stream gets wrong"
4101 );
4102 // Re-derive rather than only compare literals, so a re-pinned
4103 // fixture cannot satisfy the numbers above while the scaled-size
4104 // arithmetic has moved under them. The denominator here is the
4105 // one PARSED out of this frame, so the check cannot be satisfied by
4106 // a literal that merely happens to agree.
4107 let d = u32::from(*denom);
4108 assert_eq!(
4109 (h.upscaled_width * 8 + d / 2) / d,
4110 h.frame_width,
4111 "{name}: frame {i}: FrameWidth is not (UpscaledWidth*8 + denom/2)/denom -- \
4112 the scaled size the cell rests on is not the spec's"
4113 );
4114 }
4115
4116 // --- the pixels -----------------------------------------------------
4117 let _guard = lock_gate_counters();
4118 let before_sr = crate::superres::superres_hits();
4119 let before_scaled = crate::mc::predict_scaled_hits();
4120 let frames = decode_stream(&stream).unwrap_or_else(|e| {
4121 panic!("{name}: the pinned 4:4:4 superres stream was refused: {e}")
4122 });
4123 let scaled_up = crate::superres::superres_hits() - before_sr;
4124 let scaled_mc = crate::mc::predict_scaled_hits() - before_scaled;
4125 assert!(
4126 scaled_up > 0,
4127 "{name}: zero superres_hits -- the upscaler never ran (class \
4128 gate-blind-to-feature)"
4129 );
4130 assert!(
4131 scaled_mc > 0,
4132 "{name}: zero predict_scaled_hits -- no inter block read a scaled reference, \
4133 so the scaled-PREDICTION half of the cell is unexercised (class \
4134 gate-blind-to-feature)"
4135 );
4136 assert_eq!(frames.len(), per_frame.len(), "{name}: decoded frame count");
4137 for (i, f) in frames.iter().enumerate() {
4138 // The upscale must have REPLACED the frame: a decoder that returned
4139 // the coded-width picture fails here, and without this check the
4140 // chroma-shape assertion below could be satisfied by coded-size
4141 // planes.
4142 assert_eq!(
4143 (f.width, f.height),
4144 upscaled,
4145 "{name}: frame {i} came back {}x{}, not the UPSCALED {}x{}",
4146 f.width,
4147 f.height,
4148 upscaled.0,
4149 upscaled.1
4150 );
4151 for (plane, len) in [("U", f.u.len()), ("V", f.v.len())] {
4152 assert_eq!(
4153 len,
4154 upscaled.0 * upscaled.1,
4155 "{name}: frame {i} {plane} plane is {len} samples; at 4:4:4 upscaled it \
4156 must be full resolution ({}x{})",
4157 upscaled.0,
4158 upscaled.1
4159 );
4160 }
4161 }
4162 if aomdec_available(name) {
4163 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, name);
4164 eprintln!(
4165 "{name}: {decoded} decode-order frame(s) ({hidden} hidden) byte-exact vs \
4166 aomdec at {upscaled:?} upscaled from {per_frame:?} (denominator, coded \
4167 width) per frame, {scaled_up} upscale(s), {scaled_mc} scaled MC block(s); \
4168 fixture sha256 {fixture_sha}"
4169 );
4170 }
4171 heads
4172 }