forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

t01.rs4538 lines, 218.5 KiBHistoryRawDownload
1use super::*;
2use super::support::*;
3use super::gates_a::*;
4use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
5use crate::probe::run_with_stdin;
6use std::process::{Command, Stdio};
7
8 /// lane-av1422lift: THE 4:2:2 LIFT, in two pins. This test is the renamed,
9 /// inverted replacement for `a_non_420_subsampled_sequence_header_is_
10 /// refused_by_name`, and the two fixtures replace that gate's fixture --
11 /// a hand-built profile-2 header bolted onto a 4:2:0 TILE from this
12 /// crate's own encoder, which could never be inverted into an exactness
13 /// claim no matter how the assert was flipped (class `refusal-lifted-
14 /// without-a-gate`, and the risk study's R6).
15 ///
16 /// Both pins are REAL 4:2:2 streams from libaom's own writer over a
17 /// y4m whose header line is `C422`, so every chroma symbol in them is a
18 /// 4:2:2 chroma symbol. Provenance (both, verbatim, no other encoder):
19 ///
20 /// ```text
21 /// aomenc --codec=av1 --profile=2 \
22 /// --input-chroma-subsampling-x=1 --input-chroma-subsampling-y=0 \
23 /// --passes=1 --end-usage=q --cq-level=24 --cpu-used=0 \
24 /// --threads=1 --row-mt=0 --obu -o <pin> <source.y4m>
25 /// ```
26 ///
27 /// * `422_key_64x64.obu` -- 755 bytes, sha256
28 /// `3c9396c9e42701d720419ec2cb5577387e305482df0cb150f7f0b965edeaaffc`,
29 /// fnv1a64 `0x87fc569cf53bcbc6`. A single 64x64 8-bit KEY frame
30 /// (`--limit=1 --kf-min-dist=0 --kf-max-dist=0`) over a
31 /// hand-generated two-frame integer `C422` card source, the second
32 /// source frame unused by the `--limit=1`. The smallest thing that can
33 /// say "4:2:2 intra reconstructs".
34 /// * `422_inter_160x128_3f.obu` -- 6522 bytes, sha256
35 /// `7b54834c18f5fdc0e8606a6dc5bf4ff368402417d87fcfc2ab9758e4e9164902`,
36 /// fnv1a64 `0xf87eba3bf4fc2bb8`. Three 160x128 8-bit frames with a
37 /// panning square
38 /// (`--limit=3 --kf-min-dist=3 --kf-max-dist=3`, so frames 1 and 2 are
39 /// INTER), over a three-frame integer `C422` card source whose square
40 /// moves (6,4) -> (9,6) -> (12,8). This is what exercises the
41 /// inter-predicted 4:2:2 chroma reference: a decoder that walked the
42 /// key frame correctly and then predicted chroma from a 4:2:0-shaped
43 /// reference passes the first pin and reds here.
44 ///
45 /// Both are asserted BYTE-EXACT against ffmpeg 8.1.3's own rawvideo of
46 /// the same bytes at `yuv422p`, per plane and per frame, with the
47 /// per-plane coefficient-unit census as the non-vacuity arm (see
48 /// [`assert_422_stream_pixel_exact`]). A gate whose only assertion was
49 /// `err.contains(REFUSAL)` would have passed unchanged on a tree where
50 /// 4:2:2 decode was completely broken; that is what this replaces.
51 #[test]
52 fn a_real_422_key_frame_and_inter_sequence_decode_pixel_exact() {
53 const NAME: &str = "a_real_422_key_frame_and_inter_sequence_decode_pixel_exact";
54 if !have_ffmpeg() {
55 eprintln!("SKIP {NAME}: no ffmpeg");
56 return;
57 }
58 let key = crate_pin("422_key_64x64.obu");
59 let key_stream = read_pin(&key, 755, 0x87fc569cf53bcbc6, NAME);
60 let (units, _) = assert_422_stream_pixel_exact(NAME, &key_stream, 64, 64, 1, 8, true);
61 let (l, u, v) = (units[0], units[1], units[2]);
62 assert!(
63 l > 0 && u > 0 && v > 0,
64 "{NAME}: the key-frame pin walked no 4:2:2 chroma units [{l}, {u}, {v}]"
65 );
66
67 let inter = crate_pin("422_inter_160x128_3f.obu");
68 let inter_stream = read_pin(&inter, 6522, 0xf87eba3bf4fc2bb8, NAME);
69 let (units, _) = assert_422_stream_pixel_exact(NAME, &inter_stream, 160, 128, 3, 8, true);
70 let (l, u, v) = (units[0], units[1], units[2]);
71 assert!(
72 u > 0 && v > 0,
73 "{NAME}: the inter pin walked no 4:2:2 chroma units [{l}, {u}, {v}] -- the inter \
74 chroma reference path was never reached"
75 );
76 }
77
78 /// lane-av1422lift: 4:2:2 at 12 bits, and 4:2:2 with superres, are the two
79 /// cells the corpus had no coverage for at all (the risk study's R3 and
80 /// R9: the sweep recipe passed no 12-bit depth and no `--superres-mode`,
81 /// so every 4:2:2 measurement in the tree was 8- or 10-bit, none
82 /// superres). Both are pinned and both are byte-exact here.
83 ///
84 /// `s422_12bit_160x128.obu` -- 9214 bytes, sha256
85 /// `eacc70f75c82ad7d795efbd0242aa4ee33db917b8c1a3570ebce2570ee8bc245`,
86 /// fnv1a64 `0xa62b8e3fe6f60ae5`. 160x128, 12-bit, 3 frames,
87 /// `yuv422p12le` per ffprobe, profile 2 ("Professional").
88 ///
89 /// **Provenance is ffmpeg's libaom-av1 wrapper, not aomenc, and the
90 /// reason is measured, not preferred.** aomenc's own 12-bit y4m path
91 /// issues `AV1E_SET_CHROMA_SUBSAMPLING_X` (apps/aomenc.c:2272-2278,
92 /// reached whenever the input is not 4:2:0 and the bit depth is 12)
93 /// BEFORE `aom_codec_enc_config_set`, and on this libaom that control
94 /// returns `AOM_CODEC_INTERNAL_ERROR` for any non-4:2:0 shape -- measured
95 /// on four independently built trees
96 /// (`~/.cache/aom-oracle`, `aom-affine`, `aom-oracle2`, `aom-oracle3`):
97 /// `C422p12` and `C444p12` both die with "Failed to set chroma
98 /// subsampling x", while `C420p12` and the 8-bit `C422`/`C444` both
99 /// encode. It is not a 4:2:2-specific gap (12-bit 4:4:4 fails too) and
100 /// not a 4:2:0 gap (12-bit 4:2:0 encodes). The same control succeeds at
101 /// 8 bits, so the failure is the 12-bit configuration order, and the
102 /// workaround is a wrapper that sets the codec config first. ffmpeg's
103 /// libaom-av1 does exactly that:
104 ///
105 /// ```text
106 /// ffmpeg -f lavfi -i "testsrc2=size=160x128:rate=1:duration=3" \
107 /// -pix_fmt yuv422p12le -c:v libaom-av1 -profile:v 2 -b:v 0 -crf 30 \
108 /// -cpu-used 8 -auto-alt-ref 0 -lag-in-frames 0 \
109 /// -strict experimental -f obu s422_12bit_160x128.obu
110 /// ```
111 ///
112 /// That is libaom's encoder either way -- ffmpeg links it and calls
113 /// `aom_codec_encode` -- and the oracle side is ffmpeg's own
114 /// `yuv422p12le` rawvideo decode of the same bytes, so the pin and the
115 /// oracle come from the same library, which is the property that makes
116 /// byte-exactness a claim about OUR decoder rather than about a
117 /// disagreement between two encoders.
118 ///
119 /// `s422_superres_160x128.obu` -- 5304 bytes, sha256
120 /// `5852ff2c273cb773c4886762c6a6f2cce6e12065a690eb3a5ca2119c0b6f2957`,
121 /// fnv1a64 `0x0789d1b2851b94ae`. 160x128, 8-bit, 3 frames, `--superres-
122 /// mode=1` (fixed) over a `C422` testsrc2 source, encoded by the
123 /// aomenc recipe above plus `--superres-mode=1`. Superres is the one
124 /// 4:2:2 path whose output crop is `(round_ss(w,1) x round_ss(h,0))` at
125 /// the UPSCALED size, and it had no 4:2:2 cell anywhere.
126 #[test]
127 fn a_real_422_12bit_and_superres_stream_decode_pixel_exact() {
128 const NAME: &str = "a_real_422_12bit_and_superres_stream_decode_pixel_exact";
129 if !have_ffmpeg() {
130 eprintln!("SKIP {NAME}: no ffmpeg");
131 return;
132 }
133 let hbd = crate_pin("s422_12bit_160x128.obu");
134 let hbd_stream = read_pin(&hbd, 9214, 0xa62b8e3fe6f60ae5, NAME);
135 assert_422_stream_pixel_exact(NAME, &hbd_stream, 160, 128, 3, 12, true);
136
137 let sr = crate_pin("s422_superres_160x128.obu");
138 let sr_stream = read_pin(&sr, 5304, 0x0789d1b2851b94ae, NAME);
139 assert_422_stream_pixel_exact(NAME, &sr_stream, 160, 128, 3, 8, true);
140 }
141
142 /// lane-av1lr422: a libaom-recipe 10-bit 4:2:2 stream with loop
143 /// restoration ON, `s422_lr_10bit_200x120.obu` (129409 bytes, sha256
144 /// `5d6bc195934709390191c9ea8af167d385552c5b1330e8abd38f76a4416ba751`,
145 /// fnv1a64 `0xc5d5489355fdc2df`), 200x120, 8 frames. It was REFUSED by
146 /// the sub-8x8 plane-block check before the fix: the refusal was a
147 /// parse desync, not a wrong check. The 32x8 / 8x32 rect4 general arm
148 /// gathered the chroma dc-sign votes per mi instead of per 4-px chroma
149 /// column, which desynced the coefficient contexts. Decodes byte-exact
150 /// against ffmpeg libdav1d rawvideo.
151 #[test]
152 fn a_422_10bit_lr_stream_decodes_pixel_exact() {
153 const NAME: &str = "a_422_10bit_lr_stream_decodes_pixel_exact";
154 if !have_ffmpeg() {
155 eprintln!("SKIP {NAME}: no ffmpeg");
156 return;
157 }
158 let p = crate_pin("s422_lr_10bit_200x120.obu");
159 let stream = read_pin(&p, 129409, 0xc5d5489355fdc2df, NAME);
160 assert_422_stream_pixel_exact(NAME, &stream, 200, 120, 8, 10, true);
161 }
162
163 /// lane-av1odd440, CELL 1 of 2: `4:2:0 with an ODD luma dimension`, the
164 /// cell `lanes/av1formatsweep.report.md` left as declared debt because
165 /// "aomenc rounds a 4:2:0 frame's coded size DOWN to even, so no stream
166 /// this recipe can produce codes an odd luma dimension".
167 ///
168 /// The pin, `420_odd65x65_key.obu` (2305 bytes,
169 /// sha256 `66986019a561f81130f407f426c4379b25e6e80c2cd9ce47d517b3216e9a03cf`),
170 /// is that missing stream, built offline by
171 /// `examples/gen_coverage_cells.rs`: a 96x96 card padded to the block
172 /// grid, coded by `encode::encode_key_frame_at_size` with a 65x65 frame
173 /// header. Provenance: that example, `cargo run -p ec-av1 --example
174 /// gen_coverage_cells -- crates/ec-av1/fixtures`; no encoder, no ffmpeg,
175 /// no lavfi.
176 ///
177 /// WHY THE CELL IS NOT A RUBBER STAMP -- the chroma extent is where a
178 /// floor shows. A 65-wide 4:2:0 frame has
179 /// `ROUND_POWER_OF_TWO(65, 1) = 33` chroma columns (libaom
180 /// `av1_common_plane_width`, `av1/common/av1_common_int.h`), not 32, so
181 /// the decoded frame's own plane sizes, the rawvideo sample count and
182 /// the oracle compare all move if `decode::round_ss` is floored. The
183 /// mutation was run: flooring `round_ss` (`decode.rs:697`) turns the
184 /// `round_ss` assert below red at 32 chroma columns and the oracle arm
185 /// red at a 6273-byte raw against the oracle's 6403. The gate is
186 /// therefore not green on a floored decoder, which is the whole content
187 /// of this cell.
188 ///
189 /// The stream decodes PIXEL-EXACT against the instrumented `aomdec`
190 /// (6403 raw bytes = 65*65 + 2*33*33, byte-identical), so the cell is a
191 /// `y` and not a `–`.
192 #[test]
193 fn an_odd_luma_420_key_frame_decodes_pixel_exact() {
194 const NAME: &str = "an_odd_luma_420_key_frame_decodes_pixel_exact";
195 let _gate_lock = lock_gate_counters();
196 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
197 .join("fixtures")
198 .join("420_odd65x65_key.obu");
199 let stream = read_pin(&path, 2305, 0xf55645c4b139e8f7, NAME);
200
201 // The stream's OWN header, read from its own bytes: an odd luma size
202 // at 4:2:0, which is the cell. (Taken from the pin, not from the
203 // gate's name -- class `helper-packs-u16-for-an-8-bit-stream`.)
204 let mut probe = Av1Parser::new();
205 let mut pos = 0usize;
206 while pos < stream.len() && probe.sequence_header().is_none() {
207 let obu = probe
208 .parse_obu(&stream[pos..])
209 .unwrap_or_else(|e| panic!("{NAME}: OBU at byte {pos} does not parse: {e:?}"));
210 pos += obu.total_size;
211 }
212 let seq = probe
213 .sequence_header()
214 .unwrap_or_else(|| panic!("{NAME}: the pin carries no sequence header"));
215 assert_eq!(
216 (seq.max_frame_width, seq.max_frame_height),
217 (65, 65),
218 "{NAME}: the pin must declare an ODD luma size, it declares {}x{}",
219 seq.max_frame_width,
220 seq.max_frame_height
221 );
222 assert_eq!(
223 (
224 seq.color_config.subsampling_x,
225 seq.color_config.subsampling_y
226 ),
227 (1, 1),
228 "{NAME}: this cell is an odd luma SIZE at 4:2:0, not another chroma shape"
229 );
230
231 // The decoded frame's own extents. This arm needs no oracle, and it
232 // is the one a floored `round_ss` turns red.
233 let frames = decode_stream(&stream).expect("the odd-luma 4:2:0 pin must decode");
234 assert_eq!(frames.len(), 1, "{NAME}: frame count");
235 let frame = &frames[0];
236 assert_eq!(
237 (frame.width, frame.height),
238 (65, 65),
239 "{NAME}: decoded luma extent"
240 );
241 assert_eq!(frame.y.len(), 65 * 65, "{NAME}: decoded luma sample count");
242 assert_eq!(
243 (frame.u.len(), frame.v.len()),
244 (33 * 33, 33 * 33),
245 "{NAME}: a 65x65 4:2:0 frame has ROUND_POWER_OF_TWO(65,1) = 33 chroma \
246 columns and rows -- 32 means the extent was floored"
247 );
248
249 if !aomdec_available(NAME) {
250 return;
251 }
252 assert_rawvideo_matches(&path, &stream, NAME, 1, 8);
253 }
254
255 /// lane-av1odd440, CELL 2 of 2: the `4:4:0 (ss 0,1)` row, which the same
256 /// report called "unmeasured and unproducible by recipe". It is neither
257 /// unmeasured nor unproducible: it is NOT A CELL AT ALL.
258 ///
259 /// `subsampling_y` is coded only when `subsampling_x` is 1 (spec 5.5.2
260 /// `color_config`), so a sequence header can carry exactly three chroma
261 /// shapes -- 4:2:0 `(1,1)`, 4:2:2 `(1,0)`, 4:4:4 `(0,0)` -- and never
262 /// `(0,1)`. libaom says so in both directions: the reader leaves
263 /// `subsampling_y = 0` when `subsampling_x` is 0
264 /// (`av1_read_color_config`, `av1/decoder/decodeframe.c:4171-4175`) and
265 /// the writer ASSERTS it -- `assert(seq_params->subsampling_y == 0 &&
266 /// "4:4:0 subsampling not allowed in AV1")`, `av1/encoder/bitstream.c:
267 /// 2463-2465`. So there is no stream to decode, no fixture to pin that
268 /// a decoder could be handed, and no oracle to compare against: a
269 /// 4:4:0 row in a coverage matrix is a matrix bug, not a decoder gap.
270 ///
271 /// What is pinned, then, is the claim itself, in three arms that a
272 /// mutation turns red:
273 ///
274 /// 1. WRITER: every `(profile, bit_depth, mono, colour description,
275 /// requested subsampling)` combination a `color_config` can carry is
276 /// written by this crate's own writer and read back by this crate's
277 /// own reader. The reachable set is asserted to be EXACTLY
278 /// `{(1,1), (1,0), (0,0)}` -- each legal shape present, `(0,1)`
279 /// absent -- and, on the BYTES rather than on the round trip, the two
280 /// requests that differ only in `subsampling_y` must write identical
281 /// headers whenever `subsampling_x` is 0. A sweep that silently wrote
282 /// nothing would pass, so the count of combinations actually written
283 /// and read is asserted too.
284 /// 2. READER: the one byte that carries `subsampling_x` is found by
285 /// diffing an `(0,0)` header against an `(1,0)` one, and then all 256
286 /// values of that byte are fed back through the reader. Not one of the
287 /// headers that parse reads back `(0,1)`, because the reader never
288 /// reads a `subsampling_y` bit in that position. A reader that always
289 /// read a second bit would produce `(0,1)` at the one value that sets
290 /// both bits.
291 /// 3. THE PIN: `440_request_is_422.obu` (2014 bytes, sha256
292 /// `4afaa5470c4e010d9d970086ef514680adfe801a579e4deeec582f52d13c5e7c`,
293 /// fnv1a64 `0x98a1378df976253d`) is what this crate's writer produces
294 /// when it is handed `subsampling (0,1)` at profile 2 -- profile 2
295 /// below 12 bits is 4:2:2 and codes no subsampling bit at all, so the
296 /// request lands on `(1,0)`. The pin is asserted to read back `(1,0)`,
297 /// NOT `(0,1)`. Its frame OBU is a 4:2:0 key frame's, so the pin is a
298 /// HEADER witness, not a decodable 4:2:2 stream -- nothing here claims
299 /// pixels for it. Provenance: `examples/gen_coverage_cells.rs`, `cargo
300 /// run -p ec-av1 --example gen_coverage_cells -- crates/ec-av1/fixtures`.
301 ///
302 /// lane-av1422lift: this arm used to end "and the decoder is asserted
303 /// to refuse it by name, which is the honest outcome for the shape a
304 /// 4:4:0 request actually yields". That was honest only because the
305 /// decoder refused EVERY (1,0) header -- the assertion was about the
306 /// guard, not about these bytes. With 4:2:2 admitted, refusing these
307 /// bytes would be wrong and accepting them without comment would be
308 /// worse, so the arm now asserts the one thing that IS true of them:
309 /// the SEQUENCE HEADER, not the tile, fixes the decode's chroma
310 /// geometry. The pixel claim moved to genuinely 4:2:2 pins.
311 #[test]
312 fn the_440_cell_is_not_a_codable_chroma_shape() {
313 const NAME: &str = "the_440_cell_is_not_a_codable_chroma_shape";
314 let _gate_lock = lock_gate_counters();
315 let header_obu = |profile: u8, color: ec_av1_syntax::ColorConfig| -> Vec<u8> {
316 let (mut seq, _header) = crate::encode::key_frame_headers_colour(64, 64, 100, color)
317 .expect("the header builders accept a colour config");
318 seq.seq_profile = profile;
319 crate::sequence::sequence_header_obu(&seq).expect("writing the sequence header")
320 };
321 let shape_of = |obu: &[u8]| -> Option<(u8, u8)> {
322 let mut parser = Av1Parser::new();
323 let parsed = parser.parse_obu(obu).ok()?;
324 if !matches!(parsed.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)) {
325 return None;
326 }
327 let seq = parser.sequence_header()?;
328 Some((
329 seq.color_config.subsampling_x,
330 seq.color_config.subsampling_y,
331 ))
332 };
333
334 // ---- arm 1: the writer's whole reachable space --------------------
335 let mut reachable: std::collections::BTreeSet<(u8, u8)> = Default::default();
336 let mut asked = 0usize;
337 for profile in [0u8, 1, 2] {
338 for bit_depth in [8u8, 10, 12] {
339 for mono_chrome in [false, true] {
340 // Profile 1 is 4:4:4 and codes no mono bit; asking for
341 // monochrome there is refused by the writer, which is
342 // not a chroma shape and not this gate's subject.
343 if mono_chrome && profile == 1 {
344 continue;
345 }
346 for (label, (cp, tc, mc)) in [
347 ("unspecified", (2u8, 2u8, 2u8)),
348 ("bt709", (1u8, 1u8, 1u8)),
349 ("srgb", (1u8, 13u8, 0u8)),
350 ] {
351 for sx in [0u8, 1] {
352 for sy in [0u8, 1] {
353 let color = ec_av1_syntax::ColorConfig {
354 bit_depth,
355 mono_chrome,
356 num_planes: if mono_chrome { 1 } else { 3 },
357 color_primaries: cp,
358 transfer_characteristics: tc,
359 matrix_coefficients: mc,
360 color_range: false,
361 subsampling_x: sx,
362 subsampling_y: sy,
363 chroma_sample_position:
364 ec_av1_syntax::ChromaSamplePosition::Unknown,
365 separate_uv_delta_q: false,
366 };
367 asked += 1;
368 let obu = header_obu(profile, color);
369 // The WRITER half of the claim, measured on the
370 // bytes rather than on a round trip: with
371 // `subsampling_x == 0` the spec codes no
372 // `subsampling_y` bit at all, so the two
373 // requests that differ ONLY in `subsampling_y`
374 // must produce byte-identical headers. A
375 // writer that emitted the bit anyway (the
376 // mutation libaom's own `assert` exists to
377 // catch, av1/encoder/bitstream.c:2467-2468) fails
378 // here -- and note it does NOT fail the
379 // round trip, because the reader then absorbs
380 // the extra bit as `separate_uv_delta_q`.
381 if sx == 0 {
382 let mut other = color;
383 other.subsampling_y = 1;
384 assert_eq!(
385 obu,
386 header_obu(profile, other),
387 "{NAME}: a (0,0) and a (0,1) request wrote DIFFERENT \
388 bytes at profile {profile}, {bit_depth}-bit, mono \
389 {mono_chrome}, {label} -- `subsampling_y` must not be \
390 coded at all when `subsampling_x` is 0"
391 );
392 }
393 if let Some(got) = shape_of(&obu) {
394 assert_ne!(
395 got,
396 (0, 1),
397 "{NAME}: a 4:4:0 shape came back out of the writer at \
398 profile {profile}, {bit_depth}-bit, mono {mono_chrome}, \
399 {label}, asked for ({sx},{sy}) -- libaom forbids this \
400 shape outright (av1/encoder/bitstream.c:2467-2468)"
401 );
402 reachable.insert(got);
403 }
404 }
405 }
406 }
407 }
408 }
409 }
410 assert!(
411 asked >= 100 && reachable.len() == 3,
412 "{NAME}: the sweep asked {asked} combinations and reached {} shapes -- it must reach \
413 all three legal ones, or it is not measuring the space",
414 reachable.len()
415 );
416 assert_eq!(
417 reachable,
418 std::collections::BTreeSet::from([(0u8, 0u8), (1u8, 0u8), (1u8, 1u8)]),
419 "{NAME}: the chroma shapes a `color_config` can code are exactly 4:4:4 (0,0), 4:2:2 \
420 (1,0) and 4:2:0 (1,1)"
421 );
422
423 // ---- arm 2: the reader's bit at that position ----------------------
424 // Profile 2 at 12 bits is the only place BOTH subsampling bits are
425 // coded, so it is where a hand-built header could try to smuggle a
426 // `subsampling_y`. Find the byte that carries `subsampling_x` by
427 // diffing the two shapes, then read back all eight of its values.
428 let at_444 = |sx: u8| {
429 let color = ec_av1_syntax::ColorConfig {
430 bit_depth: 12,
431 subsampling_x: sx,
432 subsampling_y: 0,
433 chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown,
434 ..ec_av1_syntax::ColorConfig::default()
435 };
436 let (mut seq, _h) =
437 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
438 seq.seq_profile = 2;
439 let obu = crate::sequence::sequence_header_obu(&seq).unwrap();
440 let mut parser = Av1Parser::new();
441 parser.parse_obu(&obu).expect("the profile-2 header parses");
442 let seq = parser.sequence_header().expect("sequence header");
443 (
444 seq.color_config.subsampling_x,
445 seq.color_config.subsampling_y,
446 )
447 };
448 assert_eq!(at_444(0), (0, 0), "{NAME}: the sx=0 header is 4:4:4");
449 assert_eq!(at_444(1), (1, 0), "{NAME}: the sx=1 header is 4:2:2");
450 let base = {
451 let color = ec_av1_syntax::ColorConfig {
452 bit_depth: 12,
453 subsampling_x: 0,
454 subsampling_y: 0,
455 chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown,
456 ..ec_av1_syntax::ColorConfig::default()
457 };
458 let (mut seq, _h) =
459 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
460 seq.seq_profile = 2;
461 crate::sequence::sequence_header_obu(&seq).unwrap()
462 };
463 let other = {
464 let color = ec_av1_syntax::ColorConfig {
465 bit_depth: 12,
466 subsampling_x: 1,
467 subsampling_y: 0,
468 chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown,
469 ..ec_av1_syntax::ColorConfig::default()
470 };
471 let (mut seq, _h) =
472 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
473 seq.seq_profile = 2;
474 crate::sequence::sequence_header_obu(&seq).unwrap()
475 };
476 assert_eq!(
477 base.len(),
478 other.len(),
479 "{NAME}: the two headers must differ in place"
480 );
481 let byte_at = base
482 .iter()
483 .zip(&other)
484 .position(|(a, b)| a != b)
485 .expect("the two shapes must differ somewhere");
486 // Every value of that byte is fed back through the reader -- it is the
487 // LAST payload byte, so the bits a smuggled `subsampling_y` would come
488 // from are in it too (spec 5.5.2 always codes `separate_uv_delta_q`
489 // after the subsampling pair, and the payload is padded out to the
490 // byte with `trailing_bits`). A header that stops parsing is not a
491 // 4:4:0 shape and cannot be counted as one; the sweep asserts how
492 // many DID parse, so a sweep that quietly parsed nothing is not
493 // evidence of anything.
494 let mut parsed_headers = 0usize;
495 for value in 0..256u16 {
496 let mut poked = base.clone();
497 poked[byte_at] = value as u8;
498 let mut parser = Av1Parser::new();
499 let Ok(parsed) = parser.parse_obu(&poked) else {
500 continue;
501 };
502 if !matches!(parsed.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)) {
503 continue;
504 }
505 let seq = parser.sequence_header().expect("sequence header");
506 parsed_headers += 1;
507 assert_ne!(
508 (
509 seq.color_config.subsampling_x,
510 seq.color_config.subsampling_y
511 ),
512 (0, 1),
513 "{NAME}: payload byte {byte_at} = {value:#04x} read back as 4:4:0 -- the reader \
514 took a `subsampling_y` bit that spec 5.5.2 does not code when `subsampling_x` \
515 is 0"
516 );
517 }
518 assert!(
519 parsed_headers > 100,
520 "{NAME}: only {parsed_headers} of the 256 poked headers parsed -- the sweep is not \
521 measuring the reader"
522 );
523
524 // ---- arm 3: the pinned bytes a 4:4:0 request produces --------------
525 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
526 .join("fixtures")
527 .join("440_request_is_422.obu");
528 let pinned = read_pin(&path, 2014, 0x98a1378df976253d, NAME);
529 let mut parser = Av1Parser::new();
530 let obu = parser
531 .parse_obu(&pinned)
532 .unwrap_or_else(|e| panic!("{NAME}: the pin's first OBU does not parse: {e:?}"));
533 assert!(
534 matches!(obu.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)),
535 "{NAME}: the pin must start with its sequence header"
536 );
537 let seq = parser.sequence_header().expect("the pin's sequence header");
538 assert_eq!(
539 (
540 seq.color_config.subsampling_x,
541 seq.color_config.subsampling_y
542 ),
543 (1, 0),
544 "{NAME}: the pin is what a 4:4:0 request at profile 2 produces -- 4:2:2 (1,0). If this \
545 ever reads (0,1), a 4:4:0 cell became codable and this whole gate is wrong about the \
546 format."
547 );
548 // lane-av1unwritten: lane-av1422lift replaced the old 4:2:2 header
549 // refusal with "it decodes, and the decoded chroma planes are 32x64".
550 // That was the wrong contract for THIS pin: its frame OBU is a 4:2:0
551 // key frame's, so at 4:2:2 its partition symbols name subsizes with no
552 // chroma plane block, which libaom rejects as a corrupt frame
553 // ("Block size 8x16 invalid with this subsampling mode",
554 // decodeframe.c:1456) and `aomdec` does. The replacement is the
555 // REFUSAL, by that rule.
556 //
557 // The pin's remaining job is unchanged and still worth saying: it
558 // proves a 4:4:0 REQUEST at profile 2 lands on 4:2:2 (1,0), i.e. that
559 // `the_440_cell_is_not_a_codable_chroma_shape`'s claim is still true.
560 let err = decode_stream(&pinned).err().unwrap_or_else(|| {
561 panic!(
562 "{NAME}: the pin is a 4:2:2 header over a 4:2:0 tile -- libaom refuses it \
563 (aomdec: \"Block size 8x16 invalid with this subsampling mode\"), and so \
564 must we"
565 )
566 });
567 assert!(
568 err.to_string()
569 .contains("invalid with this subsampling mode"),
570 "{NAME}: the refusal must name libaom's rule, got: {err}"
571 );
572 // The pixels this pin never had: the sibling gate
573 // `a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt`
574 // pins the refusal plus a genuine 4:2:2 positive control, and every
575 // real 4:2:2 exactness claim lives on genuinely 4:2:2 pins in this
576 // file.
577 }
578
579 /// lane-av1unwritten: this pin is a MISSING REFUSAL, not a pixel defect.
580 ///
581 /// `440_request_is_422.obu` is a 4:2:2 sequence header wrapped around a
582 /// 4:2:0 key frame's tile, so the tile's partition symbols make subsizes
583 /// (8x16 among them) that have NO chroma plane block at ss (1,0). libaom
584 /// refuses exactly that, before descending into the subsize:
585 ///
586 /// ```text
587 /// $ aomdec --rawvideo -o /dev/null fixtures/440_request_is_422.obu
588 /// Warning: Failed to decode frame 1: Corrupt frame detected
589 /// Warning: Additional information: Block size 8x16 invalid with this subsampling mode
590 /// ```
591 ///
592 /// (`av1/decoder/decodeframe.c:1449-1458`,
593 /// `get_plane_block_size(subsize, ss_x, ss_y) == BLOCK_INVALID` ->
594 /// `AOM_CODEC_CORRUPT_FRAME`.) We walked those subsizes instead, and the
595 /// first version of this lane misread the downstream symptom -- a chroma
596 /// plane block covered by a square unit, whole 4x4 blocks left unwritten,
597 /// and a `EC_AV1_FINAL_DUMP` hash that CHANGED RUN TO RUN because the
598 /// unwritten samples were uninitialised plane memory.
599 ///
600 /// The contract pinned here is the one libaom has: the pin REFUSES, by a
601 /// named error that says which shape and which subsampling mode. The
602 /// positive control is a genuinely 4:2:2 pin, which must still decode --
603 /// so this gate cannot pass by refusing everything.
604 #[test]
605 fn a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt() {
606 const NAME: &str = "a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt";
607 let _gate_lock = lock_gate_counters();
608 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
609 .join("fixtures")
610 .join("440_request_is_422.obu");
611 let pinned = read_pin(&path, 2014, 0x98a1378df976253d, NAME);
612 // The refusal this gate PROVES, quoted whole -- the anchor the PROVEN
613 // row in `refusal_inventory.rs` is checked against inside this body's
614 // own bounds. The assertion below used to match only the libaom
615 // citation *inside* the string, so a reworded guard kept passing for
616 // as long as it kept citing `decodeframe.c:1456`: the half that names
617 // OUR shapes (4x8 / 8x16 / 16x4, and 8x4 at 4:4:0) was never pinned.
618 const REFUSAL: &str = "a block size 4x8, 8x16 or 16x4 (or 8x4 at 4:4:0) has no chroma \
619 plane block at this frame's subsampling mode (libaom: \"Block \
620 size %dx%d invalid with this subsampling mode\", \
621 av1/decoder/decodeframe.c:1456, refusing by the same rule)";
622 let err = decode_stream(&pinned)
623 .err()
624 .unwrap_or_else(|| panic!("{NAME}: the pin must be REFUSED, not decoded"));
625 let msg = err.to_string();
626 assert!(
627 msg.contains("invalid with this subsampling mode"),
628 "{NAME}: the refusal must name the rule it refuses by (libaom's own wording), got: \
629 {msg}"
630 );
631 assert!(
632 msg.contains(REFUSAL),
633 "{NAME}: the refusal must be this decoder's OWN string, whole -- the guard's wording \
634 drifted, so the PROVEN row no longer names what fires, got: {msg}"
635 );
636 // Positive control: a real 4:2:2 stream must still decode, so the gate
637 // cannot pass by refusing everything.
638 let ok_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
639 .join("fixtures")
640 .join("422_key_64x64.obu");
641 let ok = decode_stream(&std::fs::read(&ok_path).expect("the 4:2:2 control fixture"))
642 .unwrap_or_else(|e| panic!("{NAME}: a genuine 4:2:2 pin must still decode: {e}"));
643 assert!(
644 !ok.is_empty(),
645 "{NAME}: the 4:2:2 control decoded no frames"
646 );
647 }
648
649 /// lane-av1subsizesweep: the FRAME-EDGE walk of a BLOCK_INVALID subsize,
650 /// pinned. This is the one install site the partition-symbol guards missed,
651 /// and the sibling pin above cannot see it -- that pin's 8x16 comes from a
652 /// 16x16-level `PARTITION_VERT_B` (an interior AB strip, refused at
653 /// decode.rs:36472), while this pin's comes from the key-frame 16-level
654 /// FRAME-EDGE arm, which is not a `dec.symbol(` site at all: it reads one
655 /// gathered bit with `dec.symbol_fixed(&gather(..))` and dispatches
656 /// `decode_leaf_rect` straight off it.
657 ///
658 /// `422_header_edge16_walk.obu` (128 bytes, sha256
659 /// `e8ab2bb229896f796cdec4d2cb383b41f057ef8d364da30f160a3f55a452657f`,
660 /// fnv1a64 `0xcfa2394ebe1f7764`) is a 4:2:2 sequence header over a 4:2:0
661 /// key frame's tile, at 88x64. Width 88 is 8 mod 16, so the last 16x16
662 /// column block is COLUMN-short and the frame-edge arm fires; height 64 is
663 /// 16-aligned, so the ROW is not short and the both-cut arm is not taken.
664 /// The gathered bit names `PARTITION_VERT`, so the strip is `BLOCK_8X16`.
665 ///
666 /// libaom's own verdict, which is the rule this pin pins:
667 ///
668 /// ```text
669 /// $ aomdec --rawvideo -o /dev/null fixtures/422_header_edge16_walk.obu
670 /// Warning: Failed to decode frame 1: Corrupt frame detected
671 /// Warning: Additional information: Block size 8x16 invalid with this subsampling mode
672 /// ```
673 ///
674 /// What makes this pin different from every other refusal gate in this file
675 /// is that the 8x16 is the ONLY offending subsize in the stream. Measured
676 /// over a 260-candidate sweep (4 card textures x 5 quantizers x 13 declared
677 /// widths), this is the one candidate whose decode with the guard removed
678 /// SUCCEEDS: with the `refuse_invalid_subsize` at decode.rs:37098 deleted,
679 /// this decoder returned a full 88x64 picture where libaom refuses the
680 /// frame. So the guard is not a redundant second refusal here -- it is the
681 /// only thing between a corrupt frame and a plausible-looking decode.
682 #[test]
683 fn a_422_header_whose_only_invalid_subsize_is_the_16_level_frame_edge_walk_is_refused() {
684 const NAME: &str =
685 "a_422_header_whose_only_invalid_subsize_is_the_16_level_frame_edge_walk_is_refused";
686 let _gate_lock = lock_gate_counters();
687 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
688 .join("fixtures")
689 .join("422_header_edge16_walk.obu");
690 let pinned = read_pin(&path, 128, 0xcfa2394ebe1f7764, NAME);
691 // The shape must be the one this lane's arm carries: if the pin ever
692 // stops being an 8x16 strip the refusal is coming from somewhere else
693 // and this gate is measuring the wrong thing.
694 assert!(
695 !crate::decode::chroma_plane_block_codable(8, 16, 1, 0),
696 "{NAME}: BLOCK_8X16 must be BLOCK_INVALID at 4:2:2 -- this gate's whole \
697 subject is `av1_ss_size_lookup[BLOCK_8X16][1][0] == BLOCK_INVALID`"
698 );
699 assert!(
700 crate::decode::chroma_plane_block_codable(16, 8, 1, 0),
701 "{NAME}: the 16x8 mirror MUST stay legal at 4:2:2 (BLOCK_8X8) -- it is what \
702 keeps the new guard from refusing the sibling arm's strip"
703 );
704 let err = decode_stream(&pinned)
705 .err()
706 .unwrap_or_else(|| panic!("{NAME}: the pin must be REFUSED, not decoded"));
707 let msg = err.to_string();
708 assert!(
709 msg.contains("invalid with this subsampling mode"),
710 "{NAME}: the refusal must name libaom's rule (its own wording), got: {msg}"
711 );
712 // Positive control: a genuine 4:2:2 stream must still decode, so this
713 // gate cannot pass by refusing everything.
714 let ok_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
715 .join("fixtures")
716 .join("422_key_64x64.obu");
717 let ok = decode_stream(&std::fs::read(&ok_path).expect("the 4:2:2 control fixture"))
718 .unwrap_or_else(|e| panic!("{NAME}: a genuine 4:2:2 pin must still decode: {e}"));
719 assert!(
720 !ok.is_empty(),
721 "{NAME}: the 4:2:2 control decoded no frames"
722 );
723 }
724
725 /// lane-av1-422bigblock: the two witnessed 4:2:2 big-block defects, pinned
726 /// as fixtures (`git add -f`; `fixtures/` is gitignored).
727 ///
728 /// `422_allskip_2f.obu` (62 bytes) is a 128x128 profile-2 key frame plus
729 /// its all-skip first inter frame: the pre-port decoder read phantom
730 /// coefficient units in the inter frame and then panicked in
731 /// `reconstruct_mc_rect` on a full-height 4:2:2 chroma rect. At this
732 /// lane's HEAD the block-half port's per-axis plane-block model already
733 /// has it entropy-locked (all 20 key-frame coefficient units pair
734 /// rng-for-rng with the instrumented oracle, the inter frame reads
735 /// zero, matching the oracle) and pixel-exact vs aomdec.
736 ///
737 /// `422_sb128_3f.obu` (12543 bytes) carries the f2 128x128
738 /// `PARTITION_NONE` non-skip inter block: the mu-chunk chroma walk cut
739 /// each chunk's 32x64 chroma into a `chroma_side`-square 64x64 (twice
740 /// the units the oracle codes), indexed the prediction buffer at the
741 /// square `chroma_side` instead of `chroma_stride` (the empty-slice
742 /// panic at `push_mc_rect_tx`'s densify), and the reference plane
743 /// resolution guessed every non-4:4:4 picture quarter-height, so the
744 /// bottom mu-chunk row predicted from a clamped row-63 edge. All fixed;
745 /// both witnesses decode pixel-exact vs aomdec on the lane's local
746 /// `EC_AV1_ALLOW_422_PROBE` patch-run-restore build (recipe and measured
747 /// numbers in `lanes/av1422bigblock.report.md`).
748 ///
749 /// lane-av1422lift: `decode_stream` no longer refuses 4:2:2 at the
750 /// sequence header, so this gate stops being a refusal contract and
751 /// becomes the one it should have been: BOTH pins, byte-pinned AND
752 /// byte-exact against ffmpeg, with the per-plane coefficient-unit census
753 /// as the non-vacuity arm. The pins are unchanged and still load-bearing
754 /// (size + fnv1a64); only the assertion moved.
755 #[test]
756 fn the_pinned_422_bigblock_witnesses_decode_pixel_exact() {
757 const NAME: &str = "the_pinned_422_bigblock_witnesses_decode_pixel_exact";
758 if !have_ffmpeg() {
759 eprintln!("SKIP {NAME}: no ffmpeg");
760 return;
761 }
762 for (file, bytes, fp, frames, require_coded) in [
763 (
764 "422_allskip_2f.obu",
765 62usize,
766 0x7e4d69d3c728c55f_u64,
767 2usize,
768 false,
769 ),
770 ("422_sb128_3f.obu", 12543, 0x5171e0aab8000da7, 3, true),
771 ] {
772 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
773 .join("fixtures")
774 .join(file);
775 let data = std::fs::read(&path).unwrap_or_else(|e| {
776 panic!(
777 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
778 path.display()
779 )
780 });
781 assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
782 assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
783 let (_units, coded_delta) =
784 assert_422_stream_pixel_exact(NAME, &data, 128, 128, frames, 8, require_coded);
785 if !require_coded {
786 // `422_allskip_2f.obu` is named for what it does NOT code, and
787 // the pre-port defect was exactly that: the decoder read
788 // PHANTOM coefficient units in the all-skip inter frame and
789 // then panicked in `reconstruct_mc_rect` on a full-height
790 // 4:2:2 chroma rect. So the cell's non-vacuity is a NEGATIVE
791 // measurement on the CHROMA planes, asserted here rather than
792 // inherited: the walk ran (units > 0, which the shared body
793 // checks) and coded nothing on U or V.
794 assert_eq!(
795 (coded_delta[1], coded_delta[2]),
796 (0, 0),
797 "{NAME}: {file} CODED a chroma coefficient -- this is the all-skip inter-frame \
798 cell and a phantom residual read is exactly the defect it witnesses"
799 );
800 }
801 }
802 }
803
804 /// lane-av1muchroma: the `chroma_side * chroma_side` mu-chroma site
805 /// census, over the whole committed 4:2:2 corpus, as a per-site
806 /// REACHABILITY measurement with a non-vacuity arm.
807 ///
808 /// `lanes/av1subsizesweep.report.md` named "mu-chroma sites using
809 /// `chroma_side * chroma_side`" as unprobed residue. This lane's sweep
810 /// (env-gated probe at each of the 12 sites, run over every pinned 4:2:2
811 /// gate) measured them:
812 ///
813 /// - sites 4, 7, 10 are guarded `ss_x == 0 && ss_y == 0`, i.e. 4:4:4
814 /// ONLY -- structurally unreachable at 4:2:2, not merely unwitnessed.
815 /// - sites 2, 8 (`side > 64` mu-chunk walks) were not reached by any
816 /// committed 4:2:2 fixture; their single-reference twin, site 5, is
817 /// (side 128, plane 64x128), and its square allocation is the ENCLOSING
818 /// square, so it is 2x oversized, never short.
819 /// - sites 1, 3, 5, 6, 9, 11, 12 ARE reached. For 3/5/6/9/11/12
820 /// `chroma_side` is `max(side >> ss_x, side >> ss_y)` (decode.rs), the
821 /// ENCLOSING square of the plane rect, so at 4:2:2 the square is 2x
822 /// the per-axis extent: oversized, never short.
823 /// - site 1 alone still used `side >> ss_x` and was therefore sized at
824 /// HALF the plane block at 4:2:2. Fixed per-axis; this gate pins it.
825 ///
826 /// Non-vacuity: [`crate::decode::skip_arm_chroma_plane_block_hits`]
827 /// fires only where the per-axis and square forms differ, so a green run
828 /// that never reached the site would be vacuous and this asserts > 0.
829 #[test]
830 fn the_422_skip_arm_chroma_grid_is_sized_per_axis_not_square() {
831 const NAME: &str = "the_422_skip_arm_chroma_grid_is_sized_per_axis_not_square";
832 const FILE: &str = "s422_322x240.obu";
833 const BYTES: usize = 21096;
834 const FP: u64 = 0x9a96dda2a19d47a6;
835 const W: usize = 322;
836 const H: usize = 240;
837 const FRAMES: usize = 16;
838 let _gate_lock = lock_gate_counters();
839 let data = std::fs::read(crate_pin(FILE)).unwrap_or_else(|e| {
840 panic!("{NAME}: the committed pin {FILE} is missing ({e}) -- a failure, not a skip")
841 });
842 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
843 assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted");
844 let rect_before = crate::decode::skip_arm_chroma_rect_shapes();
845 let short_before = crate::decode::skip_arm_chroma_short_samples();
846 let ours = decode_stream(&data)
847 .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 4:2:2 stream: {e}"));
848 assert_eq!(ours.len(), FRAMES, "{NAME}: decoded frame count");
849 for (i, f) in ours.iter().enumerate() {
850 assert_eq!((f.width, f.height), (W, H), "{NAME}: frame {i} dimensions");
851 assert_eq!(
852 (f.u.len(), f.v.len()),
853 (W.div_ceil(2) * H, W.div_ceil(2) * H),
854 "{NAME}: frame {i} chroma planes are {}/{} samples -- 4:2:2 is HALF WIDTH and \
855 FULL HEIGHT; a quarter-height plane means the decode kept a 4:2:0 allocation",
856 f.u.len(),
857 f.v.len()
858 );
859 }
860 let rect_after = crate::decode::skip_arm_chroma_rect_shapes();
861 assert!(
862 rect_after > rect_before,
863 "{NAME}: no skipped block decoded at a rect chroma shape ({rect_before} -> \
864 {rect_after}) -- this gate is then VACUOUS: per-axis and square sizing are the \
865 same number at 4:2:0 and 4:4:4, so it proves nothing about the site it claims"
866 );
867 let short_after = crate::decode::skip_arm_chroma_short_samples();
868 assert_eq!(
869 short_after, short_before,
870 "{NAME}: decode_block's SKIP arm chroma grids fell {short_after} samples SHORT of \
871 their own plane block -- the square `side >> ss_x` form this lane removed allocates \
872 exactly half the plane block at 4:2:2 (ss (1,0))"
873 );
874 }
875
876 /// lane-av1floorshift: the two FRAME chroma plane allocators
877 /// (`decode_key_frame_tile_with_cdfs`, `decode_inter_tile`) size U and V as
878 /// `(width >> ss_x) x (height >> ss_y)`. `lanes/av1subsizesweep.report.md`
879 /// named them "floor-`>>` chroma plane allocators -- shape assumption at
880 /// frame edges; not probed" and left them open. This is the probe.
881 ///
882 /// **The verdict is ALREADY CORRECT, and it is structural, not
883 /// corpus-luck.** `width`/`height` are `block_grid(mi_cols, mi_rows) *
884 /// BLOCK` (`BLOCK == 32`) and the allocator is handed those, not the frame's
885 /// own `true_width`/`true_height`: both axes are multiples of 32, and
886 /// `ss_x`/`ss_y` are the sequence header's single-bit subsampling fields,
887 /// so `ss <= 1` on every stream that exists. `32k >> ss == round_ss(32k, ss)`
888 /// for every `k` and every `ss <= 1` -- the `>>` can never floor one sample
889 /// short of libaom's own chroma crop, at a frame edge or anywhere else. The
890 /// static half of the gate below proves that exhaustively over every
891 /// `mi_cols`/`mi_rows` this decoder admits.
892 ///
893 /// The corpus half keeps the instrument honest: it decodes one frame per
894 /// selectable subsampling cell and asserts the allocators were REACHED
895 /// (`frame_chroma_alloc_calls` moved), so a green run cannot be the census
896 /// having been wired to nothing.
897 ///
898 /// Witnesses, all byte-pinned (`size`, `fnv1a64`), chosen to cover all
899 /// three selectable cells and both allocators:
900 ///
901 /// | file | cell | frame | covers |
902 /// |---|---|---|---|
903 /// | `420_odd65x65_key.obu` | 4:2:0, **odd** 65x65 | key | key allocator, the odd-dimension cell where a floor WOULD show |
904 /// | `422_key_64x64.obu` | 4:2:2 (1,0) | key | key allocator, half-width/full-height |
905 /// | `444_intrabc_rect4_witness.obu` | 4:4:4 (0,0) | key | key allocator, the `ss == 0` cell where `>> ss` is the identity |
906 ///
907 /// 4:4:0 (`0,1`) is excluded and cannot be added: libaom's
908 /// `av1_read_color_config` asserts `subsampling_y == 0` when
909 /// `subsampling_x == 0`, and no of 256 header bytes reads back `(0,1)` --
910 /// the reader census at `the_reader_never_produces_440` names it.
911 #[test]
912 fn the_frame_chroma_planes_are_allocated_on_the_per_axis_floor_that_never_rounds() {
913 const NAME: &str =
914 "the_frame_chroma_planes_are_allocated_on_the_per_axis_floor_that_never_rounds";
915 let _gate_lock = lock_gate_counters();
916 for (file, bytes, fp, cell, ss) in [
917 (
918 "420_odd65x65_key.obu",
919 2305usize,
920 0xf55645c4b139e8f7u64,
921 "4:2:0",
922 (1usize, 1usize),
923 ),
924 (
925 "422_key_64x64.obu",
926 755,
927 0x87fc569cf53bcbc6,
928 "4:2:2",
929 (1, 0),
930 ),
931 (
932 "444_intrabc_rect4_witness.obu",
933 1016,
934 0x27c2fad540472994,
935 "4:4:4",
936 (0, 0),
937 ),
938 ] {
939 let data = std::fs::read(crate_pin(file))
940 .unwrap_or_else(|e| panic!("{NAME}: the committed pin {file} is missing ({e})"));
941 assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
942 assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
943 let calls_before = crate::decode::frame_chroma_alloc_calls();
944 let short_before = crate::decode::frame_chroma_alloc_short_samples();
945 let crop_before = crate::decode::frame_chroma_alloc_crop_shapes();
946 let frames = decode_stream(&data)
947 .unwrap_or_else(|e| panic!("{NAME}: {file} ({cell}) refused: {e}"));
948 let calls = crate::decode::frame_chroma_alloc_calls() - calls_before;
949 assert!(
950 calls >= frames.len(),
951 "{NAME}: {file} ({cell}) decoded {} frames but the chroma plane allocator ran \
952 {calls} times -- the instrument is not on the path this gate claims to cover",
953 frames.len()
954 );
955 // The shape the allocator owes the tile, and the shape the output
956 // crop owes the caller: libaom's chroma CROP of the frame's own
957 // dimensions (`av1_round_shift`), which is what
958 // `decode_key_frame_tile_with_cdfs`'s `Picture` crop uses. At the
959 // odd 65x65 4:2:0 cell this is 33x33 -- 1089 samples, NOT the
960 // floor 32x32 an `>>` short of the true extent would have left.
961 for (i, f) in frames.iter().enumerate() {
962 let (cw, ch) = (
963 crate::decode::round_ss(f.width, ss.0),
964 crate::decode::round_ss(f.height, ss.1),
965 );
966 assert_eq!(
967 (f.u.len(), f.v.len()),
968 (cw * ch, cw * ch),
969 "{NAME}: {file} ({cell}) frame {i} is {}x{} and its chroma planes are {} / {} \
970 samples; {cell} is a {cw}x{ch} = {} crop",
971 f.width,
972 f.height,
973 f.u.len(),
974 f.v.len(),
975 cw * ch
976 );
977 }
978 let short = crate::decode::frame_chroma_alloc_short_samples() - short_before;
979 assert_eq!(
980 short, 0,
981 "{NAME}: {file} ({cell}) allocated {short} chroma samples SHORT of the `round_ss` \
982 extent the tile's chroma walks may address -- the frame chroma planes are sized \
983 by a FLOOR `>> ss` that does not round"
984 );
985 let crop = crate::decode::frame_chroma_alloc_crop_shapes() - crop_before;
986 assert_eq!(
987 crop, 0,
988 "{NAME}: {file} ({cell}) reached a frame shape on which `>> ss` and `round_ss` \
989 disagree ({crop} frames) -- the allocators are handed a MULTIPLE OF 32 \
990 (block_grid * BLOCK) and `ss <= 1`, so this can only mean the allocator's own \
991 argument changed, and the shortfall assertion above is then vacuous on this file"
992 );
993 }
994 }
995
996 /// lane-av1floorshift: the STATIC half of the same claim, and the part that
997 /// does not need a corpus. The frame chroma allocators' shift argument is
998 /// `block_grid(mi_cols, mi_rows) * BLOCK` with `BLOCK == 32`, so for every
999 /// `mi_cols`/`mi_rows` this decoder can admit and every subsampling the
1000 /// header can carry (`ss in {0, 1}` per axis), `>> ss` and `round_ss` are
1001 /// the same number. Exhaustively checked here over a range wider than any
1002 /// frame a header can declare; the two counters above are zero for a
1003 /// reason, and this is the reason.
1004 #[test]
1005 fn the_frame_chroma_alloc_shift_argument_cannot_floor_below_round_ss() {
1006 const NAME: &str = "the_frame_chroma_alloc_shift_argument_cannot_floor_below_round_ss";
1007 const BLOCK: usize = 32;
1008 // `block_grid(mi) = mi.div_ceil(BLOCK_MI)` with `BLOCK_MI == 8`
1009 // (`tile.rs`), so the allocator's width is `(mi.div_ceil(8)) * 32`.
1010 for mi in 1..=512usize {
1011 let coded = mi.div_ceil(8) * BLOCK;
1012 for ss in 0..=1usize {
1013 assert_eq!(
1014 coded >> ss,
1015 crate::decode::round_ss(coded, ss),
1016 "{NAME}: coded {coded} (mi {mi}) at ss {ss}: the floor and the crop differ -- \
1017 the frame chroma plane would be allocated short"
1018 );
1019 // The TRUE extent is `mi * 4`; it is what the allocator
1020 // derives `true_width` from and what every chroma walk is
1021 // clamped against, so it earns the same check.
1022 let truth = mi * 4;
1023 assert_eq!(
1024 truth >> ss,
1025 crate::decode::round_ss(truth, ss),
1026 "{NAME}: true {truth} (mi {mi}) at ss {ss}: the floor and the crop differ"
1027 );
1028 }
1029 }
1030 // And the 4:4:0 cell libaom refuses, spelled out rather than left as
1031 // an assumption: at `ss (0,1)` the shift is exact too, so the site
1032 // would be correct even if the cell were ever admitted.
1033 for mi in 1..=64usize {
1034 assert_eq!((mi * 4) >> 1, crate::decode::round_ss(mi * 4, 1));
1035 assert_eq!(mi * 4, crate::decode::round_ss(mi * 4, 0));
1036 }
1037 }
1038
1039 /// lane-av1422tailskip: the WITNESS cell for the 4:2:2 intra-in-inter
1040 /// PALETTE chroma per-unit window, and its byte pin.
1041 ///
1042 /// `422_palette_intra_in_inter_384x240_17f.obu` (19344 B, sha256
1043 /// `bf1c658e9bfdc13ec1ed51e59049d2b81201941b6ef4571f8382f356ea4b815b`) is
1044 /// the one 4:2:2 cell of the 384x240 census sweep: 384x240, ss (1,0),
1045 /// 8-bit, **17 decode frames, 16 shown** (decode 1 is the hidden altref).
1046 /// Its decode-frame-1 block at mi(32,0) is a 64x64 INTRA block with a
1047 /// PALETTE -- `aomdec`'s `EC_PIB` prints `use_palette=1` there, and the
1048 /// oracle's own prediction rungs print nothing for the block because
1049 /// `av1_predict_intra_block` returns at its palette branch before them
1050 /// (`reconintra.c:1735`).
1051 ///
1052 /// At 4:2:2 that block's chroma plane block is 32x64, but
1053 /// `av1_get_max_uv_txsize` adjusts `max_tx_size_rect_lookup[BLOCK_32X64]`
1054 /// down to TX_32X32, so it codes TWO STACKED SQUARE units per plane.
1055 /// `decode_inter_block`'s `side == 64` walk armed the ONE block-sized
1056 /// 2048-entry chroma palette prediction before the loop: the first unit
1057 /// consumed all of it and the second found none pending, so it silently
1058 /// fell back to the edge DC prediction -- a flat 90/240 box where the
1059 /// oracle carries its palette (U/V rows 170..189, cols 23..31, 180 wrong
1060 /// samples per plane at the pre-filter stage). Each unit now takes its own
1061 /// `palette_window` of that buffer (`decode.rs`) -- the same helper the
1062 /// split-transform chroma paths already used.
1063 ///
1064 /// **The committed assertion follows the family's standing rule** (same
1065 /// shape as
1066 /// [`the_pinned_422_bigblock_witnesses_are_present_and_refuse_by_name`]):
1067 /// the byte pin plus this decoder's disposition of those bytes.
1068 /// lane-av1422lift: `decode_stream` no longer refuses 4:2:2 at the sequence
1069 /// header, so the OK arm is the live one -- the gate decodes the pin and
1070 /// asserts 17 decode-order frames byte-exact against aomdec with
1071 /// `palette_422_unit_window_hits()` fired. lane-av1oracledepth: the stale
1072 /// `Err` arm (it matched the pre-lift refusal string
1073 /// `"a chroma format of 4:2:2"` the decoder no longer returns, and could
1074 /// have swallowed a future decode error as green) is deleted; a refusal
1075 /// now fails this gate loudly.
1076 #[test]
1077 fn the_pinned_422_palette_intra_in_inter_cell_window_is_byte_exact() {
1078 const NAME: &str = "the_pinned_422_palette_intra_in_inter_cell_window_is_byte_exact";
1079 const FILE: &str = "422_palette_intra_in_inter_384x240_17f.obu";
1080 const BYTES: usize = 19344;
1081 const FP: u64 = 0x923ccabfcb933e90;
1082 let _gate_lock = lock_gate_counters();
1083 let data = std::fs::read(crate_pin(FILE)).unwrap_or_else(|e| {
1084 panic!("{NAME}: the committed pin {FILE} is missing ({e}) -- a failure, not a skip")
1085 });
1086 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
1087 assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted");
1088 let before = crate::decode::palette_422_unit_window_hits();
1089 // lane-av1oracledepth: the OK arm is MEASURED to be the live one (the
1090 // pinned bytes decode, 17 decode-order frames byte-exact vs aomdec,
1091 // 16 windowed units) and the old `Err` arm matching the pre-lift
1092 // refusal string "a chroma format of 4:2:2" is deleted: committed
1093 // code no longer returns that string, so the arm could only ever
1094 // swallow a FUTURE decode error that happened to contain it and read
1095 // green off a stream that decoded nothing. A refusal today now fails
1096 // this gate loudly, as it should.
1097 match decode_stream(&data) {
1098 Err(e) => {
1099 panic!(
1100 "{NAME}: {FILE} was refused by the current decoder: {e}. 4:2:2 is a \
1101 DECODED format; a refusal here is a regression, not the old sequence-\
1102 header gate"
1103 )
1104 }
1105 Ok(_) => {
1106 let windows = crate::decode::palette_422_unit_window_hits() - before;
1107 assert!(
1108 windows > 0,
1109 "{NAME}: {FILE} decoded, but no 4:2:2 intra-in-inter chroma unit took \
1110 the per-unit palette window ({windows} did) -- this cell does not \
1111 exercise the arm at all (class gate-blind-to-feature)"
1112 );
1113 let (decoded, hidden) = decode_all_frames_vs_oracle(&data, FILE);
1114 assert_eq!(
1115 decoded, 17,
1116 "{NAME}: the oracle decoded {decoded} frames in DECODE order, not 17"
1117 );
1118 assert_eq!(hidden, 1, "{NAME}: expected exactly the one hidden altref");
1119 eprintln!(
1120 "{NAME}: {decoded} decode-order frame(s) byte-exact against aomdec \
1121 ({hidden} hidden), {windows} chroma palette unit window(s)"
1122 );
1123 }
1124 }
1125 }
1126
1127 /// lane-av1-ibc128chunk: the WITNESS for the 128-root intrabc strip's
1128 /// de-square-cut mu-chunk chroma walk, and the byte pin for it.
1129 ///
1130 /// `decode_intrabc_128rect` cut each mu chunk's chroma plane block with
1131 /// `chunk_chroma = cside * 64 / side` -- a `chroma_side`-SQUARE chunk,
1132 /// i.e. the 4:2:0 count on BOTH axes (the same defect lane-av1-422bigblock
1133 /// fixed, and witnessed, in `decode_inter_block` and
1134 /// `decode_block_128rect`; this copy was deferred there as unwitnessed).
1135 /// At 4:2:2 a 64x64 mu chunk's chroma plane block is 32x64, so it holds
1136 /// TWO STACKED TX_32X32 units per plane: the square-cut walk read one per
1137 /// plane per chunk, left the chunk's lower 32 chroma rows with no
1138 /// residual at all, and stamped each unit's entropy context over a
1139 /// 16x16-mi luma span instead of 16x8.
1140 ///
1141 /// Measured red-before on the pinned witness (parent `a7d22aec`, via the
1142 /// local `EC_AV1_ALLOW_422_PROBE` patch-run-restore build): 8 chroma
1143 /// units stamped over the stream's two reached blocks and frames 0 and 3
1144 /// diverge from `aomdec` (45135 / 44540 of 245760 samples each), the
1145 /// first difference at Y sample 98368 -- frame 0, row 256, col 64, the
1146 /// top-left corner of the first 128x64 intrabc block at mi(64,0). The
1147 /// red build then lost 4 of the stream's 6 intrabc blocks to the desync.
1148 /// Green-after, same fixture: 48 chroma units stamped, all 6 blocks
1149 /// decoded, and ALL FIVE frames byte-identical to `aomdec --rawvideo`.
1150 ///
1151 /// lane-av1422lift: committed code no longer refuses 4:2:2 at the
1152 /// sequence header, so the red/green evidence above is no longer
1153 /// probe-only: this gate is the one that asserts it. Both pins are
1154 /// byte-pinned AND byte-exact against ffmpeg's `yuv422p` rawvideo of the
1155 /// same bytes, per plane and per frame, with the per-plane
1156 /// coefficient-unit census as the non-vacuity arm -- the census is what
1157 /// makes "48 chroma units stamped" a committed, reproducible number here
1158 /// instead of a sentence in a lane report. The source-scan arm below
1159 /// keeps its own claim (the per-axis SPELLING) and does not overlap.
1160 #[test]
1161 fn the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_exact() {
1162 const NAME: &str = "the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_exact";
1163 if !have_ffmpeg() {
1164 eprintln!("SKIP {NAME}: no ffmpeg");
1165 return;
1166 }
1167 for (file, bytes, fp) in [
1168 (
1169 "422_intrabc_sb128_strip.obu",
1170 1672usize,
1171 0x50f5cfc576e4cd00_u64,
1172 ),
1173 (
1174 "422_intrabc_sb128_strip_notxsearch.obu",
1175 1675,
1176 0xd4936f252ff8cff0,
1177 ),
1178 ] {
1179 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1180 .join("fixtures")
1181 .join(file);
1182 let data = std::fs::read(&path).unwrap_or_else(|e| {
1183 panic!(
1184 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
1185 path.display()
1186 )
1187 });
1188 assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
1189 assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
1190 assert_422_stream_pixel_exact(NAME, &data, 384, 320, 5, 8, true);
1191 }
1192 }
1193
1194 /// lane-av1422a2a4: the firing gate for `decode_block`'s var-tx EITHER/OR
1195 /// tail at 4:2:2 -- an INTRABC block whose var-tx tree resolved MIXED
1196 /// leaves, where the old blanket `set_txfm_ctxs` + `fill_lf_grid` publishes
1197 /// clobbered the per-leaf TXFM_CONTEXT bands libaom keeps.
1198 ///
1199 /// Provenance: aomenc profile 2, `testsrc2=size=128x112:rate=25` tiled 2x2
1200 /// to 256x224, cq 30, 3 frames (`lanes/av1422ibcrect.report.md` §2, stream
1201 /// A4). The oracle decodes it to completion; the pre-fix tree refused it
1202 /// mid-tile with the documented `decodeframe.c:1456` subsize string -- the
1203 /// E6/E7 desync-symptom class, NOT an invalid shape.
1204 ///
1205 /// Measured on the pinned bytes: the 32x32 intrabc block at mi(32,8)
1206 /// resolves leaves (0,0)+((0,4) 8x8, (4,0)+(4,4) 16x16, so
1207 /// `left_txfm[32..35]` must read 16 when the NEXT tree's sub-unit at
1208 /// (32,16) row0col0 reads its `txfm_partition` context (oracle operands
1209 /// `above=16 left=16`, ctx 9). The blanket publishes reset those cells to
1210 /// 8 -> ctx 10 -> a wrong `is_split` -> the first divergent read, and the
1211 /// refusal surfaced ~30 partition symbols later.
1212 #[test]
1213 fn the_pinned_422_intrabc_vartx_mixedtree_witnesses_decode_pixel_exact() {
1214 const NAME: &str = "the_pinned_422_intrabc_vartx_mixedtree_witnesses_decode_pixel_exact";
1215 if !have_ffmpeg() {
1216 eprintln!("SKIP {NAME}: no ffmpeg");
1217 return;
1218 }
1219 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1220 .join("fixtures")
1221 .join("422_intrabc_vartx_mixedtree_a4.obu");
1222 let data = std::fs::read(&path).unwrap_or_else(|e| {
1223 panic!(
1224 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
1225 path.display()
1226 )
1227 });
1228 assert_eq!(data.len(), 30937, "{NAME}: pinned witness size drifted");
1229 assert_eq!(
1230 fnv1a64(&data),
1231 0x6f0fc77c2217910a_u64,
1232 "{NAME}: pinned witness bytes drifted"
1233 );
1234 assert_422_stream_pixel_exact(NAME, &data, 256, 224, 3, 8, true);
1235 }
1236
1237 /// lane-av1422ibctxsel: the firing gate for `decode_intrabc_owned_rect`'s
1238 /// NON-SPLIT chroma coefficient context at 4:2:2.
1239 ///
1240 /// `lanes/av1422gathercensus.report.md` closed its ss (1, 0) class sweep
1241 /// with this one gather at STOP -- unwitnessed: `around_mi_rect` over the
1242 /// block's LUMA span feeds the CHROMA `dc_sign_ctx`, and at ss (1, 0) a
1243 /// chroma 4-px cell spans TWO luma mi columns, so the per-mi sum counts
1244 /// every chroma column twice (`around_mi_422_chroma`'s every-second
1245 /// sampling is libaom's one-vote-per-cell sum). `lane-av1422ibcrect`
1246 /// found a stream that ENTERS the gather (24 entries) but whose two
1247 /// gathers agree on every entry, so the class stayed harmless-ON-THAT-
1248 /// STREAM, not proven.
1249 ///
1250 /// This fixture is the discriminating witness: aomenc profile 2, 384x288
1251 /// 4:2:2, 4 key frames, `--sb-size=64` with the last superblock row half
1252 /// outside the frame (so the 64-root partition is a single gathered bit
1253 /// and the strips are 64x32 HORZ intra-BC strips), `--enable-tx-size-
1254 /// search=1` plus a high-frequency patch that keeps the frame's `tx_mode`
1255 /// at `TX_MODE_SELECT` (`txb_split_count > 0`; without it encodeframe.c
1256 /// :2690 downgrades every frame to `TX_MODE_LARGEST`), and a chroma band
1257 /// above the strips so a full-weight above context meets a full-weight
1258 /// left one of the opposite sign.
1259 ///
1260 /// Measured on the pinned bytes: 24 non-split chroma gathers entered (6
1261 /// strips x 4 frames; 48 plane reads), and FIVE of them -- plane 2, strips
1262 /// mi (64,16)..(64,80) of frame 0 -- read `dc_sign_ctx` 1 through the
1263 /// luma-span gather against libaom's 0 through the pair rule (`full = 2A +
1264 /// L = -8`, `pair = A + L = 0`: the double-counted above vote crosses
1265 /// zero, and the context is a sign).
1266 ///
1267 /// Red-before (the route reverted, same fixture bytes): the wrong sign
1268 /// context changes the decoded dc-sign CDF and desyncs the tile -- the
1269 /// decoder refuses the stream mid-frame with "a block size 4x8, 8x16 or
1270 /// 16x4 ... has no chroma plane block at this frame's subsampling mode",
1271 /// so NO frame decodes at all. That refusal is also the proof it is a
1272 /// desync symptom and not a real sub-8x8 shape: both oracles decode the
1273 /// pinned bytes fully. Green-after: 4/4 frames byte-exact against
1274 /// ffmpeg's `yuv422p` rawvideo, with the per-plane coefficient-unit
1275 /// census (the helper's) and the pair-rule route counter as the
1276 /// non-vacuity arms. The 4:4:4 arm below pins the guard's other side:
1277 /// the same function at ss (0, 0) keeps the verbatim luma-span gather and
1278 /// must NOT fire the route.
1279 #[test]
1280 fn a_422_intrabc_owned_rect_nonsplit_chroma_context_uses_the_pair_rule() {
1281 const NAME: &str = "a_422_intrabc_owned_rect_nonsplit_chroma_context_uses_the_pair_rule";
1282 const FILE: &str = "ibc422_nonsplit_ctx.obu";
1283 const LEN: usize = 2170;
1284 /// sha256 `4f82d5da8b4c3d6553953fc373001a1c7a729c9b189214b65503af1e04eb6b68`,
1285 /// fnv1a64 `0x92e2c4e45ca27e34`.
1286 const FNV: u64 = 0x92e2c4e45ca27e34;
1287 if !have_ffmpeg() {
1288 eprintln!("SKIP {NAME}: no ffmpeg");
1289 return;
1290 }
1291 let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1292 .join("fixtures")
1293 .join(FILE);
1294 let data = std::fs::read(&path).unwrap_or_else(|e| {
1295 panic!(
1296 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
1297 path.display()
1298 )
1299 });
1300 assert_eq!(data.len(), LEN, "{NAME}: {FILE} size drifted");
1301 assert_eq!(fnv1a64(&data), FNV, "{NAME}: {FILE} bytes drifted");
1302 // No `lock_gate_counters()` here: the bumps are thread-local, and
1303 // `assert_422_stream_pixel_exact` takes that same (non-reentrant)
1304 // mutex itself -- holding it across this call self-deadlocks.
1305 crate::decode::reset_ibc_owned_rect_422_pair_hits();
1306 assert_422_stream_pixel_exact(NAME, &data, 384, 288, 4, 8, true);
1307 let hits = crate::decode::ibc_owned_rect_422_pair_hits();
1308 assert_eq!(
1309 hits, 24,
1310 "{NAME}: the pair-rule route fired {hits} times, not 24 (6 non-split chroma gathers \
1311 x 4 frames) -- the witness stopped exercising the arm, or the guard's extent moved"
1312 );
1313 // The guard's other arm: the 4:4:4 owner-rect stream (`r512.obu`,
1314 // pinned by the gate below) reaches this same function at ss (0, 0),
1315 // where the verbatim luma-span gather is correct -- the route counter
1316 // must stay put.
1317 let r512 = std::fs::read(
1318 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures/r512.obu"),
1319 )
1320 .expect("r512.obu must exist");
1321 crate::decode::reset_ibc_owned_rect_422_pair_hits();
1322 let _ = decode_stream(&r512).expect("the 4:4:4 owner-rect witness decodes");
1323 assert_eq!(
1324 crate::decode::ibc_owned_rect_422_pair_hits(),
1325 0,
1326 "{NAME}: the 4:2:2 pair-rule route fired on a 4:4:4 stream -- the ss (1, 0) guard \
1327 leaks (class gate-blind-to-feature)"
1328 );
1329 }
1330
1331 /// lane-av1-ibc128chunk: the SOURCE-SCAN arm of the witness gate above.
1332 ///
1333 /// The decode-level half of the red/green evidence now runs in committed
1334 /// code too -- the witness gate above,
1335 /// `the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_exact`,
1336 /// decodes both pins byte-exact against ffmpeg (lane-av1422lift lifted the
1337 /// sequence-header refusal). This arm complements it by pinning the thing
1338 /// that would silently bring the defect back: the square-cut
1339 /// `chunk_chroma = cside * 64 / side` expression, and the per-axis
1340 /// replacements that replaced it at BOTH sites in
1341 /// [`decode_intrabc_128rect`] -- the mu-chunk read walk and the
1342 /// `mu_chroma` per-unit context replay. It also pins the per-axis
1343 /// counters' accessors so the arms stay reachable, and the walk's own
1344 /// per-axis extent, derived here from the same `64 >> ss` form the
1345 /// witnesses measured (4:2:0 = one TX_32X32 per plane per chunk,
1346 /// 4:2:2 = two stacked, 4:4:4 = four).
1347 #[test]
1348 fn the_intrabc_128rect_chroma_chunk_walk_stays_per_axis() {
1349 const NAME: &str = "the_intrabc_128rect_chroma_chunk_walk_stays_per_axis";
1350 let src = crate::test_source::module_source("decode");
1351 let body = src
1352 .split_once("fn decode_intrabc_128rect(")
1353 .expect("decode_intrabc_128rect must exist")
1354 .1
1355 .split_once("\nfn ")
1356 .expect("decode_intrabc_128rect must be a top-level fn")
1357 .0;
1358 // Scan CODE only: the fix's own comments quote the old expression to
1359 // say what it was, and a prose mention must not read as a
1360 // reintroduction (nor mask one).
1361 let stripped: Vec<&str> = body
1362 .lines()
1363 .map(|l| l.split_once("//").map_or(l, |(c, _)| c))
1364 .collect();
1365 let code = stripped.join("\n");
1366 let body = code.as_str();
1367 assert_eq!(
1368 body.matches("cside * 64 / side").count(),
1369 0,
1370 "{NAME}: the square-cut `cside * 64 / side` chunk extent is BACK in \
1371 decode_intrabc_128rect -- that expression is the 4:2:2 defect this \
1372 gate exists for (a 64x64 mu chunk's chroma plane block is \
1373 (64 >> ss_x) x (64 >> ss_y), not `chroma_side` square)"
1374 );
1375 // The per-axis chunk extent, declared once at the mu-chunk read walk
1376 // and once at the `mu_chroma` replay -- the two de-square-cut sites.
1377 //
1378 // The replay must ALSO enumerate every unit inside a chunk, not just
1379 // its first: counting mu CHUNKS in `rows`/`cols` and then stepping the
1380 // mi origin and reading the grid per UNIT only agrees when a chunk
1381 // holds exactly one unit (4:2:0). At 4:2:2 and 4:4:4 a chunk holds two
1382 // or four, so the per-unit body alone left the rest of the chunk with
1383 // the composed-grid smearing the replay exists to undo.
1384 for name in [
1385 "let chunk_chroma_w = (64usize) >> ss_x(fctx);",
1386 "let chunk_chroma_h = (64usize) >> ss_y(fctx);",
1387 ] {
1388 assert_eq!(
1389 body.matches(name).count(),
1390 2,
1391 "{NAME}: `{name}` must appear at BOTH de-square-cut sites in \
1392 decode_intrabc_128rect (the mu-chunk read walk and the mu_chroma \
1393 context replay), found {}",
1394 body.matches(name).count()
1395 );
1396 }
1397 for name in [
1398 "let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);",
1399 "for kr in 0..ur {",
1400 "for kc in 0..uc {",
1401 ] {
1402 assert_eq!(
1403 body.matches(name).count(),
1404 1,
1405 "{NAME}: `{name}` must appear exactly once in \
1406 decode_intrabc_128rect -- the mu_chroma replay must walk chunk \
1407 THEN unit (decode_inter_block's `mu_chroma_units` shape), found {}",
1408 body.matches(name).count()
1409 );
1410 }
1411 for name in [
1412 "let unit_luma_w = cu_tx << ss_x(fctx);",
1413 "let unit_luma_h = cu_tx << ss_y(fctx);",
1414 "let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));",
1415 "let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));",
1416 "neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h)",
1417 ] {
1418 assert_eq!(
1419 body.matches(name).count(),
1420 1,
1421 "{NAME}: `{name}` must appear exactly once in \
1422 decode_intrabc_128rect, found {}",
1423 body.matches(name).count()
1424 );
1425 }
1426 // lane-av1muchunk422sym: the CHROMA gather of that same walk must take
1427 // the 4:2:2 pair rule, exactly as `decode_inter_block`'s mu-chunk walk
1428 // does (one chroma column per pair of luma mi cells; the plain rect
1429 // gather doubles the above dc vote and flips `dc_sign_ctx` wherever
1430 // above and left cancel). Reachability is measured: the walk fires at
1431 // ss (1, 0) on `422_intrabc_sb128_strip.obu` (`EC_IBC128_BANDS`
1432 // prints); that fixture's own votes do not cancel, so THIS gate -- not
1433 // a pixel compare -- is what stops the routing being reverted.
1434 for name in [
1435 "let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {",
1436 "neighbours.around_mi_422_chroma(",
1437 ] {
1438 assert_eq!(
1439 body.matches(name).count(),
1440 1,
1441 "{NAME}: `{name}` must appear exactly once in \
1442 decode_intrabc_128rect's chroma chunk walk, found {} -- the \
1443 gather has fallen back to the square per-mi rule",
1444 body.matches(name).count()
1445 );
1446 }
1447 // The replay's own unit luma span is the lossless/lossy `cu << ss` form
1448 // (site 2 spells it separately from the read walk's `cu_tx << ss`).
1449 for name in [
1450 "let unit_luma_w = cu << ss_x(fctx);",
1451 "let unit_luma_h = cu << ss_y(fctx);",
1452 ] {
1453 assert_eq!(
1454 body.matches(name).count(),
1455 1,
1456 "{NAME}: `{name}` must appear exactly once in \
1457 decode_intrabc_128rect, found {}",
1458 body.matches(name).count()
1459 );
1460 }
1461 // The per-axis chunk extent the geometry demands, spelled out here so
1462 // the scan and the witnesses cannot disagree about it.
1463 let per_axis_units = |ss_x: u32, ss_y: u32| (64 >> ss_x) / 32 * (64 >> ss_y) / 32;
1464 assert_eq!(per_axis_units(1, 1), 1, "{NAME}: 4:2:0 must stay one unit");
1465 assert_eq!(per_axis_units(1, 0), 2, "{NAME}: 4:2:2 must be two units");
1466 assert_eq!(per_axis_units(0, 0), 4, "{NAME}: 4:4:4 must be four units");
1467 // The counters the probe arms read must stay exported.
1468 for name in [
1469 "pub fn intrabc_128rect_chroma_chunk_hits()",
1470 "pub fn intrabc_128rect_chunk_shape()",
1471 ] {
1472 assert!(
1473 src.contains(name),
1474 "{NAME}: the accessor `{name}` must stay in decode.rs"
1475 );
1476 }
1477 }
1478
1479 /// lane-av1422gather3: `decode_block_128rect`'s per-chunk CHROMA unit
1480 /// walk gathered its coefficient context with the plain square-cut
1481 /// `around_mi_rect`, so at ss (1,0) its above dc vote summed 16 LUMA mi
1482 /// cells where libaom's `get_txb_ctx_general` reads `txb_w_unit` =
1483 /// `chroma_tx / 4` = 8 CHROMA cells (one chroma column per PAIR of luma
1484 /// mi columns; both luma cells of a column carry the covering unit's
1485 /// whole-unit dc sign). That is the same pair rule the mu-chunk walks
1486 /// take (`around_mi_422_chroma`), and the gather now routes through it
1487 /// under the ss guard -- verbatim `around_mi_rect` at every other shape.
1488 ///
1489 /// Reachability is MEASURED, not assumed: the walk fires at ss (1,0) on
1490 /// both pinned `422_intrabc_sb128_strip*.obu` cells, 72 chroma unit
1491 /// gathers each (`sb128rect_chroma_replay_hits().0`, the same walk's own
1492 /// replay counter). No committed cell DISCRIMINATES the change: with the
1493 /// pair rule in place all 21 committed 4:2:2 cells are byte-exact
1494 /// against ffmpeg, exactly as the pre-change tree was (the gathered
1495 /// votes cancel at every reached unit), so THIS gate -- not a pixel
1496 /// compare -- is what stops the routing being reverted.
1497 ///
1498 /// lane-av1422mismatch9: the same decode loop now also asserts the
1499 /// `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` count (NINE per pin) and states
1500 /// why it is not a pixel miss -- the counter's predicate is a span
1501 /// DIFFERENCE, true by construction at ss (1,0); the replay re-stamps the
1502 /// identical context cells with the same per-axis pair the read walk used;
1503 /// and `record_mi_chroma` writes no pixel sample. See the assert's message.
1504 #[test]
1505 fn the_422_block_128rect_chroma_chunk_gather_stays_per_axis() {
1506 const NAME: &str = "the_422_block_128rect_chroma_chunk_gather_stays_per_axis";
1507 let src = crate::test_source::module_source("decode");
1508 let body = src
1509 .split_once("fn decode_block_128rect(")
1510 .expect("decode_block_128rect must exist")
1511 .1
1512 .split_once("\nfn ")
1513 .expect("decode_block_128rect must be a top-level fn")
1514 .0;
1515 // Scan CODE only: the fix's own comment quotes the guard form, and a
1516 // prose mention must not read as a reintroduction (nor mask one).
1517 let stripped: Vec<&str> = body
1518 .lines()
1519 .map(|l| l.split_once("//").map_or(l, |(c, _)| c))
1520 .collect();
1521 let code = stripped.join("\n");
1522 let body = code.as_str();
1523 assert_eq!(
1524 body.matches("if ss_x(fctx) == 1 && ss_y(fctx) == 0 {")
1525 .count(),
1526 1,
1527 "{NAME}: the ss (1, 0) guard over the per-chunk chroma gather must \
1528 appear exactly once in decode_block_128rect, found {}",
1529 body.matches("if ss_x(fctx) == 1 && ss_y(fctx) == 0 {")
1530 .count()
1531 );
1532 for name in [
1533 "neighbours.around_mi_422_chroma(cu_mi, luma_span, luma_span_h)",
1534 "neighbours.around_mi_rect(cu_mi, luma_span, luma_span_h)",
1535 ] {
1536 assert_eq!(
1537 body.matches(name).count(),
1538 1,
1539 "{NAME}: `{name}` must appear exactly once in \
1540 decode_block_128rect's per-chunk chroma gather, found {} -- one \
1541 arm has been dropped, so the gather has fallen back to the \
1542 square per-mi rule at ss (1, 0)",
1543 body.matches(name).count()
1544 );
1545 }
1546 // Reachability arm: the walk must actually RUN at ss (1, 0) on the
1547 // pinned strips, or the routing above is a no-op the gate cannot see.
1548 // A stream that stopped coding 128-axis intra blocks reads 0 and this
1549 // assert fails instead of passing over a decode that never reached
1550 // the fixed gather (class gate-blind-to-feature).
1551 for (file, bytes, fp) in [
1552 (
1553 "422_intrabc_sb128_strip.obu",
1554 1672usize,
1555 0x50f5cfc576e4cd00_u64,
1556 ),
1557 (
1558 "422_intrabc_sb128_strip_notxsearch.obu",
1559 1675,
1560 0xd4936f252ff8cff0,
1561 ),
1562 ] {
1563 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1564 .join("fixtures")
1565 .join(file);
1566 let data = std::fs::read(&path).unwrap_or_else(|e| {
1567 panic!(
1568 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
1569 path.display()
1570 )
1571 });
1572 assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
1573 assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
1574 let _guard = lock_gate_counters();
1575 let before = crate::decode::sb128rect_chroma_replay_hits();
1576 let frames = decode_stream(&data)
1577 .unwrap_or_else(|e| panic!("{NAME}: {file} no longer decodes cleanly: {e}"));
1578 let after = crate::decode::sb128rect_chroma_replay_hits();
1579 assert_eq!(
1580 after.0 - before.0,
1581 72,
1582 "{NAME}: {file} gathered {} chroma unit context(s) in \
1583 decode_block_128rect's per-chunk walk; 72 were measured at ss (1, 0) -- \
1584 a lower number means the gather is no longer REACHED here \
1585 (class gate-blind-to-feature)",
1586 after.0 - before.0
1587 );
1588 // lane-av1422mismatch9: `SB128RECT_REPLAY_SPAN_MISMATCH_HITS` reads
1589 // NINE on each of these two pins, and this is the only place that
1590 // number is asserted. It is NOT a pixel miss, and the three facts
1591 // below are why -- the assert encodes the measurement, not a wish:
1592 //
1593 // 1. The predicate (`decode.rs`, end of `decode_block_128rect`) is
1594 // `luma_span != luma_span_h` -- `chroma_tx << ss_x` vs
1595 // `chroma_tx << ss_y`. At ss (1, 0) the two DIFFER BY
1596 // CONSTRUCTION for every 128-root rect block, so the counter is
1597 // a shape test ("this is the 4:2:2 span shape"), not a
1598 // divergence test. Nine is the number of such blocks the five
1599 // frames code.
1600 // 2. The replay re-stamps with the SAME per-axis pair the in-loop
1601 // walk stamped with (`record_mi_chroma(cu_mi, luma_span,
1602 // luma_span_h, ...)` at both the read walk and the replay), so
1603 // it rewrites the identical context cells -- this is exactly
1604 // the `record_mi_chroma(cu_mi, luma_span, luma_span_h)` pairing
1605 // the source-scan arm above pins. The pre-lane-av1-128rectspan
1606 // defect (width passed on both axes) is caught by that
1607 // spelling arm, not by this counter.
1608 // 3. `record_mi_chroma` writes only `Neighbours::left`/`above`
1609 // (entropy-context arrays); it touches ZERO pixel samples. So
1610 // the 9 events cannot write a sample the oracle lacks. The
1611 // pixel proof is the same file's
1612 // `the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_
1613 // exact`, which pins all five frames byte-exact against
1614 // ffmpeg's `yuv422p` rawvideo.
1615 //
1616 // Change this expected count ONLY with a new measurement; a 4:2:2
1617 // stream coding more 128-root rect blocks legitimately changes it.
1618 assert_eq!(
1619 after.1 - before.1,
1620 9,
1621 "{NAME}: {file} fired the 4:2:2 span-shape arm {} time(s); NINE were \
1622 measured and are NOT a pixel miss (the predicate is `luma_span != \
1623 luma_span_h`, true by construction at ss (1,0); the replay re-stamps the \
1624 identical context cells with the same per-axis pair; `record_mi_chroma` \
1625 writes no pixel) -- see the report above",
1626 after.1 - before.1
1627 );
1628 assert_eq!(frames.len(), 5, "{NAME}: {file} frame count");
1629 }
1630 }
1631
1632 /// lane-av1422lpf: the three 4:2:2 LOSSLESS INTER witness fixtures,
1633 /// PINNED. As of lane-av1422lift they are asserted to DECODE pixel-exact
1634 /// against ffmpeg (the lane-av1422lift paragraph at the end of this doc);
1635 /// before the lift this gate asserted the SEQUENCE-HEADER refusal instead.
1636 ///
1637 /// W/X/Y (`W_intrabc.obu`, `X_intrabc_tiled.obu`, `Y_intrabc_10b.obu`) are
1638 /// the streams on which lane-av1422lpf found the seven-site chroma-extent
1639 /// PANIC family -- each site indexed a block's chroma PLANE BLOCK with
1640 /// the ENCLOSING SQUARE `max(side >> ss_x, side >> ss_y)` instead of the
1641 /// PER-AXIS `(bw >> ss_x, bh >> ss_y)` -- so the pins keep the bytes that
1642 /// witnessed it from silently changing under the gate.
1643 ///
1644 /// WHAT THIS GATE DID NOT COVER BEFORE THE LIFT, measured rather than
1645 /// argued: the refusal it asserted was the HEADER refusal, which fired
1646 /// BEFORE any of the seven sites is reachable, and it fired IDENTICALLY on
1647 /// the pre-fix tree (commit `aef4fa67` prints the same string, built and
1648 /// run for this correction). As a refusal contract the gate was therefore
1649 /// VACUOUS with respect to the seven-site fix -- it passed before and
1650 /// after the fix, and its only real content was the three pins.
1651 ///
1652 /// That refusal is GONE (lane-av1422lift lifted the sequence-header
1653 /// refusal), so the decode-level half of the evidence now runs in
1654 /// committed code: this gate's own byte-exact arm below decodes all three
1655 /// fixtures against ffmpeg. `EC_AV1_ALLOW_422_PROBE` was only ever the
1656 /// patch-run-restore bypass for the manual measurement in
1657 /// `lanes/av1422lpf.report.md`; it is still deliberately not committed.
1658 /// The source-scan arm
1659 /// `the_422_lossless_inter_chroma_walk_sites_stay_per_axis` remains the
1660 /// per-axis SPELLING proof; the pixel proof is now the committed decode.
1661 ///
1662 /// CORRECTED by lane-av1422llintra: the name said `..._panics_refuse_
1663 /// by_name`, and lane-av1422lpf's report claimed W and X now REFUSE with
1664 /// `a Golomb tail longer than this decoder reads` at frame 2. That
1665 /// refusal DOES NOT REPRODUCE on this tip: with the bypass applied, all
1666 /// three cells DECODE 16/16 -- no panic and no second refusal.
1667 ///
1668 /// lane-av1422lift: the three pins are asserted BYTE-EXACT against
1669 /// ffmpeg's rawvideo of the same bytes, per plane and per frame, with the
1670 /// per-plane coefficient-unit census as the non-vacuity arm -- so the
1671 /// three DECODE 16/16 fact the paragraph above records from a bypassed
1672 /// probe build is now a committed assertion. `Y` is the 10-bit member
1673 /// and carries the depth-correct HBD compare (`yuv422p10le`, 16-bit
1674 /// containers on both sides) rather than an 8-bit narrowing of a
1675 /// high-bit-depth cell.
1676 #[test]
1677 fn the_pinned_422_lossless_inter_witnesses_decode_pixel_exact() {
1678 const NAME: &str = "the_pinned_422_lossless_inter_witnesses_decode_pixel_exact";
1679 if !have_ffmpeg() {
1680 eprintln!("SKIP {NAME}: no ffmpeg");
1681 return;
1682 }
1683 for (file, bytes, fp, depth) in [
1684 ("W_intrabc.obu", 130_320usize, 0xb6d5c4653a32567a_u64, 8u8),
1685 ("X_intrabc_tiled.obu", 131_696, 0xb6e04621d2116ef7, 8),
1686 ("Y_intrabc_10b.obu", 202_281, 0x2ecf03435a14dbf, 10),
1687 ] {
1688 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1689 .join("fixtures")
1690 .join(file);
1691 let data = std::fs::read(&path).unwrap_or_else(|e| {
1692 panic!("{NAME}: pinned witness {file} is missing ({e}) -- the gate cannot run")
1693 });
1694 assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
1695 assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
1696 assert_422_stream_pixel_exact(NAME, &data, 320, 240, 16, depth, true);
1697 }
1698 }
1699
1700 /// lane-av1422lpf: the SOURCE-SCAN arm of the witness gate above -- one
1701 /// assertion per site, so a mutation at any single site reds exactly that
1702 /// site and leaves the other six alone.
1703 ///
1704 /// Every assertion has a NEGATIVE twin (`forbidden`) and a POSITIVE twin
1705 /// (`required`), so neither an unreverted site nor a matcher that has
1706 /// stopped matching can pass: the forbidden string is absent AND the
1707 /// required string is present in the same function body. The `required`
1708 /// half is what makes this gate non-vacuous in the
1709 /// `dead-matcher-positive-control` sense -- a scan that matched nothing
1710 /// would fail it rather than pass silently.
1711 ///
1712 /// WHAT IT DOES NOT COVER: this arm is a SPELLING scan. It cannot observe
1713 /// a decode, so it cannot prove any cell decodes and cannot prove any
1714 /// pixel -- the same limit as the witness gate above it, and stated here
1715 /// because "one assertion per site, each with a mutation proof" reads
1716 /// like more coverage than it is.
1717 ///
1718 /// `strip_code` is the same comment-stripping the arms above use: the
1719 /// fixes quote their own old expression to say what it was, and a prose
1720 /// mention must neither read as a reintroduction nor mask one.
1721 #[test]
1722 fn the_422_lossless_inter_chroma_walk_sites_stay_per_axis() {
1723 const NAME: &str = "the_422_lossless_inter_chroma_walk_sites_stay_per_axis";
1724 let src = crate::test_source::module_source("decode");
1725 let strip_code = |body: &str| -> String {
1726 body.lines()
1727 .map(|l| l.split_once("//").map_or(l, |(c, _)| c))
1728 .collect::<Vec<_>>()
1729 .join("\n")
1730 };
1731 // A SECOND form with the same comment stripping but every run of
1732 // whitespace collapsed to one space, so a matcher can span an argument
1733 // list that a line-anchored fix's own comment sits inside. Without it
1734 // the site-5 and site-6 matchers are DEAD: the mutation that reverts
1735 // them still passes, because the literal being searched for never
1736 // matched even when the fix was in place. Measured, not assumed --
1737 // `verifier-dead-matcher-positive-control`.
1738 let flatten = |body: &str| -> String {
1739 strip_code(body)
1740 .split_whitespace()
1741 .collect::<Vec<_>>()
1742 .join(" ")
1743 };
1744 let body_of = |fn_name: &str| -> String {
1745 let after = src
1746 .split_once(&format!("\nfn {fn_name}("))
1747 .unwrap_or_else(|| panic!("{NAME}: `{fn_name}` must exist in decode.rs"));
1748 let end = after.1.find("\nfn ").unwrap_or(after.1.len());
1749 strip_code(&after.1[..end])
1750 };
1751 let flat_of = |fn_name: &str| -> String {
1752 let after = src
1753 .split_once(&format!("\nfn {fn_name}("))
1754 .unwrap_or_else(|| panic!("{NAME}: `{fn_name}` must exist in decode.rs"));
1755 let end = after.1.find("\nfn ").unwrap_or(after.1.len());
1756 flatten(&after.1[..end])
1757 };
1758 // (label, enclosing fn, forbidden square-cut spelling, required
1759 // per-axis spelling, required count in that fn)
1760 let sites: [(&str, &str, &str, &str, usize); 4] = [
1761 (
1762 "site 1 -- read_inter_chroma_lossless's composed-grid extent",
1763 "read_inter_chroma_lossless",
1764 "stride * stride,\n );",
1765 "stride * blk_h,",
1766 1,
1767 ),
1768 (
1769 "site 7 -- read_intra_chroma_lossless's composed-grid extent",
1770 "read_intra_chroma_lossless",
1771 "stride * stride,\n );",
1772 "stride * blk_h,",
1773 1,
1774 ),
1775 (
1776 "site 4 -- the strip chroma rect's VERT arm at ss (1,0)",
1777 "decode_inter_block",
1778 "} else if s.horz {\n (8, 4)\n } else {\n (4, 8)\n }",
1779 "} else if ss_y(fctx) == 0 {\n (4, 16)\n } else {\n (4, 8)\n }",
1780 1,
1781 ),
1782 (
1783 "site 5 -- the mu-chunk lossless walk's prediction stride",
1784 "decode_inter_block",
1785 "(write_chroma_w, write_chroma_h), chroma_side, mode_for_tx,",
1786 "(write_chroma_w, write_chroma_h), chroma_stride, mode_for_tx,",
1787 2,
1788 ),
1789 ];
1790 for (label, fn_name, forbidden, required, count) in sites {
1791 // The last table row is written in the flattened form (it spans a
1792 // comment the fix itself wrote); the others are line-anchored.
1793 let flattened = required.contains(" mode_for_tx,");
1794 let body = if flattened {
1795 flat_of(fn_name)
1796 } else {
1797 body_of(fn_name)
1798 };
1799 assert_eq!(
1800 body.matches(forbidden).count(),
1801 0,
1802 "{NAME}: {label} is BACK -- the square-cut expression \
1803 `{forbidden}` is what this gate exists for"
1804 );
1805 assert!(
1806 body.matches(required).count() >= count,
1807 "{NAME}: {label}: the per-axis expression `{required}` must appear \
1808 at least {count} time(s) in `{fn_name}` -- found {}",
1809 body.matches(required).count()
1810 );
1811 }
1812 // Sites 2, 5 and 6 are the `chroma_side`-vs-`chroma_stride` and
1813 // `chroma_side`-vs-`chroma_buf_h` argument choices, which are
1814 // single-token differences on otherwise identical lines. Counting the
1815 // remaining `chroma_side` uses per arm is the only way to see them, so
1816 // they get their own exact-count assertions instead of a substring.
1817 let dib = body_of("decode_inter_block");
1818 // Site 2: the lossless TX_4x4 unit replay indexes the composed grid.
1819 assert_eq!(
1820 dib.matches("let start = (cr * cu + rr) * chroma_stride + cc * cu;")
1821 .count(),
1822 1,
1823 "{NAME}: site 2 -- the lossless TX_4x4 replay must index the \
1824 composed plane grid at `chroma_stride` (the plane block's own \
1825 width), not `chroma_side`"
1826 );
1827 assert_eq!(
1828 dib.matches("let start = (cr * cu + rr) * chroma_side + cc * cu;")
1829 .count(),
1830 0,
1831 "{NAME}: site 2 is BACK -- the lossless TX_4x4 replay indexes the \
1832 composed grid at the enclosing square again"
1833 );
1834 // Sites 5 and 6. The two mu-chunk walks (the single-reference and the
1835 // compound twin) take the block's `(write_chroma_w, write_chroma_h)`
1836 // and the stride SEPARATELY; the two intra-in-inter walks take both
1837 // the block shape and the region as `(chroma_stride, chroma_buf_h)`.
1838 // Every one of the four must be per-axis; the pre-fix spelling was
1839 // the enclosing square `chroma_side` for the stride, and
1840 // `(chroma_side, chroma_side)` for the intra block shape.
1841 let dibf = format!(
1842 "{}{}",
1843 flat_of("decode_inter_block"),
1844 flat_of("decode_inter_block_intra_arm"),
1845 ); // the intra arm was split out of decode_inter_block (av1split D8a)
1846 assert_eq!(
1847 dibf.matches("(chroma_stride, chroma_buf_h),").count(),
1848 3,
1849 "{NAME}: site 6 -- the two intra-in-inter walks pass the plane block \
1850 as `(chroma_stride, chroma_buf_h)` at all THREE argument positions \
1851 it occupies -- the mu-chunk walk's blk shape, and the whole-block walk's blk shape and region -- found {}",
1852 dibf.matches("(chroma_stride, chroma_buf_h),").count()
1853 );
1854 assert_eq!(
1855 dibf.matches("(chroma_side, chroma_side),").count(),
1856 0,
1857 "{NAME}: site 6 is BACK -- an intra-in-inter walk still hands the \
1858 plane block the enclosing square `chroma_side`"
1859 );
1860 // The geometry the scan cannot see, derived from the same `>> ss`
1861 // forms the fixes use, so the scan and the fix cannot disagree about
1862 // what per-axis means at each chroma format. A 16x16 luma block:
1863 // (side >> ss_x, side >> ss_y) is the plane block and
1864 // max(side >> ss_x, side >> ss_y) is the enclosing square.
1865 let plane_block = |side: usize, ss_x: u32, ss_y: u32| (side >> ss_x, side >> ss_y);
1866 let enclosing = |side: usize, ss_x: u32, ss_y: u32| {
1867 (
1868 (side >> ss_x).max(side >> ss_y),
1869 (side >> ss_x).max(side >> ss_y),
1870 )
1871 };
1872 for (label, side, ss_x, ss_y, block, square) in [
1873 ("4:2:0", 16usize, 1u32, 1u32, (8, 8), (8, 8)),
1874 ("4:2:2", 16, 1, 0, (8, 16), (16, 16)),
1875 ("4:4:4", 16, 0, 0, (16, 16), (16, 16)),
1876 ] {
1877 assert_eq!(
1878 plane_block(side, ss_x, ss_y),
1879 block,
1880 "{NAME}: the {label} chroma plane block of a {side}x{side} luma block"
1881 );
1882 assert_eq!(
1883 enclosing(side, ss_x, ss_y),
1884 square,
1885 "{NAME}: the {label} enclosing chroma square of a {side}x{side} \
1886 luma block"
1887 );
1888 }
1889 // The load-bearing claim of "unchanged at 4:2:0 and 4:4:4": the two
1890 // are the same number exactly when `ss_x == ss_y`, and DIFFERENT at
1891 // 4:2:2 -- which is what makes every site above inert there and
1892 // active at 4:2:2. If this ever held at 4:2:2 the fixes would be
1893 // untested rather than inert.
1894 assert_eq!(plane_block(16, 1, 1), enclosing(16, 1, 1));
1895 assert_eq!(plane_block(16, 0, 0), enclosing(16, 0, 0));
1896 assert_ne!(
1897 plane_block(16, 1, 0),
1898 enclosing(16, 1, 0),
1899 "{NAME}: 4:2:2 must NOT be square -- if the plane block equalled \
1900 the enclosing square at ss (1,0), none of these sites could ever \
1901 be wrong and the gates above would be measuring nothing"
1902 );
1903 // Site 4's own geometry: a PARTITION_VERT_4 strip is 4x16 luma and
1904 // pairs on COLUMNS while `ss_x == 1`, so the pair is 8x16 and its
1905 // plane block is (8 >> ss_x, 16 >> ss_y).
1906 for (label, ss_x, _ss_y, want) in [
1907 ("4:2:0", 1u32, 1u32, (4usize, 8usize)),
1908 ("4:2:2", 1, 0, (4, 16)),
1909 ("4:4:4", 0, 0, (8, 16)),
1910 ] {
1911 assert_eq!(
1912 plane_block(8, ss_x, 0).0,
1913 want.0,
1914 "{NAME}: site 4 -- the {label} VERT strip pair's chroma width"
1915 );
1916 }
1917 // ...and the HORZ arm of the same match needs NO third shape at
1918 // 4:2:2: a HORZ_4 strip pairs on ROWS only while `ss_y == 1`, and
1919 // 4:2:2 has `ss_y == 0`, so each 16x4 strip is its own chroma
1920 // reference and its own (8 >> ss_x, 4 >> 0) plane block -- which is
1921 // the (8, 4) the existing arm already returns.
1922 assert_eq!(
1923 (plane_block(16, 1, 0).0, plane_block(4, 1, 0).1),
1924 (8usize, 4usize),
1925 "{NAME}: site 4 -- the 4:2:2 HORZ strip's own plane block is already \
1926 the (8, 4) the unsplit arm returns, which is why only the VERT arm \
1927 gained a shape"
1928 );
1929 }
1930
1931 /// lane-av1422warp: the SECOND 4:2:2 coverage witness -- the one
1932 /// `422_sb128_3f.obu` could not be, because that stream's inter content
1933 /// is skip-heavy (see `lanes/av1422stripwrite.report.md`, which named a
1934 /// second fixture with real residuals, compound and warped motion above
1935 /// the vertical midpoint as the thing that would justify lifting the
1936 /// refusal). This is that fixture.
1937 ///
1938 /// `422_residual_compound_warp_16f.obu` (38845 bytes), sha256
1939 /// `d78e2afb43ce311d3d82335a945c6f80f62db4537966d881c1349a68b3aecb95`:
1940 ///
1941 /// ```text
1942 /// ffmpeg -f lavfi -i "mandelbrot=size=256x288:rate=24:maxiter=220:start_scale=3:end_scale=0.35:end_pts=300,rotate=a=0.10*t:c=none:ow=256:oh=288" \
1943 /// -frames:v 24 -pix_fmt yuv422p -f yuv4mpegpipe src422.y4m
1944 /// aomenc --codec=av1 --profile=2 --input-bit-depth=8 --limit=16
1945 /// --width=256 --height=288 --lag-in-frames=25 --auto-alt-ref=1
1946 /// --enable-global-motion=1 --pass=1
1947 /// --cq-level=24 --cpu-used=0
1948 /// --threads=4 --kf-min-dist=0 --kf-max-dist=999999 \
1949 /// src422.y4m -o a1.webm
1950 /// ffmpeg -i a1.webm -c copy -f obu -y a1.obu
1951 /// ```
1952 ///
1953 /// CORRECTED by lane-av1422lrless (reviewer P2). This doc previously
1954 /// carried a different ffmpeg filter (`rotate=a=0.10`, no `*t`, no
1955 /// `:c=none:ow/oh`) and a `-n ffp --pass=2 --fpf=...` two-pass line.
1956 /// **Neither produced these bytes.** Re-encoding from the recorded
1957 /// source `src422.y4m` (sha256
1958 /// `4d35eaf65d1a5541b3177e1183644c163b3868d8f141bed0ce9fdf833280ba9f`)
1959 /// was measured three ways: the two-pass form gives 38774 bytes
1960 /// (`e93c4ed7...`), and only adding `--pass=1` reproduces these 38845
1961 /// bytes byte for byte (`d78e2afb...`). `aomenc` DEFAULTS to two-pass,
1962 /// so the flag has to be stated to get back the pinned stream. The
1963 /// recipe above is the one that was actually run.
1964 ///
1965 /// Measured on a patch-run-restore build (the `EC_AV1_ALLOW_422_PROBE`
1966 /// bypass applied for the run, reverted after -- it is deliberately NOT
1967 /// committed). This block is the bypassed measurement; the committed
1968 /// assertion is now the byte-exact compare in the lane-av1422lift
1969 /// paragraph below:
1970 ///
1971 /// - all 16 frames pixel-exact against `aomdec --rawvideo`, 2359296
1972 /// bytes each, sha256 `4bfc2395e5ca6ea178f606e6b1ced773e26fc2d85b
1973 /// c3a6cdb63a402939aeb203` on both sides;
1974 /// - the entropy stream pairs bit-for-bit against the instrumented
1975 /// oracle -- 246735 symbol reads each, no divergence anywhere in the
1976 /// stream, not merely at the window this lane spent nine rounds
1977 /// narrowing;
1978 /// - the arms this fixture exists to cover really fire ABOVE the
1979 /// vertical midpoint: 3 upper-half blocks on a non-`TRANSLATION`
1980 /// global-motion model (`top_half_warp_hits`, gated on libaom's
1981 /// `is_global_mv_block` per slot) and 3 upper-half
1982 /// `GLOBAL_GLOBALMV` compound blocks (`top_half_compound_hits`),
1983 /// alongside 25 compound-warp, 18 compound-warp-8x8-leaf, 84
1984 /// rotzoom global-warp, 22 Wiener and 10 SGRPROJ loop-restoration
1985 /// units frame-globally.
1986 ///
1987 /// The loop-restoration numbers are load-bearing twice over: decoding
1988 /// this stream is what exposed the per-axis `read_lr` corner bug
1989 /// (`restoration.rs`, `av1_loop_restoration_corners_in_sb`), whose fix
1990 /// is what made the whole sequence pair. 4:2:0 and 4:4:4 are unchanged
1991 /// by it -- byte-identical to their pre-lane decodes, with the LR gate
1992 /// family green.
1993 ///
1994 /// lane-av1422lift: the committed assertion is now the byte pin AND
1995 /// byte-exactness against ffmpeg's `yuv422p` rawvideo of the same bytes,
1996 /// per plane and per frame, with the per-plane coefficient-unit census
1997 /// as the non-vacuity arm. The paragraph above's coverage counts (25
1998 /// compound-warp, 84 rotzoom global-warp, 22 Wiener, 10 SGRPROJ, CDEF
1999 /// 39) are what make the row non-vacuous: without them a byte-exact
2000 /// compare could be green over a stream that never entered a warp arm.
2001 #[test]
2002 fn the_pinned_422_residual_compound_warp_witness_decodes_pixel_exact() {
2003 const NAME: &str = "the_pinned_422_residual_compound_warp_witness_decodes_pixel_exact";
2004 if !have_ffmpeg() {
2005 eprintln!("SKIP {NAME}: no ffmpeg");
2006 return;
2007 }
2008 const FILE: &str = "422_residual_compound_warp_16f.obu";
2009 const BYTES: usize = 38845;
2010 const FP: u64 = 0x0e73a51e2cc0c424;
2011 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2012 .join("fixtures")
2013 .join(FILE);
2014 let data = std::fs::read(&path).unwrap_or_else(|e| {
2015 panic!(
2016 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
2017 path.display()
2018 )
2019 });
2020 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
2021 assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted");
2022 assert_422_stream_pixel_exact(NAME, &data, 256, 288, 16, 8, true);
2023 }
2024
2025 /// lane-av1422lrless: the LR-OFF half of the 4:2:2 coverage pair.
2026 ///
2027 /// This is `422_residual_compound_warp_16f.obu`'s recipe with EXACTLY
2028 /// ONE flag changed, `--enable-restoration=0`, and that is a measured
2029 /// claim rather than an assertion: both arms were re-encoded from the
2030 /// same source `src422.y4m` (sha256
2031 /// `4d35eaf65d1a5541b3177e1183644c163b3868d8f141bed0ce9fdf833280ba9f`)
2032 /// with the same aomenc invocation, and the LR-on arm reproduces the
2033 /// committed 38845 bytes byte for byte. So the pair is controlled, and
2034 /// the corners code is the only thing that can differ between their
2035 /// decodes: with restoration off, every plane's `frame_restoration_type`
2036 /// is `RESTORE_NONE`, so `read_lr` skips each plane and never computes a
2037 /// range. The LR-on stream exercises the range; this one proves the skip
2038 /// is the skip.
2039 ///
2040 /// ```text
2041 /// aomenc --codec=av1 --profile=2 --input-bit-depth=8 --limit=16
2042 /// --width=256 --height=288 --lag-in-frames=25 --auto-alt-ref=1
2043 /// --enable-global-motion=1 --pass=1 --enable-restoration=0
2044 /// --cq-level=24 --cpu-used=0
2045 /// --threads=4 --kf-min-dist=0 --kf-max-dist=999999 \
2046 /// src422.y4m -o a3.webm
2047 /// ffmpeg -i a3.webm -c copy -f obu -y a3.obu
2048 /// ```
2049 ///
2050 /// 38538 bytes, sha256
2051 /// `8bed368f7ec4bca772137c6a9c2af89e1b2767ed5f937b91bd9e72ec60aeb42f`.
2052 ///
2053 /// Measured on a patch-run-restore build (the `EC_AV1_ALLOW_422_PROBE`
2054 /// bypass applied for the run, reverted after -- deliberately not
2055 /// committed). This block is the bypassed measurement; the committed
2056 /// assertion is now the byte-exact compare in the lane-av1422lift
2057 /// paragraph below:
2058 ///
2059 /// - all 16 frames pixel-exact against `aomdec --rawvideo`, 2359296
2060 /// bytes each, sha256 `1cf47bc9e06a6e286452dfe4ffe457a85b6badd25
2061 /// 657dfd36af48262e8eb2464` on both sides;
2062 /// - the entropy stream pairs **244756-for-244756** against the
2063 /// instrumented oracle with no divergence anywhere -- a different
2064 /// read count from the LR-on sibling's 246735, which is the corners
2065 /// skip showing up in the symbol stream, so the two arms really are
2066 /// on different paths;
2067 /// - **loop restoration is proved off, not inferred from the flag**:
2068 /// all five LR counters read zero where the LR-on sibling reads
2069 /// `lr_wiener` 22, `lr_sgrproj` 10, `lr_stripe0` 26, `lr_last_stripe`
2070 /// 28;
2071 /// - and it carries MORE of the coverage than its sibling, which is
2072 /// what rescues the thin leg of the lift argument: **top-half
2073 /// compound 11** against the sibling's 3, and top-half warp 5 against
2074 /// 3. Frame-globally compound_warp 25, compound_warp_8 15, rotzoom
2075 /// global-warp 77, cdef_idx 39, part128_split 95. The stronger arm is
2076 /// the one where `read_lr` does nothing at all, so the engagement is
2077 /// not an artefact of the code under test.
2078 ///
2079 /// lane-av1422lift: same scope change as its siblings, and this is the arm
2080 /// where it matters most: this stream is the one where `read_lr` does
2081 /// nothing at all, so a byte-exact green over it is a claim about the
2082 /// per-axis path WITHOUT the loop-restoration corner fix carrying it.
2083 /// The pin stays, the compare against ffmpeg's `yuv422p` rawvideo is
2084 /// added per plane and per frame, and the per-plane coefficient-unit
2085 /// census is the non-vacuity arm.
2086 #[test]
2087 fn the_pinned_422_lr_off_witness_decodes_pixel_exact() {
2088 const NAME: &str = "the_pinned_422_lr_off_witness_decodes_pixel_exact";
2089 if !have_ffmpeg() {
2090 eprintln!("SKIP {NAME}: no ffmpeg");
2091 return;
2092 }
2093 const FILE: &str = "422_residual_compound_warp_nolr_16f.obu";
2094 const BYTES: usize = 38538;
2095 const FP: u64 = 0x4b8ff761701e2bef;
2096 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2097 .join("fixtures")
2098 .join(FILE);
2099 let data = std::fs::read(&path).unwrap_or_else(|e| {
2100 panic!(
2101 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
2102 path.display()
2103 )
2104 });
2105 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
2106 assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted");
2107 assert_422_stream_pixel_exact(NAME, &data, 256, 288, 16, 8, true);
2108 }
2109
2110 /// lane-av1422lift: 4:2:2 FILM GRAIN, and why this one gate cannot use
2111 /// the dump path or the shared body above.
2112 ///
2113 /// `EC_AV1_FINAL_DUMP` writes the picture "exactly as it is about to be
2114 /// stored into the reference slots" (`stream.rs`, the dump site beside
2115 /// the emit), which is BEFORE `apply_grain` runs on the output. ffmpeg's
2116 /// rawvideo is POST-grain. So every grain cell -- 4:2:0, 4:2:2, 12-bit,
2117 /// all of them -- is incomparable through the dump, and the corpus
2118 /// comparator hits it as a hard error rather than as a clean red
2119 /// (measured on `s422_grain_160x128.obu`: "luma identity never covers the
2120 /// display side (3 decode frames, 3 display frames)"). This gate
2121 /// therefore compares the IN-MEMORY `decode_stream` output, which is
2122 /// post-grain, exactly like
2123 /// `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact` does for
2124 /// 12-bit 4:2:0. Using the pre-grain dump here would make the gate
2125 /// permanently red for a reason that has nothing to do with grain.
2126 ///
2127 /// The pin, `s422_grain_160x128.obu` (5433 bytes, sha256
2128 /// `a4a6957b5e8298d9138f64498cab2d3008b3390fa73cd0d74aa0632b13d93d15`,
2129 /// fnv1a64 `0x2aed47614b9461b8`), is aomenc profile 2 over a `C422`
2130 /// testsrc2 160x128 3-frame source with `--film-grain-test=5`,
2131 /// `--passes=1 --end-usage=q --cq-level=24 --cpu-used=0 --threads=1
2132 /// --row-mt=0 --limit=3 --obu`.
2133 ///
2134 /// Two arms, because a green compare over a stream whose grain never ran
2135 /// is the "params-without-apply" false green:
2136 ///
2137 /// 1. the stream's OWN frame headers carry `apply_grain` and scaling
2138 /// points on all THREE planes -- at 4:2:2 that is the shape libaom's
2139 /// `generate_grain_uv_422` exists for, and it is read out of the
2140 /// bytes, not out of the flags handed to the encoder;
2141 /// 2. `film_grain::grain_hits()` moves across the decode.
2142 #[test]
2143 fn a_real_422_film_grain_stream_decodes_pixel_exact() {
2144 const NAME: &str = "a_real_422_film_grain_stream_decodes_pixel_exact";
2145 if !have_ffmpeg() {
2146 eprintln!("SKIP {NAME}: no ffmpeg");
2147 return;
2148 }
2149 let _gate_lock = lock_gate_counters();
2150 let path = crate_pin("s422_grain_160x128.obu");
2151 let stream = read_pin(&path, 5433, 0x2aed47614b9461b8, NAME);
2152 let mut probe = Av1Parser::new();
2153 let mut pos = 0usize;
2154 let mut grain_frames = 0usize;
2155 while pos < stream.len() {
2156 let obu = probe.parse_obu(&stream[pos..]).unwrap();
2157 pos += obu.total_size;
2158 if let ObuKind::Frame(header, _) = obu.kind {
2159 let fg = &header.film_grain;
2160 assert!(
2161 fg.apply_grain,
2162 "{NAME}: frame without apply_grain -- aomenc emitted params it does not apply"
2163 );
2164 assert!(
2165 fg.num_y_points > 0 && fg.num_cb_points > 0 && fg.num_cr_points > 0,
2166 "{NAME}: grain without all three planes' scaling points -- the per-axis \
2167 `generate_grain_uv_422` geometry would not be exercised"
2168 );
2169 grain_frames += 1;
2170 }
2171 }
2172 assert_eq!(
2173 grain_frames, 3,
2174 "{NAME}: expected grain on all three frames"
2175 );
2176 let before = crate::film_grain::grain_hits();
2177 let units_before = crate::decode::census_nonsub_units();
2178 let ours = decode_stream(&stream).unwrap_or_else(|e| {
2179 panic!("{NAME}: decode_stream refused a real 4:2:2 grain stream: {e}")
2180 });
2181 assert_eq!(ours.len(), 3, "{NAME}: decoded frame count");
2182 assert_eq!(
2183 ours[0].u.len(),
2184 80 * 128,
2185 "{NAME}: 160x128 4:2:2 chroma is 80x128; {} means a 4:2:0 plane",
2186 ours[0].u.len()
2187 );
2188 assert!(
2189 crate::film_grain::grain_hits() > before,
2190 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
2191 );
2192 let units = crate::decode::census_nonsub_units();
2193 for (p, plane) in ["luma", "U", "V"].into_iter().enumerate() {
2194 assert!(
2195 units[p] > units_before[p],
2196 "{NAME}: the {plane} plane walked ZERO coefficient units -- this byte-exact \
2197 compare is vacuous with respect to 4:2:2"
2198 );
2199 }
2200 let theirs = ffmpeg_decode_sequence_422(&stream, 160, 128, 3);
2201 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2202 for (plane, ours_plane, theirs_plane) in
2203 [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)]
2204 {
2205 if let Some(bad) = ours_plane
2206 .iter()
2207 .zip(theirs_plane)
2208 .position(|(x, y)| x != y)
2209 {
2210 panic!(
2211 "{NAME}: {plane} differs from ffmpeg at frame {i} sample {bad} ({} vs {})",
2212 ours_plane[bad], theirs_plane[bad]
2213 );
2214 }
2215 }
2216 }
2217 eprintln!(
2218 "{NAME}: post-grain byte-exact vs ffmpeg; grain_hits={}",
2219 crate::film_grain::grain_hits()
2220 );
2221 }
2222
2223 /// lane-av1422lift: THE CORPUS BATTERY -- the gate the 4:2:2 campaign
2224 /// earned, and the one that replaces seven gates whose only behavioural
2225 /// assertion was `err.contains(REFUSAL)`.
2226 ///
2227 /// **Why these seven.** The measurement base
2228 /// (`lanes/av1422ffmpegbase.report.md` section 2.1) recorded seven 4:2:2
2229 /// cells that diverged from ffmpeg: `s422_320x246`, `s422_322x240`,
2230 /// `s422_322x246`, `s422_352x242_10b`, `s422_384x240`,
2231 /// `s422_416x242_10b`, `s422_416x250_10b`. ALL SEVEN are closed and are
2232 /// pinned here, each byte-exact against ffmpeg with the per-plane
2233 /// coefficient-unit census as its non-vacuity arm. Six of them are
2234 /// CHROMA-only divergences at non-8-aligned geometries -- odd or
2235 /// 2-mod-4 luma dimensions, where `round_ss` and the chroma block walk
2236 /// disagree with a hardcoded `>> 1` -- which is why they are the rows a
2237 /// lift cannot afford to leave unasserted: they are the cells that would
2238 /// go quietly wrong again.
2239 ///
2240 /// **The seventh, `s422_384x240`, IS here now.** lane-av1422lift pinned six
2241 /// of the seven and deliberately left this one out: it was still red, and
2242 /// pinning a red cell inside a green gate is how a gate stops being a gate
2243 /// ("THIS BRANCH MUST NOT LAND UNTIL THAT CELL CLOSES AND THE CORPUS
2244 /// RE-MEASURES 51/51", `lanes/av1422lift.report.md` §7). The cell closed in
2245 /// lane-av1422tailskip, and NOT through the reserved group-tail chroma SKIP
2246 /// arm the risk study's R4 blamed: that lane measured it byte-exact against
2247 /// ffmpeg on all 16 displayed frames and all 17 decode-order frames, 0/0/0
2248 /// wrong samples in Y/U/V, with the fix's own counter
2249 /// (`palette_422_unit_window_hits`) non-zero on this stream.
2250 /// `lanes/av1422tailskip.report.md` §1 records the measurement and the
2251 /// refutation of the arm attribution.
2252 ///
2253 /// That lane had already committed these exact bytes under the name
2254 /// `422_palette_intra_in_inter_384x240_17f.obu` (sha256 `bf1c658e...a815b`,
2255 /// the sweep artifact byte for byte), so the row below pins THAT file
2256 /// rather than committing a second copy of one stream under a second name.
2257 /// Unlike the other six, this cell sits at an 8- AND 16-aligned geometry
2258 /// (384x240): it was the late-starting frame-1 alt-ref chroma residual
2259 /// (`lanes/av1422late.report.md`), not the `round_ss` class -- which is why
2260 /// it is pinned as its own row here rather than folded into that sentence.
2261 ///
2262 /// **The corpus re-measures 51/51**, which was the second half of the
2263 /// condition the paragraph above quotes. Re-run for this row with the
2264 /// ffmpeg-oracle census driver (`~/.cache/census422b/ffcensus.py`: display
2265 /// order, shown frames, geometry from `ffprobe`, a count over zero frames
2266 /// is a hard error) and a `dump_yuv` built from THIS lane's tree:
2267 /// **51 of 51 4:2:2 cells BYTE-EXACT** -- `s422_384x240` among them at
2268 /// 0/0/0 -- and, in the same run, all 44 4:2:0 / 4:4:4 controls BYTE-EXACT
2269 /// (95/95 over the whole corpus). That run is a measurement of this tree,
2270 /// not a re-reading of the closure report; the per-cell rows here are what
2271 /// keep the seven named ones from drifting back.
2272 ///
2273 /// **The census arm, per row.** `assert_422_stream_pixel_exact` asserts
2274 /// that all three planes read a non-zero number of coefficient units AND
2275 /// a non-zero number of units that coded at least one coefficient, on
2276 /// this row's own bytes. That is the requirement R8 named as unwritable
2277 /// before lane-av1422census422 armed the census for `(1,0)`; measured on
2278 /// this tree the OLD arming read `[0, 0, 0]` on every 4:2:2 cell while
2279 /// the same decode walked 4994 units, so a green here with no census
2280 /// assert would have proven nothing about 4:2:2.
2281 ///
2282 /// **Provenance of the seven pins.** All seven are `aomenc --codec=av1
2283 /// --profile=2 --input-bit-depth=<8|10> --cpu-used=0 --cq-level=24
2284 /// --limit=16 --auto-alt-ref=1 --enable-global-motion=1 --passes=1
2285 /// --obu` over a hand-built `C422` y4m (header line, then `FRAME\n` plus
2286 /// one frame of planes per frame -- libaom's y4minput requires those six
2287 /// bytes before EVERY frame), produced by the census sweep. The first six
2288 /// were copied in from `~/.cache/census422b/sweep/`; the seventh is the
2289 /// same sweep's `s422_384x240.obu`, which lane-av1422tailskip had already
2290 /// committed under the name in its own row (the two files are byte for
2291 /// byte identical -- sha256 `bf1c658e9bfdc13ec1ed51e59049d2b81201941b6ef45\
2292 /// 71f8382f356ea4b815b`), so it is pinned under that name here. They are
2293 /// ordinary libaom 4:2:2 streams with nothing bolted on.
2294 #[test]
2295 fn the_pinned_422_corpus_cells_decode_pixel_exact() {
2296 const NAME: &str = "the_pinned_422_corpus_cells_decode_pixel_exact";
2297 if !have_ffmpeg() {
2298 eprintln!("SKIP {NAME}: no ffmpeg");
2299 return;
2300 }
2301 // (file, bytes, fnv1a64, sha256, w, h, depth, frames)
2302 for (file, bytes, fp, sha, w, h, depth, frames) in [
2303 (
2304 "s422_320x246.obu",
2305 20692usize,
2306 0x01e556015878e04eu64,
2307 "aebd3a10d46e617b803579819f2502798076384be52e032b11b46f09eeb09a79",
2308 320usize,
2309 246usize,
2310 8u8,
2311 16usize,
2312 ),
2313 (
2314 "s422_322x240.obu",
2315 21096,
2316 0x9a96dda2a19d47a6,
2317 "e74bf7e91f23353986edf9380bcd6cb760194e619dbbdf6a239b7a05eff81799",
2318 322,
2319 240,
2320 8,
2321 16,
2322 ),
2323 (
2324 "s422_322x246.obu",
2325 20528,
2326 0x2c6f8be6d30384ab,
2327 "ee96617fe45ba963d3628f37086077a94806ef0465a74cb538a8e57d2ed900b3",
2328 322,
2329 246,
2330 8,
2331 16,
2332 ),
2333 (
2334 "s422_352x242_10b.obu",
2335 20575,
2336 0xf1d370f80d8ddc6d,
2337 "8893bbed108d7555e66c35f2f45d6e44044dcd6810b0510fb251be05dabaa2d0",
2338 352,
2339 242,
2340 10,
2341 16,
2342 ),
2343 (
2344 "s422_416x242_10b.obu",
2345 20282,
2346 0x9826402d91abbc56,
2347 "38d0b592e5e358901742122c590c8964b5d08d0ceccfa051e677c28f4b75d174",
2348 416,
2349 242,
2350 10,
2351 16,
2352 ),
2353 (
2354 "s422_416x250_10b.obu",
2355 19967,
2356 0x6b07e837eae8a6be,
2357 "d6aa7f450f54d6fb381400a0a0226da87599c00509eeb5031abe63383e272627",
2358 416,
2359 250,
2360 10,
2361 16,
2362 ),
2363 (
2364 // Census cell `s422_384x240` -- the seventh previously
2365 // diverging cell, closed by lane-av1422tailskip. Same bytes as
2366 // the sweep's `s422_384x240.obu`, already in this fixtures dir
2367 // under the name lane-av1422tailskip's own gate pins.
2368 "422_palette_intra_in_inter_384x240_17f.obu",
2369 19344usize,
2370 0x923ccabfcb933e90u64,
2371 "bf1c658e9bfdc13ec1ed51e59049d2b81201941b6ef4571f8382f356ea4b815b",
2372 384usize,
2373 240usize,
2374 8u8,
2375 16usize,
2376 ),
2377 ] {
2378 let row = format!("{NAME}[{file}]");
2379 let path = crate_pin(file);
2380 let data = std::fs::read(&path).unwrap_or_else(|e| {
2381 panic!(
2382 "{row}: pinned corpus cell {} is missing ({e}) -- the gate cannot run",
2383 path.display()
2384 )
2385 });
2386 assert_eq!(data.len(), bytes, "{row}: size drifted");
2387 assert_eq!(fnv1a64(&data), fp, "{row}: bytes drifted");
2388 // The sha256 is the corpus's own identity column (its
2389 // `cells_422_3d56.json` records one per cell and the census
2390 // verified zero drift); fnv1a64 is what `read_pin` can check
2391 // in-process without spawning sha256sum, so both are named and
2392 // the sha256 is what a re-capture must reproduce.
2393 eprintln!("{row}: sha256 {sha}");
2394 assert_422_stream_pixel_exact(&row, &data, w, h, frames, depth, true);
2395 }
2396 }
2397
2398 /// lane-av1-qmatrix: WITNESS for the lifted `using_qmatrix` refusal (the
2399 /// old gate `a_frame_using_quantisation_matrices_is_refused_by_name` is
2400 /// its mirror image -- its own panic said "flip this gate to a witness"
2401 /// the moment the dequant landed).
2402 ///
2403 /// A REAL `aomenc --enable-qm=1` stream (same source and recipe as the
2404 /// refusal's gate, plus its `--enable-qm=0` control) now DECODES, and
2405 /// every frame of both arms is pixel-exact against ffmpeg's own decode
2406 /// of the same OBU. The census proves the feature non-vacuously both
2407 /// ways (class `gate-blind-to-feature`): the parsed frame headers really
2408 /// carry `using_qmatrix = 1`, the dequantiser really SCALED transform
2409 /// units through a matrix on the qm-on arm (`qm_scaled_units() > 0`),
2410 /// and the qm-off control really scaled none (`== 0`).
2411 #[test]
2412 fn a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact() {
2413 const NAME: &str = "a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact";
2414 if !have_ffmpeg() || !have_aomenc() {
2415 eprintln!(
2416 "SKIP {NAME}: needs ffmpeg + an aomenc oracle at {}",
2417 aomenc_path().display()
2418 );
2419 return;
2420 }
2421 const W: usize = 128;
2422 const H: usize = 96;
2423 const FRAMES: usize = 3;
2424 // Every frame header's (using_qmatrix, qm_y, qm_u, qm_v), parsed
2425 // straight off the encoded bytes.
2426 let qm_headers = |stream: &[u8]| -> Vec<(bool, u8, u8, u8)> {
2427 let mut parser = Av1Parser::new();
2428 let mut pos = 0usize;
2429 let mut out = Vec::new();
2430 while pos < stream.len() {
2431 let obu = parser.parse_obu(&stream[pos..]).unwrap();
2432 pos += obu.total_size;
2433 if let ObuKind::Frame(header, _) = obu.kind {
2434 let q = &header.quantization;
2435 out.push((q.using_qmatrix, q.qm_y, q.qm_u, q.qm_v));
2436 }
2437 }
2438 out
2439 };
2440 // `census_attempt` hands back only the stream LENGTH; this witness
2441 // needs the BYTES to hand ffmpeg, so the same recipe (its base args
2442 // verbatim, `testsrc2` 128x96 @ 25fps, 3 frames) runs inline.
2443 let encode = |extra: &[&str]| -> Vec<u8> {
2444 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2445 .args([
2446 "-v",
2447 "error",
2448 "-f",
2449 "lavfi",
2450 "-i",
2451 &format!("testsrc2=size={W}x{H}:rate=25"),
2452 "-t",
2453 "0.12",
2454 "-pix_fmt",
2455 "yuv420p",
2456 "-strict",
2457 "-1",
2458 "-f",
2459 "yuv4mpegpipe",
2460 "-",
2461 ])
2462 .stdin(Stdio::null())
2463 .stdout(Stdio::piped())
2464 .stderr(Stdio::piped()), None, |c| c.output())
2465 .expect("ffmpeg failed to run");
2466 assert!(y4m.status.success(), "ffmpeg refused the {W}x{H} fixture");
2467 let mut args: Vec<String> = [
2468 "--codec=av1",
2469 "--passes=1",
2470 "--end-usage=q",
2471 "--threads=1",
2472 "--row-mt=0",
2473 "--kf-max-dist=9999",
2474 "--lag-in-frames=0",
2475 ]
2476 .iter()
2477 .map(|s| (*s).to_owned())
2478 .collect();
2479 args.push(format!("--limit={FRAMES}"));
2480 args.extend(extra.iter().map(|s| (*s).to_owned()));
2481 args.extend([
2482 "--obu".to_owned(),
2483 "-o".to_owned(),
2484 "-".to_owned(),
2485 "-".to_owned(),
2486 ]);
2487 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2488 assert!(
2489 out.status.success(),
2490 "aomenc refused {args:?}: {}",
2491 String::from_utf8_lossy(&out.stderr)
2492 );
2493 out.stdout
2494 };
2495 // Pixel-exact every decoded frame of `stream` against ffmpeg, plane
2496 // by plane, first differing sample named.
2497 let compare = |stream: &[u8], frames: usize, label: &str| {
2498 let want = ffmpeg_decode_sequence(stream, W, H, frames);
2499 let got =
2500 decode_stream(stream).unwrap_or_else(|e| panic!("{NAME}: {label} decode: {e}"));
2501 assert_eq!(got.len(), want.len(), "{NAME}: {label} frame count");
2502 for (i, (g, w)) in got.iter().zip(want.iter()).enumerate() {
2503 for (plane, (gp, wp)) in [(&g.y, &w.y), (&g.u, &w.u), (&g.v, &w.v)]
2504 .into_iter()
2505 .enumerate()
2506 {
2507 assert_eq!(
2508 gp,
2509 wp,
2510 "{NAME}: {label} frame {i} plane {plane} differs from ffmpeg (first mismatching sample: got {}, want {})",
2511 gp.iter()
2512 .zip(wp.iter())
2513 .find(|(a, b)| a != b)
2514 .map_or(0, |(a, _)| *a),
2515 gp.iter()
2516 .zip(wp.iter())
2517 .find(|(a, b)| a != b)
2518 .map_or(0, |(_, b)| *b)
2519 );
2520 }
2521 }
2522 };
2523
2524 // CONTROL: the same source and recipe with quantisation matrices OFF
2525 // -- unchanged by this lane, and it must not scale a single unit
2526 // through a matrix.
2527 crate::quant::reset_qm_scaled_units();
2528 let control_stream = encode(&["--enable-qm=0"]);
2529 let control_frames = decode_stream(&control_stream)
2530 .unwrap_or_else(|e| panic!("{NAME}: the --enable-qm=0 control must decode, got: {e}"))
2531 .len();
2532 assert!(
2533 control_frames >= 1,
2534 "{NAME}: the qm-off control decoded no frame"
2535 );
2536 for (using, y, u, v) in qm_headers(&control_stream) {
2537 assert!(
2538 !using,
2539 "{NAME}: the control's frame header set using_qmatrix"
2540 );
2541 assert_eq!(
2542 (y, u, v),
2543 (0, 0, 0),
2544 "{NAME}: the control's frame header carried qm levels {y}/{u}/{v}"
2545 );
2546 }
2547 compare(&control_stream, control_frames, "qm-off control");
2548 assert_eq!(
2549 crate::quant::qm_scaled_units(),
2550 0,
2551 "{NAME}: the qm-off control scaled units through a matrix"
2552 );
2553
2554 // The qm-on stream: decodes now, pixel-exact, levels 5 per plane as
2555 // aomenc writes them.
2556 crate::quant::reset_qm_scaled_units();
2557 let qm_stream = encode(&["--enable-qm=1"]);
2558 let qm_frames = decode_stream(&qm_stream)
2559 .unwrap_or_else(|e| panic!("{NAME}: the --enable-qm=1 stream must decode, got: {e}"))
2560 .len();
2561 assert!(qm_frames >= 1, "{NAME}: the qm-on stream decoded no frame");
2562 let headers = qm_headers(&qm_stream);
2563 assert!(
2564 !headers.is_empty() && headers.iter().all(|h| h.0),
2565 "{NAME}: not every qm-on frame header set using_qmatrix: {headers:?}"
2566 );
2567 assert!(
2568 headers.iter().all(|h| (h.1, h.2, h.3) == (5, 5, 5)),
2569 "{NAME}: expected aomenc's qm levels 5/5/5, got {headers:?}"
2570 );
2571 compare(&qm_stream, qm_frames, "qm-on");
2572 let scaled = crate::quant::qm_scaled_units();
2573 assert!(
2574 scaled > 0,
2575 "{NAME}: the --enable-qm=1 stream dequantized every unit flat -- \
2576 the matrices were never applied (class gate-blind-to-feature)"
2577 );
2578 eprintln!(
2579 "{NAME}: qm-off control {control_frames} frames exact (0 matrix-scaled units), \
2580 qm-on {qm_frames} frames exact ({scaled} matrix-scaled units, levels 5/5/5)"
2581 );
2582 }
2583
2584 /// lane-av1mono: the INVERSE of the pilot's
2585 /// `a_real_libaom_monochrome_key_frame_is_refused_by_name`, which the
2586 /// pilot's merge `d71084ae` landed on `main` (after this lane's base
2587 /// `7f4e8301`): the very same recipe now decodes, and its luma is
2588 /// byte-exact against ffmpeg's own decode of the same OBU. A merge of this
2589 /// lane into `main` must therefore resolve that pinning gate by adopting
2590 /// this witness in its place.
2591 ///
2592 /// `ffmpeg -pix_fmt gray -c:v libaom-av1` sets `color_config.mono_chrome`,
2593 /// so libaom codes NO chroma symbol anywhere in the sequence -- not the
2594 /// mode syntax, not a coefficient. That reaches all three classes this lane
2595 /// had to close: chroma SYMBOL reads (`uv_mode`/cfl/angle/palette), chroma
2596 /// COEFFICIENT reads on the rect-strip paths that call `read_coeffs_rect`
2597 /// DIRECTLY instead of through `read_plane`'s own plane gate, and the
2598 /// palette-mode neighbour band a mono sub-8x8 leaf must still clear before
2599 /// it returns (an uncleared band made the next block read `palette_y_mode`
2600 /// off the wrong CDF row and silently desynced the rest of the tile --
2601 /// measured at decode-order frame 33 of this very recipe).
2602 ///
2603 /// The 4:2:0 twin of the same source and settings is the control: it proves
2604 /// the recipe is decodable, so a failure here is about the plane count and
2605 /// not about the source or the encoder settings.
2606 #[test]
2607 fn a_real_libaom_monochrome_key_frame_decodes_pixel_exact() {
2608 const NAME: &str = "a_real_libaom_monochrome_key_frame_decodes_pixel_exact";
2609 if !have_ffmpeg() {
2610 eprintln!("SKIP {NAME}: no ffmpeg");
2611 return;
2612 }
2613 let emit = |pix: &str| -> Vec<u8> {
2614 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2615 .args([
2616 "-v",
2617 "error",
2618 "-f",
2619 "lavfi",
2620 "-i",
2621 "testsrc2=size=320x240:rate=30:duration=2",
2622 "-pix_fmt",
2623 pix,
2624 "-c:v",
2625 "libaom-av1",
2626 "-cpu-used",
2627 "8",
2628 "-b:v",
2629 "300k",
2630 "-f",
2631 "obu",
2632 "-",
2633 ])
2634 .stdin(Stdio::null())
2635 .stdout(Stdio::piped())
2636 .stderr(Stdio::piped()), None, |c| c.output())
2637 .expect("ffmpeg failed to run");
2638 assert!(
2639 out.status.success(),
2640 "{NAME}: ffmpeg ({pix}) failed: {}",
2641 String::from_utf8_lossy(&out.stderr)
2642 );
2643 out.stdout
2644 };
2645 // CONTROL: the identical recipe at 4:2:0 still decodes.
2646 let twin = decode_stream(&emit("yuv420p")).expect("the 4:2:0 twin must decode");
2647 assert!(!twin.is_empty(), "{NAME}: the 4:2:0 twin decoded no frames");
2648 // THE WITNESS: the monochrome stream decodes and every luma sample
2649 // equals ffmpeg's own decode of the same OBU.
2650 let gray = emit("gray");
2651 let ours = decode_stream(&gray)
2652 .unwrap_or_else(|e| panic!("{NAME}: the monochrome stream is REFUSED again: {e}"));
2653 let (width, height) = (320usize, 240usize);
2654 const FRAMES: usize = 60;
2655 assert_eq!(ours.len(), FRAMES, "{NAME}: expected {FRAMES} mono frames");
2656 let reference = ffmpeg_decode_gray_sequence(&gray, width, height, FRAMES);
2657 for (i, plane) in reference.chunks_exact(width * height).enumerate() {
2658 assert_eq!(ours[i].width, width, "{NAME}: frame {i} width");
2659 assert_eq!(ours[i].height, height, "{NAME}: frame {i} height");
2660 assert_eq!(
2661 ours[i].y.len(),
2662 width * height,
2663 "{NAME}: frame {i} luma length"
2664 );
2665 for (j, (got, want)) in plane.iter().zip(ours[i].y.iter()).enumerate() {
2666 assert_eq!(
2667 *want,
2668 u16::from(*got),
2669 "{NAME}: frame {i} luma sample {j} (row {}, col {}) is {want}, ffmpeg says {got}",
2670 j / width,
2671 j % width
2672 );
2673 }
2674 }
2675 eprintln!(
2676 "{NAME}: 4:2:0 twin {} frames, monochrome {} frames byte-exact vs ffmpeg",
2677 twin.len(),
2678 ours.len()
2679 );
2680 }
2681
2682 /// lane-t900 r25: the refusal "a frame OBU with no tile group" names a
2683 /// shape the parser cannot hand [`decode_stream`].
2684 ///
2685 /// `tiles` reaches that check from exactly two places -- `ObuKind::Frame`'s
2686 /// own vector and the `ObuKind::TileGroup` accumulation -- and both are
2687 /// filled by `ec_av1_syntax`'s `parse_tile_group`, whose only success path
2688 /// pushes one `Tile` per `tile_num` of the INCLUSIVE range
2689 /// `tg_start..=tg_end`. That range is never empty: the single-tile-group
2690 /// case takes `(0, num_tiles - 1)` saturating at 0, and the multi-group
2691 /// case rejects `end < start` as corrupt. So an `OBU_FRAME` either fails to
2692 /// parse or carries at least one tile, however short its payload is --
2693 /// including the empty payload the charter for this round asked to build,
2694 /// which parses into ONE zero-byte tile rather than none.
2695 ///
2696 /// Sweeping a real frame OBU's tile payload from empty upwards asserts both
2697 /// halves: every `Frame` OBU that parses has a tile, and `decode_stream`
2698 /// never reports this refusal for any of them.
2699 #[test]
2700 fn a_frame_obu_that_parses_always_carries_at_least_one_tile() {
2701 let fctx = &crate::decode::FrameCtx::new();
2702 const REFUSAL: &str = "a frame OBU with no tile group";
2703 let picture = test_card(64, 64);
2704 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2705 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2706 let mut frame_obus_parsed = 0;
2707 for len in 0..=encoded.tile.len().min(24) {
2708 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2709 stream.extend_from_slice(
2710 &crate::frame::frame_obu(&seq, &header, &encoded.tile[..len]).unwrap(),
2711 );
2712 let mut parser = Av1Parser::new();
2713 let mut pos = 0usize;
2714 while pos < stream.len() {
2715 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
2716 break;
2717 };
2718 pos += obu.total_size;
2719 if let ObuKind::Frame(_, tiles) = &obu.kind {
2720 frame_obus_parsed += 1;
2721 assert!(
2722 !tiles.is_empty(),
2723 "a {len}-byte tile payload parsed into a frame OBU with no tile group -- \
2724 the refusal {REFUSAL:?} is reachable after all"
2725 );
2726 }
2727 }
2728 if let Err(e) = decode_stream(&stream) {
2729 let e = e.to_string();
2730 assert!(
2731 !e.contains(REFUSAL),
2732 "a {len}-byte tile payload reached {REFUSAL:?}: {e}"
2733 );
2734 }
2735 }
2736 assert!(
2737 frame_obus_parsed >= 2,
2738 "the sweep parsed {frame_obus_parsed} frame OBUs -- it proves nothing about the \
2739 refusal's reachability"
2740 );
2741 }
2742
2743 /// lane-t900 r27, negative gate: a frame whose segmentation enables one of
2744 /// the three MODE-OVERRIDING features -- `SEG_LVL_REF_FRAME` (forces a
2745 /// block's reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both
2746 /// suppress symbols `decode_inter_block` reads unconditionally) -- is
2747 /// refused BY NAME and outputs no picture, rather than desyncing on the
2748 /// first block that would have obeyed the override.
2749 ///
2750 /// Written, not hand-built: `write_segmentation_params` (spec 5.9.14)
2751 /// codes `feature_enabled`/`feature_data` for every segment, so a real
2752 /// key frame carrying the flag is a two-line change to the header the
2753 /// encoder already produced. Swept over all three features and over the
2754 /// first, a middle and the last segment id.
2755 #[test]
2756 fn a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name() {
2757 let fctx = &crate::decode::FrameCtx::new();
2758 const REFUSAL: &str = "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
2759 let picture = test_card(64, 64);
2760 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2761 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2762 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
2763 for segment in [0usize, 3, 7] {
2764 let mut header = key.clone();
2765 header.segmentation.enabled = true;
2766 header.segmentation.update_map = true;
2767 header.segmentation.update_data = true;
2768 header.segmentation.feature_enabled[segment][feature] = true;
2769 header.segmentation.feature_data[segment][feature] = 1;
2770 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2771 stream.extend_from_slice(
2772 &crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap(),
2773 );
2774 let mut shown = 0;
2775 let err = decode_stream_with(&stream, |_, _, _| {
2776 shown += 1;
2777 Ok(())
2778 })
2779 .unwrap_err()
2780 .to_string();
2781 assert!(
2782 err.contains(REFUSAL),
2783 "feature {feature} segment {segment}: expected {REFUSAL:?}, got: {err}"
2784 );
2785 assert_eq!(
2786 shown, 0,
2787 "feature {feature} segment {segment}: a refused frame produced a picture"
2788 );
2789 }
2790 }
2791 }
2792
2793 /// lane-hdrlossless WITNESS → lane-av1mixloss LIFT. `--end-usage=q
2794 /// --cq-level=0 --aq-mode=1` (variance AQ over a lossless base) gives a
2795 /// high-variance segment a positive `SEG_LVL_ALT_Q` while a flat segment
2796 /// stays at `qindex == 0` (`aq_variance.c` sets `SEG_LVL_ALT_Q` per
2797 /// segment and only clamps when `base_qindex != 0`, so a lossless base is
2798 /// exactly where the mixed case comes from): a frame MIXING lossless and
2799 /// lossy segments, which this decoder refused by name until the
2800 /// per-segment lossless table (libaom `decodeframe.c:5205`,
2801 /// `xd->lossless[segment_id]`; `read_tx_size` returns TX_4X4 before it
2802 /// reads a symbol, `decodeframe.c:1170`) landed. Non-vacuity, three ways:
2803 /// (1) the header census proves the arms REALLY carry a mixed frame
2804 /// (class `gate-blind-to-feature` -- variance AQ over a lossless base is
2805 /// the whole point, not the flag spelling), (2) the WHT-unit counter
2806 /// proves the per-segment lossless reconstruction really ran, and (3)
2807 /// every decoded plane is compared SAMPLE-EXACT against ffmpeg's libaom,
2808 /// which accepts the same stream -- so the old refusal named a capability
2809 /// gap, and this gate now proves the gap closed on a real encoder output.
2810 #[test]
2811 fn a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact() {
2812 const NAME: &str = "a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact";
2813 if !have_ffmpeg() {
2814 eprintln!("SKIP {NAME}: no ffmpeg");
2815 return;
2816 }
2817 if !have_aomenc() {
2818 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2819 return;
2820 }
2821 const FRAMES: usize = 4;
2822 const WIDTH: usize = 256;
2823 const HEIGHT: usize = 192;
2824 // (source, per-arm overrides). `--end-usage=q --cq-level=0` is the
2825 // lossless base; `--aq-mode=1` is variance AQ, the only aomenc path
2826 // that sets `SEG_LVL_ALT_Q` with no clamp at base 0 (`aq_variance.c`).
2827 // Several arms because the segment split depends on the encoder's own
2828 // variance decisions (class knob-never-reached-the-tool: require at
2829 // least one arm to actually mix, and fail if none does).
2830 let arms: [(&str, &[&str]); 3] = [
2831 (
2832 "testsrc2=size=256x192:rate=25",
2833 &[
2834 "--end-usage=q",
2835 "--cq-level=0",
2836 "--aq-mode=1",
2837 "--good",
2838 "--cpu-used=3",
2839 "--sb-size=64",
2840 ],
2841 ),
2842 (
2843 "testsrc2=size=256x192:rate=25",
2844 &[
2845 "--end-usage=q",
2846 "--cq-level=0",
2847 "--aq-mode=1",
2848 "--good",
2849 "--cpu-used=5",
2850 "--sb-size=64",
2851 ],
2852 ),
2853 (
2854 "gradients=size=256x192:rate=25",
2855 &[
2856 "--end-usage=q",
2857 "--cq-level=0",
2858 "--aq-mode=1",
2859 "--good",
2860 "--cpu-used=6",
2861 "--sb-size=64",
2862 ],
2863 ),
2864 ];
2865 let mut mixed_arms = 0usize;
2866 // The WHT-unit delta below is a process-wide counter: serialize the
2867 // arms against the other counter-reading gates.
2868 let _gate_lock = lock_gate_counters();
2869 for (src, extra) in &arms {
2870 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2871 .args([
2872 "-v",
2873 "error",
2874 "-f",
2875 "lavfi",
2876 "-i",
2877 *src,
2878 "-t",
2879 "0.16",
2880 "-pix_fmt",
2881 "yuv420p",
2882 "-strict",
2883 "-1",
2884 "-f",
2885 "yuv4mpegpipe",
2886 "-",
2887 ])
2888 .stdin(Stdio::null())
2889 .stdout(Stdio::piped())
2890 .stderr(Stdio::piped()), None, |c| c.output())
2891 .expect("ffmpeg failed to run");
2892 assert!(y4m.status.success(), "{NAME}: ffmpeg failed for {src}");
2893 let limit = format!("--limit={FRAMES}");
2894 let mut args: Vec<String> = [
2895 "--codec=av1",
2896 "--passes=1",
2897 "--threads=1",
2898 "--obu",
2899 "-o",
2900 "-",
2901 "-",
2902 ]
2903 .iter()
2904 .map(|s| (*s).to_owned())
2905 .collect();
2906 args.insert(1, limit);
2907 args.extend(extra.iter().map(|s| (*s).to_owned()));
2908 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2909 assert!(
2910 out.status.success(),
2911 "{NAME}: aomenc refused {args:?}: {}",
2912 String::from_utf8_lossy(&out.stderr)
2913 );
2914 let stream = out.stdout;
2915 // (2) the stream really carries a frame the old refusal named.
2916 let mut parser = Av1Parser::new();
2917 let (mut pos, mut mixed) = (0usize, 0usize);
2918 while pos < stream.len() {
2919 let obu = parser.parse_obu(&stream[pos..]).expect("aomenc OBU parses");
2920 pos += obu.total_size.max(1);
2921 let header = match &obu.kind {
2922 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
2923 _ => continue,
2924 };
2925 if header.lossless.iter().any(|&l| l) && !header.lossless.iter().all(|&l| l) {
2926 mixed += 1;
2927 }
2928 }
2929 if mixed == 0 {
2930 eprintln!("{NAME}: arm {extra:?} coded no mixed frame -- trying the next");
2931 continue;
2932 }
2933 // (3) ours DECODES it, sample-exact against ffmpeg's libaom (the
2934 // reference decode doubles as the libaom-accepts proof). The
2935 // WHT-unit delta proves the per-segment lossless reconstruction
2936 // really ran inside a frame that is NOT `CodedLossless`.
2937 let before = crate::decode::lossless_wht_units();
2938 let ours = decode_stream(&stream).unwrap_or_else(|e| {
2939 panic!("{NAME}: a mixed-lossless frame decodes after the per-segment lift: {e}")
2940 });
2941 let wht_units = crate::decode::lossless_wht_units() - before;
2942 let refs = ffmpeg_decode_sequence(&stream, WIDTH, HEIGHT, FRAMES);
2943 assert_eq!(ours.len(), FRAMES, "{NAME}: frame count");
2944 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
2945 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
2946 .iter()
2947 .enumerate()
2948 {
2949 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
2950 assert_eq!(
2951 bad, 0,
2952 "{NAME}: arm {extra:?} frame {i} plane {plane}: {bad} samples differ"
2953 );
2954 assert_eq!(
2955 g.len(),
2956 r.len(),
2957 "{NAME}: arm {extra:?} frame {i} plane {plane}: ours has {} samples, \
2958 ffmpeg's has {} -- a short plane would zip-truncate the compare above \
2959 and hide a chroma-span defect",
2960 g.len(),
2961 r.len()
2962 );
2963 }
2964 }
2965 assert!(
2966 wht_units > 0,
2967 "{NAME}: arm {extra:?} reconstructed no Walsh-Hadamard unit -- the mixed census is lying or the lossless path never ran"
2968 );
2969 mixed_arms += 1;
2970 eprintln!(
2971 "{NAME}: arm {extra:?}: {mixed} mixed frame(s), {FRAMES} frames sample-exact vs ffmpeg, {wht_units} WHT units"
2972 );
2973 }
2974 assert!(
2975 mixed_arms > 0,
2976 "{NAME}: no arm produced a mixed lossless/lossy frame -- the witness is vacuous \
2977 (re-measure the aomenc recipe)"
2978 );
2979 }
2980
2981 /// lane-t900 r27 CENSUS behind the negative gate above: does a real
2982 /// aomenc ever ENABLE one of the three mode-overriding segmentation
2983 /// features? Measured over the recipes that turn segmentation on --
2984 /// `--aq-mode=1/2/3` (variance, complexity and cyclic-refresh AQ) and
2985 /// `--deltaq-mode=1` -- with the refusal as the instrument: if one of
2986 /// those features appeared, the decode would stop by name.
2987 ///
2988 /// lane-av1seglvl re-scope: r27's arms were all `--passes=1
2989 /// --lag-in-frames=0`, so they never coded an alt-ref frame or ran an
2990 /// encoder second pass -- the only shapes where libaom's OTHER seg
2991 /// feature setup (`configure_static_seg_features`) could ever run. The
2992 /// re-scoped half below adds alt-ref-group arms and a real two-pass arm,
2993 /// and upgrades the instrument from the refusal (blind to a pure-ALT_LF
2994 /// stream) to a direct parse of every frame header's `feature_enabled`
2995 /// table: over all of it, aomenc enables `SEG_LVL_ALT_Q` and nothing
2996 /// else.
2997 #[test]
2998 fn a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature() {
2999 if !have_aomenc() {
3000 eprintln!("SKIP a_segmentation_census_over_real_aq_streams: no aomenc");
3001 return;
3002 }
3003 const REFUSAL: &str = "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
3004 let recipes: [(&str, Vec<&str>); 6] = [
3005 ("baseline", vec!["--cpu-used=4", "--cq-level=40"]),
3006 (
3007 "aq-mode=1",
3008 vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=40"],
3009 ),
3010 (
3011 "aq-mode=2",
3012 vec!["--cpu-used=4", "--aq-mode=2", "--cq-level=40"],
3013 ),
3014 (
3015 "aq-mode=3",
3016 vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=40"],
3017 ),
3018 (
3019 "aq-mode=3 cq10",
3020 vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=10"],
3021 ),
3022 (
3023 "deltaq-mode=1",
3024 vec!["--cpu-used=4", "--deltaq-mode=1", "--cq-level=40"],
3025 ),
3026 ];
3027 // Arrival, not intent (class knob-never-reached-the-tool): a recipe
3028 // whose stream is byte-for-byte the baseline's changed nothing, and a
3029 // census over such arms would be vacuous. Measured r27: only
3030 // `--aq-mode=3` (cyclic refresh) does -- aq-mode 1/2 and deltaq-mode=1
3031 // all reproduce the baseline's 7147 B at this recipe.
3032 let mut baseline_bytes = 0usize;
3033 let mut segment_symbols = 0usize;
3034 let mut refused = 0usize;
3035 let mut decoded = 0usize;
3036 for (name, extra) in &recipes {
3037 let before = crate::decode::segment_id_hits();
3038 let (bytes, result) = census_attempt("mandelbrot", 192, 128, 8, extra);
3039 match result {
3040 Ok(pictures) => {
3041 decoded += 1;
3042 let symbols = crate::decode::segment_id_hits() - before;
3043 segment_symbols += symbols;
3044 if *name == "baseline" {
3045 baseline_bytes = bytes;
3046 }
3047 eprintln!(
3048 "SEGCENSUS {name}: {bytes} B{}, {pictures} pictures, segment_id symbols {symbols}",
3049 if bytes == baseline_bytes && *name != "baseline" {
3050 " (== baseline: the flag changed nothing)"
3051 } else {
3052 ""
3053 }
3054 );
3055 }
3056 Err(e) => {
3057 eprintln!("SEGCENSUS {name}: {bytes} B, refused: {e}");
3058 assert!(
3059 !e.contains(REFUSAL),
3060 "{name}: a real aomenc stream DOES enable a mode-overriding \
3061 segmentation feature -- the refusal is a capability gap, not a \
3062 claim about the encoder: {e}"
3063 );
3064 refused += 1;
3065 }
3066 }
3067 }
3068 eprintln!(
3069 "SEGCENSUS: {} recipes, {decoded} decoded, {refused} refused for other reasons",
3070 recipes.len()
3071 );
3072 assert_eq!(
3073 decoded,
3074 recipes.len(),
3075 "every recipe must decode; {refused} refused"
3076 );
3077 assert!(
3078 segment_symbols > 0,
3079 "no recipe coded a single segment_id symbol -- segmentation never arrived, so \
3080 this census measures nothing about the three mode-overriding features"
3081 );
3082
3083 // lane-av1seglvl re-scope: the r27 arms above are all `--passes=1
3084 // --lag-in-frames=0`, which never codes an alt-ref frame -- the one
3085 // frame type whose segmentation libaom sets up differently
3086 // (`configure_static_seg_features`, encoder_utils.c:738, is further
3087 // gated on the second pass AND on `hl_sf.static_segmentation`, which
3088 // speed_features.h itself documents as "Always set to 0"). The arms
3089 // below cover that whole remaining surface: alt-ref groups under
3090 // `--aq-mode`, a high-cq arm (the branch's own `high_q` gate is
3091 // `avg_q > 48`), and a genuine two-pass encode. The instrument is no
3092 // longer the refusal -- the refusal only fires on
3093 // REF_FRAME/SKIP/GLOBALMV, so an ALT_LF-only stream would decode
3094 // silently past it -- but a direct parse of every frame header's
3095 // `feature_enabled` table.
3096 let lag_recipes: [(&str, &str, usize, usize, Vec<&str>); 3] = [
3097 (
3098 "aq-mode=1 lag16 mandelbrot",
3099 "mandelbrot",
3100 192,
3101 128,
3102 vec![
3103 "--cpu-used=4",
3104 "--aq-mode=1",
3105 "--cq-level=45",
3106 "--lag-in-frames=16",
3107 "--auto-alt-ref=1",
3108 ],
3109 ),
3110 (
3111 "aq-mode=1 lag16 screen",
3112 "testsrc2",
3113 256,
3114 192,
3115 vec![
3116 "--cpu-used=4",
3117 "--aq-mode=1",
3118 "--cq-level=45",
3119 "--lag-in-frames=16",
3120 "--auto-alt-ref=1",
3121 ],
3122 ),
3123 (
3124 "aq-mode=1 lag16 cq63 high_q",
3125 "mandelbrot",
3126 192,
3127 128,
3128 vec![
3129 "--cpu-used=4",
3130 "--aq-mode=1",
3131 "--cq-level=63",
3132 "--lag-in-frames=16",
3133 "--auto-alt-ref=1",
3134 ],
3135 ),
3136 // `--aq-mode=2 lag16` (complexity AQ over an alt-ref group) was
3137 // measured 2026-09-24: it encodes and decodes cleanly but codes
3138 // ZERO segmentation-enabled frames -- complexity AQ never reaches
3139 // the seg table at this recipe -- so as a census arm it measures
3140 // nothing (class gate-blind-to-feature) and was dropped; the
3141 // 1-pass `aq-mode=2` r27 arm above stays.
3142 ];
3143 let mut total_enabled = 0usize;
3144 let mut total_inherited = 0usize;
3145 let mut total_alt_q = 0usize;
3146 let mut feature_frames = [0usize; SEG_LVL_MAX];
3147 for (name, source, w, h, extra) in &lag_recipes {
3148 let stream = encode_aomenc_stream(source, *w, *h, 40, extra);
3149 let (enabled, umap, inherited, alt_q, frames_per_feature) =
3150 segmentation_feature_census(&stream);
3151 eprintln!(
3152 "SEGCENSUS {name}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}"
3153 );
3154 total_enabled += enabled;
3155 total_inherited += inherited;
3156 total_alt_q += alt_q;
3157 for (f, n) in frames_per_feature.iter().enumerate() {
3158 feature_frames[f] += n;
3159 }
3160 }
3161 // The two-pass arm: `configure_static_seg_features` runs ONLY at
3162 // `is_stat_consumption_stage_twopass`, so this is the arm that would
3163 // catch its ALT_LF/REF_FRAME/SKIP tables if the dead speed feature
3164 // were ever revived.
3165 {
3166 let stream = encode_aomenc_stream_twopass(
3167 "mandelbrot",
3168 192,
3169 128,
3170 40,
3171 &[
3172 "--cpu-used=4",
3173 "--aq-mode=1",
3174 "--cq-level=45",
3175 "--lag-in-frames=16",
3176 "--auto-alt-ref=1",
3177 ],
3178 );
3179 let (enabled, umap, inherited, alt_q, frames_per_feature) =
3180 segmentation_feature_census(&stream);
3181 eprintln!(
3182 "SEGCENSUS twopass aq-mode=1 lag16: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}"
3183 );
3184 total_enabled += enabled;
3185 total_inherited += inherited;
3186 total_alt_q += alt_q;
3187 for (f, n) in frames_per_feature.iter().enumerate() {
3188 feature_frames[f] += n;
3189 }
3190 }
3191 // Premise (class gate-blind-to-feature): the arms must actually reach
3192 // the shapes the census speaks about -- segmentation-carrying frames,
3193 // frames whose map is INHERITED (update_map == 0), and frames with a
3194 // real ALT_Q table -- or the "only ALT_Q" verdict below measures
3195 // nothing.
3196 assert!(
3197 total_enabled > 0 && total_alt_q > 0,
3198 "no lag/two-pass arm carried a segmentation-enabled frame -- the census premise \
3199 never arrived"
3200 );
3201 assert!(
3202 total_inherited > 0,
3203 "no arm carried an update_map == 0 frame -- the map-inheritance path the decoder \
3204 reads segment ids through is unmeasured"
3205 );
3206 // The census verdict, over every frame of every arm: segmentation on
3207 // aomenc's CLI carries SEG_LVL_ALT_Q and NOTHING else. The three
3208 // mode-overriding features and the four ALT_LF deltas have no encoder
3209 // path: `configure_static_seg_features` (the only setter of ALT_LF/
3210 // REF_FRAME/SKIP in the tree) is gated on `hl_sf.static_segmentation`,
3211 // documented "Always set to 0" (speed_features.h), and ROI/active-map
3212 // are control-API only (aomenc.c has no flag for either).
3213 for (feature, frames) in feature_frames.iter().enumerate() {
3214 if feature == SEG_LVL_ALT_Q {
3215 continue;
3216 }
3217 assert_eq!(
3218 *frames, 0,
3219 "feature index {feature} appeared on {frames} frames of real aomenc output -- \
3220 the refusal's encoder-never-writes claim is FALSE and the mode path needs \
3221 porting before this census can stay green"
3222 );
3223 }
3224 eprintln!(
3225 "SEGCENSUS lag/twopass: {total_enabled} seg-enabled frames over 4 arms, {total_inherited} inherited-map frames, {total_alt_q} with ALT_Q, all other SEG_LVL features: 0 frames"
3226 );
3227 }
3228
3229 /// lane-av1seglvl WITNESS: the reaching stream. `--aq-mode=1` turns
3230 /// segmentation on for every frame; `--lag-in-frames=16 --auto-alt-ref=1`
3231 /// adds real alt-ref groups, so the stream mixes map-CODING frames
3232 /// (`update_map == 1`: the key frame and each group's arf) with dozens of
3233 /// map-INHERITING frames (`update_map == 0`), and an inheriting block's
3234 /// id is the MIN of the previous map over its own footprint while the
3235 /// saved map itself inherits that footprint VERBATIM
3236 /// (`copy_segment_id`, decodemv.c:342) -- heterogeneous footprints are
3237 /// exactly what a 1:4-split arf leaves behind. Stamping the minified id
3238 /// (the pre-lane defect) flattened those footprints and mis-dequantized
3239 /// scattered blocks frames later: 2 luma bytes of mandelbrot frame 35
3240 /// differed from the oracle, everything else exact.
3241 ///
3242 /// Both arms decode EVERY frame in decode order -- hidden arfs included
3243 /// -- byte-exact against the instrumented oracle, and every SHOWN frame
3244 /// pixel-exact against ffmpeg; the census counters prove the premise
3245 /// (segmentation symbols read, a wider-than-zero quantizer span from
3246 /// `SEG_LVL_ALT_Q`, and an inheritance-heavy shape).
3247 #[test]
3248 fn a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact() {
3249 const NAME: &str =
3250 "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact";
3251 // lane-av1cmpaudit2: this gate reaches the oracle without the gate
3252 // mutex, so a sibling flipping `EC_AV1_AOMDEC` (the one-byte-wrong
3253 // oracle control) could hand it a tampered oracle mid-compare.
3254 let _gate_lock = lock_gate_counters();
3255 if !have_aomenc() {
3256 eprintln!("SKIP {NAME}: no aomenc");
3257 return;
3258 }
3259 if !have_ffmpeg() {
3260 eprintln!("SKIP {NAME}: no ffmpeg");
3261 return;
3262 }
3263 let extra = [
3264 "--cpu-used=4",
3265 "--aq-mode=1",
3266 "--cq-level=45",
3267 "--lag-in-frames=16",
3268 "--auto-alt-ref=1",
3269 ];
3270 let arms: [(&str, &str, usize, usize); 2] = [
3271 ("screen testsrc2", "testsrc2", 256, 192),
3272 ("film mandelbrot", "mandelbrot", 192, 128),
3273 ];
3274 for (arm, source, width, height) in &arms {
3275 // r7: the ENCODE's frame count, bound so the compare below asserts a
3276 // spec rather than our own decode's length.
3277 const ENCODED_FRAMES: usize = 40;
3278 let stream = encode_aomenc_stream(source, *width, *height, ENCODED_FRAMES, &extra);
3279 // Premise: the shape under test really arrived -- segmentation on
3280 // every frame, the map both coded and inherited, and real ALT_Q
3281 // tables. An aomenc drift that dropped any of these would make
3282 // the decode below prove nothing (class gate-blind-to-feature).
3283 let (enabled, umap, inherited, alt_q, _) = segmentation_feature_census(&stream);
3284 eprintln!(
3285 "{NAME} {arm}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q-carrying {alt_q}"
3286 );
3287 assert!(
3288 enabled > 0 && umap > 0,
3289 "{arm}: no segmentation-carrying/map-coding frame -- the premise is gone"
3290 );
3291 assert!(
3292 inherited > 0,
3293 "{arm}: no update_map == 0 frame -- the map-inheritance path under test never runs"
3294 );
3295 assert!(
3296 alt_q > 0,
3297 "{arm}: no frame carries a SEG_LVL_ALT_Q table -- the feature under test never fires"
3298 );
3299 // Every frame in decode order -- hidden arfs included (each one
3300 // re-surfaces via show-existing in this recipe, so `hidden == 0`
3301 // is possible while `frames` still covers the whole coded set) --
3302 // byte-exact against the oracle.
3303 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, arm);
3304 assert!(frames > 0, "{arm}: decoded nothing");
3305 assert_eq!(
3306 frames, enabled,
3307 "{arm}: decode-order frame count != segmentation-enabled frame count -- the \
3308 parse and the decode disagree about the stream"
3309 );
3310 let _ = hidden;
3311 // And every shown frame pixel-exact against ffmpeg.
3312 crate::decode::reset_segment_hits();
3313 let pictures = decode_stream(&stream)
3314 .unwrap_or_else(|e| panic!("{NAME} {arm}: decode refused: {e}"));
3315 assert!(
3316 crate::decode::segment_id_hits() > 0,
3317 "{arm}: zero segment_id symbols read -- the decode proved nothing about \
3318 segmentation"
3319 );
3320 let (lo, hi) = crate::decode::block_q_span();
3321 assert!(
3322 hi > lo,
3323 "{arm}: every block dequantized at the same qindex ({lo}) -- SEG_LVL_ALT_Q \
3324 never changed any block's quantizer"
3325 );
3326 // `ENCODED_FRAMES`, not `pictures.len()`: our decode's length is the
3327 // thing UNDER TEST, so using it as the oracle's expected count is
3328 // circular -- a decode that dropped a frame would ask ffmpeg for the
3329 // same short count and the compare would silently shrink.
3330 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, *width, *height, ENCODED_FRAMES);
3331 for (i, (ours, theirs)) in pictures.iter().zip(&ffmpeg_frames).enumerate() {
3332 assert_eq!(ours.y, theirs.y, "{NAME} {arm}: frame {i} luma vs ffmpeg");
3333 assert_eq!(ours.u, theirs.u, "{NAME} {arm}: frame {i} U vs ffmpeg");
3334 assert_eq!(ours.v, theirs.v, "{NAME} {arm}: frame {i} V vs ffmpeg");
3335 }
3336 eprintln!(
3337 "{NAME} {arm}: {frames} frames decode-order exact vs oracle ({hidden} hidden), {} shown frames exact vs ffmpeg, q span {lo}..{hi}, segment_id symbols {}",
3338 pictures.len(),
3339 crate::decode::segment_id_hits()
3340 );
3341 }
3342 }
3343
3344 /// lane-t900 r27, WITNESS half of the proof for "an OBMC neighbour whose
3345 /// switchable interp filter was never recorded" (the structural half is
3346 /// `decode::tests::every_inter_record_publishes_an_obmc_readable_filter`,
3347 /// which shows no INTER cell is ever stamped with the `[3, 3]`
3348 /// sentinel): real OBMC streams whose frames use a SWITCHABLE (and dual)
3349 /// interp filter decode with the refusal firing 0 times while OBMC blends
3350 /// really read the neighbour band -- a decode that never read one would
3351 /// pass just as well and prove nothing (class gate-blind-to-feature).
3352 #[test]
3353 fn a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour() {
3354 if !have_aomenc() {
3355 eprintln!("SKIP a_real_obmc_stream_reads_a_recorded_switchable_filter: no aomenc");
3356 return;
3357 }
3358 // `--cpu-used=0` is load-bearing: at speed 4 aomenc settles on a
3359 // FRAME-level fixed interp filter, every neighbour then legitimately
3360 // carries the sentinel, and the band is never read at all (measured
3361 // r27: 0 reads over two speed-4 streams).
3362 let base = vec![
3363 "--cpu-used=0",
3364 "--enable-obmc=1",
3365 "--enable-dual-filter=1",
3366 "--min-partition-size=8",
3367 "--max-partition-size=16",
3368 "--enable-palette=0",
3369 "--enable-intrabc=0",
3370 ];
3371 let recipes: [(&str, usize, usize, Vec<&str>); 2] = [
3372 (
3373 "obmc dual cq40",
3374 192,
3375 128,
3376 [vec!["--cq-level=40"], base.clone()].concat(),
3377 ),
3378 (
3379 "obmc dual cq20",
3380 192,
3381 128,
3382 [vec!["--cq-level=20"], base.clone()].concat(),
3383 ),
3384 ];
3385 let mut reads = 0usize;
3386 let mut decoded = 0usize;
3387 for (name, w, h, extra) in &recipes {
3388 let before = crate::decode::obmc_filter_band_reads();
3389 let obmc_before = crate::decode::obmc_hits();
3390 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 8, extra);
3391 match result {
3392 Ok(pictures) => {
3393 decoded += 1;
3394 let got = crate::decode::obmc_filter_band_reads() - before;
3395 reads += got;
3396 eprintln!(
3397 "OBMCFILT {name}: {bytes} B, {pictures} pictures, {got} band reads, \
3398 {} OBMC blocks",
3399 crate::decode::obmc_hits() - obmc_before
3400 );
3401 }
3402 Err(e) => {
3403 assert!(
3404 !e.contains(
3405 "an OBMC neighbour whose switchable interp filter was never recorded"
3406 ),
3407 "{name}: a real OBMC stream reached the unrecorded-filter refusal -- \
3408 a publication site is missing: {e}"
3409 );
3410 eprintln!("OBMCFILT {name}: {bytes} B, refused for another reason: {e}");
3411 }
3412 }
3413 }
3414 assert!(
3415 decoded > 0,
3416 "no OBMC recipe decoded -- the witness is vacuous"
3417 );
3418 assert!(
3419 reads > 0,
3420 "every OBMC blend took the fixed-filter path: the band was never read, so this \
3421 proves nothing about the refusal"
3422 );
3423 }
3424
3425 /// lane-t900 r27 CENSUS for the three SUPERRES refusals -- "warp
3426 /// prediction with a scaled reference", "a sub-8x8 inter block under a
3427 /// scaled reference" and "an 8x8 partition leaf under a scaled reference".
3428 /// Six real `--superres-mode` encodes (fixed denominators and the auto
3429 /// mode, warped motion and OBMC on), decoded by this decoder: the table it
3430 /// prints is which of the three a real encoder actually reaches.
3431 ///
3432 /// Every one of them is a REAL capability gap (unlike the enumerated
3433 /// refusals elsewhere in the inventory), so this gate asserts the measured
3434 /// shape rather than "no refusal": at least one recipe must decode (else
3435 /// the census says nothing), and any refusal must be one of the three
3436 /// named superres ones -- a fourth string would be a new gap this round
3437 /// did not measure.
3438 #[test]
3439 fn a_superres_census_over_six_real_streams_records_which_scaled_refusals_fire() {
3440 if !have_aomenc() {
3441 eprintln!("SKIP a_superres_census_over_six_real_streams: no aomenc");
3442 return;
3443 }
3444 const WARP: &str = "warp prediction with a scaled reference";
3445 const SUB8: &str = "a sub-8x8 inter block under a scaled reference";
3446 const LEAF8: &str = "an 8x8 partition leaf under a scaled reference";
3447 let common = [
3448 "--enable-warped-motion=1",
3449 "--enable-obmc=1",
3450 "--enable-palette=0",
3451 "--enable-intrabc=0",
3452 ];
3453 let recipes: [(&str, usize, usize, Vec<&str>); 6] = [
3454 (
3455 "denom12 320x180 cq32",
3456 320,
3457 180,
3458 vec![
3459 "--cpu-used=4",
3460 "--superres-mode=1",
3461 "--superres-denominator=12",
3462 "--cq-level=32",
3463 ],
3464 ),
3465 (
3466 "denom12 320x180 cq50",
3467 320,
3468 180,
3469 vec![
3470 "--cpu-used=4",
3471 "--superres-mode=1",
3472 "--superres-denominator=12",
3473 "--cq-level=50",
3474 ],
3475 ),
3476 (
3477 "denom16 320x180 cq32",
3478 320,
3479 180,
3480 vec![
3481 "--cpu-used=4",
3482 "--superres-mode=1",
3483 "--superres-denominator=16",
3484 "--cq-level=32",
3485 ],
3486 ),
3487 (
3488 "denom10 192x128 cq32",
3489 192,
3490 128,
3491 vec![
3492 "--cpu-used=4",
3493 "--superres-mode=1",
3494 "--superres-denominator=10",
3495 "--cq-level=32",
3496 ],
3497 ),
3498 (
3499 "auto 320x180 cq50",
3500 320,
3501 180,
3502 vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"],
3503 ),
3504 (
3505 "auto 192x128 cq50",
3506 192,
3507 128,
3508 vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"],
3509 ),
3510 ];
3511 let (mut decoded, mut warp, mut sub8, mut leaf8) = (0, 0, 0, 0);
3512 // lane-t900 r36 (class [[gate-blind-to-feature]]): unknown refusal
3513 // strings used to `other += 1` and panic on the spot, so the census
3514 // summary below -- the whole point of the gate -- never printed when
3515 // one fired. They are collected instead, reported in the summary, and
3516 // asserted after it.
3517 let mut other: Vec<String> = Vec::new();
3518 for (name, w, h, extra) in &recipes {
3519 let mut args = extra.clone();
3520 args.extend_from_slice(&common);
3521 let before = crate::mc::predict_scaled_hits();
3522 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 10, &args);
3523 match result {
3524 Ok(pictures) => {
3525 decoded += 1;
3526 eprintln!(
3527 "SUPERRES {name}: {bytes} B, {pictures} pictures, scaled MC blocks {}",
3528 crate::mc::predict_scaled_hits() - before
3529 );
3530 }
3531 Err(e) => {
3532 eprintln!("SUPERRES {name}: {bytes} B, refused: {e}");
3533 if e.contains(WARP) {
3534 warp += 1;
3535 } else if e.contains(SUB8) {
3536 sub8 += 1;
3537 } else if e.contains(LEAF8) {
3538 leaf8 += 1;
3539 } else {
3540 other.push(format!("{name}: {e}"));
3541 }
3542 }
3543 }
3544 }
3545 eprintln!(
3546 "SUPERRES CENSUS: 6 streams, {decoded} decoded, warp {warp}x, sub8 {sub8}x, leaf8 {leaf8}x, other {}x",
3547 other.len()
3548 );
3549 assert!(
3550 other.is_empty(),
3551 "{} superres stream(s) stopped on a string this census does not know: {other:?}",
3552 other.len()
3553 );
3554 // Measured r27: the four FIXED-denominator recipes all stop at the
3555 // 8x8-leaf refusal, and the two `--superres-mode=3` (auto) streams
3556 // decode with ZERO scaled MC blocks -- auto picked denominator 8, so
3557 // those two arms carry no scaling at all and prove nothing. The warp
3558 // and sub-8x8 refusals never fire because the 8x8-leaf one sits in
3559 // front of them: whichever partition path a scaled frame takes, the
3560 // leaf guard is reached first. Lifting the leaf gap is what makes the
3561 // other two measurable, so this gate pins the ORDER, not just a count.
3562 assert!(
3563 decoded > 0,
3564 "no superres recipe decoded -- the census is vacuous"
3565 );
3566 // lane-t900 r28: all three scaled refusals are LIFTED, so the census
3567 // now pins the opposite shape -- every fixed-denominator recipe must
3568 // DECODE, and none of the three strings may come back.
3569 assert_eq!(
3570 (warp, sub8, leaf8),
3571 (0, 0, 0),
3572 "a scaled-reference refusal came back (warp {warp}, sub8 {sub8}, leaf8 {leaf8})"
3573 );
3574 assert!(
3575 decoded > 0,
3576 "no superres recipe decoded -- the census is vacuous"
3577 );
3578 }
3579
3580 /// lane-t900 r25, negative gate: a `show_existing_frame` header naming a
3581 /// slot no frame has refreshed is refused BY NAME, and outputs no picture.
3582 ///
3583 /// The OBU is hand-built because [`crate::frame::write_frame_header`]
3584 /// refuses to write one (it writes shown key and inter frames only): spec
3585 /// 5.9.2's whole header for this case is `show_existing_frame` (1) plus
3586 /// `frame_to_show_map_idx` (3), the sequence carrying neither a decoder
3587 /// model nor frame ids.
3588 ///
3589 /// Deviation from the round's charter, which asked for a key frame first
3590 /// with the named slot's `refresh_frame_flags` bit clear: a SHOWN key frame
3591 /// refreshes every slot (spec 5.9.2 forces `refresh_frame_flags` to
3592 /// `all_frames` and does not code it, which is also what
3593 /// `write_frame_header` does), so the only reachable empty-slot stream is
3594 /// one where no frame has refreshed that slot yet. The stream below is a
3595 /// valid sequence header followed by the header OBU, and every one of the
3596 /// eight slots is tried.
3597 #[test]
3598 fn a_show_existing_frame_header_naming_an_empty_slot_is_refused_by_name() {
3599 const REFUSAL: &str = "a show_existing_frame header naming an empty reference slot";
3600 let (seq, _) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
3601 for slot in 0..NUM_REF_FRAMES as u32 {
3602 let mut w = ec_core::BitWriter::new();
3603 w.write_bit(true); // show_existing_frame
3604 w.write_bits(slot, 3); // frame_to_show_map_idx
3605 crate::bits::write_byte_alignment(&mut w);
3606 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
3607 stream.extend_from_slice(&crate::obu::wrap_obu(
3608 &ec_av1_syntax::obu::ObuHeader {
3609 obu_type: ec_av1_syntax::obu::ObuType::FrameHeader,
3610 extension_flag: false,
3611 has_size_field: true,
3612 temporal_id: 0,
3613 spatial_id: 0,
3614 },
3615 &w.into_bytes(),
3616 ));
3617
3618 let mut shown = 0;
3619 let err = decode_stream_with(&stream, |_, _, _| {
3620 shown += 1;
3621 Ok(())
3622 })
3623 .unwrap_err()
3624 .to_string();
3625 assert!(
3626 err.contains(REFUSAL),
3627 "slot {slot}: expected {REFUSAL:?}, got: {err}"
3628 );
3629 assert_eq!(
3630 shown, 0,
3631 "slot {slot}: an empty slot was output as a picture"
3632 );
3633 }
3634 }
3635
3636 /// lane-t900 r25, negative gate: an inter frame whose `ref_frame_idx[0]`
3637 /// slot holds no picture -- a stream that opens on an inter frame -- is
3638 /// refused BY NAME rather than predicting from nothing.
3639 ///
3640 /// Deviation from the round's charter, which asked for a real aomenc
3641 /// two-frame stream with the key frame's OBUs stripped: this crate's own
3642 /// `write_frame_header` writes a shown INTER frame (short reference
3643 /// signalling and non-identity global motion are the parts it refuses), so
3644 /// the fixture is built from the writers, needs neither ffmpeg nor aomenc,
3645 /// and is byte-identical on every run. The tile payload is a real key
3646 /// frame's; the refusal fires on the header's reference lookup, before any
3647 /// tile is decoded.
3648 #[test]
3649 fn an_inter_frame_opening_a_stream_is_refused_by_name() {
3650 let fctx = &crate::decode::FrameCtx::new();
3651 const REFUSAL: &str = "an inter frame with no key frame before it";
3652 let picture = test_card(64, 64);
3653 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3654 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
3655 let inter = FrameHeader {
3656 frame_type: FrameType::Inter,
3657 frame_is_intra: false,
3658 // Keeps `primary_ref_frame`, `frame_size_with_refs` and
3659 // `use_ref_frame_mvs` out of the written header (spec 5.9.2).
3660 error_resilient_mode: true,
3661 primary_ref_frame: PRIMARY_REF_NONE,
3662 refresh_frame_flags: 0x02,
3663 order_hint: 1,
3664 ..key
3665 };
3666 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
3667 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
3668
3669 let mut shown = 0;
3670 let err = decode_stream_with(&stream, |_, _, _| {
3671 shown += 1;
3672 Ok(())
3673 })
3674 .unwrap_err()
3675 .to_string();
3676 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
3677 assert_eq!(
3678 shown, 0,
3679 "an inter frame with no reference produced a picture"
3680 );
3681 }
3682
3683 /// lane-t900 r26, negative gate: an inter frame whose own coded size is
3684 /// SHORTER than the reference it predicts from is refused BY NAME, and
3685 /// outputs no picture beyond the key frame that preceded it.
3686 ///
3687 /// The height mismatch is the one size difference this decoder cannot
3688 /// absorb: `mc::predict_scaled` scales horizontally (a `use_superres`
3689 /// reference), and nothing on this path scales vertically. The fixture is
3690 /// written, not hand-built: a shown key frame at 64x64 (which refreshes
3691 /// every slot), then a shown inter frame carrying
3692 /// `frame_size_override_flag` with `error_resilient_mode` set -- the one
3693 /// combination [`crate::frame::write_frame_header`] writes, since
3694 /// `frame_size_with_refs` (spec 5.9.7) is only read when error resilience
3695 /// is OFF. The inter frame's tile payload is the key frame's; the refusal
3696 /// fires on the reference's dimensions before a tile symbol is read. A 31
3697 /// row frame against a 64 row reference is past the 2x down limit.
3698 #[test]
3699 fn an_inter_frame_shorter_than_its_reference_is_refused_by_name() {
3700 let fctx = &crate::decode::FrameCtx::new();
3701 const REFUSAL: &str =
3702 "a reference picture outside the 2x down / 16x up scaling limits";
3703 let picture = test_card(64, 64);
3704 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3705 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
3706 let inter = FrameHeader {
3707 frame_type: FrameType::Inter,
3708 frame_is_intra: false,
3709 error_resilient_mode: true,
3710 primary_ref_frame: PRIMARY_REF_NONE,
3711 refresh_frame_flags: 0x02,
3712 order_hint: 1,
3713 frame_size_override_flag: true,
3714 frame_height: 31,
3715 render_height: 31,
3716 ..key.clone()
3717 };
3718 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
3719 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &key, &encoded.tile).unwrap());
3720 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
3721
3722 let mut shown = 0;
3723 let err = decode_stream_with(&stream, |_, _, _| {
3724 shown += 1;
3725 Ok(())
3726 })
3727 .unwrap_err()
3728 .to_string();
3729 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
3730 assert_eq!(
3731 shown, 1,
3732 "expected the key frame alone, got {shown} pictures"
3733 );
3734 }
3735
3736 /// lane-t900 r26, negative gate: an inter frame naming a
3737 /// `primary_ref_frame` whose reference slot has never been refreshed is
3738 /// refused BY NAME rather than decoded from the spec 8.4 default tables.
3739 ///
3740 /// Enumeration first, because the refusal's premise is an invariant: the
3741 /// picture slots and the CDF slots are written by exactly two loops in
3742 /// [`decode_stream`] (the `show_existing_frame` arm's copy and the
3743 /// end-of-frame store), and both walk the SAME `refresh_frame_flags` mask
3744 /// writing `ref_slots[i]` and `cdf_slots[i]` together -- so no slot can
3745 /// hold a picture without CDFs, and the reachable case is a slot nothing
3746 /// has refreshed at all. That is what this builds: a stream that OPENS on
3747 /// a non-error-resilient inter frame (the only header shape that codes
3748 /// `primary_ref_frame` at all, spec 5.9.2), tried at all eight slots.
3749 ///
3750 /// This refusal, not "an inter frame with no key frame before it", is the
3751 /// one such a stream reaches: the CDF load happens in the header path,
3752 /// before the reference pictures are looked up.
3753 #[test]
3754 fn an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name() {
3755 let fctx = &crate::decode::FrameCtx::new();
3756 const REFUSAL: &str =
3757 "a frame naming primary_ref_frame at a reference slot with no saved CDF state";
3758 // The invariant above, read off the source: every line that stores a
3759 // picture into a slot sits in a block that stores that slot's CDFs too.
3760 let src = crate::test_source::module_source("stream");
3761 let stores: Vec<usize> = src
3762 .lines()
3763 .enumerate()
3764 .filter(|(_, l)| l.trim().starts_with("ref_slots[i] = "))
3765 .map(|(i, _)| i)
3766 .collect();
3767 assert_eq!(
3768 stores.len(),
3769 2,
3770 "the picture slots gained a writer -- check it stores cdf_slots too"
3771 );
3772 let lines: Vec<&str> = src.lines().collect();
3773 for &i in &stores {
3774 let window = lines[i.saturating_sub(6)..(i + 6).min(lines.len())].join("\n");
3775 assert!(
3776 window.contains("cdf_slots[i] = "),
3777 "line {} stores a reference picture with no cdf_slots store beside it: a slot \
3778 can then hold a picture with no saved CDF state",
3779 i + 1
3780 );
3781 }
3782
3783 let picture = test_card(64, 64);
3784 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3785 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
3786 for slot in 0..NUM_REF_FRAMES as u8 {
3787 let inter = FrameHeader {
3788 frame_type: FrameType::Inter,
3789 frame_is_intra: false,
3790 // `primary_ref_frame` is coded only when error resilience is
3791 // off (spec 5.9.2); `frame_size_override_flag` stays clear so
3792 // the header writes a plain `frame_size()`.
3793 error_resilient_mode: false,
3794 primary_ref_frame: 0,
3795 ref_frame_idx: [slot; ec_av1_syntax::REFS_PER_FRAME],
3796 refresh_frame_flags: 0x02,
3797 order_hint: 1,
3798 ..key.clone()
3799 };
3800 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
3801 stream
3802 .extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
3803
3804 let mut shown = 0;
3805 let err = decode_stream_with(&stream, |_, _, _| {
3806 shown += 1;
3807 Ok(())
3808 })
3809 .unwrap_err()
3810 .to_string();
3811 assert!(
3812 err.contains(REFUSAL),
3813 "slot {slot}: expected {REFUSAL:?}, got: {err}"
3814 );
3815 assert_eq!(
3816 shown, 0,
3817 "slot {slot}: a frame with no CDF state produced a picture"
3818 );
3819 }
3820 }
3821
3822 /// lane-t900 r26, enumeration: no frame header a stream can carry derives
3823 /// an empty mode-info grid, so "a frame with no mode-info grid" names a
3824 /// case outside the coded domain.
3825 ///
3826 /// `compute_image_size` (spec 5.9.9) is `mi_cols = 2 * ((frame_width + 7)
3827 /// >> 3)`, which is 0 only for `frame_width == 0`, and a frame width is
3828 /// > > never 0 on any of the three paths that set one:
3829 ///
3830 /// * `frame_size()` (5.9.5) reads `frame_width_minus_1` and adds one, or
3831 /// takes the sequence's `max_frame_width` (itself `+ 1`-coded);
3832 /// * `superres_params()` (5.9.8) divides by a denominator of 9..=16 with
3833 /// rounding, whose minimum over the whole 16-bit upscaled-width domain
3834 /// is enumerated below and is 1, not 0;
3835 /// * `show_existing_frame` and `frame_size_with_refs()` copy a slot's own
3836 /// dimensions, which came from one of the above.
3837 ///
3838 /// The sweep drives the REAL header reader (write a header, parse it back)
3839 /// over every width and every height a 16-bit `frame_size()` can code,
3840 /// per axis -- the derivation is independent per axis -- rather than
3841 /// re-deriving the formula here.
3842 #[test]
3843 fn every_frame_size_a_header_can_code_has_a_mode_info_grid() {
3844 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so
3845 // it names it and pins its guard site (the decode-path guard in
3846 // decode.rs carries the same string).
3847 const REFUSAL: &str = "a frame with no mode-info grid";
3848 assert!(
3849 crate::refusal_inventory::pins_refusal(crate::test_source::module_source("stream"), REFUSAL),
3850 "this gate proves {REFUSAL:?}, but that string is no longer in stream.rs"
3851 );
3852 let mut sizes: Vec<u32> = (1..=1024).collect();
3853 sizes.extend([2048, 4095, 4096, 8192, 16384, 32768, 65535, 65536]);
3854 // `mi_cols` is nondecreasing in `frame_width`, so an empty grid can
3855 // only appear at the SMALL end -- which is why a size this crate's
3856 // tile-info writer cannot express (its tile log2 range runs out well
3857 // before 65536) is skipped rather than worked around, while every
3858 // size up to 1024 must be covered.
3859 let mut skipped: Vec<u32> = Vec::new();
3860 for n in sizes {
3861 for (w, h) in [(n, 16), (16, n)] {
3862 let Ok((seq, header)) =
3863 crate::encode::key_frame_headers(w as usize, h as usize, 100)
3864 else {
3865 skipped.push(n);
3866 continue;
3867 };
3868 let Ok(stream) = crate::frame::frame_obu(&seq, &header, &[]) else {
3869 skipped.push(n);
3870 continue;
3871 };
3872 let mut parser = Av1Parser::new();
3873 parser
3874 .parse_obu(&crate::sequence::sequence_header_obu(&seq).unwrap())
3875 .unwrap();
3876 let obu = parser.parse_obu(&stream).unwrap();
3877 let ObuKind::Frame(parsed, _) = &obu.kind else {
3878 panic!("{w}x{h}: the written frame OBU did not parse as one");
3879 };
3880 assert!(
3881 parsed.mi_cols >= 2 && parsed.mi_rows >= 2,
3882 "{w}x{h} parsed to a {}x{} mode-info grid",
3883 parsed.mi_cols,
3884 parsed.mi_rows
3885 );
3886 }
3887 }
3888 assert!(
3889 skipped.iter().all(|&n| n > 1024),
3890 "the writer could not express these small frame sizes, so the small end of the \
3891 sweep is incomplete: {skipped:?}"
3892 );
3893 // The superres arm, which no writer here can express: spec 5.9.8's
3894 // `(upscaled_width * 8 + denom / 2) / denom` over its whole domain.
3895 for denom in 9u32..=16 {
3896 for upscaled in [1u32, 2, 3, 7, 8, 9, 255, 4096, 65535, 65536] {
3897 let width = (upscaled * 8 + denom / 2) / denom;
3898 assert!(
3899 width >= 1,
3900 "superres denom {denom} maps an upscaled width of {upscaled} to {width}, \
3901 which would derive an empty mode-info grid"
3902 );
3903 }
3904 }
3905 }
3906
3907 /// lane-interedge r1 GATE (was lane-oddh r2's `#[ignore]`d twin): the INTER
3908 /// frame-edge half strips -- a `PARTITION_HORZ`/`PARTITION_VERT` forced by
3909 /// the gathered edge symbol at the 64, 32 or 16 level whose second half lies
3910 /// outside the true frame. Both of the user's films are height mod 16 == 8
3911 /// (1920x792, 3840x1608), so every inter frame crosses these nodes.
3912 ///
3913 /// r1 root cause: the inter tile's 32-level `PARTITION_HORZ`/`PARTITION_VERT`
3914 /// decoded the SECOND strip unconditionally, while libaom `decode_partition`
3915 /// (decodeframe.c, PARTITION_HORZ) guards it with `has_rows`/`has_cols` --
3916 /// so at the edge we read symbols the encoder never wrote. With that guard
3917 /// removed this gate's 72x192 cq 32 arm refuses outright and its 104x192 arm
3918 /// decodes luma rows 127..191 of frame 5 wrong (measured r1).
3919 ///
3920 /// The compare is LUMA-exact per frame plus a CONTROL size with no edge node
3921 /// at all: chroma is excluded because a chroma-only inter residue that has
3922 /// nothing to do with the frame edge is open on main (lanes/tiny-r3,
3923 /// lanes/gmaffine-r4, lanes/palette2-r8) and the control below reproduces it
3924 /// with `inter_edge_strip_hits` all zero.
3925 #[test]
3926 fn a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact() {
3927 const NAME: &str = "a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact";
3928 let _gate_lock = lock_gate_counters();
3929 if !have_ffmpeg() || !have_aomenc() {
3930 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
3931 return;
3932 }
3933 let frames = 6usize;
3934 // h mod 16 == 8 (bottom edge) and w mod 16 == 8 (right edge).
3935 let sizes: &[(usize, usize)] = &[(192, 72), (192, 88), (72, 192), (88, 192), (104, 192)];
3936 let mut totals = [0usize; 6];
3937 let mut compared = 0u32;
3938 let mut chroma_frames = 0usize;
3939 for &(width, height) in sizes {
3940 for bit_depth in [8u32, 10] {
3941 for cq in [20u32, 32, 45] {
3942 let (hits, luma_bad, chroma_bad) =
3943 inter_edge_strip_attempt(NAME, width, height, bit_depth, cq, frames);
3944 assert_eq!(
3945 luma_bad, 0,
3946 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {luma_bad} of {frames} \
3947 frames differ from ffmpeg in LUMA (edge hits {hits:?})"
3948 );
3949 // merge J, after lane-rectchroma2: the chroma residue this
3950 // gate used to tolerate WAS this decoder's -- the per-axis
3951 // narrow-block MC kernel decision read side x side instead
3952 // of the block's true dims. Full-plane now.
3953 assert_eq!(
3954 chroma_bad, 0,
3955 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {chroma_bad} of \
3956 {frames} frames differ from ffmpeg in CHROMA (edge hits {hits:?})"
3957 );
3958 for (t, h) in totals.iter_mut().zip(hits) {
3959 *t += h;
3960 }
3961 chroma_frames += chroma_bad;
3962 compared += 1;
3963 }
3964 }
3965 }
3966 // Every level x axis this recipe reaches must have fired on a COMPARED
3967 // attempt. h32 (a bottom-edge HORZ at the 32 level) is not asserted: no
3968 // recipe found in r1 makes libaom answer that gathered symbol HORZ
3969 // (sweep ~/.cache/interedge-tmp/h32.sh, 3 sizes x 6 cq, all SPLIT); it
3970 // is the transposed twin of v32, which this gate does fire.
3971 assert!(
3972 totals[0] > 0 && totals[1] > 0 && totals[3] > 0 && totals[4] > 0 && totals[5] > 0,
3973 "{NAME}: {compared} attempts luma-exact but the edge strips did not all fire \
3974 (h64,v64,h32,v32,h16,v16 = {totals:?}) -- the recipe no longer reaches the arms \
3975 this gate exists for"
3976 );
3977 // CONTROL: a size with no frame-edge node anywhere (192x128, both axes
3978 // 0 mod 64). It must be luma-exact with ZERO edge hits -- that is what
3979 // makes the chroma exclusion above a statement about a foreign defect
3980 // rather than about this lane's code.
3981 let (chits, cluma, cchroma) = inter_edge_strip_attempt(NAME, 192, 128, 8, 32, frames);
3982 assert_eq!(
3983 (chits, cluma, cchroma),
3984 ([0usize; 6], 0usize, 0usize),
3985 "{NAME}: control 192x128 (no frame-edge node) must be pixel-exact with no edge hits"
3986 );
3987 eprintln!(
3988 "{NAME}: {compared} attempts luma-exact over {} sizes, edge hits \
3989 (h64,v64,h32,v32,h16,v16)={totals:?}, 0 refusals; chroma-only frames {chroma_frames} \
3990 (control 192x128: hits {chits:?}, chroma-only frames {cchroma} -- foreign defect)",
3991 sizes.len()
3992 );
3993 }
3994
3995 /// lane-sb128 r4 GATE (was lane-oddh r2's refusal gate): the SAME real
3996 /// aomenc 64x72 `--cpu-used=0 --sb-size=128` stream that once desynced at
3997 /// the very first symbol now decodes PIXEL-EXACT against aomdec. mi_rows
3998 /// = 18 > 16, so the BLOCK_128X128 root reads a real gathered partition
3999 /// symbol (2 symbols: has_cols false, has_rows true) -- exactly the case
4000 /// r1 mis-read as a 10-symbol BLOCK_64X64 partition.
4001 ///
4002 /// The `use_128x128_superblock` assert is the "knob reached the tool"
4003 /// half: without it an aomenc that ignored `--sb-size=128` would leave
4004 /// the gate proving nothing about 128 superblocks.
4005 #[test]
4006 fn a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact() {
4007 if !have_ffmpeg() || !have_aomenc() {
4008 eprintln!("SKIP: no ffmpeg/aomenc");
4009 return;
4010 }
4011 let (width, height) = (64usize, 72usize);
4012 let y4m = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
4013 .args([
4014 "-v",
4015 "error",
4016 "-f",
4017 "lavfi",
4018 "-i",
4019 "mandelbrot=size=64x72:rate=25:start_x=-0.6:start_y=-0.4",
4020 "-t",
4021 "0.04",
4022 "-pix_fmt",
4023 "yuv420p",
4024 "-f",
4025 "yuv4mpegpipe",
4026 "-",
4027 ])
4028 .stdin(Stdio::null())
4029 .stdout(Stdio::piped())
4030 .stderr(Stdio::piped()), None, |c| c.output())
4031 .expect("ffmpeg failed to run");
4032 assert!(
4033 y4m.status.success(),
4034 "ffmpeg fixture: {}",
4035 String::from_utf8_lossy(&y4m.stderr)
4036 );
4037 let out = run_with_stdin(
4038 Command::new(aomenc_path()).args([
4039 "--codec=av1",
4040 "--passes=1",
4041 "--end-usage=q",
4042 "--cq-level=32",
4043 "--cpu-used=0",
4044 "--sb-size=128",
4045 "--min-partition-size=16",
4046 "--kf-max-dist=0",
4047 "--limit=1",
4048 "--threads=1",
4049 "--row-mt=0",
4050 "--obu",
4051 "-o",
4052 "-",
4053 "-",
4054 ]),
4055 &y4m.stdout,
4056 );
4057 assert!(
4058 out.status.success(),
4059 "aomenc refused: {}",
4060 String::from_utf8_lossy(&out.stderr)
4061 );
4062 let stream = out.stdout;
4063
4064 // The knob actually arrived: this stream's sequence header codes
4065 // `use_128x128_superblock = 1`.
4066 let mut parser = Av1Parser::new();
4067 let mut pos = 0usize;
4068 let mut sb128 = false;
4069 while pos < stream.len() {
4070 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
4071 break;
4072 };
4073 pos += obu.total_size.max(1);
4074 if let Some(seq) = parser.sequence_header() {
4075 sb128 = seq.use_128x128_superblock;
4076 break;
4077 }
4078 }
4079 assert!(
4080 sb128,
4081 "aomenc ignored --sb-size=128: this stream is 64x64-superblock"
4082 );
4083
4084 let _guard = lock_gate_counters();
4085 let before = crate::decode::part128_symbols() + crate::decode::part128_gathered_symbols();
4086 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, "sb128-oddh-64x72");
4087 assert!(frames > 0, "no frames decoded for {width}x{height}");
4088 // The 128 root actually READ a partition symbol here: at mi_rows=18
4089 // `has_rows` is true, so BLOCK_128X128 is not a forced split.
4090 let part128 =
4091 crate::decode::part128_symbols() + crate::decode::part128_gathered_symbols() - before;
4092 assert!(
4093 part128 > 0,
4094 "{width}x{height} decoded without reading a single BLOCK_128X128 \
4095 partition symbol -- the gate proves nothing about the 128 root"
4096 );
4097 eprintln!(
4098 "a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact: \
4099 {frames} frames pixel-exact ({hidden} hidden) at {width}x{height}, \
4100 part128_symbols={part128}"
4101 );
4102 }
4103
4104 /// `decode_stream` on a lone key frame's stream matches both the tile
4105 /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and
4106 /// the encoder's own reconstruction, at an even and an odd size.
4107 #[test]
4108 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
4109 // lane-b128m: the ENCODER writes at this process's superblock size, so
4110 // its own trial decode -- and the raw tile decode below -- must be given
4111 // that size too (class: stale header in the test harness).
4112 let fctx = &crate::decode::FrameCtx::for_encoder();
4113 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
4114 let picture = test_card(width, height);
4115 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4116 let via_tile = decode_key_frame_tile_lr(
4117 &encoded.tile,
4118 encoded.mi_cols,
4119 encoded.mi_rows,
4120 encoded.base_q_idx,
4121 width as u32,
4122 height as u32,
4123 // lane-fintra: the sequence bit the encoder wrote this tile under
4124 // (stale-header class -- a hard-coded `false` here reads one symbol
4125 // short at the first DC_PRED block once the search offers filter intra).
4126 crate::encode::filter_intra_on(),
4127 &encoded.cdef,
4128 &encoded.loop_filter,
4129 encoded.tx_select,
4130 // lane-intertx: the frame's own `reduced_tx_set` -- a screen
4131 // key frame at preset 0 codes the wider intra alphabets, so
4132 // the old hardcoded `true` (ours "always" wrote true) is a
4133 // stale-header bug waiting for the first screen fixture.
4134 encoded.reduced_tx_set,
4135 // `allow_screen_content_tools` off the frame the encoder
4136 // actually wrote: a screen-content picture codes two palette
4137 // symbols per intra block, and a raw tile decode that guessed
4138 // `false` desyncs at the first one (class: test asserts
4139 // against a stale header).
4140 encoded.screen,
4141 // ... and its own `allow_intrabc` (stale-header class).
4142 encoded.allow_intrabc,
4143 &encoded.loop_restoration,
4144 fctx,
4145 )
4146 .unwrap();
4147 let via_stream = decode_stream(&encoded.stream).unwrap();
4148 assert_eq!(via_stream.len(), 1, "{width}x{height}: one picture");
4149 assert_eq!(via_stream[0].y, via_tile.y, "{width}x{height}: luma");
4150 assert_eq!(via_stream[0].u, via_tile.u, "{width}x{height}: U");
4151 assert_eq!(via_stream[0].v, via_tile.v, "{width}x{height}: V");
4152 assert_eq!(
4153 via_stream[0].y, encoded.reconstruction.y,
4154 "{width}x{height}: luma vs encoder reconstruction"
4155 );
4156 }
4157 }
4158
4159 #[test]
4160 fn decode_stream_round_trips_a_gop() {
4161 let fctx = &crate::decode::FrameCtx::for_encoder();
4162 gop_round_trips(128, 64, fctx);
4163 }
4164
4165 /// Same claim at a size that is not a whole number of 32x32 blocks, so
4166 /// the inter frame's 16x16-leaf split path is exercised too.
4167 #[test]
4168 fn decode_stream_round_trips_an_odd_size_gop() {
4169 let fctx = &crate::decode::FrameCtx::for_encoder();
4170 gop_round_trips(216, 96, fctx);
4171 }
4172
4173 /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures
4174 /// `decode_stream` collects, in the same order -- the streaming path is
4175 /// the decoder now (`decode_stream` is a collecting wrapper), so an
4176 /// equivalence check here is what keeps every gate's Vec-shaped assert
4177 /// meaningful. Also pins the sink contract: one call per shown picture,
4178 /// decode indices non-decreasing, and an `Err` from the sink aborting.
4179 #[test]
4180 fn streaming_decode_matches_the_collecting_one() {
4181 let fctx = &crate::decode::FrameCtx::for_encoder();
4182 let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect();
4183 let stream = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
4184 .unwrap()
4185 .stream;
4186 let collected = decode_stream(&stream).unwrap();
4187
4188 let mut shown = Vec::new();
4189 let mut idxs = Vec::new();
4190 let mut live = 0usize;
4191 decode_stream_with(&stream, |p, idx, is_shown| {
4192 live += 1;
4193 if is_shown {
4194 idxs.push(idx);
4195 shown.push(p.clone());
4196 }
4197 Ok(())
4198 })
4199 .unwrap();
4200 assert_eq!(
4201 shown.len(),
4202 collected.len(),
4203 "callback count vs shown frames"
4204 );
4205 assert!(
4206 live >= shown.len(),
4207 "every shown picture is also a callback"
4208 );
4209 assert!(
4210 idxs.windows(2).all(|w| w[0] <= w[1]),
4211 "decode indices out of order: {idxs:?}"
4212 );
4213 for (i, (got, want)) in shown.iter().zip(&collected).enumerate() {
4214 assert_eq!(got.y, want.y, "frame {i} luma");
4215 assert_eq!(got.u, want.u, "frame {i} U");
4216 assert_eq!(got.v, want.v, "frame {i} V");
4217 }
4218
4219 // A sink error stops the decode and comes back unchanged.
4220 let mut seen = 0usize;
4221 let err = decode_stream_with(&stream, |_, _, _| {
4222 seen += 1;
4223 Err(Error::corrupt("sink says stop"))
4224 })
4225 .unwrap_err();
4226 assert_eq!(seen, 1, "decode continued past a failing sink");
4227 assert!(format!("{err}").contains("sink says stop"), "{err}");
4228 }
4229
4230 /// lane-av1oracleguard, direction 1 of 2: the 4:2:0 helper's COMPARATOR
4231 /// still bites on a real 4:2:0 pin, so the refusal added above did not
4232 /// buy its non-vacuity by making the helper stop comparing.
4233 ///
4234 /// `420_mixll_256x128_6f.obu` is 8-bit 4:2:0 at 256x128. Ours and ffmpeg
4235 /// agree on every sample of every output frame (bad == 0), then ONE U
4236 /// sample of the oracle is flipped and the same count must move to 1. A
4237 /// count that stays 0 on a flipped oracle is a comparator that compares
4238 /// nothing, and the refusal would then be the only thing this gate could
4239 /// prove.
4240 #[test]
4241 fn a_420_oracle_comparator_counts_a_flipped_oracle_sample() {
4242 const NAME: &str = "a_420_oracle_comparator_counts_a_flipped_oracle_sample";
4243 let _gate_lock = lock_gate_counters();
4244 if !have_ffmpeg() {
4245 eprintln!("SKIP {NAME}: no ffmpeg");
4246 return;
4247 }
4248 let path = crate_pin("420_mixll_256x128_6f.obu");
4249 let data = std::fs::read(&path)
4250 .unwrap_or_else(|e| panic!("{NAME}: the committed pin is missing ({e})"));
4251 assert_eq!(data.len(), 22336, "{NAME}: pin size drifted");
4252 assert_eq!(
4253 fnv1a64(&data),
4254 5694016005779287373,
4255 "{NAME}: pin bytes drifted"
4256 );
4257 assert_eq!(
4258 stream_subsampling(&data, NAME),
4259 (1, 1),
4260 "{NAME}: this cell must be a 4:2:0 pin -- the refusal arm uses other pins"
4261 );
4262
4263 let decoded = decode_stream(&data)
4264 .unwrap_or_else(|e| panic!("{NAME}: the committed 4:2:0 pin did not decode: {e}"));
4265 // The pin name is the spec: `420_mixll_256x128_6f` is 6 shown frames.
4266 // `decoded.len()` is the value under test, so it must not be the count
4267 // handed to ffmpeg (count-vacuity ceiling is 0).
4268 const SHOWN: usize = 6;
4269 assert_eq!(decoded.len(), SHOWN, "{NAME}: the pin is 6 shown frames");
4270 let want = ffmpeg_decode_sequence(&data, 256, 128, SHOWN);
4271 assert_eq!(decoded.len(), want.len(), "{NAME}: decoded/frame count");
4272
4273 let plane_mismatches = |ours: &[Pic], theirs: &[Pic], plane: u8| -> usize {
4274 ours.iter()
4275 .zip(theirs)
4276 .map(|(a, b)| {
4277 let (a, b) = match plane {
4278 0 => (&a.y, &b.y),
4279 1 => (&a.u, &b.u),
4280 _ => (&a.v, &b.v),
4281 };
4282 a.iter().zip(b).filter(|&(x, y)| x != y).count()
4283 })
4284 .sum()
4285 };
4286 let clean: Vec<usize> = (0..3)
4287 .map(|p| plane_mismatches(&decoded, &want, p))
4288 .collect();
4289 assert_eq!(
4290 clean,
4291 vec![0, 0, 0],
4292 "{NAME}: the 4:2:0 oracle arm is not byte-exact to start with, so a flipped sample \
4293 would prove nothing"
4294 );
4295
4296 // Flip exactly one oracle sample and the count MUST move.
4297 let mut flipped = want.clone();
4298 flipped[0].u[0] ^= 1;
4299 let moved: Vec<usize> = (0..3)
4300 .map(|p| plane_mismatches(&decoded, &flipped, p))
4301 .collect();
4302 assert_eq!(
4303 moved,
4304 vec![0, 1, 0],
4305 "{NAME}: one flipped oracle U sample must move the U comparison count 0 -> 1 and \
4306 leave Y and V at 0; got {moved:?} -- the comparator does not bite, so this gate \
4307 cannot tell a working oracle arm from a vacuous one"
4308 );
4309 eprintln!(
4310 "{NAME}: clean per-plane counts {clean:?}, after one flipped oracle U sample {moved:?}"
4311 );
4312 }
4313
4314 /// lane-av1oracleguard, direction 2 of 2 (8-bit): the 4:2:0 helper must
4315 /// REFUSE a real 4:2:2 pin instead of letting ffmpeg convert it. The
4316 /// message must name the REAL subsampling AND the sibling to use -- a
4317 /// bare "wrong shape" would leave the caller to rediscover the fix.
4318 ///
4319 /// Before this lane, `ffmpeg_decode_sequence(&422_key_64x64, 64, 64, 1)`
4320 /// RETURNED a 4:2:0-converted picture without complaint, which is the
4321 /// silent-green the refusal exists to stop. This gate needs no ffmpeg at
4322 /// all: the guard runs before the spawn, so a host without ffmpeg still
4323 /// proves the refusal.
4324 #[test]
4325 fn a_420_oracle_helper_refuses_a_422_pin() {
4326 const NAME: &str = "a_420_oracle_helper_refuses_a_422_pin";
4327 let _gate_lock = lock_gate_counters();
4328 let path = crate_pin("422_key_64x64.obu");
4329 let stream = read_pin(&path, 755, 0x87fc569cf53bcbc6, NAME);
4330 assert_eq!(
4331 stream_subsampling(&stream, NAME),
4332 (1, 0),
4333 "{NAME}: the pin must really be 4:2:2 (1,0), or this proves nothing"
4334 );
4335 let msg = panic_message(|| {
4336 ffmpeg_decode_sequence(&stream, 64, 64, 1);
4337 })
4338 .unwrap_or_else(|| {
4339 panic!(
4340 "{NAME}: ffmpeg_decode_sequence ACCEPTED a (1,0) stream. ffmpeg converted it to \
4341 4:2:0 and the helper returned a green-looking comparison"
4342 )
4343 });
4344 for needle in ["(1,0)", "4:2:2", "ffmpeg_decode_sequence_422"] {
4345 assert!(
4346 msg.contains(needle),
4347 "{NAME}: the refusal must name {needle:?}; it said: {msg}"
4348 );
4349 }
4350 eprintln!("{NAME}: refused -> {msg}");
4351 }
4352
4353 /// lane-av1oracleguard, direction 2 of 2 (high depth): the same refusal on
4354 /// `ffmpeg_decode_sequence_10bit` and `_12bit`, which ask ffmpeg for
4355 /// `yuv420p10le`/`yuv420p12le` and slice chroma at `width * height / 4`
4356 /// exactly as the 8-bit helper does. Pinned 4:2:2 at both depths.
4357 #[test]
4358 fn a_420_high_bit_depth_oracle_helpers_refuse_a_422_pin() {
4359 const NAME: &str = "a_420_high_bit_depth_oracle_helpers_refuse_a_422_pin";
4360 let _gate_lock = lock_gate_counters();
4361 let cells: [(&str, usize, u64, fn(&[u8]) -> Vec<Pic>); 2] = [
4362 (
4363 "s422_352x242_10b.obu",
4364 20575,
4365 17425395593908182125,
4366 |s: &[u8]| ffmpeg_decode_sequence_10bit(s, 352, 242, 1),
4367 ),
4368 (
4369 "s422_12bit_160x128.obu",
4370 9214,
4371 0xa62b8e3fe6f60ae5,
4372 |s: &[u8]| ffmpeg_decode_sequence_12bit(s, 160, 128, 1),
4373 ),
4374 ];
4375 for (file, len, fnv, call) in cells {
4376 let path = crate_pin(file);
4377 let stream = read_pin(&path, len, fnv, NAME);
4378 assert_eq!(
4379 stream_subsampling(&stream, NAME),
4380 (1, 0),
4381 "{NAME}/{file}: the pin must really be 4:2:2 (1,0), or this proves nothing"
4382 );
4383 let msg = panic_message(|| {
4384 call(&stream);
4385 })
4386 .unwrap_or_else(|| {
4387 panic!(
4388 "{NAME}/{file}: the 4:2:0 high-bit-depth oracle helper ACCEPTED a (1,0) \
4389 stream -- ffmpeg converted it and the helper returned a comparison that \
4390 could pass green"
4391 )
4392 });
4393 for needle in ["(1,0)", "4:2:2", "ffmpeg_decode_sequence_422_depth"] {
4394 assert!(
4395 msg.contains(needle),
4396 "{NAME}/{file}: the refusal must name {needle:?}; it said: {msg}"
4397 );
4398 }
4399 eprintln!("{NAME}/{file}: refused -> {msg}");
4400 }
4401 }
4402
4403 /// lane-av1422mixll10: a skipped INTRABC 8x8 leaf inside a LOSSLESS
4404 /// segment of a 4:2:2 frame predicts its whole 4x8 chroma plane block --
4405 /// both TX_4X4 units, each windowed off the DV frame copy. The defect
4406 /// arm pushed only the first 4x4 (at `cpy`), leaving rows
4407 /// `cpy+4..cpy+8` unwritten: frame 0's U(140..143, 188..191) read the
4408 /// sentinel poison 0 against the oracle's 664 (16 samples, all planes
4409 /// otherwise exact). Pin `422_mixll_intrabc_lossless_320x240_5f.obu`
4410 /// (aomenc profile 1, 320x240 yuv422p10le, mixed-lossless AQ segment +
4411 /// intrabc screen content; 79333 bytes, sha256
4412 /// `9fa1f1d28d61e3096d70908728f9cdfa1a570b9769a3d31e8d385a61c12a2b25`).
4413 /// Gate: every frame of all three planes byte-exact against ffmpeg's
4414 /// `yuv422p10le`, plus the non-vacuity controls (the pin's chroma census
4415 /// must show coded units, and one flipped oracle sample must move the
4416 /// count).
4417 #[test]
4418 fn a_422_mixll_intrabc_lossless_leaf_predicts_whole_chroma_plane_block() {
4419 const NAME: &str = "a_422_mixll_intrabc_lossless_leaf_predicts_whole_chroma_plane_block";
4420 const FILE: &str = "422_mixll_intrabc_lossless_320x240_5f.obu";
4421 const LEN: usize = 79333;
4422 const FNV: u64 = 8342335520738450773;
4423 const W: usize = 320;
4424 const H: usize = 240;
4425 const SHOWN: usize = 5;
4426 let _gate_lock = lock_gate_counters();
4427 if !have_ffmpeg() {
4428 eprintln!("SKIP {NAME}: no ffmpeg");
4429 return;
4430 }
4431 let path = crate_pin(FILE);
4432 let stream = read_pin(&path, LEN, FNV, NAME);
4433 assert_eq!(
4434 stream_subsampling(&stream, NAME),
4435 (1, 0),
4436 "{NAME}: the pin must really be 4:2:2 (1,0)"
4437 );
4438 assert_eq!(
4439 stream_bit_depth(&stream, NAME),
4440 10,
4441 "{NAME}: the pin is a 10-bit cell"
4442 );
4443 let _ = stream_bit_depth(&stream, NAME);
4444
4445 let decoded = decode_stream(&stream)
4446 .unwrap_or_else(|e| panic!("{NAME}: the committed 4:2:2 pin did not decode: {e}"));
4447 assert_eq!(
4448 decoded.len(),
4449 SHOWN,
4450 "{NAME}: the pin is {SHOWN} shown frames"
4451 );
4452 let want = ffmpeg_decode_sequence_422_depth(&stream, W, H, SHOWN, 10, "yuv422p10le");
4453 assert_eq!(decoded.len(), want.len(), "{NAME}: decoded/frame count");
4454
4455 let plane_mismatches = |ours: &[Pic], theirs: &[Pic], plane: u8| -> usize {
4456 ours.iter()
4457 .zip(theirs)
4458 .map(|(a, b)| {
4459 let (a, b) = match plane {
4460 0 => (&a.y, &b.y),
4461 1 => (&a.u, &b.u),
4462 _ => (&a.v, &b.v),
4463 };
4464 a.iter().zip(b).filter(|&(x, y)| x != y).count()
4465 })
4466 .sum()
4467 };
4468 let clean: Vec<usize> = (0..3)
4469 .map(|p| plane_mismatches(&decoded, &want, p))
4470 .collect();
4471 assert_eq!(
4472 clean,
4473 vec![0, 0, 0],
4474 "{NAME}: the fix must be byte-exact against ffmpeg on every plane of every frame; \
4475 got {clean:?} (16 differs on frame 0 U would be the unwritten 4x4 again)"
4476 );
4477
4478 // Non-vacuity: one flipped oracle U sample must move the U count.
4479 let mut flipped = want.clone();
4480 flipped[0].u[188 * (W / 2) + 140] ^= 1;
4481 let moved: Vec<usize> = (0..3)
4482 .map(|p| plane_mismatches(&decoded, &flipped, p))
4483 .collect();
4484 assert_eq!(
4485 moved,
4486 vec![0, 1, 0],
4487 "{NAME}: one flipped oracle U sample at (140,188) must move the U count 0 -> 1; \
4488 got {moved:?} -- the comparator does not bite"
4489 );
4490 eprintln!(
4491 "{NAME}: byte-exact vs ffmpeg on all {SHOWN} frames; flip control moved {moved:?}"
4492 );
4493 }
4494
4495 /// lane-av1oracledepth: the 8-bit `ffmpeg_decode_sequence_444` must REFUSE
4496 /// a real 10-bit 4:4:4 pin instead of letting ffmpeg convert it down to
4497 /// `yuv444p`. ffmpeg does not fail on the depth mismatch -- it re-scales
4498 /// -- so a gate built on the 8-bit helper would compare ffmpeg's rescaled
4499 /// planes against our 10-bit decode and could read exact. The message
4500 /// must name the real depth AND the depth-generic sibling
4501 /// `ffmpeg_decode_sequence_444_depth`, so the caller has the fix in front
4502 /// of it.
4503 ///
4504 /// Needs no ffmpeg at all: the guard runs before the spawn, so a host
4505 /// without ffmpeg still proves the refusal.
4506 #[test]
4507 fn the_8bit_444_oracle_helper_refuses_a_10bit_444_pin() {
4508 const NAME: &str = "the_8bit_444_oracle_helper_refuses_a_10bit_444_pin";
4509 let _gate_lock = lock_gate_counters();
4510 let path = crate_pin("444_lossy_palette_chroma_352x242_10b.obu");
4511 let stream = read_pin(&path, 24875, 0x7fda_dbb4_3bbf_9af3, NAME);
4512 assert_eq!(
4513 stream_bit_depth(&stream, NAME),
4514 10,
4515 "{NAME}: the pin must really be 10-bit, or this proves nothing"
4516 );
4517 assert_eq!(
4518 stream_subsampling(&stream, NAME),
4519 (0, 0),
4520 "{NAME}: the pin must really be 4:4:4 (0,0), or this proves nothing"
4521 );
4522 let msg = panic_message(|| {
4523 ffmpeg_decode_sequence_444(&stream, 352, 242, 1);
4524 })
4525 .unwrap_or_else(|| {
4526 panic!(
4527 "{NAME}: ffmpeg_decode_sequence_444 ACCEPTED a 10-bit 4:4:4 stream. ffmpeg \
4528 converted it to yuv444p and the helper returned a green-looking comparison"
4529 )
4530 });
4531 for needle in ["not 8-bit", "ffmpeg_decode_sequence_444_depth"] {
4532 assert!(
4533 msg.contains(needle),
4534 "{NAME}: the refusal must name {needle:?}; it said: {msg}"
4535 );
4536 }
4537 eprintln!("{NAME}: refused -> {msg}");
4538 }