forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB231663eTahinli3 months ago1475 commits

stream.rs19097 lines, 866.7 KiBHistoryRawDownload
1//! The stream-level entry point a real decoder needs: walk a raw AV1 OBU
2//! stream (`Encoded::stream`, or any low-overhead-format bitstream this
3//! crate's own writers produce) via [`ec_av1_syntax::Av1Parser`] and dispatch
4//! each frame's tile payload to [`crate::decode::decode_key_frame_tile_with_cdfs`] /
5//! [`crate::decode::decode_inter_frame_tile_with_cdfs`], threading a
6//! single-slot picture DPB exactly as [`crate::encode::encode_sequence`] does
7//! on the write side, plus the full 8-slot *CDF* reference bank spec 7.20
8//! (`load_cdfs`) and 7.4 (the reference frame update) describe: a frame whose
9//! header names `primary_ref_frame != PRIMARY_REF_NONE` resumes from the
10//! adapted table a previous frame's `refresh_frame_flags` left in that slot,
11//! rather than the spec 8.4 defaults.
12//!
13//! This is the only reachable path for a caller that does not have the
14//! encoder's own `Encoded::tile`/`mi_cols`/`mi_rows`/`base_q_idx` fields (they
15//! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is
16//! an implementation detail of how this crate happens to build it).
17
18use ec_av1_syntax::{
19 Av1Parser, FrameHeader, FrameType, MAX_SEGMENTS, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE,
20 SEG_LVL_GLOBALMV, SEG_LVL_REF_FRAME, SEG_LVL_SKIP, Tile, TxMode,
21};
22use ec_core::{Error, Result};
23
24use crate::cdf_state::Cdfs;
25use crate::decode;
26use crate::decode::{
27 decode_inter_frame_tile_with_cdfs, decode_key_frame_tile, decode_key_frame_tile_with_cdfs,
28 q_ctx_of,
29};
30use crate::encode::Picture;
31
32/// lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the
33/// current thread, overriding the environment variable. Every ffmpeg/aomdec
34/// pixel gate in this repo compares SHOWN frames only (class
35/// gate-blind-to-hidden-frames), so the hidden alt-ref frames a real aomenc
36/// stream carries were never compared at all; the gate that does compare
37/// them needs a dump path that cannot race a sibling test's decode on
38/// another thread, which a process-global env var cannot give.
39thread_local! {
40 static FINAL_DUMP_PREFIX: std::cell::RefCell<Option<String>> =
41 const { std::cell::RefCell::new(None) };
42}
43
44/// Sets (or with `None` clears) this thread's `EC_AV1_FINAL_DUMP` prefix.
45#[allow(dead_code)]
46pub(crate) fn set_final_dump_prefix(prefix: Option<String>) {
47 FINAL_DUMP_PREFIX.with(|c| *c.borrow_mut() = prefix);
48}
49
50fn final_dump_prefix() -> Option<String> {
51 FINAL_DUMP_PREFIX
52 .with(|c| c.borrow().clone())
53 .or_else(|| std::env::var("EC_AV1_FINAL_DUMP").ok())
54}
55
56/// 32x32-level 1:4 strip counters, for `decode_probe`'s fixture search:
57/// (HORZ_4 strips, VERT_4 strips, strips that read coefficients).
58pub fn rect4_32_counters() -> (usize, usize, usize) {
59 (
60 crate::decode::rect4_32_horz_hits(),
61 crate::decode::rect4_32_vert_hits(),
62 crate::decode::rect4_coeff_hits(),
63 )
64}
65
66/// Decode every frame in a raw AV1 OBU stream, in coding order.
67///
68/// A key frame becomes the reference for the inter frames that follow it,
69/// until the next key frame resets the DPB — the same single-slot chain
70/// [`crate::encode::encode_sequence`] threads on the write side. Only a
71/// `Frame` OBU (an uncompressed header and its tile group in one OBU, which
72/// is all this crate's encoder ever writes) carries a tile payload; sequence
73/// headers and temporal delimiters are consumed for the state they carry (or
74/// skipped) and produce no picture.
75///
76/// # Errors
77/// Returns an error when the stream is truncated or malformed (as
78/// [`Av1Parser`] reports it), when a frame header names anything this
79/// crate's tile decoders do not reconstruct (see their own docs), or when an
80/// inter frame appears before any key frame has supplied a reference.
81pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
82 let final_dump = final_dump_prefix();
83 let mut parser = Av1Parser::new();
84 let mut pictures = Vec::new();
85 let mut pictures_decoded: usize = 0;
86 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
87 // previous frame's `refresh_frame_flags` stored into it, exactly like the
88 // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,
89 // not simply "the previous frame decoded"; a frame whose own predecessor
90 // didn't refresh that slot (an altref/hidden frame, or any GOP with more
91 // than one live reference) must keep predicting from whatever picture is
92 // still sitting there. Round 7's cdffwd hunt: a global `reference`
93 // overwritten every frame silently always used "the most recent decode"
94 // instead, producing a bit-exact motion vector into the WRONG picture --
95 // luma-only (chroma coincidentally shares this fixture's flat regions)
96 // and small-magnitude (the two pictures mostly agree), which is exactly
97 // what made it look like a rounding bug rather than a wrong reference.
98 let mut ref_slots: [Option<Picture>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
99 // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion
100 // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom
101 // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was
102 // decoded with -- `Picture` itself carries neither, so both ride
103 // alongside `ref_slots` on the exact same `refresh_frame_flags` update.
104 let mut motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES] =
105 std::array::from_fn(|_| None);
106 let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES];
107 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
108 // previous frame's `refresh_frame_flags` stored into it -- the frame's
109 // own end-of-tile adapted table, or (when the frame set
110 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
111 let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
112 // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also
113 // remembers the segment map the frame stored there decoded, which is what
114 // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds`
115 // (spec `load_previous_segment_ids`) for temporal segment-id prediction
116 // and for a `segmentation_update_map == 0` frame's inherited map.
117 let mut seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
118
119 let mut pos = 0usize;
120 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec
121 // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone
122 // `OBU_FRAME_HEADER` first, with `show_existing_frame == false` and no
123 // tile payload of its own -- `OBU_FRAME` (the `ObuKind::Frame` arm below)
124 // only ever folds ONE tile group into the header's own OBU. Stash the
125 // header here and accumulate tiles from each `OBU_TILE_GROUP` that
126 // follows until every tile of the frame has arrived.
127 let mut pending_header: Option<Box<FrameHeader>> = None;
128 let mut pending_tiles: Vec<Tile> = Vec::new();
129 while pos < data.len() {
130 let obu = parser.parse_obu(&data[pos..])?;
131 let obu_offset = pos;
132 pos += obu.total_size;
133
134 if let ObuKind::FrameHeader(header) = &obu.kind {
135 if !header.show_existing_frame {
136 // Before this fix, this branch fired unconditionally for
137 // EVERY `FrameHeader` OBU (including this one), so a
138 // standalone header always fell into the `show_existing_frame`
139 // slot lookup below and misreported "a show_existing_frame
140 // header naming an empty reference slot" for a frame that was
141 // never a show_existing_frame header at all.
142 pending_header = Some(header.clone());
143 pending_tiles = Vec::new();
144 continue;
145 }
146 // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this
147 // OBU only names a DPB slot to output again -- the coded-frame
148 // count and the shown-picture count are different things (a
149 // hidden altref's own `Frame` OBU below is never pushed to
150 // `pictures` on its own; it is only pushed here, later, when a
151 // `show_existing_frame` header names its slot). Before r15 this
152 // arm didn't exist at all: every `ObuKind::Frame` was pushed
153 // unconditionally regardless of `show_frame`, so a hidden altref
154 // was emitted (wrongly, in decode order) and its real
155 // `show_existing_frame` output was silently dropped.
156 let slot = header.frame_to_show_map_idx as usize;
157 let picture = ref_slots[slot].clone().ok_or_else(|| {
158 Error::unsupported(
159 "AV1 decode_stream",
160 "a show_existing_frame header naming an empty reference slot",
161 )
162 })?;
163 for i in 0..NUM_REF_FRAMES {
164 if header.refresh_frame_flags & (1 << i) != 0 {
165 cdf_slots[i] = cdf_slots[slot].clone();
166 ref_slots[i] = Some(picture.clone());
167 motion_field_slots[i] = motion_field_slots[slot].clone();
168 seg_map_slots[i] = seg_map_slots[slot].clone();
169 order_hint_slots[i] = order_hint_slots[slot];
170 }
171 }
172 let output = if header.film_grain.apply_grain {
173 // lane-hbd10 r1: grain synthesis is bit-depth generic
174 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
175 let bit_depth = parser
176 .sequence_header()
177 .map_or(8, |seq| seq.color_config.bit_depth);
178 let mc_identity = parser
179 .sequence_header()
180 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
181 crate::film_grain::apply_grain(
182 &picture,
183 &header.film_grain,
184 mc_identity,
185 bit_depth as u32,
186 )
187 } else {
188 picture
189 };
190 pictures.push(output);
191 continue;
192 }
193 // `tiles_base_offset` is added to every `Tile::offset` below to reach
194 // an absolute position in `data`. `OBU_FRAME`'s tiles are relative to
195 // this OBU's own `obu_offset`; an accumulated run of `OBU_TILE_GROUP`s
196 // may span several different OBUs (each at a different offset in
197 // `data`), so those tiles are normalised to an absolute offset the
198 // moment they are appended to `pending_tiles`, and `tiles_base_offset`
199 // is 0 for that case.
200 let (header, tiles, tiles_base_offset): (Box<FrameHeader>, Vec<Tile>, usize) =
201 match obu.kind {
202 ObuKind::Frame(header, tiles) => (header, tiles, obu_offset),
203 ObuKind::TileGroup(new_tiles) => {
204 let header = pending_header.clone().ok_or_else(|| {
205 Error::corrupt(
206 "AV1 decode_stream: a tile group OBU with no preceding frame header",
207 )
208 })?;
209 let expected = header.tile_info.cols * header.tile_info.rows;
210 pending_tiles.extend(new_tiles.into_iter().map(|mut t| {
211 t.offset += obu_offset;
212 t
213 }));
214 if (pending_tiles.len() as u32) < expected {
215 continue;
216 }
217 pending_header = None;
218 (header, std::mem::take(&mut pending_tiles), 0)
219 }
220 _ => continue,
221 };
222 // Every tile is decoded below through `tile_bufs`; this only rejects a
223 // frame OBU that carries no tile group at all.
224 if tiles.is_empty() {
225 return Err(Error::unsupported(
226 "AV1 decode_stream",
227 "a frame OBU with no tile group",
228 ));
229 }
230 // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
231 // block of each 64x64) only reads a literal `cdef_idx` when
232 // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a
233 // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is
234 // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into
235 // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so
236 // a `cdef_bits > 0` stream no longer needs this refusal.
237 // Both frame types now read their transform size under
238 // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads
239 // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's
240 // `decode_inter_block`/`decode_inter_block8` read the recursive
241 // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the
242 // blanket inter-frame refusal that used to stand here is gone. What
243 // remains refused is named at its own site in `read_block_tx_size`.
244 // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`,
245 // libaom decodemv.c): three more per-block/per-SB symbols this crate
246 // never reads at all, each gated by a header field this decoder
247 // otherwise accepts uncomplaining -- the same silent-desync shape
248 // `use_filter_intra` was. `allow_screen_content_tools` gates both
249 // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/
250 // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel`
251 // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse
252 // before desyncing rather than silently miscode, the same pattern as
253 // the CDEF/TxMode::Select refusals above.
254 // lane-screen r2: key frames consume (not reconstruct) palette/
255 // intrabc syntax via read_intra_mode, and decode_inter_block/
256 // decode_inter_block8's own intra-sub-block branches now consume
257 // palette the same way (libaom's read_intra_block_mode_info has no
258 // intrabc call at all -- that symbol is intra-frame-only). A
259 // genuine palette/intrabc use still refuses by name deeper in the
260 // block readers, so no whole-frame refusal is needed here anymore.
261 // lane-realworld r5: both delta_q (maybe_read_delta_q, CURRENT_Q_IDX)
262 // and delta_lf (maybe_read_delta_lf, CURRENT_DELTA_LF ->
263 // Neighbours::delta_lf_grid -> lf_level) are now read and applied;
264 // no whole-frame refusal needed here anymore.
265 //
266 // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an
267 // earlier round), `BIT_DEPTH` is wired from this frame's own sequence
268 // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10`
269 // stream decodes pixel-exact against ffmpeg's own decode of the same
270 // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The
271 // blanket refusal that used to be here is gone; `film_grain.rs` and
272 // `superres.rs` still refuse narrowly by name (their own hardcoded
273 // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes
274 // will show up as a real pixel mismatch, not a silent truncation --
275 // the whole reason the widen (and this wiring) happened.
276 // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9,
277 // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the
278 // per-segment quantizer (spec 7.12.2) and loop-filter level
279 // (spec 7.14.4). The three features that instead REWRITE a block's
280 // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the
281 // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress
282 // symbols `decode_inter_block` unconditionally reads) -- have no
283 // reader on the inter path, so they still refuse by name rather than
284 // desyncing. aomenc's `--aq-mode` segmentation only ever sets
285 // `SEG_LVL_ALT_Q`.
286 if header.segmentation.enabled {
287 for segment in 0..MAX_SEGMENTS {
288 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
289 if header.segmentation.feature_enabled[segment][feature] {
290 return Err(Error::unsupported(
291 "AV1 decode_stream",
292 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",
293 ));
294 }
295 }
296 }
297 }
298 // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the
299 // primary reference frame's slot, and is all-zero without one.
300 let prev_seg_map = if header.primary_ref_frame == PRIMARY_REF_NONE {
301 None
302 } else {
303 seg_map_slots[header.ref_frame_idx[header.primary_ref_frame as usize] as usize].clone()
304 };
305 decode::set_segmentation(
306 header.segmentation,
307 header.mi_rows as usize,
308 header.mi_cols as usize,
309 prev_seg_map.as_deref(),
310 );
311 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
312 // symbol (spec 7.16's upscaling is a pixel-domain post-process
313 // libaom's `decodeframe.c` runs between CDEF and loop restoration,
314 // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile
315 // reads stay bit-exact in sync and `crate::superres::upscale_picture`
316 // (below, after decode) makes its `Picture` the spec-correct
317 // `upscaled_width` instead of silently staying at `frame_width`.
318 // lane-superres r10: an INTER frame under `use_superres` no longer
319 // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3)
320 // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/
321 // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes
322 // at the downscaled `frame_width` and upscales its own output the
323 // same way the key-frame branch above does (see the inter branch
324 // below). The combinations `predict_scaled` does not cover
325 // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8
326 // leaf) still refuse by name, deep in `decode.rs`, rather than
327 // silently mispredicting -- see `refusal_inventory.rs`.
328 // Loop restoration carries per-restoration-unit symbols in the tile
329 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
330 // superblock walk) -- lane-lr r2 ported the reader
331 // (`crate::restoration`), r3 moved this refusal check to AFTER the
332 // tile decode call below (was here, before it, in r2 -- meaning
333 // `read_lr` was NEVER actually reached through `decode_stream`, the
334 // gap the r3 gate caught live: 40/40 attempts hit this refusal with
335 // zero `read_lr_unit` hits). Checking post-decode instead proves the
336 // superblock walk actually survived `read_lr` (no desync) before
337 // refusing on the true remaining gap: decoded Wiener/SGR filters are
338 // stored per unit but never applied to pixels.
339 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
340 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
341 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
342 // zero vector only under `GmType == IDENTITY` -- any other warp
343 // model needs the full affine/translation MV derivation this
344 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
345 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
346 // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
347 // to every one of the 7 single-reference slots `decode_inter_block`
348 // can now select.
349 //
350 // lane-gm r2 STEP-8 ATTEMPT (reverted): removing this refusal
351 // exposed a real pixel mismatch --
352 // a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact
353 // seed 43, frame 1 luma, with EC_WEDGE_GATE_ATTEMPTS=20
354 // EC_AV1_REQUIRE_AOMENC=1 -- so the single-ref/compound MV wiring
355 // is not yet provably correct end to end; keeping the refusal
356 // until that seed is captured (EC_AV1_GATE_DUMP), self-pinned, and
357 // root-caused rather than shipping a wrong decode.
358 //
359 // lane-gm r3 ROOT CAUSE (pinned, range-ladder-confirmed, still not
360 // fixed): the mismatch is NOT an mv/mvstack/entropy bug -- msac
361 // RANGE at the first divergent block (mi=(8,0), frame 1) matches
362 // aomdec's own `EC_PART` trace bit-for-bit (rng=38664 both sides),
363 // and this decoder's own `gm_get_motion_vector` for that block
364 // (ROTZOOM, seed 43's own header) computes the spec-correct
365 // mv=(-8,8) (hand-verified against mv.h's `block_center_x`/`_y`,
366 // which found and fixed a real `- 1` omission in `warp.rs` --
367 // harmless for THIS block's rounding but a genuine spec bug fixed
368 // regardless). The actual gap: `reconinter.c`'s `allow_warp` has a
369 // `global_warp_allowed` branch (`warp_types.global_warp_allowed =
370 // is_global_mv_block(...)`, `reconinter_enc.c:281`) that predicts
371 // an `is_global_mv_block` block (ROTZOOM/AFFINE GLOBALMV, >=8x8)
372 // with the FULL per-pixel affine global-motion warp, independent
373 // of `motion_mode` -- this decoder only ever builds a warp
374 // prediction for local `WARPED_CAUSAL` motion mode and falls back
375 // to plain translational MC with the block-centre mv for every
376 // other GLOBALMV block, which is only a centre-point approximation
377 // of the true per-pixel warp. That is the entire remaining gap.
378 // lane-gm r4: `decode.rs` now feeds `global_motion[ref]` into
379 // `crate::warp::global_warp_params` for every single-ref
380 // `is_global_mv_block` (ROTZOOM/AFFINE), matching `allow_warp`'s
381 // `global_warp_allowed` branch -- ROTZOOM is pin-verified
382 // (`gm-seed43.obu`, frame 1 luma MATCH) and TRANSLATION already
383 // worked (`gm_get_motion_vector`'s translation-only mv, no warp
384 // needed). AFFINE is untested this round (no aomenc fixture in the
385 // wedge gate reached a 6-parameter model) -- keep refusing it by
386 // name rather than shipping an unverified decode.
387 // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom
388 // can never write a 6-parameter model -- its encoder-side search is
389 // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`,
390 // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) --
391 // which is why four rounds of `--enable-global-motion=1` recipes
392 // never reached the case. `scripts/build-aom-affine-oracle.sh` widens
393 // exactly that search range in a side build, and
394 // `a_real_affine_global_motion_stream_decodes_pixel_exact` below
395 // decodes its output pixel-exact against ffmpeg with
396 // `affine_gm_hits() > 0`, i.e. real blocks predicted through the
397 // 6-parameter warp. Nothing in the decoder needed changing: the
398 // header reader already reads params 4/5 with their own subexp refs
399 // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s
400 // shear-validity check + `warp_affine` are model-agnostic.
401 // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two
402 // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and
403 // refused the shape by name rather than guess-fix it. r5 localized
404 // the mismatch to an ordinary NEWMV/GOLDEN block, not the new
405 // global-warp branch at all -- proving "two active slots" was a
406 // correlated symptom, not the cause. r6 range-laddered that block
407 // against aomdec's `EC_TRACE_MODE` (identical `rng` before/after
408 // mode info -- symbol consumption bit-exact) and found the real
409 // defect in `mvstack.rs`'s single-reference predictor fallback:
410 // libaom's `setup_ref_mv_list` fills any `mv_ref_list` slot the real
411 // neighbour scan left short with this block's OWN global motion
412 // vector for its ref (`gm_get_motion_vector`), not zero -- invisible
413 // whenever the live ref's global motion is itself
414 // identity/translation, wrong the moment it's a real ROTZOOM/AFFINE
415 // and the querying block's own stack comes up short (frame 14's
416 // mi=(0,0), the very first block decoded, has no neighbours at
417 // all). Fixed at the predictor fallback; the refusal above (single
418 // untested shape: AFFINE on a single-ref frame) stays, but the
419 // *multi-slot* refusal this comment used to guard is lifted -- the
420 // r5/r6 pin (seed-43 wedge-gate mismatch) now decodes all 24 frames
421 // byte-exact with it gone.
422 // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
423 // `comp_mode` per block whenever this frame's own `reference_select`
424 // header bit is set (spec 5.11.25), and refuse by name the blocks
425 // that pick `COMPOUND_REFERENCE` -- two-reference motion
426 // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
427 // is wired at the block level too (forced NEAREST_NEARESTMV compound
428 // of `skip_mode_frame`, plain average blend), so the old blanket
429 // `skip_mode_present` refusal is gone.
430 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
431 // which tile's end-of-tile adapted CDFs become the frame's own.
432 // lane-tiles r8: this comment used to claim a `!= 0` refusal existed
433 // "further down" -- it did not (`decode.rs` reads
434 // `tile_info.context_update_tile_id` generically at both the
435 // key-frame and inter-frame tile loops' `result_cdfs = cdfs` sites,
436 // never hardcoded to tile 0); stale documentation, not a real gap.
437 // `a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact`
438 // hard-asserts a live aomenc stream naming tile 1/2/3 decodes
439 // pixel-exact, so the capability is now proven as well as described
440 // correctly.
441 //
442 // lane-tiles r4/r6/r7/r8: the multi-tile refusal itself is scoped,
443 // not blanket. `decode_key_frame_tile_with_cdfs` and (r6)
444 // `decode_inter_frame_tile_with_cdfs` both genuinely loop every
445 // tile, `mvstack.rs`'s `MiGrid` is bounded per tile
446 // (`MiGrid::set_tile_bounds`), and `PlaneBuf`'s `tile_x0/y0/x1/y1`
447 // origin receives real values at every call site (r6's
448 // `set_tile_origin` sweep). r7 proved the two remaining
449 // tile-*column* gaps closed (inter frames, >2 columns with loop
450 // filtering on). r8 proved tile *rows* the same way: the per-tile
451 // loop's row math (`tile_num / tile_info.cols`,
452 // `mi_row_starts`/`set_tile_origin`'s `y0`/`y1`) is exactly
453 // symmetric with the column path already proven, and
454 // `a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact`
455 // (bypass gate, loop filter ON) confirmed it: 20/20 pixel-exact.
456 // `a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_
457 // stream` below re-proves it through this entry point. Tile columns
458 // and tile rows (any count, loop filter on) are no longer capped.
459 // `Tile::offset` is relative to the buffer `parse_obu` was handed
460 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
461 // to `obu_offset`, not to `data` as a whole.
462 let tile_bufs: Vec<&[u8]> = tiles
463 .iter()
464 .map(|t| {
465 data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size)
466 .ok_or(Error::NeedMore)
467 })
468 .collect::<Result<_>>()?;
469 let enable_filter_intra = parser
470 .sequence_header()
471 .is_some_and(|seq| seq.enable_filter_intra);
472 let enable_dual_filter = parser
473 .sequence_header()
474 .is_some_and(|seq| seq.enable_dual_filter);
475 let enable_edge_filter = parser
476 .sequence_header()
477 .is_some_and(|seq| seq.enable_intra_edge_filter);
478 // Inter frames' intra blocks read this through a thread-local that only
479 // the key-frame tile path used to set; without this call a stream whose
480 // inter frames are decoded on a thread that previously decoded a
481 // different sequence would inherit that sequence's bit.
482 crate::decode::set_enable_edge_filter(enable_edge_filter);
483 // lane-sb128 r1: `use_128x128_superblock` (spec 5.5.1). The key-frame
484 // tile path reads the 128 partition root and recurses SPLIT into the
485 // four 64x64 quadrants; the inter tile path is still written for a
486 // 64x64 root only (its own superblock loop, OBMC/mvstack neighbour
487 // caps and `read_cdef` reset all key off `SB_MI`), so refuse there by
488 // name rather than desync. A frame at most 64x64 decodes identically
489 // either way (its 128 root reads no symbol -- neither half is in
490 // frame, so SPLIT is inferred), so the refusal is scoped to frames
491 // bigger than one 64x64 superblock.
492 let use_sb128 = parser
493 .sequence_header()
494 .is_some_and(|seq| seq.use_128x128_superblock);
495 let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);
496 crate::decode::set_sb128(sb128_active);
497 if sb128_active && header.frame_type != FrameType::Key {
498 return Err(Error::unsupported(
499 "AV1 decode_stream",
500 "an inter frame under a 128x128 superblock (this decoder's inter tile path recurses a 64x64 superblock root only)",
501 ));
502 }
503 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
504 // which every dequant/inverse-transform clamp reads -- set per frame,
505 // not once per process, for the same cross-sequence-on-one-thread
506 // reason as `set_enable_edge_filter` above. Defaults to 8 when no
507 // sequence header has been seen yet, matching every existing fixture.
508 let bit_depth = parser
509 .sequence_header()
510 .map_or(8, |seq| seq.color_config.bit_depth);
511 // lane-bd12: the sequence-header parser accepts `twelve_bit`, but every
512 // rounding shift below is written for 8/10-bit only -- `warp.rs`'s
513 // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses
514 // `round_0 + max(bd + FILTER_BITS - round_0 - 14, 0)` (5 at bd 12), the
515 // MC `round_0`/`round_1` change at 12-bit (libaom convolve.h:83), the
516 // Wiener rounding bits change, and neither CDEF nor film grain has a
517 // 12-bit path. Refuse by name rather than decode silently wrong pixels.
518 if bit_depth == 12 {
519 return Err(Error::unsupported(
520 "AV1 decode_stream",
521 "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)",
522 ));
523 }
524 crate::decode::set_bit_depth(bit_depth);
525 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
526 let enable_masked_compound = parser
527 .sequence_header()
528 .is_some_and(|seq| seq.enable_masked_compound);
529 let enable_jnt_comp = parser
530 .sequence_header()
531 .is_some_and(|seq| seq.enable_jnt_comp);
532 // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's
533 // read site doc.
534 let enable_interintra_compound = parser
535 .sequence_header()
536 .is_some_and(|seq| seq.enable_interintra_compound);
537 let interp_fixed = match header.interpolation_filter {
538 ec_av1_syntax::InterpolationFilter::Switchable => None,
539 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
540 };
541 // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
542 // from that reference slot's saved CDF state instead of the spec 8.4
543 // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
544 // builds.
545 let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
546 None
547 } else {
548 let slot = header.ref_frame_idx[header.primary_ref_frame as usize] as usize;
549 Some(cdf_slots[slot].clone().ok_or_else(|| {
550 Error::unsupported(
551 "AV1 decode_stream",
552 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
553 )
554 })?)
555 };
556 let started_from = initial_cdfs.clone();
557
558 let order_hint_bits = parser
559 .sequence_header()
560 .map_or(0, |seq| seq.order_hint_bits);
561 // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
562 // of the picture sitting in each of its 7 single references' DPB
563 // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
564 // (a later frame projects from it) whether or not this frame itself
565 // reads temporal candidates.
566 let ref_order_hints: [u32; 7] =
567 std::array::from_fn(|i| order_hint_slots[header.ref_frame_idx[i] as usize]);
568
569 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
570 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
571 &tile_bufs,
572 &header.tile_info,
573 header.mi_cols,
574 header.mi_rows,
575 header.quantization.base_q_idx,
576 crate::quant::QuantDeltas {
577 y_dc: i32::from(header.quantization.delta_q_y_dc),
578 u_dc: i32::from(header.quantization.delta_q_u_dc),
579 u_ac: i32::from(header.quantization.delta_q_u_ac),
580 v_dc: i32::from(header.quantization.delta_q_v_dc),
581 v_ac: i32::from(header.quantization.delta_q_v_ac),
582 },
583 header.frame_width,
584 header.frame_height,
585 enable_filter_intra,
586 enable_edge_filter,
587 &header.cdef,
588 &header.loop_filter,
589 &header.loop_restoration,
590 initial_cdfs,
591 header.tx_mode == TxMode::Select,
592 header.reduced_tx_set,
593 header.allow_screen_content_tools,
594 header.allow_intrabc,
595 header.delta,
596 )?;
597 // lane-superres stage 3, spec 7.16: upscale AFTER deblock+CDEF
598 // (both already applied inside `decode_key_frame_tile_with_cdfs`)
599 // and BEFORE this picture is stored as a reference or handed to
600 // the caller -- loop restoration is not yet ported, so there is
601 // no LR step here for the upscale to precede.
602 // r3: the real decoded margin beyond `frame_width` (set by the
603 // call above, right before anything else can overwrite it) --
604 // see `decode::take_last_frame_wide_margin`'s doc.
605 let wide_margin = crate::decode::take_last_frame_wide_margin();
606 let picture = if header.use_superres {
607 crate::superres::upscale_picture(
608 &picture,
609 header.upscaled_width as usize,
610 wide_margin.as_ref(),
611 bit_depth as u32,
612 )
613 } else {
614 picture
615 };
616 // A key frame codes no inter blocks -- its own saved motion
617 // field has no cells set, matching libaom's own "intra frame
618 // contributes nothing to a later projection" behaviour, but
619 // still carries `order_hint`/`ref_order_hints` for the distance
620 // arithmetic a later frame's projection needs.
621 let motion_field = crate::motion_field::MotionField::new(
622 header.mi_cols as usize,
623 header.mi_rows as usize,
624 header.order_hint,
625 ref_order_hints,
626 );
627 (picture, end_cdfs, motion_field)
628 } else {
629 let last_slot = header.ref_frame_idx[0] as usize;
630 let reference = ref_slots[last_slot].as_ref().ok_or_else(|| {
631 Error::unsupported(
632 "AV1 decode_stream",
633 "an inter frame with no key frame before it",
634 )
635 })?;
636 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
637 // (spec 7.8/7.20). Any of them having no picture yet is not a
638 // stream error on its own: `decode_inter_block` only needs a
639 // given slot when a block actually selects that reference, and
640 // refuses by name there if the slot is still empty -- widened
641 // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
642 // one of the 7 single-reference slots.
643 // lane-fimv r1: record the header state the fimv gate asserts on
644 // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause).
645 if header.force_integer_mv {
646 decode::note_force_integer_mv_frame();
647 }
648 let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| {
649 if ref_frame == 0 {
650 None
651 } else {
652 ref_slots
653 .get(header.ref_frame_idx[ref_frame - 1] as usize)
654 .and_then(Option::as_ref)
655 }
656 });
657 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
658 // this frame's header actually asks for temporal candidates --
659 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
660 // behaviour bit for bit when this is `None` (see its own doc).
661 let tpl_field = header.use_ref_frame_mvs.then(|| {
662 crate::motion_field::setup_motion_field(
663 &motion_field_slots,
664 header.ref_frame_idx,
665 header.order_hint,
666 order_hint_bits,
667 header.mi_rows as usize,
668 header.mi_cols as usize,
669 )
670 });
671 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
672 &tile_bufs,
673 &header.tile_info,
674 header.mi_cols,
675 header.mi_rows,
676 header.quantization.base_q_idx,
677 crate::quant::QuantDeltas {
678 y_dc: i32::from(header.quantization.delta_q_y_dc),
679 u_dc: i32::from(header.quantization.delta_q_u_dc),
680 u_ac: i32::from(header.quantization.delta_q_u_ac),
681 v_dc: i32::from(header.quantization.delta_q_v_dc),
682 v_ac: i32::from(header.quantization.delta_q_v_ac),
683 },
684 header.frame_width,
685 header.frame_height,
686 reference,
687 other_refs,
688 &header.cdef,
689 &header.loop_filter,
690 &header.loop_restoration,
691 initial_cdfs,
692 header.allow_high_precision_mv,
693 header.force_integer_mv,
694 header.ref_frame_sign_bias,
695 header.global_motion,
696 interp_fixed,
697 enable_dual_filter,
698 order_hint_bits,
699 header.order_hint,
700 ref_order_hints,
701 tpl_field.as_ref(),
702 header.reference_select,
703 enable_masked_compound,
704 enable_jnt_comp,
705 enable_interintra_compound,
706 header.skip_mode_present,
707 header.skip_mode_frame,
708 header.reduced_tx_set,
709 header.tx_mode == TxMode::Select,
710 header.is_motion_mode_switchable,
711 header.allow_warped_motion,
712 header.allow_screen_content_tools,
713 header.delta,
714 )?;
715 // lane-superres r10: mirrors the key-frame branch above --
716 // `decode_inter_frame_tile_with_cdfs` decodes at the downscaled
717 // `frame_width`/`frame_height` and crops to it; upscale AFTER
718 // (deblock/CDEF/LR already applied inside that call) BEFORE this
719 // picture is stored as a reference or shown, same margin
720 // mechanism (`take_last_frame_wide_margin`, read immediately
721 // after the call, before any other frame decode can overwrite
722 // it).
723 let wide_margin = crate::decode::take_last_frame_wide_margin();
724 let picture = if header.use_superres {
725 crate::superres::upscale_picture(
726 &picture,
727 header.upscaled_width as usize,
728 wide_margin.as_ref(),
729 bit_depth as u32,
730 )
731 } else {
732 picture
733 };
734 (picture, end_cdfs, motion_field)
735 };
736 // lane-lr r4: the Wiener/self-guided pixel filters are wired
737 // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
738 // `uses_lr` frames now decode all the way to pixels.
739 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
740 // *initial* table into the slots it refreshes, not the adapted
741 // end-of-tile one.
742 let stored_cdfs = if header.disable_frame_end_update_cdf {
743 started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
744 } else {
745 // Spec 7.20 `save_cdfs` (libaom `av1_reset_cdf_symbol_counters`):
746 // the adapted table is saved with every symbol counter zeroed,
747 // not with the counts the tile's own decode left behind.
748 let mut end_cdfs = end_cdfs;
749 end_cdfs.reset_counts();
750 end_cdfs
751 };
752 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
753 use std::io::Write;
754 if let Ok(mut f) = std::fs::OpenOptions::new()
755 .create(true)
756 .append(true)
757 .open(&path)
758 {
759 let _ = writeln!(f, "=== frame idx={} ===", pictures.len());
760 let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
761 let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
762 let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
763 let _ = writeln!(f, "skip {:?}", stored_cdfs.skip);
764 let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv);
765 let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv);
766 let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv);
767 let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint);
768 }
769 }
770 // lane-comppin r3: decode-order (not display-order) dump of every
771 // frame's own post-deblock buffer -- the pre-existing pixel diff
772 // (`scratch_isolate_pinned_mismatch`) only ever compares *shown*
773 // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a
774 // later shown frame is otherwise invisible; diff this byte-for-byte
775 // against `EC_AV1_POSTFILT_DUMP.fN` from the instrumented aomdec
776 // build to isolate whether the defect is in a hidden frame's own
777 // reconstruction or downstream of it.
778 if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") {
779 use std::io::Write;
780 let idx = pictures_decoded;
781 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
782 // lane-hbd r4: debug dump narrows to u8 -- this diagnostic
783 // predates 10-bit support and is an 8-bit-oracle comparison
784 // only (aomdec's own dump is 8-bit here too).
785 let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
786 let _ = f.write_all(&narrow(&picture.y));
787 let _ = f.write_all(&narrow(&picture.u));
788 let _ = f.write_all(&narrow(&picture.v));
789 }
790 }
791 // lane-hidden r1: the frame exactly as it is about to be stored into
792 // the reference slots -- after deblock/CDEF/LR/superres, in DECODE
793 // order, hidden (`show_frame == 0`) alt-ref frames included, and
794 // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the
795 // u8-narrowing diagnostic dumps above. Matches the instrumented
796 // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte
797 // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a
798 // hidden frame's pixels comparable at all.
799 if let Some(prefix) = &final_dump {
800 use std::io::Write;
801 if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{pictures_decoded}")) {
802 let mut buf = Vec::new();
803 for plane in [&picture.y, &picture.u, &picture.v] {
804 if bit_depth == 8 {
805 buf.extend(plane.iter().map(|&s| s as u8));
806 } else {
807 for &s in plane {
808 buf.extend_from_slice(&s.to_le_bytes());
809 }
810 }
811 }
812 let _ = f.write_all(&buf);
813 }
814 }
815 pictures_decoded += 1;
816 let decoded_seg_map = decode::take_segment_ids();
817 for i in 0..NUM_REF_FRAMES {
818 if header.refresh_frame_flags & (1 << i) != 0 {
819 cdf_slots[i] = Some(stored_cdfs.clone());
820 // Spec 7.18.3.1: synthesized grain is never stored for later
821 // prediction -- the reference bank always keeps the clean,
822 // pre-grain decode, even though the frame pushed onto the
823 // caller's output below carries the grained picture.
824 ref_slots[i] = Some(picture.clone());
825 motion_field_slots[i] = Some(motion_field.clone());
826 seg_map_slots[i] = Some(decoded_seg_map.clone());
827 order_hint_slots[i] = header.order_hint;
828 }
829 }
830 // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a
831 // KEY frame coded with `show_frame == 0`, output later by a
832 // `show_existing_frame` header -- counted only once its tiles have
833 // decoded, so the gate's assert covers decoded-and-compared frames.
834 if header.frame_type == FrameType::Key && !header.show_frame {
835 decode::note_fwd_kf();
836 }
837 if header.show_frame {
838 let output = if header.film_grain.apply_grain {
839 let mc_identity = parser
840 .sequence_header()
841 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
842 crate::film_grain::apply_grain(
843 &picture,
844 &header.film_grain,
845 mc_identity,
846 bit_depth as u32,
847 )
848 } else {
849 picture
850 };
851 pictures.push(output);
852 }
853 }
854 Ok(pictures)
855}
856
857#[cfg(test)]
858mod tests {
859 use super::*;
860 use crate::encode::{Picture as Pic, encode_key_frame, encode_sequence};
861
862 fn test_card(width: usize, height: usize) -> Pic {
863 let mut picture = Pic::grey(width, height);
864 for row in 0..height {
865 for col in 0..width {
866 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
867 }
868 }
869 for row in 0..height / 2 {
870 for col in 0..width / 2 {
871 let i = row * width / 2 + col;
872 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
873 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
874 }
875 }
876 picture
877 }
878
879 fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic {
880 let mut picture = Pic::grey(width, height);
881 for y in 0..height {
882 for x in 0..width {
883 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
884 let gradient = sx * 200.0 / width as f64;
885 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
886 }
887 }
888 for y in 0..height / 2 {
889 for x in 0..width / 2 {
890 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
891 let i = y * width / 2 + x;
892 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
893 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
894 }
895 }
896 picture
897 }
898
899 /// A stream whose sequence header says `twelve_bit` is refused by name
900 /// rather than decoded with the 8/10-bit rounding shifts (`warp.rs`'s
901 /// hard `REDUCE_BITS_HORIZ = 3`, MC/Wiener round bits, ungated CDEF and
902 /// film grain). Reachability, not a pixel claim: the header is written at
903 /// `seq_profile = 2` so `twelve_bit` is actually coded, and the frame's
904 /// tile payload is never reached.
905 #[test]
906 fn a_twelve_bit_sequence_header_is_refused_by_name() {
907 let picture = test_card(64, 64);
908 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
909 let mut color = ec_av1_syntax::ColorConfig {
910 bit_depth: 12,
911 ..Default::default()
912 };
913 color.num_planes = 3;
914 // Only seq_profile 2 codes the `twelve_bit` bit (spec 5.5.2).
915 let (mut seq, header) =
916 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
917 seq.seq_profile = 2;
918 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
919 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap());
920
921 let err = decode_stream(&stream).unwrap_err().to_string();
922 assert!(
923 err.contains(
924 "a bit depth of 12 (this decoder is gated at 8 and 10 only: \
925 warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)"
926 ),
927 "expected the 12-bit refusal, got: {err}"
928 );
929 }
930
931 /// `decode_stream` on a lone key frame's stream matches both the tile
932 /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and
933 /// the encoder's own reconstruction, at an even and an odd size.
934 #[test]
935 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
936 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
937 let picture = test_card(width, height);
938 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
939 let via_tile = decode_key_frame_tile(
940 &encoded.tile,
941 encoded.mi_cols,
942 encoded.mi_rows,
943 encoded.base_q_idx,
944 width as u32,
945 height as u32,
946 false,
947 &ec_av1_syntax::CdefParams::default(),
948 &ec_av1_syntax::LoopFilterParams::default(),
949 false,
950 // Our own encoder always writes `reduced_tx_set: true`.
951 true,
952 false,
953 false,
954 )
955 .unwrap();
956 let via_stream = decode_stream(&encoded.stream).unwrap();
957 assert_eq!(via_stream.len(), 1, "{width}x{height}: one picture");
958 assert_eq!(via_stream[0].y, via_tile.y, "{width}x{height}: luma");
959 assert_eq!(via_stream[0].u, via_tile.u, "{width}x{height}: U");
960 assert_eq!(via_stream[0].v, via_tile.v, "{width}x{height}: V");
961 assert_eq!(
962 via_stream[0].y, encoded.reconstruction.y,
963 "{width}x{height}: luma vs encoder reconstruction"
964 );
965 }
966 }
967
968 /// A GOP (key frame plus panned inter frames, so blocks actually take
969 /// motion) decodes bit-exact through `decode_stream` alone, threading its
970 /// own DPB rather than a test-supplied reference.
971 fn gop_round_trips(width: usize, height: usize) {
972 let pictures: Vec<_> = (0..4)
973 .map(|i| panned_test_card(width, height, i * 3))
974 .collect();
975 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
976 let decoded = decode_stream(&encoded.stream).unwrap();
977 assert_eq!(decoded.len(), encoded.frames.len());
978 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
979 assert_eq!(
980 got.y, frame.reconstruction.y,
981 "{width}x{height} frame {i} luma"
982 );
983 assert_eq!(
984 got.u, frame.reconstruction.u,
985 "{width}x{height} frame {i} U"
986 );
987 assert_eq!(
988 got.v, frame.reconstruction.v,
989 "{width}x{height} frame {i} V"
990 );
991 }
992 }
993
994 #[test]
995 fn decode_stream_round_trips_a_gop() {
996 gop_round_trips(128, 64);
997 }
998
999 /// Same claim at a size that is not a whole number of 32x32 blocks, so
1000 /// the inter frame's 16x16-leaf split path is exercised too.
1001 #[test]
1002 fn decode_stream_round_trips_an_odd_size_gop() {
1003 gop_round_trips(216, 96);
1004 }
1005
1006 use std::io::Write;
1007 use std::process::{Command, Stdio};
1008
1009 /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`,
1010 /// `skip_mode`/compound) all read a process-global atomic counter delta
1011 /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to
1012 /// prove a real block picked the feature under test, not just that a
1013 /// header bit was set. Under `cargo test`'s default parallel run, a
1014 /// SIBLING test's own decode bumps the same global counter mid-gate --
1015 /// a false "fired" reading pixel-compares an attempt the gate would
1016 /// otherwise `continue` past, on top of genuine defects that path may
1017 /// still have. Serialising every counter-delta gate behind this one
1018 /// mutex makes firing detection honest again (matches the existing
1019 /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`).
1020 static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1021 /// Three-bucket gate summary (class [[gate-skips-on-its-own-failure]]):
1022 /// every attempt lands in exactly one bucket -- decoded pixel-exact WITH
1023 /// the feature counter moving, decoded pixel-exact WITHOUT it, or a named
1024 /// refusal -- and the three sum to the attempts made.
1025 fn gate_buckets(name: &str, counted_exact: u32, uncounted_exact: u32, named_refusals: usize) {
1026 eprintln!(
1027 "{name}: buckets counted-exact={counted_exact} uncounted-exact={uncounted_exact} \
1028 named-refusals={named_refusals} (attempts {})",
1029 counted_exact as usize + uncounted_exact as usize + named_refusals
1030 );
1031 }
1032
1033 fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
1034 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
1035 }
1036
1037 /// lane-cdfflake: a cheap, dependency-free (FNV-1a, not cryptographic --
1038 /// this is a load-bearing-identity fingerprint for flake triage, not a
1039 /// security digest, so no `sha2` dep is pulled in) fixture fingerprint
1040 /// for the cdf-forwarding gate's instrumentation below.
1041 fn fnv1a64(bytes: &[u8]) -> u64 {
1042 let mut hash = 0xcbf29ce484222325u64;
1043 for &b in bytes {
1044 hash ^= b as u64;
1045 hash = hash.wrapping_mul(0x100000001b3);
1046 }
1047 hash
1048 }
1049
1050 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
1051 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
1052 /// aomenc gate decodes its stream through ffmpeg and is meaningless
1053 /// without it -- turns it into a hard failure. Without this the require
1054 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
1055 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
1056 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
1057 fn have_ffmpeg() -> bool {
1058 let present = Command::new("ffmpeg")
1059 .arg("-version")
1060 .stdout(Stdio::null())
1061 .stderr(Stdio::null())
1062 .status()
1063 .is_ok_and(|s| s.success());
1064 assert!(
1065 present
1066 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
1067 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
1068 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
1069 );
1070 present
1071 }
1072
1073 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
1074 fn ffmpeg_decode_sequence(
1075 stream: &[u8],
1076 width: usize,
1077 height: usize,
1078 frames: usize,
1079 ) -> Vec<Pic> {
1080 let mut child = Command::new("ffmpeg")
1081 .args([
1082 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
1083 ])
1084 .stdin(Stdio::piped())
1085 .stdout(Stdio::piped())
1086 .stderr(Stdio::piped())
1087 .spawn()
1088 .expect("ffmpeg failed to start");
1089 child
1090 .stdin
1091 .take()
1092 .expect("ffmpeg stdin")
1093 .write_all(stream)
1094 .expect("writing the stream to ffmpeg");
1095 let out = child.wait_with_output().expect("ffmpeg failed to run");
1096 assert!(
1097 out.status.success(),
1098 "ffmpeg refused the stream: {}",
1099 String::from_utf8_lossy(&out.stderr)
1100 );
1101 let (luma, chroma) = (width * height, width * height / 4);
1102 let frame_bytes = luma + 2 * chroma;
1103 assert_eq!(
1104 out.stdout.len(),
1105 frame_bytes * frames,
1106 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
1107 String::from_utf8_lossy(&out.stderr)
1108 );
1109 (0..frames)
1110 .map(|i| {
1111 let base = i * frame_bytes;
1112 Pic {
1113 width,
1114 height,
1115 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
1116 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
1117 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
1118 }
1119 })
1120 .collect()
1121 }
1122
1123 /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples
1124 /// are 2-byte little-endian, one full 16-bit range regardless of the
1125 /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the
1126 /// bit depth). The 8-bit helper above stays untouched -- every existing
1127 /// gate depends on it.
1128 fn ffmpeg_decode_sequence_10bit(
1129 stream: &[u8],
1130 width: usize,
1131 height: usize,
1132 frames: usize,
1133 ) -> Vec<Pic> {
1134 let mut child = Command::new("ffmpeg")
1135 .args([
1136 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt",
1137 "yuv420p10le", "-",
1138 ])
1139 .stdin(Stdio::piped())
1140 .stdout(Stdio::piped())
1141 .stderr(Stdio::piped())
1142 .spawn()
1143 .expect("ffmpeg failed to start");
1144 child
1145 .stdin
1146 .take()
1147 .expect("ffmpeg stdin")
1148 .write_all(stream)
1149 .expect("writing the stream to ffmpeg");
1150 let out = child.wait_with_output().expect("ffmpeg failed to run");
1151 assert!(
1152 out.status.success(),
1153 "ffmpeg refused the stream: {}",
1154 String::from_utf8_lossy(&out.stderr)
1155 );
1156 let (luma, chroma) = (width * height, width * height / 4);
1157 let frame_samples = luma + 2 * chroma;
1158 let frame_bytes = frame_samples * 2;
1159 assert_eq!(
1160 out.stdout.len(),
1161 frame_bytes * frames,
1162 "expected {frames} 4:2:0 10-bit frames, ffmpeg said: {}",
1163 String::from_utf8_lossy(&out.stderr)
1164 );
1165 fn le16(bytes: &[u8]) -> Vec<u16> {
1166 bytes
1167 .chunks_exact(2)
1168 .map(|c| u16::from_le_bytes([c[0], c[1]]))
1169 .collect()
1170 }
1171 (0..frames)
1172 .map(|i| {
1173 let base = i * frame_bytes;
1174 Pic {
1175 width,
1176 height,
1177 y: le16(&out.stdout[base..base + luma * 2]),
1178 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
1179 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
1180 }
1181 })
1182 .collect()
1183 }
1184
1185 /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an
1186 /// independent decoder, not just this crate checking its own tile path.
1187 #[test]
1188 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
1189 if !have_ffmpeg() {
1190 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
1191 return;
1192 }
1193 let (width, height) = (128usize, 64usize);
1194 let pictures: Vec<_> = (0..3)
1195 .map(|i| panned_test_card(width, height, i * 3))
1196 .collect();
1197 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
1198 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
1199 let decoded = decode_stream(&encoded.stream).unwrap();
1200 assert_eq!(decoded.len(), 3);
1201 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
1202 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");
1203 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");
1204 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");
1205 }
1206 }
1207
1208 /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME`
1209 /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s
1210 /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc
1211 /// attempts never could: frame 0 is a real key frame (this crate's own
1212 /// encoder, real texture), refreshing all 8 DPB slots as spec requires --
1213 /// slot 3 keeps that exact picture from here on. Frame 1 is a hand-coded
1214 /// inter frame whose lone 32x32 block is *intra* (`DC_PRED`, `skip`),
1215 /// refreshing only slot 0 with a flat 128 block -- distinguishable from
1216 /// frame 0's real texture, so slot 0 (`LAST_FRAME`) and slot 3
1217 /// (`GOLDEN_FRAME`) hold visibly different pictures once frame 2 runs.
1218 /// Frame 2 is a hand-coded inter frame naming `ref_frame_idx[3] = 3`
1219 /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose
1220 /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME`
1221 /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy
1222 /// of GOLDEN's picture, so its output must equal frame 0's own
1223 /// reconstruction exactly, and must differ from frame 1's -- proof the
1224 /// decoder actually read the golden plane, not silently substituted
1225 /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a
1226 /// deblock/MC residue that turned out to be film-grain synthesis
1227 /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN);
1228 /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing
1229 /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so
1230 /// this fixture flips back to its round-4 pixel-exact form. ffmpeg
1231 /// decodes the identical wire bytes as the foreign oracle
1232 /// (shared-oracle-blindness class): this crate's own decoder agreeing
1233 /// with itself would prove nothing.
1234 #[test]
1235 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
1236 if !have_ffmpeg() {
1237 eprintln!(
1238 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
1239 );
1240 return;
1241 }
1242 use crate::cdf_state::Cdfs;
1243 use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of};
1244 use crate::encode::{inter_frame_headers, key_frame_headers};
1245 use crate::frame::frame_obu;
1246 use crate::msac::SymbolEncoder;
1247 use crate::mvstack::{
1248 GOLDEN_FRAME, MiGrid, find_mv_stack, single_ref_p1_ctx, single_ref_p3_ctx,
1249 single_ref_p5_ctx,
1250 };
1251 use crate::obu::temporal_delimiter;
1252
1253 let (width, height) = (32usize, 32usize);
1254 let base_q_idx = 100u8;
1255 // The whole picture is one 32x32 block: `partition_ctx`/`skip_ctx`/
1256 // `intra_inter_ctx`'s neighbour inputs are all "no neighbour yet" --
1257 // a fresh `Neighbours`' `above_side_mi`/`left_side_mi` start at `SB`
1258 // (64), so `partition_ctx_mi`'s `side_mi * 2 <= side` (32) is false
1259 // on both axes (ctx 0), and `above_skip`/`left_skip`/`above_inter`/
1260 // `left_inter`/`above_ref`/`left_ref` all start `false`/`-1`
1261 // (decode.rs `Neighbours::new`) -- computed here without
1262 // constructing the (module-private) `Neighbours` itself.
1263 const PARTITION_NONE: usize = 0;
1264 let ii_ctx = intra_inter_ctx(false, false, false, false);
1265 let sr_p1_ctx = single_ref_p1_ctx(None, None, None, None);
1266 let sr_p3_ctx = single_ref_p3_ctx(None, None, None, None);
1267 let sr_p5_ctx = single_ref_p5_ctx(None, None, None, None);
1268
1269 for run in 0..4 {
1270 let picture = test_card(width, height);
1271 let key = encode_key_frame(&picture, base_q_idx, 0.5).unwrap();
1272 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
1273
1274 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
1275 // 128 block (no neighbours to predict `DC_PRED` from).
1276 let (_, header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
1277 let tile1 = {
1278 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1279 let mut enc = SymbolEncoder::new();
1280 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
1281 enc.symbol(1, &mut cdfs.skip[0]); // skip
1282 enc.symbol(0, &mut cdfs.intra_inter[ii_ctx]); // is_inter = false
1283 enc.symbol(0, &mut cdfs.y_mode[3]); // DC_PRED, size group 3 (32x32)
1284 enc.symbol(0, &mut cdfs.uv_mode_cfl[0]); // DC_PRED
1285 enc.finish()
1286 };
1287 let mut stream = key.stream.clone();
1288 stream.extend(temporal_delimiter());
1289 stream.extend(frame_obu(&seq, &header1, &tile1).unwrap());
1290
1291 // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME,
1292 // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0).
1293 let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap();
1294 header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1
1295 let tile2 = {
1296 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1297 let mut enc = SymbolEncoder::new();
1298 let grid = MiGrid::new(8, 8);
1299 let stack = find_mv_stack(&grid, 0, 0, 8, 8, GOLDEN_FRAME, 8, 8);
1300 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
1301 enc.symbol(1, &mut cdfs.skip[0]); // skip
1302 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter = true
1303 enc.symbol(0, &mut cdfs.single_ref[sr_p1_ctx][0]); // p1: LAST/LAST2/LAST3/GOLDEN group
1304 enc.symbol(1, &mut cdfs.single_ref[sr_p3_ctx][2]); // p3: GOLDEN/LAST3 sub-group
1305 enc.symbol(1, &mut cdfs.single_ref[sr_p5_ctx][4]); // p5: GOLDEN_FRAME
1306 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new -> not NEWMV
1307 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero -> not GLOBALMV
1308 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // nearest -> NEARESTMV, (0, 0)
1309 enc.finish()
1310 };
1311 stream.extend(temporal_delimiter());
1312 stream.extend(frame_obu(&seq, &header2, &tile2).unwrap());
1313
1314 let before = non_last_ref_hits();
1315 let decoded = decode_stream(&stream).unwrap();
1316 assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures");
1317 assert!(
1318 non_last_ref_hits() > before,
1319 "run {run}: GOLDEN_FRAME never fired"
1320 );
1321
1322 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3);
1323 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
1324 assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg");
1325 assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg");
1326 assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg");
1327 }
1328 assert_eq!(
1329 decoded[0].y, key.reconstruction.y,
1330 "run {run}: frame 0 vs the encoder's own reconstruction"
1331 );
1332 assert_eq!(
1333 decoded[2].y, key.reconstruction.y,
1334 "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names"
1335 );
1336 assert_ne!(
1337 decoded[2].y, decoded[1].y,
1338 "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \
1339 distinguishable -- the gate proves nothing"
1340 );
1341 }
1342 }
1343
1344 /// Builds a `gradients` lavfi source string with colours derived from
1345 /// `seed`, not left to the filter's own default.
1346 ///
1347 /// Measured (lane-fixdet r1): ffmpeg's `gradients` source IGNORES its
1348 /// `seed=` parameter for colour selection -- five encodes of an
1349 /// identical command line (same `seed=`, same everything) produced five
1350 /// different fixtures, because the unset `c0..c9` stops are randomized
1351 /// from something other than that seed. Every one of this file's ~20
1352 /// gate fixtures built a `gradients` source this way, so none of them
1353 /// had a reproducible input: a pin captured from one run could not be
1354 /// regenerated, and "attempt N failed" was as likely to be a different
1355 /// fixture as a different decode outcome.
1356 ///
1357 /// Freezing the colours outright (as the earliest four gates below do,
1358 /// hand-picking `c0=red:c1=blue:c2=green`) fixes reproducibility but
1359 /// throws away the per-attempt content variety the sweep gates need to
1360 /// make features (OBMC, warp, wedge, ...) fire at all -- this repo's own
1361 /// `sampler-decorrelated-gate` class. So: derive `c0..c3` deterministically
1362 /// FROM the seed with a plain integer hash, and keep passing `seed=`
1363 /// itself too, so a future ffmpeg that actually honours it only adds
1364 /// more variety, never removes the determinism this buys.
1365 fn gradients_source(seed: u32, width: usize, height: usize, tail: &str) -> String {
1366 fn hash_color(seed: u32, salt: u32) -> String {
1367 let h = seed
1368 .wrapping_mul(2_654_435_761)
1369 .wrapping_add(salt.wrapping_mul(0x9E37_79B9))
1370 ^ (seed.rotate_left(13));
1371 format!("0x{:06x}", h & 0x00ff_ffff)
1372 }
1373 let (c0, c1, c2, c3) = (
1374 hash_color(seed, 0),
1375 hash_color(seed, 1),
1376 hash_color(seed, 2),
1377 hash_color(seed, 3),
1378 );
1379 format!("gradients=size={width}x{height}:c0={c0}:c1={c1}:c2={c2}:c3={c3}:seed={seed}:{tail}")
1380 }
1381
1382 /// The determinism guard: same seed twice must byte-match ffmpeg's own
1383 /// output; different seeds must not. Regresses this fix if it ever
1384 /// breaks.
1385 #[test]
1386 fn gradients_source_is_reproducible_per_seed() {
1387 if !have_ffmpeg() {
1388 eprintln!("SKIP gradients_source_is_reproducible_per_seed: no ffmpeg");
1389 return;
1390 }
1391 fn render_hash(lavfi: &str) -> Vec<u8> {
1392 let out = Command::new("ffmpeg")
1393 .args([
1394 "-v", "error", "-f", "lavfi", "-i", lavfi, "-frames:v", "1", "-f", "rawvideo",
1395 "-",
1396 ])
1397 .stdin(Stdio::null())
1398 .stdout(Stdio::piped())
1399 .stderr(Stdio::piped())
1400 .output()
1401 .expect("ffmpeg failed to run");
1402 assert!(out.status.success(), "ffmpeg refused {lavfi}");
1403 out.stdout
1404 }
1405 let a1 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
1406 let a2 = render_hash(&gradients_source(43, 64, 64, "duration=0.04:rate=25"));
1407 let a3 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
1408 assert_eq!(a1, a3, "same seed must reproduce byte-identical output");
1409 assert_ne!(a1, a2, "different seeds must not collide");
1410 }
1411
1412 /// Encodes a real libaom-av1 stream (via ffmpeg's own encoder, not this
1413 /// crate's) with the same reduced-partition flags lane-av1adst's r6
1414 /// probe found still select `ADST_ADST`/`ADST_DCT`/`DCT_ADST` on
1415 /// gradient content (TX_SET_INTRA_2), and decodes it with
1416 /// [`decode_stream`] -- lifting the round-2 refusal is only real if it
1417 /// gets past an encoder this crate never wrote a byte of.
1418 fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {
1419 libaom_encode_with(lavfi, width, height, crf, &[])
1420 }
1421
1422 /// As [`libaom_encode`], with extra encoder args appended -- used to pin
1423 /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8`
1424 /// RD search is not otherwise stable run-to-run on this box, and lavfi
1425 /// `gradients` needs its own `seed=` for the same reason) and to gate
1426 /// individual feature flags (`-enable-cdef 0`) a given fixture needs off.
1427 fn libaom_encode_with(
1428 lavfi: &str,
1429 width: usize,
1430 height: usize,
1431 crf: u32,
1432 extra: &[&str],
1433 ) -> Option<Vec<u8>> {
1434 let mut args = vec![
1435 "-v",
1436 "error",
1437 "-f",
1438 "lavfi",
1439 "-i",
1440 lavfi,
1441 "-frames:v",
1442 "1",
1443 "-pix_fmt",
1444 "yuv420p",
1445 "-c:v",
1446 "libaom-av1",
1447 ];
1448 let crf_str = crf.to_string();
1449 args.extend(["-crf", &crf_str]);
1450 args.extend([
1451 "-cpu-used",
1452 "8",
1453 "-enable-rect-partitions",
1454 "0",
1455 "-enable-ab-partitions",
1456 "0",
1457 "-enable-1to4-partitions",
1458 "0",
1459 "-enable-angle-delta",
1460 "0",
1461 "-enable-cfl-intra",
1462 "0",
1463 ]);
1464 args.extend(extra.iter().copied());
1465 args.extend(["-f", "obu", "-"]);
1466 let out = Command::new("ffmpeg")
1467 .args(&args)
1468 .stdin(Stdio::null())
1469 .stdout(Stdio::piped())
1470 .stderr(Stdio::piped())
1471 .output()
1472 .expect("ffmpeg failed to run");
1473 if !out.status.success() {
1474 eprintln!(
1475 "ffmpeg refused to encode {lavfi} at {width}x{height}: {}",
1476 String::from_utf8_lossy(&out.stderr)
1477 );
1478 return None;
1479 }
1480 Some(out.stdout)
1481 }
1482
1483 /// The end-to-end gate: two real libaom-av1 configs, decoded with
1484 /// [`decode_stream`] and checked against ffmpeg's own decode of the same
1485 /// bytes. Not every config this encoder writes decodes yet (partitions
1486 /// below 16x16, AB partitions, CfL and others remain round-2 gaps per the
1487 /// r6 catalogue) -- both configs here pick `cpu-used 8` plus the
1488 /// partition/angle-delta/CfL flags r6 found narrow the encoder onto this
1489 /// decoder's supported syntax, while still landing on non-`DCT_DCT` tx
1490 /// types on gradient content.
1491 #[test]
1492 fn a_real_libaom_stream_with_adst_decodes_end_to_end() {
1493 if !have_ffmpeg() {
1494 eprintln!("SKIP a_real_libaom_stream_with_adst_decodes_end_to_end: no ffmpeg");
1495 return;
1496 }
1497 let configs: [(String, usize, usize, u32); 2] = [
1498 ("testsrc2=size=64x64:rate=1".to_string(), 64, 64, 15),
1499 (gradients_source(42, 64, 64, "rate=1"), 64, 64, 15),
1500 ];
1501 let mut verdicts = Vec::new();
1502 for (lavfi, width, height, crf) in configs {
1503 let lavfi = lavfi.as_str();
1504 let Some(stream) = libaom_encode(lavfi, width, height, crf) else {
1505 verdicts.push(format!("{lavfi}: ffmpeg itself refused to encode"));
1506 continue;
1507 };
1508 match decode_stream(&stream) {
1509 Ok(frames) => {
1510 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1511 let matches = frames[0].y == ffmpeg_frames[0].y
1512 && frames[0].u == ffmpeg_frames[0].u
1513 && frames[0].v == ffmpeg_frames[0].v;
1514 verdicts.push(format!(
1515 "{lavfi}: decoded, {} ffmpeg's own decode",
1516 if matches { "MATCHES" } else { "MISMATCHES" }
1517 ));
1518 // Not a hard `assert!`: libaom's own mode decisions at
1519 // `cpu-used 8` are not observed stable run-to-run on this
1520 // box (multi-threaded RD search), so a run that happens
1521 // to land on a still-unsupported syntax element (e.g. a
1522 // partition below 16x16, a separate round-2 gap) can
1523 // decode without erroring yet disagree -- that failure
1524 // mode belongs to those other gaps, not to this round's
1525 // ADST wiring, and the eprintln below reports it either
1526 // way rather than hiding it.
1527 }
1528 Err(e) => {
1529 verdicts.push(format!("{lavfi}: still refuses ({e})"));
1530 }
1531 }
1532 }
1533 eprintln!("libaom ADST end-to-end verdicts:");
1534 for v in &verdicts {
1535 eprintln!(" {v}");
1536 }
1537 }
1538
1539 /// Hardened past the report-only test above: a real libaom-av1 gradients
1540 /// stream, pinned deterministic (`gradients`' own `seed=`, plus
1541 /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search
1542 /// cannot pick a different mode set run to run) and with CDEF turned off
1543 /// (this decoder's tile path never applies that in-loop filter -- see
1544 /// `cdef_is_active` in `decode_stream` -- so a stream that leaves it on
1545 /// decodes-but-wrong instead of refusing at cdef_bits==0; ffmpeg's
1546 /// `-enable-cdef 0` keeps this fixture out of that gap rather than this
1547 /// test working around it). Asserts pixel-exact against ffmpeg's own
1548 /// decode of the identical bytes, not just "decoded without error".
1549 #[test]
1550 fn a_real_libaom_gradients_stream_decodes_pixel_exact() {
1551 if !have_ffmpeg() {
1552 eprintln!("SKIP a_real_libaom_gradients_stream_decodes_pixel_exact: no ffmpeg");
1553 return;
1554 }
1555 let (width, height) = (64, 64);
1556 let stream = libaom_encode_with(
1557 &gradients_source(42, width, height, "rate=1"),
1558 width,
1559 height,
1560 15,
1561 &[
1562 "-threads",
1563 "1",
1564 "-row-mt",
1565 "0",
1566 "-tile-columns",
1567 "0",
1568 "-tile-rows",
1569 "0",
1570 "-enable-cdef",
1571 "0",
1572 ],
1573 )
1574 .expect("ffmpeg encode");
1575 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
1576 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1577 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
1578 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
1579 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
1580 }
1581
1582 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but at
1583 /// 32x32 (below `is_cfl_allowed`'s 32x32 luma bound as a *single*
1584 /// undivided block, spec 5.11.5) rather than 64x64 -- a whole 64x64 SB
1585 /// is never CFL-eligible itself, only its <=32x32 partitions, and
1586 /// `testsrc2`/`gradients` at 64x64 with rect/ab/1to4/angle-delta search
1587 /// disabled reliably pick a whole-SB `PARTITION_NONE` (probed
1588 /// lane-av1real r2), so no fixture at that size exercises CfL at all.
1589 /// A 32x32 frame is exactly the whole-block, CFL-allowed case, and
1590 /// lane-av1real r2 found `gradients` there reliably selects
1591 /// `UV_CFL_PRED` (`uv_mode=13`) across a crf sweep -- `testsrc2` there
1592 /// stays DC. Proves the CfL port this round added, not just DC-chroma
1593 /// decode: pixel-exact against ffmpeg's own decode, not just "decoded".
1594 ///
1595 #[test]
1596 fn a_real_libaom_cfl_stream_decodes_pixel_exact() {
1597 if !have_ffmpeg() {
1598 eprintln!("SKIP a_real_libaom_cfl_stream_decodes_pixel_exact: no ffmpeg");
1599 return;
1600 }
1601 let (width, height) = (32, 32);
1602 let stream = libaom_encode_with(
1603 &gradients_source(42, width, height, "rate=1"),
1604 width,
1605 height,
1606 15,
1607 &[
1608 "-threads",
1609 "1",
1610 "-row-mt",
1611 "0",
1612 "-tile-columns",
1613 "0",
1614 "-tile-rows",
1615 "0",
1616 "-enable-cdef",
1617 "0",
1618 ],
1619 )
1620 .expect("ffmpeg encode");
1621 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
1622 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1623 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
1624 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
1625 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
1626 }
1627
1628 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves
1629 /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
1630 /// proves `apply_cdef` itself, not just that this decoder still works
1631 /// when the filter never fires. Gradient content at a low crf reliably
1632 /// gives libaom something to dering. If a run happens to land on
1633 /// `cdef_bits > 0` (per-64x64 `cdef_idx`, still unimplemented -- see the
1634 /// refusal in `decode_stream`) the stream is skipped rather than failed:
1635 /// that gap is named by the refusal's own error text, not silently
1636 /// swallowed here.
1637 #[test]
1638 fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
1639 if !have_ffmpeg() {
1640 eprintln!(
1641 "SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: no ffmpeg"
1642 );
1643 return;
1644 }
1645 let (width, height) = (64, 64);
1646 let stream = libaom_encode_with(
1647 &gradients_source(42, width, height, "rate=1"),
1648 width,
1649 height,
1650 30,
1651 &[
1652 "-threads",
1653 "1",
1654 "-row-mt",
1655 "0",
1656 "-tile-columns",
1657 "0",
1658 "-tile-rows",
1659 "0",
1660 ],
1661 )
1662 .expect("ffmpeg encode");
1663 match decode_stream(&stream) {
1664 Ok(frames) => {
1665 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1666 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (CDEF on)");
1667 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (CDEF on)");
1668 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (CDEF on)");
1669 }
1670 Err(e) => {
1671 eprintln!("SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: {e}");
1672 }
1673 }
1674 }
1675
1676 /// Path to a real `aomenc` build carrying the reference options this
1677 /// fixture needs (`--max-partition-size`, `--enable-tx-size-search`,
1678 /// `--loopfilter-control`) -- this box's `ffmpeg` links a libaom too old
1679 /// to expose `enable-tx-size-search`/`loopfilter-control` through its
1680 /// own `-aom-params` passthrough (probed live: "Cannot find aom
1681 /// option"), so [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]
1682 /// shells out to the standalone binary instead of ffmpeg's libaom-av1
1683 /// wrapper every other test here uses. `EC_AV1_AOMENC` overrides the
1684 /// default dev-build path; the test skips (not fails) when neither this
1685 /// nor `ffmpeg` is present.
1686 fn aomenc_path() -> std::path::PathBuf {
1687 if let Some(p) = std::env::var_os("EC_AV1_AOMENC") {
1688 return std::path::PathBuf::from(p);
1689 }
1690 // The oracle used to live only under `/tmp`, which this box's tmpfs
1691 // guard reclaims -- when it did, all 20 aomenc gates below went
1692 // silently vacuous (SKIP, suite still green). The durable location
1693 // is provisioned by `scripts/build-aom-oracle.sh`; the `/tmp` path
1694 // stays last as a legacy fallback.
1695 let mut candidates = Vec::new();
1696 if let Some(home) = std::env::var_os("HOME") {
1697 candidates.push(std::path::PathBuf::from(&home).join(".cache/aom-oracle/build/aomenc"));
1698 }
1699 candidates.push("/tmp/libaom-src/build/encoder/aomenc".into());
1700 candidates
1701 .iter()
1702 .find(|p| p.is_file())
1703 .cloned()
1704 .unwrap_or_else(|| candidates.remove(0))
1705 }
1706
1707 /// Whether the aomenc oracle is present. Absence normally SKIPs (a
1708 /// checkout without the oracle should still run the rest of the suite),
1709 /// but `EC_AV1_REQUIRE_AOMENC=1` turns it into a hard failure so a batch
1710 /// run cannot report green off 20 skipped gates.
1711 /// Where a pinned stream lives. `fixtures/` is a symlink to a durable
1712 /// directory outside the repo, so a pin captured in one session is still
1713 /// there in the next; a session scratchpad is not (tmpfs reaps it, and
1714 /// four pins were silently dead because of that).
1715 fn pin_dir() -> std::path::PathBuf {
1716 if let Some(p) = std::env::var_os("EC_AV1_PIN_DIR") {
1717 return std::path::PathBuf::from(p);
1718 }
1719 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1720 .join("../../fixtures")
1721 .canonicalize()
1722 .unwrap_or_else(|_| std::path::PathBuf::from("fixtures"))
1723 }
1724
1725 fn have_aomenc() -> bool {
1726 let present = aomenc_path().is_file();
1727 assert!(
1728 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
1729 "EC_AV1_REQUIRE_AOMENC is set but no aomenc at {} -- run scripts/build-aom-oracle.sh",
1730 aomenc_path().display()
1731 );
1732 present
1733 }
1734
1735 /// The instrumented `aomdec` beside the `aomenc` oracle
1736 /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`).
1737 fn aomdec_path() -> std::path::PathBuf {
1738 if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") {
1739 return std::path::PathBuf::from(p);
1740 }
1741 aomenc_path().with_file_name("aomdec")
1742 }
1743
1744 /// Decodes `stream` with both this decoder and the instrumented oracle
1745 /// `aomdec`, and compares EVERY decoded frame in DECODE order --
1746 /// including the hidden (`show_frame == 0`) alt-ref frames no other gate
1747 /// in this repo can see, because `decode_stream` only pushes shown
1748 /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames
1749 /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces
1750 /// only as drift on some later shown frame, if at all).
1751 ///
1752 /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it
1753 /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in
1754 /// `decode_stream`, the oracle's in rung 12 of
1755 /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as
1756 /// u16 LE. Returns `(frames_decoded, hidden_frames)`.
1757 fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) {
1758 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
1759 let _ = std::fs::remove_dir_all(&dir);
1760 std::fs::create_dir_all(&dir).expect("scratch dir");
1761 let obu = dir.join("in.obu");
1762 std::fs::write(&obu, stream).expect("writing the stream");
1763 let aom_prefix = dir.join("aom");
1764 let out = Command::new(aomdec_path())
1765 .args(["--codec=av1", "-o"])
1766 .arg(dir.join("out.y4m"))
1767 .arg(&obu)
1768 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
1769 .stdin(Stdio::null())
1770 .stdout(Stdio::piped())
1771 .stderr(Stdio::piped())
1772 .output()
1773 .expect("aomdec failed to run");
1774 assert!(
1775 out.status.success(),
1776 "{name}: the oracle aomdec refused the stream: {}",
1777 String::from_utf8_lossy(&out.stderr)
1778 );
1779 let count_dumps = |prefix: &std::path::Path| -> usize {
1780 let mut n = 0usize;
1781 while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() {
1782 n += 1;
1783 }
1784 n
1785 };
1786 let oracle_frames = count_dumps(&aom_prefix);
1787 assert!(
1788 oracle_frames > 0,
1789 "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \
1790 scripts/instrument-aom-oracle.sh is missing from {}",
1791 aomdec_path().display()
1792 );
1793 let ours_prefix = dir.join("ours");
1794 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
1795 let decoded = decode_stream(stream);
1796 set_final_dump_prefix(None);
1797 let shown = decoded
1798 .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}"))
1799 .len();
1800 let our_frames = count_dumps(&ours_prefix);
1801 assert_eq!(
1802 our_frames, oracle_frames,
1803 "{name}: decoded {our_frames} frames in decode order, the oracle decoded \
1804 {oracle_frames}"
1805 );
1806 for i in 0..oracle_frames {
1807 let want =
1808 std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
1809 let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
1810 assert_eq!(
1811 got.len(),
1812 want.len(),
1813 "{name}: decode-order frame {i} is {} bytes, the oracle's is {}",
1814 got.len(),
1815 want.len()
1816 );
1817 if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) {
1818 let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count();
1819 panic!(
1820 "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \
1821 hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \
1822 bytes differ -- stream pinned at {}",
1823 oracle_frames - shown,
1824 got[at],
1825 want[at],
1826 obu.display()
1827 );
1828 }
1829 }
1830 let hidden = oracle_frames - shown;
1831 let _ = std::fs::remove_dir_all(&dir);
1832 (oracle_frames, hidden)
1833 }
1834
1835 /// lane-hidden r2: the `--arnr-maxframes=0` SECOND ARM of an existing
1836 /// gate -- the gate's own recipe is never changed, this re-encodes the
1837 /// same fixture with libaom's temporal alt-ref filter switched off and
1838 /// runs [`decode_all_frames_vs_oracle`] on the result. Measured: with
1839 /// the filter at its default EVERY alt-ref recipe in this file emits
1840 /// ZERO hidden frames (the candidates are filtered away), so the
1841 /// hidden-frame compare on the gate's own stream is vacuous; this arm
1842 /// is what actually puts `show_frame == 0` frames on the wire.
1843 ///
1844 /// Runs at most once per gate name per process (the loop gates sweep
1845 /// dozens of attempts and each arm costs a full encode + two decodes).
1846 /// A stream this decoder refuses BY NAME skips the arm -- the arm is
1847 /// about hidden frames, not about that capability gap -- while a pixel
1848 /// mismatch is a hard failure raised inside the compare.
1849 fn hidden_arnr_arm(name: &str, y4m: &[u8], args: &[&str]) -> Option<(usize, usize)> {
1850 static ARMED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
1851 std::sync::OnceLock::new();
1852 if !ARMED
1853 .get_or_init(Default::default)
1854 .lock()
1855 .unwrap()
1856 .insert(name.to_string())
1857 {
1858 return None;
1859 }
1860 let mut arm: Vec<&str> = vec!["--arnr-maxframes=0"];
1861 arm.extend_from_slice(args);
1862 let mut child = Command::new(aomenc_path())
1863 .args(&arm)
1864 .stdin(Stdio::piped())
1865 .stdout(Stdio::piped())
1866 .stderr(Stdio::piped())
1867 .spawn()
1868 .expect("aomenc failed to start");
1869 child
1870 .stdin
1871 .take()
1872 .expect("aomenc stdin")
1873 .write_all(y4m)
1874 .expect("writing y4m to aomenc");
1875 let out = child.wait_with_output().expect("aomenc failed to run");
1876 assert!(
1877 out.status.success(),
1878 "{name} HIDDEN-ARM: aomenc refused its own recipe plus --arnr-maxframes=0: {}",
1879 String::from_utf8_lossy(&out.stderr)
1880 );
1881 let stream = out.stdout;
1882 match decode_stream(&stream) {
1883 Err(e) => {
1884 let msg = e.to_string();
1885 assert!(
1886 msg.contains("unsupported"),
1887 "{name} HIDDEN-ARM failed outright: {msg}"
1888 );
1889 eprintln!("{name} HIDDEN-ARM: skipped on a named refusal: {msg}");
1890 None
1891 }
1892 Ok(_) => Some(decode_all_frames_vs_oracle(&stream, &format!("{name}-arnr0"))),
1893 }
1894 }
1895
1896
1897 /// The repo's first hidden-frame pixel gate. Every other aomenc gate
1898 /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and
1899 /// both sides emit SHOWN frames only -- so an alt-ref frame that is
1900 /// decoded, stored into a reference slot and never displayed was, until
1901 /// this gate, never compared to anything (class
1902 /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the
1903 /// default `--lag-in-frames`, so they are full of exactly these frames.
1904 ///
1905 /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc
1906 /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's
1907 /// temporal filter on, this fixture's alt-ref candidates get filtered
1908 /// away and the encoder emits ZERO hidden frames (measured: 0 hidden
1909 /// with the filter on, 3 with it off), which would have made the gate
1910 /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so
1911 /// a recipe that stops producing hidden frames fails rather than skips.
1912 #[test]
1913 fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() {
1914 const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact";
1915 let _gate_lock = lock_gate_counters();
1916 if !have_ffmpeg() {
1917 eprintln!("SKIP {NAME}: no ffmpeg");
1918 return;
1919 }
1920 if !have_aomenc() {
1921 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1922 return;
1923 }
1924 for bit_depth in [8u32, 10u32] {
1925 let (width, height, frames) = (64usize, 64usize, 40usize);
1926 let duration = frames as f64 / 25.0;
1927 let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25");
1928 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
1929 let y4m = Command::new("ffmpeg")
1930 .args([
1931 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
1932 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
1933 ])
1934 .stdin(Stdio::null())
1935 .stdout(Stdio::piped())
1936 .stderr(Stdio::piped())
1937 .output()
1938 .expect("ffmpeg failed to run");
1939 assert!(
1940 y4m.status.success(),
1941 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1942 String::from_utf8_lossy(&y4m.stderr)
1943 );
1944 let depth_arg = format!("--bit-depth={bit_depth}");
1945 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1946 let mut child = Command::new(aomenc_path())
1947 .args([
1948 // lane-defon r1: the repo's only gate that decodes hidden
1949 // frames is also the only place a FORWARD KEYFRAME can be
1950 // proven -- a KEY frame with `show_frame == 0`, which is
1951 // exactly the shape this gate already compares in decode
1952 // order. On-values go before the base list (aomenc keeps
1953 // the FIRST occurrence of a repeated flag).
1954 "--enable-fwd-kf=1",
1955 "--fwd-kf-dist=8",
1956 "--codec=av1",
1957 "--passes=1",
1958 "--end-usage=q",
1959 "--cq-level=45",
1960 "--cpu-used=0",
1961 "--threads=1",
1962 "--row-mt=0",
1963 "--kf-max-dist=1000",
1964 "--enable-order-hint=1",
1965 "--auto-alt-ref=1",
1966 "--lag-in-frames=25",
1967 "--arnr-maxframes=0",
1968 &depth_arg,
1969 &input_depth_arg,
1970 // The same tool set every sibling inter gate pins -- the
1971 // open capability gaps (rect/AB partitions, warped/OBMC,
1972 // masked compound, palette, ...) are other lanes' work;
1973 // this gate is about hidden frames, not about them.
1974 "--enable-warped-motion=0",
1975 "--enable-obmc=0",
1976 "--enable-masked-comp=0",
1977 "--enable-interintra-comp=0",
1978 "--enable-onesided-comp=0",
1979 "--enable-interintra-wedge=0",
1980 "--enable-smooth-interintra=0",
1981 "--enable-rect-partitions=0",
1982 "--enable-ab-partitions=0",
1983 "--enable-1to4-partitions=0",
1984 "--enable-filter-intra=0",
1985 "--enable-smooth-intra=0",
1986 "--enable-paeth-intra=0",
1987 "--enable-directional-intra=0",
1988 "--enable-angle-delta=0",
1989 "--enable-tx-size-search=0",
1990 "--enable-cdef=0",
1991 "--enable-restoration=0",
1992 "--max-partition-size=32",
1993 "--min-partition-size=32",
1994 "--enable-palette=0",
1995 "--enable-intrabc=0",
1996 "--enable-cfl-intra=0",
1997 "--enable-ref-frame-mvs=0",
1998 "--obu",
1999 "-o",
2000 "-",
2001 "-",
2002 ])
2003 .stdin(Stdio::piped())
2004 .stdout(Stdio::piped())
2005 .stderr(Stdio::piped())
2006 .spawn()
2007 .expect("aomenc failed to start");
2008 child
2009 .stdin
2010 .take()
2011 .expect("aomenc stdin")
2012 .write_all(&y4m.stdout)
2013 .expect("writing y4m to aomenc");
2014 let out = child.wait_with_output().expect("aomenc failed to run");
2015 assert!(
2016 out.status.success(),
2017 "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}",
2018 String::from_utf8_lossy(&out.stderr)
2019 );
2020 let stream = out.stdout;
2021 let fwd_kf_before = crate::decode::fwd_kf_hits();
2022 let (total, hidden) =
2023 decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit"));
2024 let fwd_kf = crate::decode::fwd_kf_hits() - fwd_kf_before;
2025 assert!(
2026 hidden >= 2,
2027 "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \
2028 {total} decoded -- the gate would be vacuous (class \
2029 gate-blind-to-hidden-frames)"
2030 );
2031 // lane-defon r1: `--enable-fwd-kf=1` is spelled on this recipe, so
2032 // a KEY frame with `show_frame == 0` must actually have been
2033 // decoded -- otherwise the on-value proves nothing.
2034 assert!(
2035 fwd_kf > 0,
2036 "{NAME}: the {bit_depth}-bit recipe decoded {total} frames ({hidden} hidden) but \
2037 zero forward keyframes -- --enable-fwd-kf=1 --fwd-kf-dist=8 never reached the \
2038 bitstream"
2039 );
2040 eprintln!(
2041 "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, {fwd_kf} \
2042 forward keyframes, all pixel-exact vs the oracle in decode order"
2043 );
2044 }
2045 }
2046
2047 /// A real `aomenc` filter-intra fixture: every other intra mode disabled
2048 /// (smooth/paeth/directional/angle-delta) and
2049 /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s
2050 /// <=32x32 bound means `use_filter_intra` never reads at all, spec
2051 /// 5.11.14), so the only way this frame codes is `DC_PRED` with filter
2052 /// intra on top -- `--loopfilter-control=0` is required too: this
2053 /// decoder has no in-loop deblocking filter at all, and libaom's default
2054 /// (on) smooths every block-boundary column, which first looked like a
2055 /// filter-intra math bug (mismatches straddling the 32-pixel block
2056 /// seam) until the recipe without it round-tripped byte-exact. Checks
2057 /// [`decode::filter_intra_hits`] actually moved (a process-global
2058 /// counter, so before/after rather than an absolute value) to prove the
2059 /// symbol fired, then pixel-exactness against ffmpeg's own decode of the
2060 /// identical bytes on every plane.
2061 #[test]
2062 fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {
2063 if !have_ffmpeg() {
2064 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no ffmpeg");
2065 return;
2066 }
2067 if !have_aomenc() {
2068 eprintln!(
2069 "SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no aomenc at {}",
2070 aomenc_path().display()
2071 );
2072 return;
2073 }
2074 let (width, height) = (64usize, 64usize);
2075 // Recipe-search hooks: with the encoder pinned to one thread the
2076 // stream is a deterministic function of (seed, cq), so a firing recipe
2077 // can be searched for without a rebuild.
2078 let fi_seed: u32 = std::env::var("EC_FI_SEED")
2079 .ok()
2080 .and_then(|v| v.parse().ok())
2081 .unwrap_or(42);
2082 let fi_source = gradients_source(fi_seed, 64, 64, "duration=0.04:rate=25");
2083 let fi_cq = std::env::var("EC_FI_CQ").unwrap_or_else(|_| "40".to_string());
2084 let fi_cq_arg = format!("--cq-level={fi_cq}");
2085 let y4m = Command::new("ffmpeg")
2086 .args([
2087 "-v",
2088 "error",
2089 "-f",
2090 "lavfi",
2091 "-i",
2092 &fi_source,
2093 "-pix_fmt",
2094 "yuv420p",
2095 "-f",
2096 "yuv4mpegpipe",
2097 "-",
2098 ])
2099 .stdin(Stdio::null())
2100 .stdout(Stdio::piped())
2101 .stderr(Stdio::piped())
2102 .output()
2103 .expect("ffmpeg failed to run");
2104 assert!(
2105 y4m.status.success(),
2106 "ffmpeg refused to generate the y4m fixture: {}",
2107 String::from_utf8_lossy(&y4m.stderr)
2108 );
2109 let mut child = Command::new(aomenc_path())
2110 .args([
2111 "--codec=av1",
2112 "--passes=1",
2113 "--end-usage=q",
2114 &fi_cq_arg,
2115 "--cpu-used=0",
2116 // Every sibling gate pins these; this one did not, and a
2117 // multi-threaded aomenc is not deterministic, so each run
2118 // encoded a slightly different stream and the gate flaked
2119 // against whichever features that run happened to pick.
2120 // Pinning them makes seed 42 mean one stream (class
2121 // `parallel-flake-is-attempt-selection`).
2122 "--threads=1",
2123 "--row-mt=0",
2124 "--enable-filter-intra=1",
2125 "--enable-smooth-intra=0",
2126 "--enable-paeth-intra=0",
2127 "--enable-directional-intra=0",
2128 "--enable-angle-delta=0",
2129 "--enable-tx-size-search=0",
2130 "--enable-cdef=0",
2131 "--max-partition-size=32",
2132 "--loopfilter-control=0",
2133 "--enable-palette=0",
2134 "--enable-intrabc=0",
2135 "--obu",
2136 "-o",
2137 "-",
2138 "-",
2139 ])
2140 .stdin(Stdio::piped())
2141 .stdout(Stdio::piped())
2142 .stderr(Stdio::piped())
2143 .spawn()
2144 .expect("aomenc failed to start");
2145 child
2146 .stdin
2147 .take()
2148 .expect("aomenc stdin")
2149 .write_all(&y4m.stdout)
2150 .expect("writing the y4m fixture to aomenc");
2151 let out = child.wait_with_output().expect("aomenc failed to run");
2152 assert!(
2153 out.status.success(),
2154 "aomenc refused the fixture: {}",
2155 String::from_utf8_lossy(&out.stderr)
2156 );
2157 let stream = out.stdout;
2158 let before = decode::filter_intra_hits();
2159 // `screen_content_tools_determination` (libaom encoder_utils.c) is a
2160 // real internal trial-encode/PSNR comparison, not a flag this CLI
2161 // exposes a knob for -- on this flat gradient fixture it lands on
2162 // `allow_screen_content_tools=0` most runs but occasionally trips
2163 // over its 0.9 dB threshold the other way even with palette/intrabc
2164 // both disabled. That is a genuine separate gap (`decode_stream`
2165 // never reads `intrabc`/`palette_mode_info`), not a filter-intra
2166 // regression, so it is skipped here exactly as
2167 // `a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact`
2168 // above skips its own still-unsupported-gap runs.
2169 let frames = match decode_stream(&stream) {
2170 Ok(frames) => frames,
2171 Err(e) => {
2172 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: {e}");
2173 return;
2174 }
2175 };
2176 assert!(
2177 decode::filter_intra_hits() > before,
2178 "use_filter_intra never fired decoding this stream"
2179 );
2180 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
2181 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
2182 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
2183 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
2184 }
2185
2186 /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`
2187 /// (SMPTE colour bars -- a handful of large flat luma regions, exactly
2188 /// the "flat, few-colour, repetitive" content `av1_choose_palette_map`'s
2189 /// RD trial rewards) with `hue=s=0` to flatten chroma to one constant
2190 /// value, so `DC_PRED` already nails every chroma block with zero
2191 /// residual and the encoder's own RD never has a reason to spend bits on
2192 /// a *UV* palette too (a real symbol this decoder still refuses --
2193 /// lane-palette r3's own scope is Y only). `smptebars` has no seed to
2194 /// vary, so the fixture is deterministic by construction; hashed twice
2195 /// below to prove it rather than assert it. `--enable-rect-partitions=0`
2196 /// / `-ab-` / `-1to4-` keep every intra block square, sidestepping the
2197 /// rect-strip screen-content refusal at `read_intra_mode_rect`
2198 /// (decode.rs ~2226) -- that refusal is this lane's own next milestone,
2199 /// not this gate's. `--sb-size=64` and `--threads=1 --row-mt=0` are the
2200 /// sibling-lane facts this charter paid for: a single 64x64 frame is one
2201 /// superblock either way, but pinning them keeps the recipe identical to
2202 /// every other gate in this file. HARD-asserts
2203 /// [`decode::palette_hits`] moved -- a stream that never reads a real
2204 /// palette block would refuse (or not) by construction without proving
2205 /// this milestone at all.
2206 ///
2207 /// lane-palette r4/r6/r7: r3/r4 found that this fixture's reconstructed
2208 /// pixels did not match ffmpeg's decode of the same bytes even though
2209 /// every symbol read by `decode_color_index_map` checked line-for-line
2210 /// against the oracle and matched. r6's range trace (`compare-range-not-tell`)
2211 /// pinned the real cause: `decode_color_index_map` was called from the
2212 /// wrong syntax position -- inline right after the Y colours, instead of
2213 /// after the whole mode-info read (UV palette mode_info + `filter_intra`,
2214 /// `av1_visit_palette`'s real call order). r7 ported the UV palette
2215 /// mode_info read and moved the colour-index-map decode after
2216 /// `filter_intra`; this gate now asserts a real pixel match instead of
2217 /// the old named refusal.
2218 #[test]
2219 fn a_real_aomenc_stream_with_palette_y_decodes_pixel_exact() {
2220 const NAME: &str = "a_real_aomenc_stream_with_palette_y_decodes_pixel_exact";
2221 if !have_ffmpeg() {
2222 eprintln!("SKIP {NAME}: no ffmpeg");
2223 return;
2224 }
2225 if !have_aomenc() {
2226 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2227 return;
2228 }
2229 let source = "smptebars=size=64x64:rate=25";
2230 fn render(source: &str) -> Vec<u8> {
2231 Command::new("ffmpeg")
2232 .args([
2233 "-v",
2234 "error",
2235 "-f",
2236 "lavfi",
2237 "-i",
2238 source,
2239 "-vf",
2240 "hue=s=0",
2241 "-pix_fmt",
2242 "yuv420p",
2243 "-t",
2244 "0.04",
2245 "-f",
2246 "yuv4mpegpipe",
2247 "-",
2248 ])
2249 .stdin(Stdio::null())
2250 .stdout(Stdio::piped())
2251 .stderr(Stdio::piped())
2252 .output()
2253 .expect("ffmpeg failed to run")
2254 .stdout
2255 }
2256 let y4m_a = render(source);
2257 let y4m_b = render(source);
2258 assert_eq!(
2259 y4m_a, y4m_b,
2260 "smptebars must render byte-identical across two runs"
2261 );
2262 let y4m = y4m_a;
2263 let mut child = Command::new(aomenc_path())
2264 .args([
2265 "--codec=av1",
2266 "--passes=1",
2267 "--end-usage=q",
2268 "--cq-level=30",
2269 "--cpu-used=0",
2270 "--threads=1",
2271 "--row-mt=0",
2272 "--sb-size=64",
2273 "--tune-content=screen",
2274 "--enable-palette=1",
2275 "--enable-intrabc=0",
2276 "--enable-rect-partitions=0",
2277 "--enable-ab-partitions=0",
2278 "--enable-1to4-partitions=0",
2279 "--min-partition-size=32",
2280 "--max-partition-size=32",
2281 "--enable-filter-intra=0",
2282 "--enable-smooth-intra=0",
2283 "--enable-paeth-intra=0",
2284 "--enable-directional-intra=0",
2285 "--enable-angle-delta=0",
2286 "--enable-cfl-intra=0",
2287 "--enable-cdef=0",
2288 "--enable-restoration=0",
2289 "--enable-tx-size-search=0",
2290 "--loopfilter-control=0",
2291 "--obu",
2292 "-o",
2293 "-",
2294 "-",
2295 ])
2296 .stdin(Stdio::piped())
2297 .stdout(Stdio::piped())
2298 .stderr(Stdio::piped())
2299 .spawn()
2300 .expect("aomenc failed to start");
2301 child
2302 .stdin
2303 .take()
2304 .expect("aomenc stdin")
2305 .write_all(&y4m)
2306 .expect("writing y4m to aomenc");
2307 let out = child.wait_with_output().expect("aomenc failed to run");
2308 assert!(
2309 out.status.success(),
2310 "aomenc refused the fixture: {}",
2311 String::from_utf8_lossy(&out.stderr)
2312 );
2313 let stream = out.stdout;
2314 let before = decode::palette_hits();
2315 let frames = match decode_stream(&stream) {
2316 Ok(frames) => frames,
2317 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2318 };
2319 assert!(
2320 decode::palette_hits() > before,
2321 "palette_y_mode never fired decoding this stream -- gate is vacuous"
2322 );
2323 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1);
2324 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
2325 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
2326 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
2327 }
2328
2329 /// lane-hbd r5: a real `aomenc --bit-depth=10` stream, decoded through
2330 /// this crate's own 10-bit planes (`Picture` widened to `u16` in an
2331 /// earlier round) and checked pixel-exact against ffmpeg's own decode of
2332 /// the identical bytes via [`ffmpeg_decode_sequence_10bit`]. Confirms
2333 /// (hard-asserts, not just trusts) the sequence header this stream
2334 /// actually parses to says `bit_depth == 10` before trusting any pixel
2335 /// match -- a stream that silently fell back to 8-bit would still
2336 /// "match" trivially.
2337 #[test]
2338 fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {
2339 const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact";
2340 if !have_ffmpeg() {
2341 eprintln!("SKIP {NAME}: no ffmpeg");
2342 return;
2343 }
2344 if !have_aomenc() {
2345 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2346 return;
2347 }
2348 let (width, height) = (64usize, 64usize);
2349 let y4m = Command::new("ffmpeg")
2350 .args([
2351 "-v",
2352 "error",
2353 "-f",
2354 "lavfi",
2355 "-i",
2356 &gradients_source(42, width, height, "duration=0.04:rate=25"),
2357 "-pix_fmt",
2358 "yuv420p10le",
2359 "-strict",
2360 "-1",
2361 "-t",
2362 "0.04",
2363 "-f",
2364 "yuv4mpegpipe",
2365 "-",
2366 ])
2367 .stdin(Stdio::null())
2368 .stdout(Stdio::piped())
2369 .stderr(Stdio::piped())
2370 .output()
2371 .expect("ffmpeg failed to run");
2372 assert!(
2373 y4m.status.success(),
2374 "ffmpeg failed to render the 10-bit fixture: {}",
2375 String::from_utf8_lossy(&y4m.stderr)
2376 );
2377 let mut child = Command::new(aomenc_path())
2378 .args([
2379 "--codec=av1",
2380 "--passes=1",
2381 "--end-usage=q",
2382 "--cq-level=30",
2383 "--cpu-used=0",
2384 "--threads=1",
2385 "--row-mt=0",
2386 "--sb-size=64",
2387 "--input-bit-depth=10",
2388 "--bit-depth=10",
2389 "--limit=1",
2390 "--obu",
2391 "-o",
2392 "-",
2393 "-",
2394 ])
2395 .stdin(Stdio::piped())
2396 .stdout(Stdio::piped())
2397 .stderr(Stdio::piped())
2398 .spawn()
2399 .expect("aomenc failed to start");
2400 child
2401 .stdin
2402 .take()
2403 .expect("aomenc stdin")
2404 .write_all(&y4m.stdout)
2405 .expect("writing y4m to aomenc");
2406 let out = child.wait_with_output().expect("aomenc failed to run");
2407 assert!(
2408 out.status.success(),
2409 "aomenc refused the 10-bit fixture: {}",
2410 String::from_utf8_lossy(&out.stderr)
2411 );
2412 let stream = out.stdout;
2413 // Confirm the sequence header this stream actually parses to before
2414 // trusting any pixel comparison below.
2415 let mut probe = Av1Parser::new();
2416 let mut pos = 0usize;
2417 while pos < stream.len() && probe.sequence_header().is_none() {
2418 let obu = probe.parse_obu(&stream[pos..]).unwrap();
2419 pos += obu.total_size;
2420 }
2421 let seq = probe
2422 .sequence_header()
2423 .expect("stream has a sequence header OBU");
2424 assert_eq!(
2425 seq.color_config.bit_depth, 10,
2426 "{NAME}: aomenc did not actually write a 10-bit sequence header"
2427 );
2428 let frames = match decode_stream(&stream) {
2429 Ok(frames) => frames,
2430 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit stream: {e}"),
2431 };
2432 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
2433 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (10-bit)");
2434 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (10-bit)");
2435 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
2436 }
2437
2438 /// The 10-bit *inter* counterpart of the gate above: a real `aomenc`
2439 /// `yuv420p10le` sequence whose non-key frames are plain forward
2440 /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0
2441 /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate),
2442 /// decoded pixel-exact on every frame. 10-bit intra was proven exact by
2443 /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated.
2444 #[test]
2445 fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() {
2446 const NAME: &str = "a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact";
2447 let _gate_lock = lock_gate_counters();
2448 if !have_ffmpeg() {
2449 eprintln!("SKIP {NAME}: no ffmpeg");
2450 return;
2451 }
2452 if !have_aomenc() {
2453 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2454 return;
2455 }
2456 let (width, height, frame_count) = (128usize, 64usize, 16usize);
2457 let y4m = Command::new("ffmpeg")
2458 .args([
2459 "-v",
2460 "error",
2461 "-f",
2462 "lavfi",
2463 "-i",
2464 &gradients_source(42, width, height, "duration=0.64:rate=25"),
2465 "-pix_fmt",
2466 "yuv420p10le",
2467 "-strict",
2468 "-1",
2469 "-t",
2470 "0.64",
2471 "-f",
2472 "yuv4mpegpipe",
2473 "-",
2474 ])
2475 .stdin(Stdio::null())
2476 .stdout(Stdio::piped())
2477 .stderr(Stdio::piped())
2478 .output()
2479 .expect("ffmpeg failed to run");
2480 assert!(
2481 y4m.status.success(),
2482 "ffmpeg failed to render the 10-bit fixture: {}",
2483 String::from_utf8_lossy(&y4m.stderr)
2484 );
2485 let mut child = Command::new(aomenc_path())
2486 .args([
2487 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
2488 // occurrence, so overrides go before the base list).
2489 "--loopfilter-control=1",
2490 "--codec=av1",
2491 "--passes=1",
2492 "--end-usage=q",
2493 "--cq-level=15",
2494 "--cpu-used=0",
2495 "--threads=1",
2496 "--row-mt=0",
2497 "--sb-size=64",
2498 "--input-bit-depth=10",
2499 "--bit-depth=10",
2500 "--lag-in-frames=0",
2501 "--auto-alt-ref=0",
2502 "--kf-max-dist=1000",
2503 "--error-resilient=1",
2504 "--aq-mode=0",
2505 "--deltaq-mode=0",
2506 "--enable-rect-partitions=0",
2507 "--enable-ab-partitions=0",
2508 "--enable-1to4-partitions=0",
2509 "--enable-filter-intra=0",
2510 "--enable-smooth-intra=0",
2511 "--enable-paeth-intra=0",
2512 "--enable-directional-intra=0",
2513 "--enable-angle-delta=0",
2514 "--enable-tx-size-search=0",
2515 "--enable-cdef=1",
2516 "--enable-restoration=1",
2517 "--min-partition-size=16",
2518 "--max-partition-size=32",
2519 "--enable-palette=0",
2520 "--enable-intrabc=0",
2521 "--enable-cfl-intra=0",
2522 "--enable-ref-frame-mvs=0",
2523 "--obu",
2524 "-o",
2525 "-",
2526 "-",
2527 ])
2528 .stdin(Stdio::piped())
2529 .stdout(Stdio::piped())
2530 .stderr(Stdio::piped())
2531 .spawn()
2532 .expect("aomenc failed to start");
2533 child
2534 .stdin
2535 .take()
2536 .expect("aomenc stdin")
2537 .write_all(&y4m.stdout)
2538 .expect("writing y4m to aomenc");
2539 let out = child.wait_with_output().expect("aomenc failed to run");
2540 assert!(
2541 out.status.success(),
2542 "aomenc refused the 10-bit fixture: {}",
2543 String::from_utf8_lossy(&out.stderr)
2544 );
2545 let stream = out.stdout;
2546 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
2547 std::fs::write(dump, &stream).expect("dump stream");
2548 }
2549 let mut probe = Av1Parser::new();
2550 let mut pos = 0usize;
2551 while pos < stream.len() && probe.sequence_header().is_none() {
2552 let obu = probe.parse_obu(&stream[pos..]).unwrap();
2553 pos += obu.total_size;
2554 }
2555 assert_eq!(
2556 probe
2557 .sequence_header()
2558 .expect("stream has a sequence header OBU")
2559 .color_config
2560 .bit_depth,
2561 10,
2562 "{NAME}: aomenc did not actually write a 10-bit sequence header"
2563 );
2564 let before_deblock = decode::deblock_hits();
2565 let before_inter = decode::inter_pred_hits();
2566 let before_lr = crate::restoration::wiener_hits()
2567 + crate::restoration::sgrproj_hits()
2568 + crate::restoration::switchable_hits();
2569 let frames = match decode_stream(&stream) {
2570 Ok(frames) => frames,
2571 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"),
2572 };
2573 assert!(
2574 decode::inter_pred_hits() > before_inter,
2575 "{NAME}: no inter-predicted block decoded -- the gate proves nothing"
2576 );
2577 assert!(
2578 decode::deblock_hits() > before_deblock,
2579 "{NAME}: no deblocking edge fired -- raise cq-level"
2580 );
2581 // Loop restoration is where the 10-bit inter/intra defect lived
2582 // (lane-hbdinter r1: the self-guided box sums were never brought back
2583 // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened
2584 // to pick RESTORE_NONE would pass while proving nothing.
2585 assert!(
2586 crate::restoration::wiener_hits()
2587 + crate::restoration::sgrproj_hits()
2588 + crate::restoration::switchable_hits()
2589 > before_lr,
2590 "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level"
2591 );
2592 eprintln!(
2593 "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}",
2594 decode::inter_pred_hits() - before_inter,
2595 decode::deblock_hits() - before_deblock,
2596 decode::cdef_idx_hits(),
2597 crate::restoration::wiener_hits(),
2598 crate::restoration::sgrproj_hits(),
2599 );
2600 assert_eq!(frames.len(), frame_count);
2601 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count);
2602 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2603 if got.y != want.y || got.u != want.u || got.v != want.v {
2604 let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu");
2605 let _ = std::fs::write(&pin, &stream);
2606 let first = |a: &Vec<u16>, b: &Vec<u16>| {
2607 a.iter()
2608 .zip(b)
2609 .enumerate()
2610 .find(|(_, (x, y))| x != y)
2611 .map(|(k, (x, y))| (k, *x, *y))
2612 };
2613 panic!(
2614 "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}",
2615 first(&got.y, &want.y),
2616 first(&got.u, &want.u),
2617 first(&got.v, &want.v),
2618 pin.display()
2619 );
2620 }
2621 }
2622 }
2623
2624 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1`
2625 /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the
2626 /// identical bytes (ffmpeg synthesizes grain by default -- no
2627 /// grain-disable flag is passed anywhere in this file). Proves the
2628 /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`,
2629 /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather
2630 /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed
2631 /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a
2632 /// silent 8-bit fallback nor a stream aomenc emitted without
2633 /// `apply_grain` can make it pass vacuously.
2634 #[test]
2635 fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() {
2636 const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact";
2637 if !have_ffmpeg() {
2638 eprintln!("SKIP {NAME}: no ffmpeg");
2639 return;
2640 }
2641 if !have_aomenc() {
2642 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2643 return;
2644 }
2645 let (width, height) = (64usize, 64usize);
2646 let stream = encode_10bit_gradients(
2647 NAME,
2648 width,
2649 height,
2650 1,
2651 &["--film-grain-test=1", "--limit=1"],
2652 );
2653 assert_eq!(
2654 parsed_bit_depth(&stream),
2655 10,
2656 "{NAME}: aomenc did not actually write a 10-bit sequence header"
2657 );
2658 let mut probe = Av1Parser::new();
2659 let mut pos = 0usize;
2660 let mut saw_grain = false;
2661 while pos < stream.len() {
2662 let obu = probe.parse_obu(&stream[pos..]).unwrap();
2663 pos += obu.total_size;
2664 if let ObuKind::Frame(header, _) = obu.kind
2665 && header.film_grain.apply_grain
2666 {
2667 // A grain block whose scaling LUT is empty would blend a
2668 // zero delta into every pixel and let this gate pass without
2669 // the bit-depth math mattering at all.
2670 assert!(
2671 header.film_grain.num_y_points > 0,
2672 "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op"
2673 );
2674 saw_grain = true;
2675 }
2676 }
2677 assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain");
2678 let before = crate::film_grain::grain_hits();
2679 let frames = match decode_stream(&stream) {
2680 Ok(frames) => frames,
2681 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2682 };
2683 assert!(
2684 crate::film_grain::grain_hits() > before,
2685 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
2686 );
2687 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
2688 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
2689 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
2690 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
2691 eprintln!("{NAME}: pixel-exact, grain_hits={}", crate::film_grain::grain_hits());
2692 }
2693
2694 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1
2695 /// --superres-denominator=12` key frame, decoded pixel-exact against
2696 /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s
2697 /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit
2698 /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts
2699 /// `bit_depth == 10` and `superres_hits > 0`.
2700 #[test]
2701 fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() {
2702 const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact";
2703 if !have_ffmpeg() {
2704 eprintln!("SKIP {NAME}: no ffmpeg");
2705 return;
2706 }
2707 if !have_aomenc() {
2708 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2709 return;
2710 }
2711 let (width, height) = (64usize, 64usize);
2712 let stream = encode_10bit_gradients(
2713 NAME,
2714 width,
2715 height,
2716 1,
2717 &[
2718 "--limit=1",
2719 "--kf-max-dist=0",
2720 "--superres-mode=1",
2721 "--superres-denominator=12",
2722 "--superres-kf-denominator=12",
2723 "--enable-rect-partitions=0",
2724 "--enable-ab-partitions=0",
2725 "--enable-1to4-partitions=0",
2726 "--enable-filter-intra=0",
2727 "--enable-smooth-intra=0",
2728 "--enable-paeth-intra=0",
2729 "--enable-directional-intra=0",
2730 "--enable-angle-delta=0",
2731 "--enable-tx-size-search=0",
2732 "--enable-cdef=0",
2733 "--enable-restoration=0",
2734 "--max-partition-size=32",
2735 "--min-partition-size=32",
2736 "--enable-palette=0",
2737 "--enable-intrabc=0",
2738 "--enable-cfl-intra=0",
2739 ],
2740 );
2741 assert_eq!(
2742 parsed_bit_depth(&stream),
2743 10,
2744 "{NAME}: aomenc did not actually write a 10-bit sequence header"
2745 );
2746 let before = crate::superres::superres_hits();
2747 let frames = match decode_stream(&stream) {
2748 Ok(frames) => frames,
2749 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2750 };
2751 assert!(
2752 crate::superres::superres_hits() > before,
2753 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
2754 );
2755 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
2756 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
2757 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
2758 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
2759 eprintln!(
2760 "{NAME}: pixel-exact, superres_hits={}",
2761 crate::superres::superres_hits()
2762 );
2763 }
2764
2765 /// lane-hbdgates r1: drive one 10-bit aomenc recipe over `seeds`, decode
2766 /// every attempt and pixel-compare every SHOWN frame against ffmpeg's own
2767 /// 10-bit decode of the identical bytes. Per-tool firing counters are
2768 /// sampled PER ATTEMPT and summed only over attempts that decoded *and*
2769 /// compared -- a stream that hit a named refusal contributes nothing
2770 /// (class `counter-from-refused-stream`). Named refusals are tolerated
2771 /// and reported; a pixel mismatch is a hard failure, never a SKIP.
2772 fn ten_bit_tool_gate(
2773 name: &str,
2774 width: usize,
2775 height: usize,
2776 frames: usize,
2777 extra: &[&str],
2778 seeds: &[u32],
2779 counters: &[(&str, fn() -> usize)],
2780 ) {
2781 fn first_diff(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
2782 ours.iter()
2783 .zip(theirs.iter())
2784 .position(|(a, b)| a != b)
2785 .map(|i| {
2786 format!(
2787 "first diff at index {i} (row {}, col {}): ours {} vs ffmpeg {}",
2788 i / width,
2789 i % width,
2790 ours[i],
2791 theirs[i]
2792 )
2793 })
2794 }
2795 let mut totals = vec![0usize; counters.len()];
2796 let mut refusals: Vec<String> = Vec::new();
2797 let mut compared = 0usize;
2798 for &seed in seeds {
2799 let stream = encode_10bit_gradients_seed(name, seed, width, height, frames, extra);
2800 assert_eq!(
2801 parsed_bit_depth(&stream),
2802 10,
2803 "{name}: aomenc did not write a 10-bit sequence header (seed {seed})"
2804 );
2805 let before: Vec<usize> = counters.iter().map(|(_, f)| f()).collect();
2806 let decoded = match decode_stream(&stream) {
2807 Ok(frames) => frames,
2808 Err(e) => {
2809 refusals.push(format!("seed {seed}: {e}"));
2810 continue;
2811 }
2812 };
2813 // Deltas are read BEFORE the pixel compare so a mismatch report
2814 // says whether the tool under test actually fired on the failing
2815 // stream (a mismatch with a zero delta is some other defect).
2816 let deltas: Vec<usize> = counters
2817 .iter()
2818 .zip(before.iter())
2819 .map(|((_, f), b)| f() - b)
2820 .collect();
2821 let fired: Vec<String> = counters
2822 .iter()
2823 .zip(deltas.iter())
2824 .map(|((label, _), d)| format!("{label}={d}"))
2825 .collect();
2826 let fired = fired.join(" ");
2827 let reference = ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len());
2828 assert_eq!(
2829 decoded.len(),
2830 reference.len(),
2831 "{name}: seed {seed}: shown-frame count vs ffmpeg"
2832 );
2833 for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() {
2834 for (plane, (a, b), w) in [
2835 ("Y", (&ours.y, &theirs.y), width),
2836 ("U", (&ours.u, &theirs.u), width / 2),
2837 ("V", (&ours.v, &theirs.v), width / 2),
2838 ] {
2839 if let Some(d) = first_diff(a, b, w) {
2840 panic!("{name}: seed {seed} frame {i} plane {plane}: {d} [{fired}]");
2841 }
2842 }
2843 }
2844 compared += 1;
2845 for (i, d) in deltas.iter().enumerate() {
2846 totals[i] += d;
2847 }
2848 }
2849 assert!(
2850 compared > 0,
2851 "{name}: every attempt hit a named refusal:\n{}",
2852 refusals.join("\n")
2853 );
2854 for (i, (label, _)) in counters.iter().enumerate() {
2855 assert!(
2856 totals[i] > 0,
2857 "{name}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
2858 the gate would prove nothing about that tool. refusals:\n{}",
2859 refusals.join("\n")
2860 );
2861 }
2862 let summary: Vec<String> = counters
2863 .iter()
2864 .zip(totals.iter())
2865 .map(|((label, _), t)| format!("{label}={t}"))
2866 .collect();
2867 eprintln!(
2868 "{name}: {compared}/{} attempts pixel-exact, {}",
2869 seeds.len(),
2870 summary.join(" ")
2871 );
2872 }
2873
2874 /// lane-hbdgates r1: the four intra tools that had an 8-bit gate and no
2875 /// 10-bit one (`filter-intra`, `smooth-intra`, `paeth-intra`,
2876 /// `intra-edge-filter`) on ONE real 10-bit `aomenc` key frame, each with
2877 /// its own hard-asserted counter. His two films are yuv420p10le, so an
2878 /// 8-bit-only gate for these tools proves nothing about the streams that
2879 /// matter (lane-covbd r1).
2880 #[test]
2881 fn a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact() {
2882 const NAME: &str = "a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact";
2883 if !have_ffmpeg() {
2884 eprintln!("SKIP {NAME}: no ffmpeg");
2885 return;
2886 }
2887 if !have_aomenc() {
2888 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2889 return;
2890 }
2891 ten_bit_tool_gate(
2892 NAME,
2893 64,
2894 64,
2895 1,
2896 &[
2897 "--limit=1",
2898 "--kf-max-dist=0",
2899 "--enable-filter-intra=1",
2900 "--enable-smooth-intra=1",
2901 "--enable-paeth-intra=1",
2902 "--enable-intra-edge-filter=1",
2903 "--enable-directional-intra=1",
2904 "--enable-angle-delta=0",
2905 "--enable-rect-partitions=0",
2906 "--enable-ab-partitions=0",
2907 "--enable-1to4-partitions=0",
2908 "--enable-tx-size-search=0",
2909 "--enable-cdef=0",
2910 "--enable-restoration=0",
2911 "--max-partition-size=32",
2912 "--min-partition-size=16",
2913 "--enable-palette=0",
2914 "--enable-intrabc=0",
2915 "--enable-cfl-intra=0",
2916 "--enable-ref-frame-mvs=0",
2917 ],
2918 &[42, 7, 11, 23, 31, 57],
2919 &[
2920 ("filter_intra_hits", decode::filter_intra_hits),
2921 ("smooth_pred_hits", crate::intra::smooth_pred_hits),
2922 ("paeth_pred_hits", crate::intra::paeth_pred_hits),
2923 ("intra_edge_filter_hits", crate::intra::intra_edge_filter_hits),
2924 ],
2925 );
2926 }
2927
2928 /// lane-hbdgates r1: `--enable-restoration=1` at 10 bits. Every earlier
2929 /// bit-depth gate ran `--enable-restoration=0`, which is exactly why two
2930 /// high-bit-depth loop-restoration defects survived to 2026-09-01
2931 /// (SGR box sums unscaled, Wiener clamp at the 8-bit bound). Same recipe
2932 /// as the 8-bit LR gate, at 10 bits.
2933 // Written `#[ignore]`d on lane-hbdgates (the branch lacked lane-hbdinter's
2934 // 10-bit LR fix and failed at seed 42, frame 0, Y index 122: ours 351 vs
2935 // ffmpeg 350). Un-ignored on the merge into main 2026-09-01, where the
2936 // SGR box-sum scaling and the Wiener clamp are fixed: 16/16 attempts
2937 // pixel-exact, lr_hits=28.
2938 #[test]
2939 fn a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact() {
2940 const NAME: &str = "a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact";
2941 if !have_ffmpeg() {
2942 eprintln!("SKIP {NAME}: no ffmpeg");
2943 return;
2944 }
2945 if !have_aomenc() {
2946 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2947 return;
2948 }
2949 // 192x128 = 3x2 superblocks, so `read_lr` is re-entered per SB
2950 // (the 8-bit LR gate's own trap warning); cq-level=15 because
2951 // aomenc's RD only picks a non-RESTORE_NONE frame type at low cq.
2952 ten_bit_tool_gate(
2953 NAME,
2954 192,
2955 128,
2956 1,
2957 &[
2958 "--limit=1",
2959 "--kf-max-dist=0",
2960 "--cq-level=15",
2961 "--enable-restoration=1",
2962 "--enable-cdef=0",
2963 "--enable-rect-partitions=0",
2964 "--enable-ab-partitions=0",
2965 "--enable-1to4-partitions=0",
2966 "--enable-filter-intra=0",
2967 "--enable-smooth-intra=0",
2968 "--enable-paeth-intra=0",
2969 "--enable-tx-size-search=0",
2970 "--max-partition-size=32",
2971 "--min-partition-size=16",
2972 "--enable-palette=0",
2973 "--enable-intrabc=0",
2974 "--enable-cfl-intra=0",
2975 "--enable-ref-frame-mvs=0",
2976 ],
2977 &LR_SEEDS,
2978 &[("lr_hits", ten_bit_lr_hits)],
2979 );
2980 }
2981
2982 /// Seeds swept by the 10-bit LR gate (the 8-bit gate needs ~40 attempts
2983 /// to land a non-RESTORE_NONE frame; every attempt here still has to
2984 /// decode pixel-exact).
2985 const LR_SEEDS: [u32; 16] = [42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
2986
2987 /// Wiener + SGR + switchable loop-restoration firings, summed.
2988 fn ten_bit_lr_hits() -> usize {
2989 crate::restoration::wiener_hits()
2990 + crate::restoration::sgrproj_hits()
2991 + crate::restoration::switchable_hits()
2992 }
2993
2994 /// lane-hbdgates r1: `--enable-rect-partitions=1 --enable-ab-partitions=1`
2995 /// at 10 bits, one intra stream, one counter per tool
2996 /// (`rect_partition_hits`, `partab_hits`) so a stream that only fired the
2997 /// rect arms cannot stand in for AB.
2998 #[test]
2999 fn a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact() {
3000 const NAME: &str = "a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact";
3001 if !have_ffmpeg() {
3002 eprintln!("SKIP {NAME}: no ffmpeg");
3003 return;
3004 }
3005 if !have_aomenc() {
3006 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3007 return;
3008 }
3009 // The 8-bit free-partition/AB recipe, verbatim, at 10 bits: AB
3010 // splits are an INTER dispatch here (intra-frame AB is still a named
3011 // refusal), so the stream needs alt-refs and 24 frames, not one key
3012 // frame.
3013 ten_bit_tool_gate(
3014 NAME,
3015 64,
3016 64,
3017 24,
3018 &[
3019 "--cq-level=45",
3020 "--kf-max-dist=1000",
3021 "--auto-alt-ref=1",
3022 "--lag-in-frames=16",
3023 "--enable-fwd-kf=0",
3024 "--enable-order-hint=1",
3025 "--enable-warped-motion=1",
3026 "--enable-obmc=1",
3027 "--tune-content=default",
3028 "--enable-masked-comp=0",
3029 "--enable-interintra-comp=0",
3030 "--enable-onesided-comp=0",
3031 "--enable-interintra-wedge=0",
3032 "--enable-smooth-interintra=0",
3033 "--enable-rect-partitions=1",
3034 "--enable-ab-partitions=1",
3035 "--enable-1to4-partitions=0",
3036 "--enable-filter-intra=0",
3037 "--enable-smooth-intra=0",
3038 "--enable-paeth-intra=0",
3039 "--enable-directional-intra=0",
3040 "--enable-angle-delta=0",
3041 "--enable-tx-size-search=0",
3042 "--enable-cdef=0",
3043 "--enable-restoration=0",
3044 "--max-partition-size=32",
3045 "--min-partition-size=16",
3046 "--enable-palette=0",
3047 "--enable-intrabc=0",
3048 "--enable-cfl-intra=0",
3049 "--enable-ref-frame-mvs=0",
3050 ],
3051 &LR_SEEDS,
3052 &[
3053 ("rect_partition_hits", decode::rect_partition_hits),
3054 ("partab_hits", decode::partab_hits),
3055 ],
3056 );
3057 }
3058
3059 /// `bit_depth` of the first sequence header in `stream`.
3060 fn parsed_bit_depth(stream: &[u8]) -> u8 {
3061 let mut probe = Av1Parser::new();
3062 let mut pos = 0usize;
3063 while pos < stream.len() && probe.sequence_header().is_none() {
3064 let obu = probe.parse_obu(&stream[pos..]).unwrap();
3065 pos += obu.total_size;
3066 }
3067 probe
3068 .sequence_header()
3069 .expect("stream has a sequence header OBU")
3070 .color_config
3071 .bit_depth
3072 }
3073
3074 /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and
3075 /// encode it with a real 10-bit `aomenc`, returning the OBU stream.
3076 /// `extra` carries the tool flags under test.
3077 fn encode_10bit_gradients(
3078 name: &str,
3079 width: usize,
3080 height: usize,
3081 frames: usize,
3082 extra: &[&str],
3083 ) -> Vec<u8> {
3084 encode_10bit_gradients_seed(name, 42, width, height, frames, extra)
3085 }
3086
3087 /// As [`encode_10bit_gradients`], but with the fixture seed exposed --
3088 /// lane-hbdgates r1 sweeps seeds so a tool that aomenc's RD declines on
3089 /// one fixture still gets a firing stream.
3090 fn encode_10bit_gradients_seed(
3091 name: &str,
3092 seed: u32,
3093 width: usize,
3094 height: usize,
3095 frames: usize,
3096 extra: &[&str],
3097 ) -> Vec<u8> {
3098 let duration = frames as f64 / 25.0;
3099 // lane-ab32 r1: `--ec-fixture-noise` is not an aomenc flag -- it is a
3100 // fixture request, consumed (and stripped) here: the smooth gradients
3101 // source codes as PARTITION_NONE everywhere, so a partition gate needs
3102 // seeded noise on top of it to give the RD a reason to split.
3103 let noisy = extra.contains(&"--ec-fixture-noise");
3104 let stripped: Vec<&str> = extra
3105 .iter()
3106 .copied()
3107 .filter(|a| *a != "--ec-fixture-noise")
3108 .collect();
3109 let extra: &[&str] = &stripped;
3110 let base = gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
3111 let source = if noisy {
3112 format!("{base},noise=alls=40:all_seed={seed}")
3113 } else {
3114 base
3115 };
3116 let y4m = Command::new("ffmpeg")
3117 .args([
3118 "-v",
3119 "error",
3120 "-f",
3121 "lavfi",
3122 "-i",
3123 &source,
3124 "-pix_fmt",
3125 "yuv420p10le",
3126 "-strict",
3127 "-1",
3128 "-t",
3129 &format!("{duration}"),
3130 "-f",
3131 "yuv4mpegpipe",
3132 "-",
3133 ])
3134 .stdin(Stdio::null())
3135 .stdout(Stdio::piped())
3136 .stderr(Stdio::piped())
3137 .output()
3138 .expect("ffmpeg failed to run");
3139 assert!(
3140 y4m.status.success(),
3141 "{name}: ffmpeg failed to render the 10-bit fixture: {}",
3142 String::from_utf8_lossy(&y4m.stderr)
3143 );
3144 let mut args: Vec<&str> = vec!["--codec=av1", "--passes=1", "--end-usage=q"];
3145 // lane-hbdgates r1: a caller-supplied `--cq-level` REPLACES the
3146 // default rather than being appended after it -- two `--cq-level`
3147 // flags on one aomenc line is a coin flip on which one lands.
3148 if !extra.iter().any(|a| a.starts_with("--cq-level=")) {
3149 args.push("--cq-level=30");
3150 }
3151 args.extend_from_slice(&[
3152 "--cpu-used=0",
3153 "--threads=1",
3154 "--row-mt=0",
3155 "--sb-size=64",
3156 "--input-bit-depth=10",
3157 "--bit-depth=10",
3158 ]);
3159 args.extend_from_slice(extra);
3160 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
3161 let mut child = Command::new(aomenc_path())
3162 .args(&args)
3163 .stdin(Stdio::piped())
3164 .stdout(Stdio::piped())
3165 .stderr(Stdio::piped())
3166 .spawn()
3167 .expect("aomenc failed to start");
3168 child
3169 .stdin
3170 .take()
3171 .expect("aomenc stdin")
3172 .write_all(&y4m.stdout)
3173 .expect("writing y4m to aomenc");
3174 let out = child.wait_with_output().expect("aomenc failed to run");
3175 assert!(
3176 out.status.success(),
3177 "{name}: aomenc refused the 10-bit fixture: {}",
3178 String::from_utf8_lossy(&out.stderr)
3179 );
3180 out.stdout
3181 }
3182
3183 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
3184 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
3185 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
3186 /// which flattened chroma to a single value specifically to avoid
3187 /// exercising this path). Same square-only recipe as the palette-Y gate
3188 /// (`--enable-rect-partitions=0`/`-ab-`/`-1to4-`, fixed 32x32 partition)
3189 /// so a UV palette block never lands inside the still-refused HORZ/VERT
3190 /// screen-content strip. HARD-asserts [`decode::palette_uv_hits`] moved
3191 /// -- a stream that never reads a real UV palette block would decode (or
3192 /// not) by construction without proving this milestone at all
3193 /// ([[gate-blind-to-feature]]).
3194 #[test]
3195 fn a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact() {
3196 const NAME: &str = "a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact";
3197 if !have_ffmpeg() {
3198 eprintln!("SKIP {NAME}: no ffmpeg");
3199 return;
3200 }
3201 if !have_aomenc() {
3202 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3203 return;
3204 }
3205 let source = "testsrc2=size=64x64:rate=25";
3206 fn render(source: &str) -> Vec<u8> {
3207 Command::new("ffmpeg")
3208 .args([
3209 "-v",
3210 "error",
3211 "-f",
3212 "lavfi",
3213 "-i",
3214 source,
3215 "-pix_fmt",
3216 "yuv420p",
3217 "-t",
3218 "0.16",
3219 "-f",
3220 "yuv4mpegpipe",
3221 "-",
3222 ])
3223 .stdin(Stdio::null())
3224 .stdout(Stdio::piped())
3225 .stderr(Stdio::piped())
3226 .output()
3227 .expect("ffmpeg failed to run")
3228 .stdout
3229 }
3230 let y4m_a = render(source);
3231 let y4m_b = render(source);
3232 assert_eq!(
3233 y4m_a, y4m_b,
3234 "testsrc2 must render byte-identical across two runs"
3235 );
3236 let y4m = y4m_a;
3237 let mut child = Command::new(aomenc_path())
3238 .args([
3239 "--codec=av1",
3240 "--passes=1",
3241 "--end-usage=q",
3242 "--cq-level=30",
3243 "--cpu-used=0",
3244 "--threads=1",
3245 "--row-mt=0",
3246 "--sb-size=64",
3247 "--tune-content=screen",
3248 "--enable-palette=1",
3249 "--enable-intrabc=0",
3250 "--enable-rect-partitions=0",
3251 "--enable-ab-partitions=0",
3252 "--enable-1to4-partitions=0",
3253 "--min-partition-size=32",
3254 "--max-partition-size=32",
3255 "--enable-filter-intra=0",
3256 "--enable-cdef=0",
3257 "--enable-restoration=0",
3258 "--enable-tx-size-search=0",
3259 "--loopfilter-control=0",
3260 "--obu",
3261 "-o",
3262 "-",
3263 "-",
3264 ])
3265 .stdin(Stdio::piped())
3266 .stdout(Stdio::piped())
3267 .stderr(Stdio::piped())
3268 .spawn()
3269 .expect("aomenc failed to start");
3270 child
3271 .stdin
3272 .take()
3273 .expect("aomenc stdin")
3274 .write_all(&y4m)
3275 .expect("writing y4m to aomenc");
3276 let out = child.wait_with_output().expect("aomenc failed to run");
3277 assert!(
3278 out.status.success(),
3279 "aomenc refused the fixture: {}",
3280 String::from_utf8_lossy(&out.stderr)
3281 );
3282 let stream = out.stdout;
3283 let before = decode::palette_uv_hits();
3284 let frames = match decode_stream(&stream) {
3285 Ok(frames) => frames,
3286 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
3287 };
3288 assert!(
3289 decode::palette_uv_hits() > before,
3290 "palette_uv_mode never fired decoding this stream -- gate is vacuous"
3291 );
3292 let frame_count = frames.len();
3293 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, frame_count);
3294 for i in 0..frame_count {
3295 assert_eq!(frames[i].y, ffmpeg_frames[i].y, "luma vs ffmpeg, frame {i}");
3296 assert_eq!(frames[i].u, ffmpeg_frames[i].u, "U vs ffmpeg, frame {i}");
3297 assert_eq!(frames[i].v, ffmpeg_frames[i].v, "V vs ffmpeg, frame {i}");
3298 }
3299 }
3300
3301 /// A real `aomenc` fixture that lands palette syntax on a HORZ/VERT
3302 /// intra strip (lane-palette2 r5, gating r4's `read_intra_mode_rect`
3303 /// wiring). `smptebars`/`rgbtestsrc` at plain default settings both hit a
3304 /// SQUARE palette refusal or an unrelated 32x32 `HORZ_A`/`VERT_A`/etc
3305 /// partition FIRST on every size/cq combo probed -- `--enable-ab-
3306 /// partitions=0` measurably does not stop aomenc choosing one at this
3307 /// screen-content tune (byte-identical output with `=0` vs `=1`, same
3308 /// aomenc quirk as `[[lane-sbpart-r2]]`'s SB-level AB). Forcing
3309 /// `--min/max-partition-size=64` sidesteps that whole 32x32-level code
3310 /// path: the only choices left at the (single, key-frame) superblock are
3311 /// NONE/SPLIT/HORZ/VERT/AB/1to4 straight from [`decode_block_rect64`],
3312 /// and a size/cq sweep (measured live this round) reliably lands
3313 /// PARTITION_HORZ/VERT with a real (non-split-tx) palette block on both
3314 /// sources. Drives `decode_stream` directly (below any refusal) and
3315 /// HARD-asserts [`decode::palette_rect_hits`] moved on every attempt that
3316 /// didn't refuse, before comparing pixels ([[gate-blind-to-feature]]) --
3317 /// a decode that never lands a rect palette block is not a match.
3318 #[test]
3319 fn a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact() {
3320 const NAME: &str = "a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact";
3321 let _gate_lock = lock_gate_counters();
3322 if !have_ffmpeg() {
3323 eprintln!("SKIP {NAME}: no ffmpeg");
3324 return;
3325 }
3326 if !have_aomenc() {
3327 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3328 return;
3329 }
3330 let mut matched = 0u32;
3331 let mut uncounted_exact = 0u32;
3332 let mut named_refusals = 0u32;
3333 let mut attempts = 0u32;
3334 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
3335 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
3336 for src_name in ["smptebars", "rgbtestsrc"] {
3337 for (width, height) in sizes {
3338 for cq in cqs {
3339 attempts += 1;
3340 let source = format!("{src_name}=size={width}x{height}:rate=25");
3341 let y4m = Command::new("ffmpeg")
3342 .args([
3343 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p",
3344 "-t", "0.04", "-f", "yuv4mpegpipe", "-",
3345 ])
3346 .stdin(Stdio::null())
3347 .stdout(Stdio::piped())
3348 .stderr(Stdio::piped())
3349 .output()
3350 .expect("ffmpeg failed to run");
3351 assert!(
3352 y4m.status.success(),
3353 "ffmpeg fixture: {}",
3354 String::from_utf8_lossy(&y4m.stderr)
3355 );
3356 let cq_arg = format!("--cq-level={cq}");
3357 let mut child = Command::new(aomenc_path())
3358 .args([
3359 "--codec=av1",
3360 "--passes=1",
3361 "--end-usage=q",
3362 &cq_arg,
3363 "--cpu-used=4",
3364 "--threads=1",
3365 "--row-mt=0",
3366 "--sb-size=64",
3367 "--enable-palette=1",
3368 "--min-partition-size=16",
3369 "--max-partition-size=64",
3370 "--obu",
3371 "-o",
3372 "-",
3373 "-",
3374 ])
3375 .stdin(Stdio::piped())
3376 .stdout(Stdio::piped())
3377 .stderr(Stdio::piped())
3378 .spawn()
3379 .expect("aomenc failed to start");
3380 child
3381 .stdin
3382 .take()
3383 .expect("aomenc stdin")
3384 .write_all(&y4m.stdout)
3385 .expect("writing y4m to aomenc");
3386 let out = child.wait_with_output().expect("aomenc failed to run");
3387 assert!(
3388 out.status.success(),
3389 "aomenc refused the fixture ({source} cq={cq}): {}",
3390 String::from_utf8_lossy(&out.stderr)
3391 );
3392 let stream = out.stdout;
3393 let before = crate::decode::palette_rect_hits();
3394 let frames = match decode_stream(&stream) {
3395 Err(e) => {
3396 let msg = e.to_string();
3397 assert!(
3398 msg.contains("unsupported"),
3399 "{NAME} failed outright, not a named refusal \
3400 ({source} cq={cq}): {msg}"
3401 );
3402 named_refusals += 1;
3403 eprintln!("{source} cq={cq}: refusal: {msg}");
3404 continue;
3405 }
3406 Ok(frames) => frames,
3407 };
3408 // A successful decode is ALWAYS pixel-compared; the hit
3409 // counter only decides whether the attempt counts toward
3410 // the hit-asserting total (class
3411 // [[gate-skips-on-its-own-failure]]: the old `continue`
3412 // here let 16/70 decoded attempts past without any pixel
3413 // check at all).
3414 let counted = crate::decode::palette_rect_hits() != before;
3415 if !counted {
3416 eprintln!(
3417 "{NAME}: {source} cq={cq} decoded without ever landing a rect \
3418 palette block (palette_rect_hits unchanged) -- pixel-compared, \
3419 not counted toward the hit assertion"
3420 );
3421 }
3422 let frame_count = frames.len();
3423 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
3424 if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| {
3425 got.y != want.y || got.u != want.u || got.v != want.v
3426 }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
3427 {
3428 std::fs::write(&path, &stream).expect("writing pinned stream");
3429 eprintln!(
3430 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
3431 );
3432 }
3433 for i in 0..frame_count {
3434 assert_eq!(
3435 frames[i].y, ffmpeg_frames[i].y,
3436 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
3437 );
3438 assert_eq!(
3439 frames[i].u, ffmpeg_frames[i].u,
3440 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
3441 );
3442 assert_eq!(
3443 frames[i].v, ffmpeg_frames[i].v,
3444 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
3445 );
3446 }
3447 if counted {
3448 matched += 1;
3449 } else {
3450 uncounted_exact += 1;
3451 }
3452 }
3453 }
3454 }
3455 assert!(
3456 matched > 0,
3457 "{NAME}: no attempt out of {attempts} ever landed a matching rect palette \
3458 block ({named_refusals} named refusals) -- palette_rect_hits never proven \
3459 pixel-exact"
3460 );
3461 eprintln!(
3462 "{NAME}: {matched}/{attempts} attempts matched pixel-exact, \
3463 {uncounted_exact} decoded-and-pixel-exact but uncounted, {named_refusals} \
3464 named refusals, palette_rect_hits={}",
3465 crate::decode::palette_rect_hits()
3466 );
3467 }
3468
3469 /// The BROAD case (lane-palette2 r6, per its charter): a HORZ/VERT intra
3470 /// strip in a screen-content-tools frame that does NOT necessarily use a
3471 /// palette. This is what the refusal r4 removed actually guarded --
3472 /// [`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`] above
3473 /// gates the rarer "and picks a palette" case, which r5 measured RD
3474 /// almost never chooses -- 39/70 of that same sweep DID land here (a
3475 /// clean rect-strip decode with `palette_rect_hits` unchanged), just
3476 /// uncounted by r5's narrower assertion. Same `--min/max-partition-size=64`
3477 /// recipe r5 measured live to dodge the 32x32-level AB-partition quirk
3478 /// ([[lane-sbpart-r2]]), single key frame, size/cq sweep. HARD-asserts
3479 /// [`decode::rect_screen_content_hits`] moved -- proof this stream
3480 /// actually ran [`read_intra_mode_rect`]'s screen-content-tools branch --
3481 /// before comparing pixels.
3482 #[test]
3483 fn a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact() {
3484 const NAME: &str = "a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact";
3485 let _gate_lock = lock_gate_counters();
3486 if !have_ffmpeg() {
3487 eprintln!("SKIP {NAME}: no ffmpeg");
3488 return;
3489 }
3490 if !have_aomenc() {
3491 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3492 return;
3493 }
3494 let mut matched = 0u32;
3495 // Blocks that reconstructed a palette-Y prediction through a SPLIT
3496 // luma transform (lane-palette2 r7's lifted refusal): the same
3497 // screen-content streams exercise it, so this gate proves both.
3498 let mut split_palette_matched = 0u32;
3499 let mut uncounted_exact = 0u32;
3500 let mut named_refusals = 0u32;
3501 let mut attempts = 0u32;
3502 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
3503 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
3504 for src_name in ["smptebars", "rgbtestsrc"] {
3505 for (width, height) in sizes {
3506 for cq in cqs {
3507 attempts += 1;
3508 let source = format!("{src_name}=size={width}x{height}:rate=25");
3509 let y4m = Command::new("ffmpeg")
3510 .args([
3511 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p",
3512 "-t", "0.04", "-f", "yuv4mpegpipe", "-",
3513 ])
3514 .stdin(Stdio::null())
3515 .stdout(Stdio::piped())
3516 .stderr(Stdio::piped())
3517 .output()
3518 .expect("ffmpeg failed to run");
3519 assert!(
3520 y4m.status.success(),
3521 "ffmpeg fixture: {}",
3522 String::from_utf8_lossy(&y4m.stderr)
3523 );
3524 let cq_arg = format!("--cq-level={cq}");
3525 let mut child = Command::new(aomenc_path())
3526 .args([
3527 "--codec=av1",
3528 "--passes=1",
3529 "--end-usage=q",
3530 &cq_arg,
3531 "--cpu-used=4",
3532 "--threads=1",
3533 "--row-mt=0",
3534 "--sb-size=64",
3535 "--enable-palette=1",
3536 "--min-partition-size=16",
3537 "--max-partition-size=64",
3538 "--obu",
3539 "-o",
3540 "-",
3541 "-",
3542 ])
3543 .stdin(Stdio::piped())
3544 .stdout(Stdio::piped())
3545 .stderr(Stdio::piped())
3546 .spawn()
3547 .expect("aomenc failed to start");
3548 child
3549 .stdin
3550 .take()
3551 .expect("aomenc stdin")
3552 .write_all(&y4m.stdout)
3553 .expect("writing y4m to aomenc");
3554 let out = child.wait_with_output().expect("aomenc failed to run");
3555 assert!(
3556 out.status.success(),
3557 "aomenc refused the fixture ({source} cq={cq}): {}",
3558 String::from_utf8_lossy(&out.stderr)
3559 );
3560 let stream = out.stdout;
3561 let before = crate::decode::rect_screen_content_hits();
3562 let split_before = crate::decode::palette_split_tx_hits();
3563 let frames = match decode_stream(&stream) {
3564 Err(e) => {
3565 let msg = e.to_string();
3566 assert!(
3567 msg.contains("unsupported"),
3568 "{NAME} failed outright, not a named refusal \
3569 ({source} cq={cq}): {msg}"
3570 );
3571 named_refusals += 1;
3572 eprintln!("{source} cq={cq}: refusal: {msg}");
3573 continue;
3574 }
3575 Ok(frames) => frames,
3576 };
3577 // Same integrity rule as the palette gate above: decoded
3578 // means pixel-compared, counter or no counter.
3579 let counted = crate::decode::rect_screen_content_hits() != before;
3580 if !counted {
3581 eprintln!(
3582 "{NAME}: {source} cq={cq} decoded without ever running the rect \
3583 screen-content path (rect_screen_content_hits unchanged) -- \
3584 pixel-compared, not counted toward the hit assertion"
3585 );
3586 }
3587 let frame_count = frames.len();
3588 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
3589 if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| {
3590 got.y != want.y || got.u != want.u || got.v != want.v
3591 }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
3592 {
3593 std::fs::write(&path, &stream).expect("writing pinned stream");
3594 eprintln!(
3595 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
3596 );
3597 }
3598 for i in 0..frame_count {
3599 assert_eq!(
3600 frames[i].y, ffmpeg_frames[i].y,
3601 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
3602 );
3603 assert_eq!(
3604 frames[i].u, ffmpeg_frames[i].u,
3605 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
3606 );
3607 assert_eq!(
3608 frames[i].v, ffmpeg_frames[i].v,
3609 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
3610 );
3611 }
3612 if counted {
3613 matched += 1;
3614 } else {
3615 uncounted_exact += 1;
3616 }
3617 if counted && crate::decode::palette_split_tx_hits() > split_before {
3618 split_palette_matched += 1;
3619 }
3620 }
3621 }
3622 }
3623 assert!(
3624 split_palette_matched > 0,
3625 "{NAME}: no pixel-exact attempt ever reconstructed a palette block with a \
3626 split luma transform -- the lifted refusal is ungated"
3627 );
3628 assert!(
3629 matched > 0,
3630 "{NAME}: no attempt out of {attempts} ever landed a matching rect \
3631 screen-content block ({named_refusals} named refusals) -- \
3632 rect_screen_content_hits never proven pixel-exact"
3633 );
3634 eprintln!(
3635 "{NAME}: {matched}/{attempts} attempts matched pixel-exact \
3636 ({split_palette_matched} of them through a split-transform palette block), \
3637 {uncounted_exact} decoded-and-pixel-exact but uncounted, \
3638 {named_refusals} named refusals, rect_screen_content_hits={}, \
3639 palette_split_tx_hits={}",
3640 crate::decode::rect_screen_content_hits(),
3641 crate::decode::palette_split_tx_hits()
3642 );
3643 }
3644
3645 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s
3646 /// harness, but with the deblocking filter left *on* (no
3647 /// `--loopfilter-control=0`) at a crf high enough that libaom actually
3648 /// picks a nonzero level -- proves `apply_deblock` itself, not just that
3649 /// this decoder still works when every edge lands on level 0. CDEF
3650 /// stays off so a pixel mismatch can only come from the loop filter.
3651 #[test]
3652 fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() {
3653 if !have_ffmpeg() {
3654 eprintln!(
3655 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no ffmpeg"
3656 );
3657 return;
3658 }
3659 if !have_aomenc() {
3660 eprintln!(
3661 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no aomenc at {}",
3662 aomenc_path().display()
3663 );
3664 return;
3665 }
3666 let (width, height) = (64usize, 64usize);
3667 let source = gradients_source(42, width, height, "duration=0.04:rate=25");
3668 let y4m = Command::new("ffmpeg")
3669 .args(["-v", "error", "-f", "lavfi", "-i"])
3670 .arg(&source)
3671 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
3672 .stdin(Stdio::null())
3673 .stdout(Stdio::piped())
3674 .stderr(Stdio::piped())
3675 .output()
3676 .expect("ffmpeg failed to run");
3677 assert!(
3678 y4m.status.success(),
3679 "ffmpeg fixture: {}",
3680 String::from_utf8_lossy(&y4m.stderr)
3681 );
3682 let mut child = Command::new(aomenc_path())
3683 .args([
3684 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
3685 // occurrence, so overrides go before the base list).
3686 "--loopfilter-control=1",
3687 "--codec=av1",
3688 "--passes=1",
3689 "--end-usage=q",
3690 "--cq-level=55",
3691 "--cpu-used=0",
3692 "--enable-filter-intra=0",
3693 "--enable-smooth-intra=0",
3694 "--enable-paeth-intra=0",
3695 "--enable-directional-intra=0",
3696 "--enable-angle-delta=0",
3697 "--enable-tx-size-search=0",
3698 "--enable-cdef=0",
3699 // Loop restoration is a named refusal (aomenc's RD picks
3700 // Sgrproj on this kind of content) -- off in every recipe
3701 // whose test targets a different surface.
3702 "--enable-restoration=0",
3703 "--max-partition-size=32",
3704 "--enable-palette=0",
3705 "--enable-intrabc=0",
3706 "--enable-cfl-intra=0",
3707 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
3708 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
3709 "--enable-ref-frame-mvs=0",
3710 "--obu",
3711 "-o",
3712 "-",
3713 "-",
3714 ])
3715 .stdin(Stdio::piped())
3716 .stdout(Stdio::piped())
3717 .stderr(Stdio::piped())
3718 .spawn()
3719 .expect("aomenc failed to start");
3720 child
3721 .stdin
3722 .take()
3723 .expect("aomenc stdin")
3724 .write_all(&y4m.stdout)
3725 .expect("writing y4m to aomenc");
3726 let out = child.wait_with_output().expect("aomenc failed to run");
3727 assert!(
3728 out.status.success(),
3729 "aomenc refused the fixture: {}",
3730 String::from_utf8_lossy(&out.stderr)
3731 );
3732 let stream = out.stdout;
3733 let before = decode::deblock_hits();
3734 let frames = match decode_stream(&stream) {
3735 Ok(frames) => frames,
3736 Err(e) => {
3737 eprintln!(
3738 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: {e}"
3739 );
3740 return;
3741 }
3742 };
3743 assert!(
3744 decode::deblock_hits() > before,
3745 "no deblocking edge fired decoding this stream -- raise cq-level"
3746 );
3747 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3748 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
3749 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
3750 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
3751 }
3752
3753 /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`],
3754 /// but WITHOUT `--enable-tx-size-search=0` -- the one flag every other
3755 /// recipe in this file pins off specifically to keep the stream on
3756 /// `TxMode::Largest`. Dropped, aomenc's RD is free to pick
3757 /// `TxMode::Select` and split some blocks' luma transform below their own
3758 /// side (spec 5.11.16), which is what this test's `tx_depth_hits()`
3759 /// counter proves actually happened -- a stream that resolves every
3760 /// `tx_depth` to 0 would pixel-match by construction (identical to
3761 /// `TxMode::Largest`) without exercising the new split-TU decode path at
3762 /// all. Same multi-seed retry shape as
3763 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]:
3764 /// aomenc's own RD is free (with tx-size search on) to also occasionally
3765 /// pick `allow_screen_content_tools` on this content, a separate,
3766 /// already-named refusal -- try several seeds, and the first stream that
3767 /// both decodes AND actually split a transform must be pixel-exact.
3768 #[test]
3769 fn a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact() {
3770 if !have_ffmpeg() {
3771 eprintln!(
3772 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no ffmpeg"
3773 );
3774 return;
3775 }
3776 if !have_aomenc() {
3777 eprintln!(
3778 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no aomenc at {}",
3779 aomenc_path().display()
3780 );
3781 return;
3782 }
3783 let (width, height) = (64usize, 64usize);
3784 let mut refusals = Vec::new();
3785 let mut uncounted_exact = 0u32;
3786 for attempt in 0..40u32 {
3787 let seed = 42 + attempt;
3788 // A flat gradient never has enough local detail for the RD
3789 // search to prefer a split transform over the block's own full
3790 // size -- `mandelbrot`'s fractal boundary gives every attempt
3791 // (a different `start_scale`) sharp, varied-frequency edges.
3792 // start_scale 5.0 is the proven first try (decodes pixel-exact
3793 // AND reads the seven-symbol set-1 tx_type rows on TX8 TUs);
3794 // later attempts walk down for variety when aomenc's RD flips
3795 // elsewhere.
3796 let source = format!(
3797 "mandelbrot=size=64x64:start_scale={}:rate=25",
3798 5.0 - f64::from(attempt) * 0.06
3799 );
3800 let y4m = Command::new("ffmpeg")
3801 .args([
3802 "-v",
3803 "error",
3804 "-f",
3805 "lavfi",
3806 "-i",
3807 &source,
3808 // Desaturated: chroma stays flat (constant 128) so
3809 // `uv_mode` always resolves to `DC_PRED` and this
3810 // decoder's still-unsupported directional-chroma round-2
3811 // gap never fires, leaving the luma detail alone to
3812 // drive whether `TxMode::Select`'s RD splits a block.
3813 "-vf",
3814 "hue=s=0",
3815 "-pix_fmt",
3816 "yuv420p",
3817 "-t",
3818 "0.04",
3819 "-f",
3820 "yuv4mpegpipe",
3821 "-",
3822 ])
3823 .stdin(Stdio::null())
3824 .stdout(Stdio::piped())
3825 .stderr(Stdio::piped())
3826 .output()
3827 .expect("ffmpeg failed to run");
3828 assert!(
3829 y4m.status.success(),
3830 "ffmpeg fixture: {}",
3831 String::from_utf8_lossy(&y4m.stderr)
3832 );
3833 let mut child = Command::new(aomenc_path())
3834 .args([
3835 "--codec=av1",
3836 "--passes=1",
3837 "--end-usage=q",
3838 "--cq-level=45",
3839 "--cpu-used=0",
3840 "--enable-rect-partitions=0",
3841 "--enable-ab-partitions=0",
3842 "--enable-1to4-partitions=0",
3843 "--enable-filter-intra=0",
3844 // Every non-DC intra tool off: directional chroma and
3845 // angle deltas are separate round-2 gaps, and DC-only
3846 // residual is exactly what gives the RD search a reason
3847 // to split a transform.
3848 "--enable-smooth-intra=0",
3849 "--enable-paeth-intra=0",
3850 "--enable-directional-intra=0",
3851 "--enable-angle-delta=0",
3852 "--enable-cdef=0",
3853 // Loop restoration is a named refusal (aomenc's RD picks
3854 // Sgrproj on this kind of content) -- off in every recipe
3855 // whose test targets a different surface.
3856 "--enable-restoration=0",
3857 "--max-partition-size=32",
3858 // 16x16 blocks are what split into the TX8 TUs whose
3859 // set-1 tx_type rows this gate exists to prove; some
3860 // scales resolve depth 2 (TX4, a named refusal) and the
3861 // attempt loop just moves on.
3862 "--min-partition-size=16",
3863 "--enable-palette=0",
3864 "--enable-intrabc=0",
3865 "--enable-cfl-intra=0",
3866 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
3867 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
3868 "--enable-ref-frame-mvs=0",
3869 "--obu",
3870 "-o",
3871 "-",
3872 "-",
3873 ])
3874 .stdin(Stdio::piped())
3875 .stdout(Stdio::piped())
3876 .stderr(Stdio::piped())
3877 .spawn()
3878 .expect("aomenc failed to start");
3879 child
3880 .stdin
3881 .take()
3882 .expect("aomenc stdin")
3883 .write_all(&y4m.stdout)
3884 .expect("writing y4m to aomenc");
3885 let out = child.wait_with_output().expect("aomenc failed to run");
3886 assert!(
3887 out.status.success(),
3888 "aomenc refused the fixture: {}",
3889 String::from_utf8_lossy(&out.stderr)
3890 );
3891 let stream = out.stdout;
3892 let before = decode::tx_depth_hits();
3893 let frames = match decode_stream(&stream) {
3894 Ok(frames) => frames,
3895 Err(e) => {
3896 refusals.push(format!("seed {seed}: {e}"));
3897 continue;
3898 }
3899 };
3900 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
3901 // is ALWAYS pixel-compared below; the hit counter only decides whether
3902 // the attempt counts toward the firing total.
3903 let counted = decode::tx_depth_hits() != before;
3904 if !counted {
3905 uncounted_exact += 1;
3906 refusals.push(format!(
3907 "seed {seed}: decoded and pixel-compared, but no block resolved a split \
3908 tx_depth"
3909 ));
3910 }
3911 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3912 assert_eq!(
3913 frames[0].y, ffmpeg_frames[0].y,
3914 "luma vs ffmpeg (seed {seed})"
3915 );
3916 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
3917 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
3918 if counted {
3919 gate_buckets(
3920 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
3921 1,
3922 uncounted_exact,
3923 refusals.len() - uncounted_exact as usize,
3924 );
3925 return;
3926 }
3927 }
3928 gate_buckets(
3929 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
3930 0,
3931 uncounted_exact,
3932 refusals.len() - uncounted_exact as usize,
3933 );
3934 eprintln!(
3935 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: every attempt \
3936 hit a named refusal or never split a transform:\n{}",
3937 refusals.join("\n")
3938 );
3939 }
3940
3941 /// lane-txselect's decisive gate: a real aomenc INTER sequence WITHOUT
3942 /// `--enable-tx-size-search=0`, the flag every other inter recipe in this
3943 /// file pins off precisely to keep the stream on `TxMode::Largest`.
3944 /// Dropped, aomenc takes its own default (`TX_MODE_SELECT` -- which is
3945 /// what both of the user's real films use), and an inter block's
3946 /// transform size is then the recursive `txfm_split` tree of spec
3947 /// 5.11.17 rather than one whole-block transform. A stream that decoded
3948 /// pixel-exact while every `txfm_split` symbol resolved to "no split"
3949 /// would prove nothing (it is `TxMode::Largest` by another name), so this
3950 /// gate hard-asserts BOTH counters: at least one `txfm_split` symbol read
3951 /// AND at least one split actually taken. Exhausting every attempt is a
3952 /// FAILURE, not a SKIP -- an unfired gate is a vacuous gate.
3953 #[test]
3954 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact() {
3955 tx_select_inter_gate(8);
3956 }
3957
3958 /// The 10-bit arm of the gate above (lane-txselect r2): both of the
3959 /// user's films are `yuv420p10le` and var-tx is exactly the tool they
3960 /// use, so an 8-bit-only proof would not reach them. Same recipe plus
3961 /// `-b 10 --input-bit-depth=10`.
3962 #[test]
3963 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact_10bit() {
3964 tx_select_inter_gate(10);
3965 }
3966
3967 fn tx_select_inter_gate(bit_depth: u32) {
3968 if !have_ffmpeg() {
3969 eprintln!(
3970 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no ffmpeg"
3971 );
3972 return;
3973 }
3974 if !have_aomenc() {
3975 eprintln!(
3976 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no aomenc at {}",
3977 aomenc_path().display()
3978 );
3979 return;
3980 }
3981 let (width, height, frame_count) = (64usize, 64usize, 4usize);
3982 let mut refusals = Vec::new();
3983 let mut uncounted_exact = 0u32;
3984 for attempt in 0..40u32 {
3985 let seed = 42 + attempt;
3986 // Detail is what makes aomenc's RD prefer a split transform; a
3987 // flat gradient resolves every `txfm_split` to 0. `mandelbrot`'s
3988 // fractal boundary is the same source the sibling intra tx-select
3989 // gate uses, at a different `start_scale` per attempt.
3990 let source = format!(
3991 "mandelbrot=size=64x64:start_scale={}:rate=25",
3992 5.0 - f64::from(attempt) * 0.06
3993 );
3994 let y4m = Command::new("ffmpeg")
3995 .args([
3996 "-v",
3997 "error",
3998 "-f",
3999 "lavfi",
4000 "-i",
4001 &source,
4002 // Desaturated chroma: `uv_mode` stays DC_PRED, so the
4003 // still-refused directional-chroma gap never fires and
4004 // luma detail alone drives the transform split.
4005 "-vf",
4006 "hue=s=0",
4007 "-pix_fmt",
4008 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
4009 // y4m carries no official 10-bit tag; ffmpeg writes one
4010 // only under `-strict -1` (a no-op at 8 bit).
4011 "-strict",
4012 "-1",
4013 "-t",
4014 "0.16",
4015 "-f",
4016 "yuv4mpegpipe",
4017 "-strict",
4018 "-1",
4019 "-",
4020 ])
4021 .stdin(Stdio::null())
4022 .stdout(Stdio::piped())
4023 .stderr(Stdio::piped())
4024 .output()
4025 .expect("ffmpeg failed to run");
4026 assert!(
4027 y4m.status.success(),
4028 "ffmpeg fixture: {}",
4029 String::from_utf8_lossy(&y4m.stderr)
4030 );
4031 let depth_args: &[&str] = if bit_depth == 10 {
4032 &["-b", "10", "--input-bit-depth=10"]
4033 } else {
4034 &[]
4035 };
4036 let mut child = Command::new(aomenc_path())
4037 .args(depth_args)
4038 .args([
4039 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
4040 // occurrence, so overrides go before the base list).
4041 "--enable-tx-size-search=1",
4042 "--codec=av1",
4043 "--passes=1",
4044 "--end-usage=q",
4045 "--cq-level=55",
4046 "--cpu-used=0",
4047 "--lag-in-frames=0",
4048 "--auto-alt-ref=0",
4049 "--kf-max-dist=1000",
4050 "--threads=1",
4051 "--row-mt=0",
4052 "--enable-order-hint=0",
4053 "--enable-warped-motion=0",
4054 "--enable-obmc=0",
4055 "--enable-masked-comp=0",
4056 "--enable-interintra-comp=0",
4057 "--enable-dist-wtd-comp=0",
4058 "--enable-diff-wtd-comp=0",
4059 "--enable-onesided-comp=0",
4060 "--enable-interintra-wedge=0",
4061 "--enable-smooth-interintra=0",
4062 "--enable-rect-partitions=0",
4063 "--enable-ab-partitions=0",
4064 "--enable-1to4-partitions=0",
4065 "--enable-filter-intra=0",
4066 "--enable-smooth-intra=0",
4067 "--enable-paeth-intra=0",
4068 "--enable-directional-intra=0",
4069 "--enable-angle-delta=0",
4070 // DELIBERATELY ABSENT: --enable-tx-size-search=0.
4071 "--enable-cdef=0",
4072 "--enable-restoration=0",
4073 "--max-partition-size=32",
4074 // Sub-16 inter partitions are a separate named refusal
4075 // (this decoder codes no inter block below 16x16 through
4076 // the square path this gate drives), and detailed content
4077 // makes aomenc's RD reach for them on nearly every seed.
4078 "--min-partition-size=16",
4079 "--enable-palette=0",
4080 "--enable-intrabc=0",
4081 "--enable-cfl-intra=0",
4082 "--enable-ref-frame-mvs=0",
4083 "--obu",
4084 "-o",
4085 "-",
4086 "-",
4087 ])
4088 .stdin(Stdio::piped())
4089 .stdout(Stdio::piped())
4090 .stderr(Stdio::piped())
4091 .spawn()
4092 .expect("aomenc failed to start");
4093 child
4094 .stdin
4095 .take()
4096 .expect("aomenc stdin")
4097 .write_all(&y4m.stdout)
4098 .expect("writing y4m to aomenc");
4099 let out = child.wait_with_output().expect("aomenc failed to run");
4100 assert!(
4101 out.status.success(),
4102 "aomenc refused the fixture: {}",
4103 String::from_utf8_lossy(&out.stderr)
4104 );
4105 let stream = out.stdout;
4106 let (reads_before, hits_before) =
4107 (decode::txfm_split_reads(), decode::txfm_split_hits());
4108 let frames = match decode_stream(&stream) {
4109 Ok(frames) => frames,
4110 Err(e) => {
4111 let msg = e.to_string();
4112 assert!(
4113 msg.contains("unsupported"),
4114 "tx-select inter decode failed outright (seed {seed}): {msg}"
4115 );
4116 refusals.push(format!("seed {seed}: {msg}"));
4117 continue;
4118 }
4119 };
4120 let (reads, hits) = (
4121 decode::txfm_split_reads() - reads_before,
4122 decode::txfm_split_hits() - hits_before,
4123 );
4124 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
4125 // is ALWAYS pixel-compared below; the hit counter only decides whether
4126 // the attempt counts toward the firing total.
4127 let counted = hits != 0;
4128 if !counted {
4129 uncounted_exact += 1;
4130 refusals.push(format!(
4131 "seed {seed}: decoded and pixel-compared, but no block took a txfm_split \
4132 ({reads} symbols read)"
4133 ));
4134 }
4135 let ffmpeg_frames = if bit_depth == 10 {
4136 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
4137 } else {
4138 ffmpeg_decode_sequence(&stream, width, height, frame_count)
4139 };
4140 assert_eq!(frames.len(), frame_count);
4141 eprintln!(
4142 "txselect gate {bit_depth}-bit seed={seed}: txfm_split reads={reads} splits taken={hits}"
4143 );
4144 // Name the first differing sample before the assert fires: a
4145 // 64x64 plane's `assert_eq!` output is 4096 numbers, useless for
4146 // locating a desync.
4147 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4148 for (plane, (g, w)) in [
4149 ("Y", (&got.y, &want.y)),
4150 ("U", (&got.u, &want.u)),
4151 ("V", (&got.v, &want.v)),
4152 ] {
4153 let stride = if plane == "Y" { width } else { width / 2 };
4154 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
4155 eprintln!(
4156 "txselect gate seed={seed}: frame {i} {plane} first diff at \
4157 ({}, {}) got {} want {} ({} samples differ)",
4158 at % stride,
4159 at / stride,
4160 g[at],
4161 w[at],
4162 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
4163 );
4164 let coords: Vec<String> = g
4165 .iter()
4166 .zip(w.iter())
4167 .enumerate()
4168 .filter(|(_, (a, b))| a != b)
4169 .take(12)
4170 .map(|(k, (a, b))| format!("({},{})={a}/{b}", k % stride, k / stride))
4171 .collect();
4172 eprintln!("txselect gate seed={seed}: frame {i} {plane} diffs {coords:?}");
4173 }
4174 }
4175 }
4176 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4177 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
4178 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
4179 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
4180 }
4181 if counted {
4182 gate_buckets(
4183 &format!("tx_select_inter_gate({bit_depth})"),
4184 1,
4185 uncounted_exact,
4186 refusals.len() - uncounted_exact as usize,
4187 );
4188 return;
4189 }
4190 }
4191 gate_buckets(
4192 &format!("tx_select_inter_gate({bit_depth})"),
4193 0,
4194 uncounted_exact,
4195 refusals.len() - uncounted_exact as usize,
4196 );
4197 panic!(
4198 "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}",
4199 refusals.join("\n")
4200 );
4201 }
4202
4203 /// lane-chroma r2 stage 1: a real aomenc key frame with
4204 /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`)
4205 /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still-
4206 /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never
4207 /// fires; smooth *luma* neighbours are exactly what this gate wants to
4208 /// exercise, proving [`decode::smooth_luma_hits`] actually landed a
4209 /// directional block next to a smooth-predicted one and decoded
4210 /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix).
4211 #[test]
4212 fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() {
4213 if !have_ffmpeg() {
4214 eprintln!(
4215 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg"
4216 );
4217 return;
4218 }
4219 if !have_aomenc() {
4220 eprintln!(
4221 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}",
4222 aomenc_path().display()
4223 );
4224 return;
4225 }
4226 let (width, height) = (64usize, 64usize);
4227 let mut refusals = Vec::new();
4228 let mut fired_runs = 0u32;
4229 let mut uncounted_exact = 0u32;
4230 for attempt in 0..40u32 {
4231 let seed = 42 + attempt;
4232 let source = format!(
4233 "mandelbrot=size=64x64:start_scale={}:rate=25",
4234 5.0 - f64::from(attempt) * 0.06
4235 );
4236 let y4m = Command::new("ffmpeg")
4237 .args([
4238 "-v",
4239 "error",
4240 "-f",
4241 "lavfi",
4242 "-i",
4243 &source,
4244 "-pix_fmt",
4245 "yuv420p",
4246 "-t",
4247 "0.04",
4248 "-f",
4249 "yuv4mpegpipe",
4250 "-",
4251 ])
4252 .stdin(Stdio::null())
4253 .stdout(Stdio::piped())
4254 .stderr(Stdio::piped())
4255 .output()
4256 .expect("ffmpeg failed to run");
4257 assert!(
4258 y4m.status.success(),
4259 "ffmpeg fixture: {}",
4260 String::from_utf8_lossy(&y4m.stderr)
4261 );
4262 let mut child = Command::new(aomenc_path())
4263 .args([
4264 "--codec=av1",
4265 "--passes=1",
4266 "--end-usage=q",
4267 "--cq-level=45",
4268 "--cpu-used=0",
4269 "--enable-rect-partitions=0",
4270 "--enable-ab-partitions=0",
4271 "--enable-1to4-partitions=0",
4272 "--enable-filter-intra=0",
4273 "--enable-smooth-intra=1",
4274 // Smooth/paeth chroma is a still-refused, separate
4275 // round-2 gap -- off so no attempt trips it while this
4276 // gate is purely about luma's edge-filter fix.
4277 "--enable-paeth-intra=0",
4278 "--enable-tx-size-search=0",
4279 "--enable-cdef=0",
4280 "--enable-restoration=0",
4281 "--enable-intra-edge-filter=1",
4282 "--max-partition-size=32",
4283 "--min-partition-size=16",
4284 "--enable-palette=0",
4285 "--enable-intrabc=0",
4286 "--enable-cfl-intra=0",
4287 "--enable-ref-frame-mvs=0",
4288 "--obu",
4289 "-o",
4290 "-",
4291 "-",
4292 ])
4293 .stdin(Stdio::piped())
4294 .stdout(Stdio::piped())
4295 .stderr(Stdio::piped())
4296 .spawn()
4297 .expect("aomenc failed to start");
4298 child
4299 .stdin
4300 .take()
4301 .expect("aomenc stdin")
4302 .write_all(&y4m.stdout)
4303 .expect("writing y4m to aomenc");
4304 let out = child.wait_with_output().expect("aomenc failed to run");
4305 assert!(
4306 out.status.success(),
4307 "aomenc refused the fixture: {}",
4308 String::from_utf8_lossy(&out.stderr)
4309 );
4310 let stream = out.stdout;
4311 let smooth_before = decode::smooth_luma_hits();
4312 let frames = match decode_stream(&stream) {
4313 Ok(frames) => frames,
4314 Err(e) => {
4315 refusals.push(format!("seed {seed}: {e}"));
4316 continue;
4317 }
4318 };
4319 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
4320 // is ALWAYS pixel-compared below; the hit counter only decides whether
4321 // the attempt counts toward the firing total.
4322 let counted = decode::smooth_luma_hits() != smooth_before;
4323 if counted {
4324 fired_runs += 1;
4325 } else {
4326 uncounted_exact += 1;
4327 refusals.push(format!(
4328 "seed {seed}: decoded and pixel-compared, but no smooth-luma-neighbour block \
4329 fired"
4330 ));
4331 }
4332 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4333 assert_eq!(
4334 frames[0].y, ffmpeg_frames[0].y,
4335 "luma vs ffmpeg (seed {seed})"
4336 );
4337 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
4338 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
4339 if fired_runs >= 4 {
4340 gate_buckets(
4341 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
4342 fired_runs,
4343 uncounted_exact,
4344 refusals.len() - uncounted_exact as usize,
4345 );
4346 return;
4347 }
4348 }
4349 gate_buckets(
4350 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
4351 fired_runs,
4352 uncounted_exact,
4353 refusals.len() - uncounted_exact as usize,
4354 );
4355 assert!(
4356 fired_runs > 0,
4357 "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}",
4358 refusals.join("\n")
4359 );
4360 }
4361
4362 /// The smooth/paeth-chroma gate (lane-chroma r1/r3): a real aomenc key
4363 /// frame with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the
4364 /// opposite of the directional-chroma gate below, which turns these OFF
4365 /// to keep this gap from firing while directional chroma is under test).
4366 /// Some seeds won't pick smooth/paeth for chroma at all -- retry like
4367 /// every other real-encoder gate here, but the first attempt that
4368 /// actually fires [`decode::smooth_uv_hits`] must decode pixel-exact.
4369 #[test]
4370 fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() {
4371 if !have_ffmpeg() {
4372 eprintln!(
4373 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg"
4374 );
4375 return;
4376 }
4377 if !have_aomenc() {
4378 eprintln!(
4379 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}",
4380 aomenc_path().display()
4381 );
4382 return;
4383 }
4384 let (width, height) = (64usize, 64usize);
4385 let mut refusals = Vec::new();
4386 let mut fired_runs = 0u32;
4387 let mut uncounted_exact = 0u32;
4388 for attempt in 0..40u32 {
4389 let seed = 42 + attempt;
4390 let source = format!(
4391 "mandelbrot=size=64x64:start_scale={}:rate=25",
4392 5.0 - f64::from(attempt) * 0.06
4393 );
4394 let y4m = Command::new("ffmpeg")
4395 .args([
4396 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-t",
4397 "0.04", "-f", "yuv4mpegpipe", "-",
4398 ])
4399 .stdin(Stdio::null())
4400 .stdout(Stdio::piped())
4401 .stderr(Stdio::piped())
4402 .output()
4403 .expect("ffmpeg failed to run");
4404 assert!(
4405 y4m.status.success(),
4406 "ffmpeg fixture: {}",
4407 String::from_utf8_lossy(&y4m.stderr)
4408 );
4409 let mut child = Command::new(aomenc_path())
4410 .args([
4411 "--codec=av1",
4412 "--passes=1",
4413 "--end-usage=q",
4414 "--cq-level=45",
4415 "--cpu-used=0",
4416 "--enable-rect-partitions=0",
4417 "--enable-ab-partitions=0",
4418 "--enable-1to4-partitions=0",
4419 "--enable-filter-intra=0",
4420 "--enable-smooth-intra=1",
4421 "--enable-paeth-intra=1",
4422 "--enable-tx-size-search=0",
4423 "--enable-cdef=0",
4424 "--enable-restoration=0",
4425 "--enable-intra-edge-filter=1",
4426 "--max-partition-size=32",
4427 // 8x8/leaf8 splits are a separate, already-named refusal.
4428 "--min-partition-size=16",
4429 "--enable-palette=0",
4430 "--enable-intrabc=0",
4431 "--enable-cfl-intra=0",
4432 "--enable-ref-frame-mvs=0",
4433 "--obu",
4434 "-o",
4435 "-",
4436 "-",
4437 ])
4438 .stdin(Stdio::piped())
4439 .stdout(Stdio::piped())
4440 .stderr(Stdio::piped())
4441 .spawn()
4442 .expect("aomenc failed to start");
4443 child
4444 .stdin
4445 .take()
4446 .expect("aomenc stdin")
4447 .write_all(&y4m.stdout)
4448 .expect("writing y4m to aomenc");
4449 let out = child.wait_with_output().expect("aomenc failed to run");
4450 assert!(
4451 out.status.success(),
4452 "aomenc refused the fixture: {}",
4453 String::from_utf8_lossy(&out.stderr)
4454 );
4455 let stream = out.stdout;
4456 let smooth_before = decode::smooth_uv_hits();
4457 let frames = match decode_stream(&stream) {
4458 Ok(frames) => frames,
4459 Err(e) => {
4460 refusals.push(format!("seed {seed}: {e}"));
4461 continue;
4462 }
4463 };
4464 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
4465 // is ALWAYS pixel-compared below; the hit counter only decides whether
4466 // the attempt counts toward the firing total.
4467 let counted = decode::smooth_uv_hits() != smooth_before;
4468 if counted {
4469 fired_runs += 1;
4470 } else {
4471 uncounted_exact += 1;
4472 refusals.push(format!(
4473 "seed {seed}: decoded and pixel-compared, but no smooth/paeth uv_mode fired"
4474 ));
4475 }
4476 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4477 assert_eq!(
4478 frames[0].y, ffmpeg_frames[0].y,
4479 "luma vs ffmpeg (seed {seed})"
4480 );
4481 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
4482 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
4483 if fired_runs >= 4 {
4484 gate_buckets(
4485 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
4486 fired_runs,
4487 uncounted_exact,
4488 refusals.len() - uncounted_exact as usize,
4489 );
4490 return;
4491 }
4492 }
4493 gate_buckets(
4494 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
4495 fired_runs,
4496 uncounted_exact,
4497 refusals.len() - uncounted_exact as usize,
4498 );
4499 assert!(
4500 fired_runs > 0,
4501 "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}",
4502 refusals.join("\n")
4503 );
4504 }
4505
4506 /// The directional-chroma/angle-delta gate: a real aomenc key frame with
4507 /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the
4508 /// opposite of every sibling recipe's `=0`, which existed specifically to
4509 /// keep this round-2 gap from firing while a different surface was under
4510 /// test). A colourful, sharp-edged source gives the RD search a reason to
4511 /// pick a directional `uv_mode` and/or a nonzero angle delta -- some
4512 /// seeds still won't, so retry like every other real-encoder gate here,
4513 /// but the first attempt that actually fires either counter must decode
4514 /// pixel-exact.
4515 #[test]
4516 fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() {
4517 if !have_ffmpeg() {
4518 eprintln!(
4519 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg"
4520 );
4521 return;
4522 }
4523 if !have_aomenc() {
4524 eprintln!(
4525 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}",
4526 aomenc_path().display()
4527 );
4528 return;
4529 }
4530 let (width, height) = (64usize, 64usize);
4531 let mut refusals = Vec::new();
4532 let mut fired_runs = 0u32;
4533 let mut uncounted_exact = 0u32;
4534 for attempt in 0..40u32 {
4535 let seed = 42 + attempt;
4536 let source = format!(
4537 "mandelbrot=size=64x64:start_scale={}:rate=25",
4538 5.0 - f64::from(attempt) * 0.06
4539 );
4540 let y4m = Command::new("ffmpeg")
4541 .args([
4542 "-v",
4543 "error",
4544 "-f",
4545 "lavfi",
4546 "-i",
4547 &source,
4548 "-pix_fmt",
4549 "yuv420p",
4550 "-t",
4551 "0.04",
4552 "-f",
4553 "yuv4mpegpipe",
4554 "-",
4555 ])
4556 .stdin(Stdio::null())
4557 .stdout(Stdio::piped())
4558 .stderr(Stdio::piped())
4559 .output()
4560 .expect("ffmpeg failed to run");
4561 assert!(
4562 y4m.status.success(),
4563 "ffmpeg fixture: {}",
4564 String::from_utf8_lossy(&y4m.stderr)
4565 );
4566 let mut child = Command::new(aomenc_path())
4567 .args([
4568 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
4569 // occurrence, so overrides go before the base list).
4570 "--enable-directional-intra=1",
4571 "--codec=av1",
4572 "--passes=1",
4573 "--end-usage=q",
4574 "--cq-level=45",
4575 "--cpu-used=0",
4576 "--enable-rect-partitions=0",
4577 "--enable-ab-partitions=0",
4578 "--enable-1to4-partitions=0",
4579 "--enable-filter-intra=0",
4580 // Smooth/Paeth chroma is a separate, still-refused round-2
4581 // gap (an unrelated `Edges::build` no-neighbour bug this
4582 // lane does not cover) -- off so the RD search's only
4583 // non-DC/CFL chroma choice left is directional.
4584 "--enable-smooth-intra=0",
4585 "--enable-paeth-intra=0",
4586 "--enable-tx-size-search=0",
4587 "--enable-cdef=0",
4588 "--enable-restoration=0",
4589 // The intra edge filter/upsample (spec 7.11.2.7-2.9) is
4590 // now implemented (`directional()`) -- left ON (aomenc's
4591 // own default) so this gate actually exercises it instead
4592 // of the un-filtered fast path a disabled flag would keep
4593 // testing.
4594 "--enable-intra-edge-filter=1",
4595 "--max-partition-size=32",
4596 // Same reason as the tx-select gate above: 8x8 and other
4597 // sub-16x16 splits are a separate, already-named refusal.
4598 "--min-partition-size=16",
4599 "--enable-palette=0",
4600 "--enable-intrabc=0",
4601 "--enable-cfl-intra=0",
4602 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
4603 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
4604 "--enable-ref-frame-mvs=0",
4605 "--obu",
4606 "-o",
4607 "-",
4608 "-",
4609 ])
4610 .stdin(Stdio::piped())
4611 .stdout(Stdio::piped())
4612 .stderr(Stdio::piped())
4613 .spawn()
4614 .expect("aomenc failed to start");
4615 child
4616 .stdin
4617 .take()
4618 .expect("aomenc stdin")
4619 .write_all(&y4m.stdout)
4620 .expect("writing y4m to aomenc");
4621 let out = child.wait_with_output().expect("aomenc failed to run");
4622 assert!(
4623 out.status.success(),
4624 "aomenc refused the fixture: {}",
4625 String::from_utf8_lossy(&out.stderr)
4626 );
4627 let stream = out.stdout;
4628 let (uv_before, angle_before) =
4629 (decode::directional_uv_hits(), decode::angle_delta_hits());
4630 let frames = match decode_stream(&stream) {
4631 Ok(frames) => frames,
4632 Err(e) => {
4633 refusals.push(format!("seed {seed}: {e}"));
4634 continue;
4635 }
4636 };
4637 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
4638 // is ALWAYS pixel-compared below; the hit counter only decides whether
4639 // the attempt counts toward the firing total.
4640 let counted = decode::directional_uv_hits() != uv_before
4641 || decode::angle_delta_hits() != angle_before;
4642 if counted {
4643 fired_runs += 1;
4644 } else {
4645 uncounted_exact += 1;
4646 refusals.push(format!(
4647 "seed {seed}: decoded and pixel-compared, but neither a directional uv_mode \
4648 nor a nonzero angle delta fired"
4649 ));
4650 }
4651 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4652 assert_eq!(
4653 frames[0].y, ffmpeg_frames[0].y,
4654 "luma vs ffmpeg (seed {seed})"
4655 );
4656 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
4657 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
4658 if fired_runs >= 4 {
4659 gate_buckets(
4660 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
4661 fired_runs,
4662 uncounted_exact,
4663 refusals.len() - uncounted_exact as usize,
4664 );
4665 return;
4666 }
4667 }
4668 gate_buckets(
4669 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
4670 fired_runs,
4671 uncounted_exact,
4672 refusals.len() - uncounted_exact as usize,
4673 );
4674 assert!(
4675 fired_runs > 0,
4676 "every attempt hit a named refusal or never exercised directional chroma:\n{}",
4677 refusals.join("\n")
4678 );
4679 }
4680
4681 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
4682 /// --auto-alt-ref=0` keep every non-key frame a simple forward
4683 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this
4684 /// decoder's inter path does not model), `--kf-max-dist` past the clip's
4685 /// own length keeps frame 0 the only key frame.
4686 /// lane-inter8 r1: the inter tile path's SB-level `PARTITION_NONE` -- a
4687 /// whole 64x64 superblock coded as ONE inter block, which is what aomenc
4688 /// picks for static content and which this decoder refused by name
4689 /// ("an inter SB-level partition type other than SPLIT") until this
4690 /// round. HARD-asserts [`decode::inter_sb_none_hits`] moved (the arm
4691 /// really fired, class refusal-lifted-without-a-gate) and every frame is
4692 /// pixel-exact vs ffmpeg; a decode error is a FAILURE here, never a SKIP
4693 /// (class gate-skips-on-its-own-failure).
4694 /// lane-inter8 r1: generalised so the same recipe can target a deeper
4695 /// level of the inter partition tree -- `min_part` is aomenc's
4696 /// `--min-partition-size`, and `hits`/`what` name the counter that proves
4697 /// the arm under test really fired.
4698 #[track_caller]
4699 fn inter_sb_none_gate(
4700 name: &str,
4701 ten_bit: bool,
4702 min_part: &str,
4703 max_part: &str,
4704 hits: fn() -> usize,
4705 what: &str,
4706 // lane-inter8 r3: extra aomenc flags + the frame width they need.
4707 // `--tile-columns=1` needs a frame at least two superblocks wide or
4708 // aomenc silently codes one tile column and the arm is vacuous.
4709 extra: &[&str],
4710 width: usize,
4711 ) {
4712 if !have_ffmpeg() {
4713 eprintln!("SKIP {name}: no ffmpeg");
4714 return;
4715 }
4716 if !have_aomenc() {
4717 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
4718 return;
4719 }
4720 let (height, frame_count) = (64usize, 4usize);
4721 // A deterministic synthetic source with real motion (a static source
4722 // codes every inter frame as skip and never exercises the residual
4723 // path); bounded with `-t` (class gate-loader-slurps-whole-file).
4724 let y4m = Command::new("ffmpeg")
4725 .args([
4726 "-v",
4727 "error",
4728 "-f",
4729 "lavfi",
4730 "-i",
4731 &format!("mandelbrot=size={width}x{height}:rate=25"),
4732 "-t",
4733 "0.16",
4734 "-pix_fmt",
4735 if ten_bit { "yuv420p10le" } else { "yuv420p" },
4736 // y4m calls 10-bit unofficial (same as the 10-bit key-frame
4737 // gate's own fixture).
4738 "-strict",
4739 "-1",
4740 "-f",
4741 "yuv4mpegpipe",
4742 "-",
4743 ])
4744 .stdin(Stdio::null())
4745 .stdout(Stdio::piped())
4746 .stderr(Stdio::piped())
4747 .output()
4748 .expect("ffmpeg failed to run");
4749 assert!(
4750 y4m.status.success(),
4751 "{name}: ffmpeg fixture: {}",
4752 String::from_utf8_lossy(&y4m.stderr)
4753 );
4754 let mut args: Vec<String> = [
4755 "--codec=av1",
4756 "--passes=1",
4757 "--end-usage=q",
4758 "--cq-level=40",
4759 "--cpu-used=0",
4760 "--lag-in-frames=0",
4761 "--auto-alt-ref=0",
4762 "--kf-max-dist=1000",
4763 // No cross-frame CDF forwarding in this fixture (see the
4764 // deblocking gate's own note).
4765 "--error-resilient=1",
4766 // This gate targets the SB-level NONE arm only: rect/AB/1-to-4
4767 // partitions and sub-16x16 splits stay off so a failure here
4768 // cannot be another lane's missing arm.
4769 "--enable-rect-partitions=0",
4770 "--enable-ab-partitions=0",
4771 "--enable-1to4-partitions=0",
4772 "--enable-filter-intra=0",
4773 "--enable-smooth-intra=0",
4774 "--enable-paeth-intra=0",
4775 "--enable-directional-intra=0",
4776 "--enable-angle-delta=0",
4777 "--enable-tx-size-search=0",
4778 "--enable-cdef=0",
4779 "--enable-restoration=0",
4780 "--enable-palette=0",
4781 "--enable-intrabc=0",
4782 "--enable-cfl-intra=0",
4783 "--enable-ref-frame-mvs=0",
4784 "--obu",
4785 "-o",
4786 "-",
4787 "-",
4788 ]
4789 .iter()
4790 .map(|s| (*s).to_string())
4791 .collect();
4792 for e in extra {
4793 args.insert(1, (*e).to_string());
4794 }
4795 args.insert(1, format!("--min-partition-size={min_part}"));
4796 args.insert(1, format!("--max-partition-size={max_part}"));
4797 if ten_bit {
4798 args.insert(1, "--input-bit-depth=10".to_string());
4799 args.insert(1, "--bit-depth=10".to_string());
4800 }
4801 let mut child = Command::new(aomenc_path())
4802 .args(&args)
4803 .stdin(Stdio::piped())
4804 .stdout(Stdio::piped())
4805 .stderr(Stdio::piped())
4806 .spawn()
4807 .expect("aomenc failed to start");
4808 child
4809 .stdin
4810 .take()
4811 .expect("aomenc stdin")
4812 .write_all(&y4m.stdout)
4813 .expect("writing y4m to aomenc");
4814 let out = child.wait_with_output().expect("aomenc failed to run");
4815 assert!(
4816 out.status.success(),
4817 "{name}: aomenc refused the fixture: {}",
4818 String::from_utf8_lossy(&out.stderr)
4819 );
4820 let stream = out.stdout;
4821 let before = hits();
4822 let frames = match decode_stream(&stream) {
4823 Ok(frames) => frames,
4824 Err(e) => {
4825 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
4826 let _ = std::fs::write(&pin, &stream);
4827 panic!("{name}: decode_stream refused a real aomenc stream: {e} (pinned at {})", pin.display());
4828 }
4829 };
4830 assert!(
4831 hits() > before,
4832 "{name}: no {what} fired -- this gate proves nothing"
4833 );
4834 let ffmpeg_frames = if ten_bit {
4835 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
4836 } else {
4837 ffmpeg_decode_sequence(&stream, width, height, frame_count)
4838 };
4839 assert_eq!(frames.len(), frame_count, "{name}: frame count");
4840 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4841 if got.y != want.y || got.u != want.u || got.v != want.v {
4842 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
4843 let _ = std::fs::write(&pin, &stream);
4844 panic!("{name}: frame {i} mismatch vs ffmpeg -- stream pinned at {}", pin.display());
4845 }
4846 }
4847 }
4848
4849 #[test]
4850 fn a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
4851 inter_sb_none_gate(
4852 "a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
4853 false,
4854 "32",
4855 "64",
4856 decode::inter_sb_none_hits,
4857 "whole-superblock inter PARTITION_NONE",
4858 &[],
4859 64,
4860 );
4861 }
4862
4863 #[test]
4864 fn a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
4865 inter_sb_none_gate(
4866 "a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
4867 true,
4868 "32",
4869 "64",
4870 decode::inter_sb_none_hits,
4871 "whole-superblock inter PARTITION_NONE",
4872 &[],
4873 64,
4874 );
4875 }
4876
4877 /// lane-inter8 r1: the same recipe with `--min-partition-size=8`, so
4878 /// aomenc's RD may split a 16x16 inter block into four 8x8 leaves. The
4879 /// interior (non-edge-straddling) `PARTITION_SPLIT` at the 16x16 level
4880 /// was refused by name until this round; the straddle path always ran the
4881 /// same loop, so only [`decode::inter_sub16_split_hits`] -- which counts
4882 /// interior splits only -- proves the newly-lifted alphabet value fired.
4883 // lane-inter8 r2: GREEN. The neighbour side bands are mi-granular, every
4884 // leaf stamps its own 2x2-mi span (including the compound-return path
4885 // that used to skip `record_mi` entirely) and the compound
4886 // group/index contexts read the LEAF's mi cell, not its 16x16's corner.
4887 /// lane-inter8 r3, from lane-sub8's verifier finding: the mi-granular
4888 /// inter neighbour bands added in r2 must reset per TILE (above) and per
4889 /// SB row (left) and guard availability tile-relative, so the same recipe
4890 /// runs again at 128x64 with two tile columns -- a leaf on the second
4891 /// tile's first column has no left neighbour and must not read the first
4892 /// tile's band.
4893 // lane-inter8 r3: RED for a reason OUTSIDE this lane -- at 128x64 (the
4894 // narrowest frame two tile columns can exist in) aomenc codes an
4895 // SB-level rect partition on the KEY frame despite
4896 // --enable-rect-partitions=0, so the stream stops at "a superblock-level
4897 // partition type other than NONE or SPLIT" (lane-sbpart's arm) before a
4898 // single 8x8 leaf is reached. The tile-relative audit it was written for
4899 // was done by inspection instead: every reader of the mi bands guards on
4900 // `tile_row0_mi`/`tile_col0_mi` (no `> 0` guard exists in decode.rs),
4901 // `start_tile` resets the above mi bands over the tile's own mi column
4902 // span and `start_row` resets every left mi band.
4903 #[ignore = "lane-inter8 r3: blocked by the SB-level rect-partition refusal at 128x64 (lane-sbpart's arm), not by tile context"]
4904 #[test]
4905 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact()
4906 {
4907 inter_sb_none_gate(
4908 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact",
4909 false,
4910 "8",
4911 "16",
4912 decode::inter_sub16_split_hits,
4913 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
4914 &["--tile-columns=1"],
4915 128,
4916 );
4917 }
4918
4919 #[test]
4920 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
4921 inter_sb_none_gate(
4922 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
4923 false,
4924 "8",
4925 "16",
4926 decode::inter_sub16_split_hits,
4927 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
4928 &[],
4929 64,
4930 );
4931 }
4932
4933 #[test]
4934 // lane-inter8 r2: still RED, and ignored rather than deleted -- the 8-bit
4935 // twin above is green, this 10-bit recipe stops at "an INTER 32x32
4936 // partition type this decoder does not code (value=9)". That is OUR
4937 // desync, proven: `EC_TRACE=1 aomdec` on the pinned stream reads
4938 // 16 `bsize=9 value=3` (SPLIT) partitions and never a single value=9
4939 // anywhere (class refusal-from-own-desync; the r1 ledger line claiming
4940 // aomenc emits PARTITION_VERT_4 despite --enable-1to4-partitions=0 is
4941 // hereby disproven). The divergence itself is not yet bisected.
4942 #[ignore = "lane-inter8 r2: 10-bit twin still desyncs (surfaces as a bogus 32x32 value=9 refusal); 8-bit gate is green"]
4943 fn a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
4944 inter_sb_none_gate(
4945 "a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
4946 true,
4947 "8",
4948 "16",
4949 decode::inter_sub16_split_hits,
4950 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
4951 &[],
4952 64,
4953 );
4954 }
4955
4956 /// lane-eobc1 r1: an INTER sequence whose CHROMA coefficient blocks come
4957 /// off the class-1 (`TX_CLASS_HORIZ`/`VERT`) `eob_pt` row. Chroma codes
4958 /// no `tx_type` symbol of its own -- it inherits the colocated luma type
4959 /// (`av1_get_tx_type`, `blockd.h:1291`) -- so an 8x8 inter leaf whose
4960 /// luma picks `H_*`/`V_*` puts its 4x4 chroma on a CDF row this crate
4961 /// wired for only some sizes until this round (`eob_pt_class1: None` in
4962 /// 9 of 16 `TxbSet` arms, chroma 4x4/8x8 among them).
4963 ///
4964 /// The full tx set stays on (no `--reduced-tx-type-set=1`) and
4965 /// `--enable-flip-idtx=1` is asked for explicitly; the sinusoidal-stripe
4966 /// luma of the `tx_class1` key-frame gate is what actually resolves 1D
4967 /// types, and the temporally-moving chroma ramp keeps chroma out of
4968 /// `all_zero` so it has an `eob` to read at all. Attempts sweep cq and
4969 /// stripe period; a run counts only when
4970 /// [`decode::chroma_eob_class1_hits`] moved, and every shown frame is
4971 /// compared pixel-exact vs ffmpeg (a decode error is a FAILURE, never a
4972 /// SKIP -- class gate-skips-on-its-own-failure).
4973 fn chroma_class1_eob_gate(name: &str, ten_bit: bool) {
4974 if !have_ffmpeg() {
4975 eprintln!("SKIP {name}: no ffmpeg");
4976 return;
4977 }
4978 if !have_aomenc() {
4979 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
4980 return;
4981 }
4982 let (width, height, frame_count) = (64usize, 64usize, 4usize);
4983 let mut refusals = Vec::new();
4984 for attempt in 0..12u32 {
4985 let cq = 28 + (attempt % 4) * 10;
4986 let period = [4u32, 6, 8][(attempt as usize / 4) % 3];
4987 let y4m = Command::new("ffmpeg")
4988 .args([
4989 "-v",
4990 "error",
4991 "-f",
4992 "lavfi",
4993 "-i",
4994 &format!("testsrc2=size={width}x{height}:rate=25"),
4995 "-vf",
4996 &format!(
4997 "geq=lum='128+80*sin(2*PI*Y/{period})':cb='128+60*sin(2*PI*(X+8*T)/{period})':cr='128+60*sin(2*PI*(Y+8*T)/{period})',noise=alls=6:allf=t:all_seed=7"
4998 ),
4999 "-t",
5000 "0.16",
5001 "-pix_fmt",
5002 if ten_bit { "yuv420p10le" } else { "yuv420p" },
5003 "-strict",
5004 "-1",
5005 "-f",
5006 "yuv4mpegpipe",
5007 "-",
5008 ])
5009 .stdin(Stdio::null())
5010 .stdout(Stdio::piped())
5011 .stderr(Stdio::piped())
5012 .output()
5013 .expect("ffmpeg failed to run");
5014 assert!(
5015 y4m.status.success(),
5016 "{name}: ffmpeg fixture: {}",
5017 String::from_utf8_lossy(&y4m.stderr)
5018 );
5019 let mut args: Vec<String> = [
5020 "--codec=av1",
5021 "--passes=1",
5022 "--end-usage=q",
5023 "--cpu-used=0",
5024 "--lag-in-frames=0",
5025 "--auto-alt-ref=0",
5026 "--kf-max-dist=1000",
5027 "--error-resilient=1",
5028 "--enable-flip-idtx=1",
5029 "--reduced-tx-type-set=0",
5030 "--min-partition-size=8",
5031 "--max-partition-size=16",
5032 // Motion tools this decoder refuses by name, kept off so a
5033 // refusal here can only be about the coefficient path.
5034 "--enable-global-motion=0",
5035 "--enable-warped-motion=0",
5036 "--enable-obmc=0",
5037 "--enable-rect-partitions=0",
5038 "--enable-ab-partitions=0",
5039 "--enable-1to4-partitions=0",
5040 "--enable-filter-intra=0",
5041 "--enable-smooth-intra=0",
5042 "--enable-paeth-intra=0",
5043 "--enable-directional-intra=0",
5044 "--enable-angle-delta=0",
5045 "--enable-tx-size-search=0",
5046 "--enable-cdef=0",
5047 "--enable-restoration=0",
5048 "--loopfilter-control=0",
5049 "--enable-palette=0",
5050 "--enable-intrabc=0",
5051 "--enable-cfl-intra=0",
5052 "--enable-ref-frame-mvs=0",
5053 "--obu",
5054 "-o",
5055 "-",
5056 "-",
5057 ]
5058 .iter()
5059 .map(|s| (*s).to_string())
5060 .collect();
5061 args.insert(1, format!("--cq-level={cq}"));
5062 if ten_bit {
5063 args.insert(1, "--input-bit-depth=10".to_string());
5064 args.insert(1, "--bit-depth=10".to_string());
5065 }
5066 let mut child = Command::new(aomenc_path())
5067 .args(&args)
5068 .stdin(Stdio::piped())
5069 .stdout(Stdio::piped())
5070 .stderr(Stdio::piped())
5071 .spawn()
5072 .expect("aomenc failed to start");
5073 child
5074 .stdin
5075 .take()
5076 .expect("aomenc stdin")
5077 .write_all(&y4m.stdout)
5078 .expect("writing y4m to aomenc");
5079 let out = child.wait_with_output().expect("aomenc failed to run");
5080 assert!(
5081 out.status.success(),
5082 "{name}: aomenc refused the fixture: {}",
5083 String::from_utf8_lossy(&out.stderr)
5084 );
5085 let stream = out.stdout;
5086 let before = decode::chroma_eob_class1_hits();
5087 let frames = match decode_stream(&stream) {
5088 Ok(frames) => frames,
5089 // A named refusal ("unsupported: ...") is another lane's arm
5090 // and moves this attempt on; anything else is a real decode
5091 // failure and fails the gate on the spot.
5092 Err(e) if e.to_string().contains("unsupported") => {
5093 refusals.push(format!("cq={cq} period={period}: {e}"));
5094 continue;
5095 }
5096 Err(e) => {
5097 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
5098 let _ = std::fs::write(&pin, &stream);
5099 panic!(
5100 "{name}: decode_stream failed on a real aomenc stream (cq={cq} period={period}): {e} (pinned at {})",
5101 pin.display()
5102 );
5103 }
5104 };
5105 if decode::chroma_eob_class1_hits() == before {
5106 refusals.push(format!(
5107 "cq={cq} period={period}: decoded, but no chroma block read a class-1 eob_pt row"
5108 ));
5109 continue;
5110 }
5111 let ffmpeg_frames = if ten_bit {
5112 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
5113 } else {
5114 ffmpeg_decode_sequence(&stream, width, height, frame_count)
5115 };
5116 assert_eq!(frames.len(), frame_count, "{name}: frame count");
5117 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5118 if got.y != want.y || got.u != want.u || got.v != want.v {
5119 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
5120 let _ = std::fs::write(&pin, &stream);
5121 panic!(
5122 "{name}: frame {i} mismatch vs ffmpeg (cq={cq} period={period}) -- stream pinned at {}",
5123 pin.display()
5124 );
5125 }
5126 }
5127 return;
5128 }
5129 panic!("{name}: no attempt fired a class-1 chroma eob: {refusals:?}");
5130 }
5131
5132 #[test]
5133 fn a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
5134 chroma_class1_eob_gate(
5135 "a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
5136 false,
5137 );
5138 }
5139
5140 #[test]
5141 fn a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
5142 chroma_class1_eob_gate(
5143 "a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
5144 true,
5145 );
5146 }
5147
5148 #[test]
5149 fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() {
5150 if !have_ffmpeg() {
5151 eprintln!(
5152 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no ffmpeg"
5153 );
5154 return;
5155 }
5156 if !have_aomenc() {
5157 eprintln!(
5158 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no aomenc at {}",
5159 aomenc_path().display()
5160 );
5161 return;
5162 }
5163 let (width, height, frame_count) = (64usize, 64usize, 4usize);
5164 let source = gradients_source(42, width, height, "duration=0.16:rate=25");
5165 let y4m = Command::new("ffmpeg")
5166 .args(["-v", "error", "-f", "lavfi", "-i"])
5167 .arg(&source)
5168 .args([
5169 "-pix_fmt",
5170 "yuv420p",
5171 "-f",
5172 "yuv4mpegpipe",
5173 "-",
5174 ])
5175 .stdin(Stdio::null())
5176 .stdout(Stdio::piped())
5177 .stderr(Stdio::piped())
5178 .output()
5179 .expect("ffmpeg failed to run");
5180 assert!(
5181 y4m.status.success(),
5182 "ffmpeg fixture: {}",
5183 String::from_utf8_lossy(&y4m.stderr)
5184 );
5185 let mut child = Command::new(aomenc_path())
5186 .args([
5187 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
5188 // occurrence, so overrides go before the base list).
5189 "--loopfilter-control=1",
5190 "--codec=av1",
5191 "--passes=1",
5192 "--end-usage=q",
5193 "--cq-level=55",
5194 "--cpu-used=0",
5195 "--lag-in-frames=0",
5196 "--auto-alt-ref=0",
5197 "--kf-max-dist=1000",
5198 // Forces `primary_ref_frame = PRIMARY_REF_NONE` on every
5199 // frame (spec 5.9.2): without it a real encoder's inter
5200 // frame loads its initial CDF state from the previous
5201 // frame's *adapted* tables (spec 7.20's `load_cdfs`), which
5202 // this decoder never does -- it always starts each frame's
5203 // `Cdfs` from the spec defaults (`decode.rs`'s
5204 // `Cdfs::new(q_ctx)`, called fresh per frame in
5205 // `decode_stream`). Without this flag the inter frame's
5206 // very first symbol desyncs immediately (traced 2026-08-27:
5207 // no coefficient trace at all before the tile's first
5208 // partition read comes back an out-of-alphabet value). A
5209 // real decoder needs cross-frame CDF forwarding to handle
5210 // that stream; this fixture sidesteps it the same way a
5211 // real broadcast/low-latency encode legitimately can.
5212 "--error-resilient=1",
5213 "--enable-rect-partitions=0",
5214 "--enable-ab-partitions=0",
5215 "--enable-1to4-partitions=0",
5216 "--enable-filter-intra=0",
5217 "--enable-smooth-intra=0",
5218 "--enable-paeth-intra=0",
5219 "--enable-directional-intra=0",
5220 "--enable-angle-delta=0",
5221 "--enable-tx-size-search=0",
5222 "--enable-cdef=0",
5223 // Loop restoration is a named refusal (aomenc's RD picks
5224 // Sgrproj on this kind of content) -- off in every recipe
5225 // whose test targets a different surface.
5226 "--enable-restoration=0",
5227 "--max-partition-size=32",
5228 "--enable-palette=0",
5229 "--enable-intrabc=0",
5230 "--enable-cfl-intra=0",
5231 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
5232 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
5233 "--enable-ref-frame-mvs=0",
5234 "--obu",
5235 "-o",
5236 "-",
5237 "-",
5238 ])
5239 .stdin(Stdio::piped())
5240 .stdout(Stdio::piped())
5241 .stderr(Stdio::piped())
5242 .spawn()
5243 .expect("aomenc failed to start");
5244 child
5245 .stdin
5246 .take()
5247 .expect("aomenc stdin")
5248 .write_all(&y4m.stdout)
5249 .expect("writing y4m to aomenc");
5250 let out = child.wait_with_output().expect("aomenc failed to run");
5251 assert!(
5252 out.status.success(),
5253 "aomenc refused the fixture: {}",
5254 String::from_utf8_lossy(&out.stderr)
5255 );
5256 let stream = out.stdout;
5257 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
5258 std::fs::write(dump, &stream).expect("dump stream");
5259 }
5260 let before = decode::deblock_hits();
5261 let frames = match decode_stream(&stream) {
5262 Ok(frames) => frames,
5263 Err(e) => {
5264 eprintln!(
5265 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: {e}"
5266 );
5267 return;
5268 }
5269 };
5270 assert!(
5271 decode::deblock_hits() > before,
5272 "no deblocking edge fired decoding this sequence -- raise cq-level"
5273 );
5274 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
5275 assert_eq!(frames.len(), frame_count);
5276 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5277 // gradients' colors ignore its seed, so this gate encodes fresh
5278 // content every run -- a mismatch here may never reproduce.
5279 // Self-pin the stream before panicking so the failure is
5280 // bisectable (replay: EC_AV1_PIN on scratch_isolate_pinned_mismatch).
5281 let ok = got.y == want.y && got.u == want.u && got.v == want.v;
5282 if !ok {
5283 let pin = std::env::temp_dir().join("ec-av1-deblocking-gate-fail.obu");
5284 let _ = std::fs::write(&pin, &stream);
5285 panic!("frame {i} mismatch vs ffmpeg -- stream pinned at {}", pin.display());
5286 }
5287 }
5288 }
5289
5290 /// The decisive cross-frame CDF forwarding test: identical to
5291 /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`]
5292 /// except it drops `--error-resilient=1`, so aomenc codes every inter
5293 /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`)
5294 /// and expects the decoder to resume from the previous frame's *adapted*
5295 /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding,
5296 /// frame 1's very first tile symbol desyncs (an out-of-alphabet
5297 /// partition read); with it, every frame decodes pixel-exact.
5298 #[test]
5299 fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() {
5300 if !have_ffmpeg() {
5301 eprintln!(
5302 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg"
5303 );
5304 return;
5305 }
5306 if !have_aomenc() {
5307 eprintln!(
5308 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}",
5309 aomenc_path().display()
5310 );
5311 return;
5312 }
5313 let (width, height, frame_count) = (64usize, 64usize, 4usize);
5314 // The fixture's content varies run to run (lavfi gradients ignores its
5315 // seed option for the c0..c7 colors -- they default to "random"), so:
5316 // most encodes of this recipe trip one of the decoder's NAMED round-2
5317 // refusals (a reference other than LAST_FRAME, a sub-16 partition --
5318 // genuine coverage gaps, separately documented), and only some produce
5319 // a stream fully inside this decoder's declared support. So: attempt
5320 // several seeds, and the first stream that DECODES must be pixel-exact
5321 // -- that assertion is what guards the forwarded-CDF state (a wrong
5322 // table decodes plausible-but-wrong pixels; the counter-reset bug this
5323 // gate caught did exactly that). Exhausting every attempt on named
5324 // refusals skips loudly, listing them.
5325 let mut refusals = Vec::new();
5326 for attempt in 0..8u32 {
5327 let seed = 42 + attempt;
5328 let source = gradients_source(seed, 64, 64, "duration=0.16:rate=25");
5329 let y4m = Command::new("ffmpeg")
5330 .args([
5331 "-v",
5332 "error",
5333 "-f",
5334 "lavfi",
5335 "-i",
5336 &source,
5337 "-pix_fmt",
5338 "yuv420p",
5339 "-f",
5340 "yuv4mpegpipe",
5341 "-",
5342 ])
5343 .stdin(Stdio::null())
5344 .stdout(Stdio::piped())
5345 .stderr(Stdio::piped())
5346 .output()
5347 .expect("ffmpeg failed to run");
5348 assert!(
5349 y4m.status.success(),
5350 "ffmpeg fixture: {}",
5351 String::from_utf8_lossy(&y4m.stderr)
5352 );
5353 // lane-cdfflake: hard length check on the y4m fixture itself --
5354 // a truncated/racing ffmpeg write would otherwise surface as a
5355 // downstream pixel mismatch indistinguishable from a real decode
5356 // defect. y4m frames are `FRAME\n` (6 bytes) + raw 4:2:0 payload;
5357 // find the header/frame-data boundary at the first `FRAME` marker
5358 // rather than parsing the header fields (duration/rate can move
5359 // the header text length without moving the frame math).
5360 let marker_at = y4m
5361 .stdout
5362 .windows(5)
5363 .position(|w| w == b"FRAME")
5364 .expect("y4m stream missing FRAME marker");
5365 let frame_420_bytes = width * height * 3 / 2;
5366 assert_eq!(
5367 y4m.stdout.len(),
5368 marker_at + frame_count * (6 + frame_420_bytes),
5369 "y4m fixture length mismatch (seed {seed})"
5370 );
5371 let y4m_hash = fnv1a64(&y4m.stdout);
5372 let mut child = Command::new(aomenc_path())
5373 .args([
5374 "--codec=av1",
5375 "--passes=1",
5376 "--end-usage=q",
5377 "--cq-level=55",
5378 "--cpu-used=0",
5379 "--lag-in-frames=0",
5380 "--auto-alt-ref=0",
5381 "--kf-max-dist=1000",
5382 // `--threads=1` (not the default): a multithreaded RD search
5383 // makes aomenc's screen-content-tools heuristic race (seen
5384 // flaky under `cargo test`'s own parallelism -- the same
5385 // fixture, same seed, occasionally sets
5386 // `allow_screen_content_tools`, a round-2 gap unrelated to
5387 // CDF forwarding), so pin it to one thread for a
5388 // deterministic header.
5389 "--threads=1",
5390 "--row-mt=0",
5391 // `--enable-order-hint=0` kills BWDREF/ALTREF entirely (no
5392 // order hints -> no bidirectional distance weighting) and,
5393 // combined with `--auto-alt-ref=0`/`--lag-in-frames=0`
5394 // above, leaves aomenc's RD search only LAST_FRAME/
5395 // LAST2_FRAME/LAST3_FRAME/GOLDEN_FRAME to pick from --
5396 // GOLDEN itself needs no order hint (it is the keyframe's
5397 // fixed slot, not a distance-weighted reference), so this
5398 // does not suppress GOLDEN selection the way the sibling
5399 // CDF-forwarding gate's own comment worried about; it just
5400 // narrows the pool this gate needs GOLDEN to win out of.
5401 "--enable-order-hint=0",
5402 "--enable-warped-motion=0",
5403 "--enable-obmc=0",
5404 "--enable-masked-comp=0",
5405 "--enable-interintra-comp=0",
5406 "--enable-dist-wtd-comp=0",
5407 "--enable-diff-wtd-comp=0",
5408 "--enable-onesided-comp=0",
5409 "--enable-interintra-wedge=0",
5410 "--enable-smooth-interintra=0",
5411 "--enable-rect-partitions=0",
5412 "--enable-ab-partitions=0",
5413 "--enable-1to4-partitions=0",
5414 "--enable-filter-intra=0",
5415 "--enable-smooth-intra=0",
5416 "--enable-paeth-intra=0",
5417 "--enable-directional-intra=0",
5418 "--enable-angle-delta=0",
5419 "--enable-tx-size-search=0",
5420 "--enable-cdef=0",
5421 // Loop restoration is a named refusal (aomenc's RD picks
5422 // Sgrproj on this kind of content) -- off in every recipe
5423 // whose test targets a different surface.
5424 "--enable-restoration=0",
5425 "--max-partition-size=32",
5426 "--enable-palette=0",
5427 "--enable-intrabc=0",
5428 "--enable-cfl-intra=0",
5429 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
5430 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
5431 "--enable-ref-frame-mvs=0",
5432 "--obu",
5433 "-o",
5434 "-",
5435 "-",
5436 ])
5437 .stdin(Stdio::piped())
5438 .stdout(Stdio::piped())
5439 .stderr(Stdio::piped())
5440 .spawn()
5441 .expect("aomenc failed to start");
5442 child
5443 .stdin
5444 .take()
5445 .expect("aomenc stdin")
5446 .write_all(&y4m.stdout)
5447 .expect("writing y4m to aomenc");
5448 let out = child.wait_with_output().expect("aomenc failed to run");
5449 assert!(
5450 out.status.success(),
5451 "aomenc refused the fixture: {}",
5452 String::from_utf8_lossy(&out.stderr)
5453 );
5454 let stream = out.stdout;
5455 let stream_hash = fnv1a64(&stream);
5456 // A named `unsupported` refusal is a documented coverage gap (each
5457 // one carries its own test debt elsewhere), not a forwarding verdict
5458 // -- try the next seed. Any stream that DECODES must be pixel-exact,
5459 // and any non-refusal error is a hard failure.
5460 let frames = match decode_stream(&stream) {
5461 Err(e) => {
5462 let msg = e.to_string();
5463 assert!(
5464 msg.contains("unsupported"),
5465 "cross-frame CDF forwarding failed outright (seed {seed}): {msg}"
5466 );
5467 refusals.push(format!("seed {seed}: {msg}"));
5468 continue;
5469 }
5470 Ok(frames) => frames,
5471 };
5472 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
5473 assert_eq!(frames.len(), frame_count);
5474 // lane-cdfflake: reconstruct ffmpeg's raw reference bytes (the
5475 // three per-frame slices are contiguous chunks of the raw
5476 // `-f rawvideo` output ffmpeg_decode_sequence sliced, so
5477 // concatenating them back is bit-for-bit the same bytes ffmpeg
5478 // actually produced -- no second ffmpeg invocation needed).
5479 let ffmpeg_raw: Vec<u8> = ffmpeg_frames
5480 .iter()
5481 .flat_map(|p| p.y.iter().chain(&p.u).chain(&p.v).map(|&v| v as u8))
5482 .collect();
5483 let ffmpeg_raw_hash = fnv1a64(&ffmpeg_raw);
5484 eprintln!(
5485 "cdfflake attempt seed={seed}: y4m_hash={y4m_hash:016x} \
5486 stream_hash={stream_hash:016x} ffmpeg_raw_hash={ffmpeg_raw_hash:016x}"
5487 );
5488 // lane-av1golden3: pin the exact raw stream on the first mismatch
5489 // so a flaky-looking gate failure becomes a deterministic, static
5490 // fixture to bisect against -- env-gated, no cost on a normal run.
5491 let mismatched = frames
5492 .iter()
5493 .zip(&ffmpeg_frames)
5494 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
5495 if mismatched {
5496 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
5497 std::fs::write(&path, &stream).expect("writing pinned stream");
5498 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
5499 }
5500 // lane-cdfflake: unconditional pin on mismatch -- the aomenc
5501 // stream AND ffmpeg's raw reference bytes, so a flake caught
5502 // under load names the liar (stream bytes differ from a
5503 // clean rerun -> subprocess instability; reference bytes
5504 // differ -> ffmpeg instability; both stable -> real decode
5505 // defect) without relying on the env var being set.
5506 // The pin goes to `fixtures/`, which outlives the session: an
5507 // earlier version wrote to a session scratchpad, so once tmpfs
5508 // reaped it a real mismatch aborted on the write instead of
5509 // reporting itself. A failed write must not mask the assert
5510 // below either, so it warns rather than panicking.
5511 let sp = pin_dir();
5512 let stream_pin = sp.join(format!("cdfflake-stream-seed{seed}.bin"));
5513 let ref_pin = sp.join(format!("cdfflake-ffmpeg-raw-seed{seed}.bin"));
5514 for (path, bytes) in [(&stream_pin, &stream), (&ref_pin, &ffmpeg_raw)] {
5515 if let Err(e) = std::fs::write(path, bytes) {
5516 eprintln!("cdfflake: could not pin to {}: {e}", path.display());
5517 }
5518 }
5519 eprintln!(
5520 "cdfflake MISMATCH seed={seed}: pinned stream + ffmpeg reference to {}",
5521 sp.display()
5522 );
5523 }
5524 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5525 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
5526 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
5527 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
5528 }
5529 return;
5530 }
5531 eprintln!(
5532 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: every \
5533 attempt hit a named refusal:\n{}",
5534 refusals.join("\n")
5535 );
5536 }
5537
5538 /// lane-av1golden3: reproduces the pinned mismatch bytes captured by
5539 /// `EC_AV1_GATE_DUMP=$SP/golden3-pin.obu` off
5540 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
5541 /// (seed 47, frame 1 U). Deterministic and static -- no aomenc/ffmpeg
5542 /// re-encode involved, only re-decodes the fixed bytes on disk, so it is
5543 /// `#[ignore]`d (the file only exists on this machine's scratchpad) but
5544 /// gives a fast red/green loop for the actual fix.
5545 #[test]
5546 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
5547 fn pinned_golden3_stream_decodes_pixel_exact() {
5548 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
5549 .map(std::path::PathBuf::from)
5550 .unwrap_or_else(|_| pin_dir().join("golden3-pin.obu"));
5551 let Ok(stream) = std::fs::read(&path) else {
5552 eprintln!(
5553 "SKIP pinned_golden3_stream_decodes_pixel_exact: no pinned bytes at {} \
5554 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
5555 path.display()
5556 );
5557 return;
5558 };
5559 if !have_ffmpeg() {
5560 eprintln!("SKIP pinned_golden3_stream_decodes_pixel_exact: no ffmpeg");
5561 return;
5562 }
5563 let frames = decode_stream(&stream).expect("pinned stream must decode");
5564 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
5565 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5566 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
5567 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
5568 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
5569 }
5570 }
5571
5572 /// lane-av1golden4: reproduces the pinned mismatch bytes captured by
5573 /// `EC_AV1_GATE_DUMP=$SP/golden4-pin.obu` off
5574 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
5575 /// (seed 43, frame 3 luma) the round the GOLDEN mask lifted. Deterministic
5576 /// and static -- `#[ignore]`d, run manually.
5577 #[test]
5578 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
5579 fn pinned_golden4_stream_decodes_pixel_exact() {
5580 use crate::decode::non_last_ref_hits;
5581 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
5582 .map(std::path::PathBuf::from)
5583 .unwrap_or_else(|_| pin_dir().join("golden4-pin.obu"));
5584 let Ok(stream) = std::fs::read(&path) else {
5585 eprintln!(
5586 "SKIP pinned_golden4_stream_decodes_pixel_exact: no pinned bytes at {} \
5587 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
5588 path.display()
5589 );
5590 return;
5591 };
5592 if !have_ffmpeg() {
5593 eprintln!("SKIP pinned_golden4_stream_decodes_pixel_exact: no ffmpeg");
5594 return;
5595 }
5596 let before = non_last_ref_hits();
5597 let frames = decode_stream(&stream).expect("pinned stream must decode");
5598 eprintln!(
5599 "non_last_ref_hits before={before} after={}",
5600 non_last_ref_hits()
5601 );
5602 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
5603 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5604 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
5605 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
5606 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
5607 }
5608 }
5609
5610 /// lane-av1golden7 round 9: pins the residual GOLDEN_FRAME MC bug found
5611 /// by the forwarding gate once film grain is out of the way (1/20 real
5612 /// aomenc streams, frame 3 luma, apply_grain=false, `non_last_ref_hits`
5613 /// delta=2). `GOLDEN_FRAME` refuses by name until this decodes exact.
5614 #[test]
5615 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
5616 fn pinned_golden7_stream_decodes_pixel_exact() {
5617 use crate::decode::non_last_ref_hits;
5618 let path = concat!(
5619 env!("CARGO_MANIFEST_DIR"),
5620 "/../../fixtures/golden7-forwarding-mismatch.obu"
5621 );
5622 let stream = std::fs::read(path).expect("reading pinned stream");
5623 if !have_ffmpeg() {
5624 eprintln!("SKIP pinned_golden7_stream_decodes_pixel_exact: no ffmpeg");
5625 return;
5626 }
5627 let before = non_last_ref_hits();
5628 let frames = decode_stream(&stream).expect("pinned stream must decode");
5629 eprintln!(
5630 "non_last_ref_hits before={before} after={}",
5631 non_last_ref_hits()
5632 );
5633 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
5634 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5635 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
5636 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
5637 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
5638 }
5639 }
5640
5641 /// lane-av1refs's decisive single-non-LAST-reference gate: identical
5642 /// recipe to
5643 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
5644 /// except `--enable-order-hint=0` is DROPPED (that flag's own comment on
5645 /// the sibling test names it as exactly what suppresses aomenc's RD from
5646 /// ever picking `GOLDEN_FRAME`) and the sequence runs 8 frames, not 4 --
5647 /// more chances for the RD search to reach past the first GOP's initial
5648 /// key frame. `--auto-alt-ref=0` stays: this decoder only supports
5649 /// `LAST_FRAME`/`GOLDEN_FRAME` so far, and alt-ref/backward references
5650 /// are still a named refusal, not this gate's target. A stream that
5651 /// decodes without firing [`decode::non_last_ref_hits`] is not a
5652 /// coverage win for this round -- SKIP it as a genuine, named miss
5653 /// rather than pass silently on untested ground.
5654 #[test]
5655 fn a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact() {
5656 if !have_ffmpeg() {
5657 eprintln!(
5658 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no ffmpeg"
5659 );
5660 return;
5661 }
5662 if !have_aomenc() {
5663 eprintln!(
5664 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no aomenc at {}",
5665 aomenc_path().display()
5666 );
5667 return;
5668 }
5669 let (width, height, frame_count) = (64usize, 64usize, 8usize);
5670 let mut refusals = Vec::new();
5671 let mut never_fired = 0u32;
5672 // aomenc's own RD search is nondeterministic run-to-run even at
5673 // `--threads=1` (confirmed live: identical CLI args, identical
5674 // input, two different output byte streams) -- so beyond varying
5675 // the fixture's seed, each attempt is its own independent coin
5676 // flip against every named refusal below. 120 attempts (not 40)
5677 // to give that coin flip enough tries to land on a stream this
5678 // decoder both accepts and that fires GOLDEN_FRAME. `duration=0.32`
5679 // at `rate=25` (not `0.24`) matches every sibling gate's own
5680 // frame-count fixture exactly -- a shorter duration here once
5681 // produced a frame-0 (keyframe, no reference at all) luma mismatch
5682 // against ffmpeg, i.e. a source-frame-count rounding artifact of
5683 // this recipe's own choosing, not a decoder bug.
5684 for attempt in 0..120u32 {
5685 let seed = 42 + attempt % 40;
5686 let source = gradients_source(seed, 64, 64, "duration=0.32:rate=25");
5687 let y4m = Command::new("ffmpeg")
5688 .args([
5689 "-v",
5690 "error",
5691 "-f",
5692 "lavfi",
5693 "-i",
5694 &source,
5695 "-pix_fmt",
5696 "yuv420p",
5697 "-f",
5698 "yuv4mpegpipe",
5699 "-",
5700 ])
5701 .stdin(Stdio::null())
5702 .stdout(Stdio::piped())
5703 .stderr(Stdio::piped())
5704 .output()
5705 .expect("ffmpeg failed to run");
5706 assert!(
5707 y4m.status.success(),
5708 "ffmpeg fixture: {}",
5709 String::from_utf8_lossy(&y4m.stderr)
5710 );
5711 let mut child = Command::new(aomenc_path())
5712 .args([
5713 "--codec=av1",
5714 "--passes=1",
5715 "--end-usage=q",
5716 "--cq-level=55",
5717 "--cpu-used=0",
5718 "--lag-in-frames=0",
5719 "--auto-alt-ref=0",
5720 "--kf-max-dist=1000",
5721 "--threads=1",
5722 "--row-mt=0",
5723 // Narrows the RD search's reference alphabet toward
5724 // LAST_FRAME/GOLDEN_FRAME -- without this, aomenc's RD is
5725 // just as likely to pick LAST2/LAST3/BWDREF/ALTREF2/
5726 // ALTREF (this decoder's already-documented, still-open
5727 // refusals), starving this gate of the one reference it
5728 // targets.
5729 "--max-reference-frames=3",
5730 "--reduced-reference-set=1",
5731 "--enable-warped-motion=0",
5732 "--enable-obmc=0",
5733 "--enable-masked-comp=0",
5734 "--enable-interintra-comp=0",
5735 "--enable-dist-wtd-comp=0",
5736 "--enable-diff-wtd-comp=0",
5737 "--enable-onesided-comp=0",
5738 "--enable-interintra-wedge=0",
5739 "--enable-smooth-interintra=0",
5740 "--enable-rect-partitions=0",
5741 "--enable-ab-partitions=0",
5742 "--enable-1to4-partitions=0",
5743 "--enable-filter-intra=0",
5744 "--enable-smooth-intra=0",
5745 "--enable-paeth-intra=0",
5746 "--enable-directional-intra=0",
5747 "--enable-angle-delta=0",
5748 "--enable-tx-size-search=0",
5749 "--enable-cdef=0",
5750 "--enable-restoration=0",
5751 // `min == max == 32` forces PARTITION_NONE for every
5752 // 32x32 block, not just biases toward it -- with
5753 // `--min-partition-size=16` alone aomenc's exhaustive
5754 // `cpu-used=0` RD search still occasionally read HORZ/
5755 // VERT/SPLIT partitions below 32x32 despite
5756 // `--enable-rect-partitions=0`/`--enable-ab-partitions=0`/
5757 // `--enable-1to4-partitions=0` all being off (two
5758 // separate, already-documented round-2 gaps: "a
5759 // partition below 16x16", "a partition type this encoder
5760 // never writes"), starving this gate's already-narrow
5761 // seed pool. Locking both bounds to 32 removes any
5762 // partition-depth choice from the search entirely, so
5763 // this gate can isolate GOLDEN_FRAME selection alone.
5764 "--max-partition-size=32",
5765 "--min-partition-size=32",
5766 "--enable-palette=0",
5767 "--enable-intrabc=0",
5768 "--enable-cfl-intra=0",
5769 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
5770 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
5771 "--enable-ref-frame-mvs=0",
5772 // `--tune-content=film` was dropped: on this box it
5773 // makes aomenc emit `apply_grain` almost every attempt
5774 // (lane-av1golden8 round 10 measurement, live: 120/120
5775 // real attempts hit a named refusal, 0 ever fired
5776 // GOLDEN_FRAME -- mostly `apply_grain`, dominated by its
5777 // own recipe flag) -- film grain synthesis has its own
5778 // dedicated refusal test and must not starve this gate
5779 // of the GOLDEN_FRAME draws it exists to prove. Default
5780 // content tuning still occasionally flips
5781 // `allow_screen_content_tools` on for this synthetic
5782 // gradient content (a separate, already-documented open
5783 // refusal), which the 120-attempt coin flip below
5784 // tolerates the same way.
5785 "--obu",
5786 "-o",
5787 "-",
5788 "-",
5789 ])
5790 .stdin(Stdio::piped())
5791 .stdout(Stdio::piped())
5792 .stderr(Stdio::piped())
5793 .spawn()
5794 .expect("aomenc failed to start");
5795 child
5796 .stdin
5797 .take()
5798 .expect("aomenc stdin")
5799 .write_all(&y4m.stdout)
5800 .expect("writing y4m to aomenc");
5801 let out = child.wait_with_output().expect("aomenc failed to run");
5802 assert!(
5803 out.status.success(),
5804 "aomenc refused the fixture: {}",
5805 String::from_utf8_lossy(&out.stderr)
5806 );
5807 let stream = out.stdout;
5808 let before = decode::non_last_ref_hits();
5809 let frames = match decode_stream(&stream) {
5810 Err(e) => {
5811 let msg = e.to_string();
5812 assert!(
5813 msg.contains("unsupported"),
5814 "a golden-reference stream failed outright (seed {seed}): {msg}"
5815 );
5816 refusals.push(format!("seed {seed}: {msg}"));
5817 continue;
5818 }
5819 Ok(frames) => frames,
5820 };
5821 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
5822 // is ALWAYS pixel-compared below; the hit counter only decides whether
5823 // the attempt counts toward the firing total.
5824 // This seed's RD search may never have picked GOLDEN_FRAME -- a
5825 // genuine miss, not a refusal, and not a reason to skip the pixels.
5826 let counted = decode::non_last_ref_hits() != before;
5827 if !counted {
5828 never_fired += 1;
5829 }
5830 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
5831 assert_eq!(frames.len(), frame_count);
5832 // Same pin-on-mismatch pattern as the CDF forwarding gate above:
5833 // env-gated, no cost on a normal run.
5834 let mismatched = frames
5835 .iter()
5836 .zip(&ffmpeg_frames)
5837 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
5838 if mismatched {
5839 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
5840 std::fs::write(&path, &stream).expect("writing pinned stream");
5841 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
5842 }
5843 }
5844 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5845 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
5846 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
5847 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
5848 }
5849 if counted {
5850 eprintln!(
5851 "FIRING seed {seed}: non_last_ref_hits advanced by {}",
5852 decode::non_last_ref_hits() - before
5853 );
5854 gate_buckets(
5855 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
5856 1,
5857 never_fired,
5858 refusals.len(),
5859 );
5860 return;
5861 }
5862 }
5863 gate_buckets(
5864 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
5865 0,
5866 never_fired,
5867 refusals.len(),
5868 );
5869 eprintln!(
5870 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: \
5871 {never_fired} attempts decoded but never fired GOLDEN_FRAME, and every other \
5872 attempt hit a named refusal:\n{}",
5873 refusals.join("\n")
5874 );
5875 }
5876
5877 /// lane-av1refs's decisive gate for the 5 references widened past
5878 /// `LAST_FRAME`/`GOLDEN_FRAME`: same envelope and pin-on-mismatch
5879 /// pattern as
5880 /// [`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`],
5881 /// generalised over `(target_ref, extra_args, frame_count)` so each of
5882 /// `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` gets its own attempt pool
5883 /// and its own proof that `decode::ref_hits(target_ref)` -- not just
5884 /// `non_last_ref_hits`, which cannot distinguish one reference from
5885 /// another -- actually advanced. `--max-reference-frames=3
5886 /// --reduced-reference-set=1` (the golden gate's own narrowing) is
5887 /// DROPPED here: both suppress exactly the references this gate needs
5888 /// aomenc's RD to reach.
5889 fn a_real_aomenc_single_ref_gate(
5890 gate_name: &str,
5891 target_ref: i8,
5892 target_ref_name: &str,
5893 extra_args: &[&str],
5894 width: usize,
5895 height: usize,
5896 frame_count: usize,
5897 attempts: u32,
5898 ) {
5899 let _gate_lock = lock_gate_counters();
5900 if !have_ffmpeg() {
5901 eprintln!("SKIP {gate_name}: no ffmpeg");
5902 return;
5903 }
5904 if !have_aomenc() {
5905 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
5906 return;
5907 }
5908 let mut refusals = Vec::new();
5909 let mut never_fired = 0u32;
5910 for attempt in 0..attempts {
5911 let seed = 42 + attempt % 40;
5912 let duration = frame_count as f64 / 25.0;
5913 let source =
5914 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
5915 let y4m = Command::new("ffmpeg")
5916 .args([
5917 "-v",
5918 "error",
5919 "-f",
5920 "lavfi",
5921 "-i",
5922 &source,
5923 "-pix_fmt",
5924 "yuv420p",
5925 "-f",
5926 "yuv4mpegpipe",
5927 "-",
5928 ])
5929 .stdin(Stdio::null())
5930 .stdout(Stdio::piped())
5931 .stderr(Stdio::piped())
5932 .output()
5933 .expect("ffmpeg failed to run");
5934 assert!(
5935 y4m.status.success(),
5936 "ffmpeg fixture: {}",
5937 String::from_utf8_lossy(&y4m.stderr)
5938 );
5939 let mut args: Vec<&str> = vec![
5940 "--codec=av1",
5941 "--passes=1",
5942 "--end-usage=q",
5943 "--cq-level=55",
5944 "--cpu-used=0",
5945 "--kf-max-dist=1000",
5946 "--threads=1",
5947 "--row-mt=0",
5948 "--enable-warped-motion=0",
5949 "--enable-obmc=0",
5950 "--enable-masked-comp=0",
5951 "--enable-interintra-comp=0",
5952 "--enable-dist-wtd-comp=0",
5953 "--enable-diff-wtd-comp=0",
5954 "--enable-onesided-comp=0",
5955 "--enable-interintra-wedge=0",
5956 "--enable-smooth-interintra=0",
5957 "--enable-rect-partitions=0",
5958 "--enable-ab-partitions=0",
5959 "--enable-1to4-partitions=0",
5960 "--enable-filter-intra=0",
5961 "--enable-smooth-intra=0",
5962 "--enable-paeth-intra=0",
5963 "--enable-directional-intra=0",
5964 "--enable-angle-delta=0",
5965 "--enable-tx-size-search=0",
5966 "--enable-cdef=0",
5967 "--enable-restoration=0",
5968 "--max-partition-size=32",
5969 "--min-partition-size=32",
5970 "--enable-palette=0",
5971 "--enable-intrabc=0",
5972 "--enable-cfl-intra=0",
5973 // use_ref_frame_mvs (temporal MV projection) is unimplemented in
5974 // mvstack; leaving it on silently desyncs symbols on inter frames.
5975 "--enable-ref-frame-mvs=0",
5976 "--obu",
5977 "-o",
5978 "-",
5979 "-",
5980 ];
5981 // extra_args goes right before the trailing "-o", "-", "-" triple.
5982 let tail = args.split_off(args.len() - 3);
5983 args.extend_from_slice(extra_args);
5984 args.extend_from_slice(&tail);
5985 let mut child = Command::new(aomenc_path())
5986 .args(&args)
5987 .stdin(Stdio::piped())
5988 .stdout(Stdio::piped())
5989 .stderr(Stdio::piped())
5990 .spawn()
5991 .expect("aomenc failed to start");
5992 child
5993 .stdin
5994 .take()
5995 .expect("aomenc stdin")
5996 .write_all(&y4m.stdout)
5997 .expect("writing y4m to aomenc");
5998 let out = child.wait_with_output().expect("aomenc failed to run");
5999 assert!(
6000 out.status.success(),
6001 "aomenc refused the fixture: {}",
6002 String::from_utf8_lossy(&out.stderr)
6003 );
6004 let stream = out.stdout;
6005 let before = decode::ref_hits(target_ref);
6006 let frames = match decode_stream(&stream) {
6007 Err(e) => {
6008 let msg = e.to_string();
6009 assert!(
6010 msg.contains("unsupported"),
6011 "{gate_name} failed outright (seed {seed}): {msg}"
6012 );
6013 refusals.push(format!("seed {seed}: {msg}"));
6014 continue;
6015 }
6016 Ok(frames) => frames,
6017 };
6018 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
6019 // is ALWAYS pixel-compared below; the hit counter only decides whether
6020 // the attempt counts toward the firing total.
6021 let counted = decode::ref_hits(target_ref) != before;
6022 if !counted {
6023 never_fired += 1;
6024 }
6025 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
6026 assert_eq!(frames.len(), frame_count);
6027 let mismatched = frames
6028 .iter()
6029 .zip(&ffmpeg_frames)
6030 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
6031 if mismatched {
6032 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
6033 std::fs::write(&path, &stream).expect("writing pinned stream");
6034 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
6035 }
6036 }
6037 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6038 assert_eq!(
6039 got.y, want.y,
6040 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
6041 );
6042 assert_eq!(
6043 got.u, want.u,
6044 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
6045 );
6046 assert_eq!(
6047 got.v, want.v,
6048 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
6049 );
6050 }
6051 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
6052 // stream again, comparing EVERY decode-order frame -- the hidden
6053 // (show_frame == 0) alt-ref frames the ffmpeg compare above
6054 // cannot see, because both sides of it emit shown frames only.
6055 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, gate_name);
6056 eprintln!(
6057 "{gate_name} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
6058 {hidden_n} hidden, all pixel-exact vs the oracle"
6059 );
6060 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
6061 // libaom's temporal alt-ref filter absorbs this recipe's hidden
6062 // frames, so the compare above is vacuous -- re-encode the same
6063 // fixture with --arnr-maxframes=0 and compare THOSE.
6064 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(gate_name, &y4m.stdout, &args) {
6065 eprintln!(
6066 "{gate_name} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
6067 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
6068 );
6069 }
6070 if counted {
6071 eprintln!(
6072 "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}",
6073 decode::ref_hits(target_ref) - before
6074 );
6075 gate_buckets(gate_name, 1, never_fired, refusals.len());
6076 return;
6077 }
6078 }
6079 gate_buckets(gate_name, 0, never_fired, refusals.len());
6080 eprintln!(
6081 "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \
6082 and every other attempt hit a named refusal:\n{}",
6083 refusals.join("\n")
6084 );
6085 }
6086
6087 /// lane-av1comp: proves `reference_select`/`comp_mode` are actually read
6088 /// off a real bitstream rather than only unit-tested in isolation --
6089 /// `--auto-alt-ref=1 --lag-in-frames=16` gives aomenc a backward
6090 /// reference to pick `COMPOUND_REFERENCE` with, `--enable-order-hint=1`
6091 /// is required for it to ever consider compound at all. Three
6092 /// acceptable outcomes: (a) a stream where `reference_select` never
6093 /// actually drove a block to `COMPOUND_REFERENCE` decodes bit-exact end
6094 /// to end (proving the per-block `comp_mode` read did not desync the
6095 /// single-ref blocks around it); (b) a stream that does fire compound
6096 /// is refused by name with [`decode::comp_mode_hits`] having advanced
6097 /// (proving `comp_mode`/`read_compound_ref_frames` consumed the right
6098 /// symbols before refusing, rather than desyncing and refusing for an
6099 /// unrelated reason) -- masked/wedge compound (`comp_group_idx == 1`)
6100 /// and a partition below 16x16 (a real, separately tracked capability
6101 /// gap) are the two refusal arms this can still legitimately name; (c)
6102 /// r13 wired plain `COMPOUND_AVERAGE` MC for real, so as of r15 a
6103 /// stream that fires compound may also decode fully -- accepted only
6104 /// when every output frame is pixel-exact against ffmpeg.
6105 #[test]
6106 fn a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly() {
6107 const NAME: &str = "a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly";
6108 let _gate_lock = lock_gate_counters();
6109 if !have_ffmpeg() {
6110 eprintln!("SKIP {NAME}: no ffmpeg");
6111 return;
6112 }
6113 if !have_aomenc() {
6114 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6115 return;
6116 }
6117 let (width, height, frame_count) = (64usize, 64usize, 20usize);
6118 let mut refusals = Vec::new();
6119 let mut never_fired = 0u32;
6120 for attempt in 0..60u32 {
6121 let seed = 42 + attempt % 40;
6122 let duration = frame_count as f64 / 25.0;
6123 let source =
6124 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
6125 let y4m = Command::new("ffmpeg")
6126 .args([
6127 "-v",
6128 "error",
6129 "-f",
6130 "lavfi",
6131 "-i",
6132 &source,
6133 "-pix_fmt",
6134 "yuv420p",
6135 "-f",
6136 "yuv4mpegpipe",
6137 "-",
6138 ])
6139 .stdin(Stdio::null())
6140 .stdout(Stdio::piped())
6141 .stderr(Stdio::piped())
6142 .output()
6143 .expect("ffmpeg failed to run");
6144 assert!(
6145 y4m.status.success(),
6146 "ffmpeg fixture: {}",
6147 String::from_utf8_lossy(&y4m.stderr)
6148 );
6149 let args: Vec<&str> = vec![
6150 "--codec=av1",
6151 "--passes=1",
6152 "--end-usage=q",
6153 "--cq-level=45",
6154 "--cpu-used=0",
6155 "--kf-max-dist=1000",
6156 "--threads=1",
6157 "--row-mt=0",
6158 "--auto-alt-ref=1",
6159 "--lag-in-frames=16",
6160 "--enable-order-hint=1",
6161 "--enable-warped-motion=0",
6162 "--enable-obmc=0",
6163 "--enable-masked-comp=0",
6164 "--enable-interintra-comp=0",
6165 "--enable-onesided-comp=0",
6166 "--enable-interintra-wedge=0",
6167 "--enable-smooth-interintra=0",
6168 "--enable-rect-partitions=0",
6169 "--enable-ab-partitions=0",
6170 "--enable-1to4-partitions=0",
6171 "--enable-filter-intra=0",
6172 "--enable-smooth-intra=0",
6173 "--enable-paeth-intra=0",
6174 "--enable-directional-intra=0",
6175 "--enable-angle-delta=0",
6176 "--enable-tx-size-search=0",
6177 "--enable-cdef=0",
6178 "--enable-restoration=0",
6179 "--max-partition-size=32",
6180 "--min-partition-size=32",
6181 "--enable-palette=0",
6182 "--enable-intrabc=0",
6183 "--enable-cfl-intra=0",
6184 "--enable-ref-frame-mvs=0",
6185 "--obu",
6186 "-o",
6187 "-",
6188 "-",
6189 ];
6190 let mut child = Command::new(aomenc_path())
6191 .args(&args)
6192 .stdin(Stdio::piped())
6193 .stdout(Stdio::piped())
6194 .stderr(Stdio::piped())
6195 .spawn()
6196 .expect("aomenc failed to start");
6197 child
6198 .stdin
6199 .take()
6200 .expect("aomenc stdin")
6201 .write_all(&y4m.stdout)
6202 .expect("writing y4m to aomenc");
6203 let out = child.wait_with_output().expect("aomenc failed to run");
6204 assert!(
6205 out.status.success(),
6206 "aomenc refused the fixture: {}",
6207 String::from_utf8_lossy(&out.stderr)
6208 );
6209 let stream = out.stdout;
6210 let before = decode::comp_mode_hits();
6211 match decode_stream(&stream) {
6212 Err(e) => {
6213 let msg = e.to_string();
6214 let fired = decode::comp_mode_hits() > before;
6215 assert!(
6216 msg.contains("unsupported"),
6217 "{NAME} failed outright (seed {seed}): {msg}"
6218 );
6219 if fired {
6220 // `comp_mode` firing does not stop the block walk --
6221 // a later, unrelated block in the same tile can
6222 // still hit any other named refusal this decoder
6223 // carries. A partition below 16x16 is a real, open
6224 // capability gap tracked on its own (not a
6225 // COMPOUND_REFERENCE defect); accept it here too
6226 // rather than fail a compound-specific gate on a
6227 // partition-search coincidence. lane-av1blend r7:
6228 // re-swept the wide gate with the plain-average
6229 // blend unmasked (r6/r7's ref_ctx fix alone) and it
6230 // still mismatches on real streams beyond that one
6231 // bug -- re-masked comp_group_idx == 0 too, so this
6232 // stays a legal named refusal.
6233 assert!(
6234 msg.contains("COMPOUND_REFERENCE") || msg.contains("a partition"),
6235 "{NAME}: comp_mode fired (seed {seed}) but the refusal \
6236 was for something else: {msg}"
6237 );
6238 let advanced = decode::comp_mode_hits() - before;
6239 eprintln!(
6240 "{NAME} FIRING seed {seed}: comp_mode hits advanced by \
6241 {advanced}, refused by name as expected: {msg}"
6242 );
6243 return;
6244 }
6245 refusals.push(format!("seed {seed}: {msg}"));
6246 continue;
6247 }
6248 Ok(frames) => {
6249 // class [[gate-skips-on-its-own-failure]]: a decode that
6250 // succeeded is ALWAYS pixel-compared below; the hit counter
6251 // only decides whether the attempt counts as firing.
6252 let counted = decode::comp_mode_hits() != before;
6253 if !counted {
6254 never_fired += 1;
6255 }
6256 // Outcome (c): plain COMPOUND_AVERAGE decoded fully --
6257 // non-negotiable pixel exactness, no tolerance.
6258 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
6259 assert_eq!(frames.len(), frame_count);
6260 let mismatched = frames
6261 .iter()
6262 .zip(&ffmpeg_frames)
6263 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
6264 if mismatched {
6265 let pin = std::env::temp_dir().join("ec-av1-reference-select-gate-fail.obu");
6266 let _ = std::fs::write(&pin, &stream);
6267 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
6268 std::fs::write(&path, &stream).expect("writing pinned stream");
6269 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
6270 }
6271 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6272 assert_eq!(
6273 got.y, want.y,
6274 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
6275 pin.display()
6276 );
6277 assert_eq!(
6278 got.u, want.u,
6279 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
6280 pin.display()
6281 );
6282 assert_eq!(
6283 got.v, want.v,
6284 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
6285 pin.display()
6286 );
6287 }
6288 } else {
6289 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6290 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
6291 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
6292 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
6293 }
6294 }
6295 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
6296 // stream again, comparing EVERY decode-order frame -- the hidden
6297 // (show_frame == 0) alt-ref frames the ffmpeg compare above
6298 // cannot see, because both sides of it emit shown frames only.
6299 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
6300 eprintln!(
6301 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
6302 {hidden_n} hidden, all pixel-exact vs the oracle"
6303 );
6304 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
6305 // libaom's temporal alt-ref filter absorbs this recipe's hidden
6306 // frames, so the compare above is vacuous -- re-encode the same
6307 // fixture with --arnr-maxframes=0 and compare THOSE.
6308 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
6309 eprintln!(
6310 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
6311 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
6312 );
6313 }
6314 if counted {
6315 eprintln!(
6316 "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \
6317 fully and pixel-exact",
6318 decode::comp_mode_hits() - before
6319 );
6320 gate_buckets(NAME, 1, never_fired, refusals.len());
6321 return;
6322 }
6323 }
6324 }
6325 }
6326 gate_buckets(NAME, 0, never_fired, refusals.len());
6327 eprintln!(
6328 "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \
6329 block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \
6330 reached comp_mode:\n{}",
6331 refusals.join("\n")
6332 );
6333 }
6334
6335 /// lane-av1comp round 14's decisive gate for `skip_mode`: same
6336 /// pin-on-mismatch pattern as [`a_real_aomenc_single_ref_gate`], proving
6337 /// [`decode::skip_mode_hits`] actually advanced (a real block picked
6338 /// `skip_mode`, not just that the frame header bit was set) and that the
6339 /// resulting forced-compound `NEAREST_NEARESTMV` decode is still
6340 /// pixel-exact against ffmpeg. `--auto-alt-ref=1 --lag-in-frames=16
6341 /// --enable-fwd-kf=0` (backward references) plus
6342 /// `--enable-ref-frame-mvs=0` (unimplemented temporal MV projection,
6343 /// same as every other gate here) is aomenc's own requirement for
6344 /// `skip_mode_present` to ever be considered at all (spec 5.9.22 needs
6345 /// both a forward and a backward reference candidate).
6346 #[test]
6347 fn a_real_aomenc_stream_with_compound_references_decodes_pixel_exact() {
6348 const NAME: &str = "a_real_aomenc_stream_with_compound_references_decodes_pixel_exact";
6349 let _gate_lock = lock_gate_counters();
6350 if !have_ffmpeg() {
6351 eprintln!("SKIP {NAME}: no ffmpeg");
6352 return;
6353 }
6354 if !have_aomenc() {
6355 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6356 return;
6357 }
6358 let (width, height, frame_count) = (64usize, 64usize, 24usize);
6359 let mut refusals = Vec::new();
6360 let mut never_fired = 0u32;
6361 for attempt in 0..80u32 {
6362 let seed = 42 + attempt % 40;
6363 let duration = frame_count as f64 / 25.0;
6364 let source =
6365 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
6366 let y4m = Command::new("ffmpeg")
6367 .args([
6368 "-v",
6369 "error",
6370 "-f",
6371 "lavfi",
6372 "-i",
6373 &source,
6374 "-pix_fmt",
6375 "yuv420p",
6376 "-f",
6377 "yuv4mpegpipe",
6378 "-",
6379 ])
6380 .stdin(Stdio::null())
6381 .stdout(Stdio::piped())
6382 .stderr(Stdio::piped())
6383 .output()
6384 .expect("ffmpeg failed to run");
6385 assert!(
6386 y4m.status.success(),
6387 "ffmpeg fixture: {}",
6388 String::from_utf8_lossy(&y4m.stderr)
6389 );
6390 let args: Vec<&str> = vec![
6391 "--codec=av1",
6392 "--passes=1",
6393 "--end-usage=q",
6394 "--cq-level=45",
6395 "--cpu-used=0",
6396 "--kf-max-dist=1000",
6397 "--threads=1",
6398 "--row-mt=0",
6399 "--auto-alt-ref=1",
6400 "--lag-in-frames=16",
6401 "--enable-fwd-kf=0",
6402 "--enable-order-hint=1",
6403 "--enable-warped-motion=0",
6404 "--enable-obmc=0",
6405 "--enable-masked-comp=0",
6406 "--enable-interintra-comp=0",
6407 "--enable-onesided-comp=0",
6408 "--enable-interintra-wedge=0",
6409 "--enable-smooth-interintra=0",
6410 "--enable-rect-partitions=0",
6411 "--enable-ab-partitions=0",
6412 "--enable-1to4-partitions=0",
6413 "--enable-filter-intra=0",
6414 "--enable-smooth-intra=0",
6415 "--enable-paeth-intra=0",
6416 "--enable-directional-intra=0",
6417 "--enable-angle-delta=0",
6418 "--enable-tx-size-search=0",
6419 "--enable-cdef=0",
6420 "--enable-restoration=0",
6421 "--max-partition-size=32",
6422 "--min-partition-size=32",
6423 "--enable-palette=0",
6424 "--enable-intrabc=0",
6425 "--enable-cfl-intra=0",
6426 "--enable-ref-frame-mvs=0",
6427 "--obu",
6428 "-o",
6429 "-",
6430 "-",
6431 ];
6432 let mut child = Command::new(aomenc_path())
6433 .args(&args)
6434 .stdin(Stdio::piped())
6435 .stdout(Stdio::piped())
6436 .stderr(Stdio::piped())
6437 .spawn()
6438 .expect("aomenc failed to start");
6439 child
6440 .stdin
6441 .take()
6442 .expect("aomenc stdin")
6443 .write_all(&y4m.stdout)
6444 .expect("writing y4m to aomenc");
6445 let out = child.wait_with_output().expect("aomenc failed to run");
6446 assert!(
6447 out.status.success(),
6448 "aomenc refused the fixture: {}",
6449 String::from_utf8_lossy(&out.stderr)
6450 );
6451 let stream = out.stdout;
6452 let before = decode::skip_mode_hits();
6453 let frames = match decode_stream(&stream) {
6454 Err(e) => {
6455 let msg = e.to_string();
6456 assert!(
6457 msg.contains("unsupported"),
6458 "{NAME} failed outright (seed {seed}): {msg}"
6459 );
6460 refusals.push(format!("seed {seed}: {msg}"));
6461 continue;
6462 }
6463 Ok(frames) => frames,
6464 };
6465 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
6466 // is ALWAYS pixel-compared below; the hit counter only decides whether
6467 // the attempt counts toward the firing total.
6468 let counted = decode::skip_mode_hits() != before;
6469 if !counted {
6470 never_fired += 1;
6471 }
6472 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
6473 assert_eq!(frames.len(), frame_count);
6474 let mismatched = frames
6475 .iter()
6476 .zip(&ffmpeg_frames)
6477 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
6478 if mismatched {
6479 let pin = std::env::temp_dir().join("ec-av1-compound-refs-gate-fail.obu");
6480 let _ = std::fs::write(&pin, &stream);
6481 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
6482 std::fs::write(&path, &stream).expect("writing pinned stream");
6483 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
6484 }
6485 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6486 assert_eq!(
6487 got.y, want.y,
6488 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
6489 pin.display()
6490 );
6491 assert_eq!(
6492 got.u, want.u,
6493 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
6494 pin.display()
6495 );
6496 assert_eq!(
6497 got.v, want.v,
6498 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
6499 pin.display()
6500 );
6501 }
6502 }
6503 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
6504 // stream again, comparing EVERY decode-order frame -- the hidden
6505 // (show_frame == 0) alt-ref frames the ffmpeg compare above
6506 // cannot see, because both sides of it emit shown frames only.
6507 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
6508 eprintln!(
6509 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
6510 {hidden_n} hidden, all pixel-exact vs the oracle"
6511 );
6512 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
6513 // libaom's temporal alt-ref filter absorbs this recipe's hidden
6514 // frames, so the compare above is vacuous -- re-encode the same
6515 // fixture with --arnr-maxframes=0 and compare THOSE.
6516 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
6517 eprintln!(
6518 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
6519 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
6520 );
6521 }
6522 if counted {
6523 eprintln!(
6524 "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}",
6525 decode::skip_mode_hits() - before
6526 );
6527 gate_buckets(NAME, 1, never_fired, refusals.len());
6528 return;
6529 }
6530 }
6531 gate_buckets(NAME, 0, never_fired, refusals.len());
6532 eprintln!(
6533 "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \
6534 other attempt hit a named refusal:\n{}",
6535 refusals.join("\n")
6536 );
6537 }
6538
6539 /// lane-motionmode round 1: `--enable-obmc=1 --enable-warped-motion=0`
6540 /// on the base recipe (`--auto-alt-ref=1 --lag-in-frames=16
6541 /// --enable-fwd-kf=0 --enable-ref-frame-mvs=0`) -- pixel-exact against
6542 /// ffmpeg, gated on [`decode::obmc_hits`] actually advancing (a real
6543 /// block picked `OBMC_CAUSAL`, not just that the header bit was set).
6544 /// Structure copied from
6545 /// `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`:
6546 /// a seed sweep with a named-refusal escape hatch and an
6547 /// `EC_AV1_GATE_DUMP` pin on mismatch.
6548 #[test]
6549 fn a_real_aomenc_stream_with_obmc_decodes_pixel_exact() {
6550 const NAME: &str = "a_real_aomenc_stream_with_obmc_decodes_pixel_exact";
6551 let _gate_lock = lock_gate_counters();
6552 if !have_ffmpeg() {
6553 eprintln!("SKIP {NAME}: no ffmpeg");
6554 return;
6555 }
6556 if !have_aomenc() {
6557 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6558 return;
6559 }
6560 let (width, height, frame_count) = (64usize, 64usize, 24usize);
6561 let mut refusals = Vec::new();
6562 let mut never_fired = 0u32;
6563 for attempt in 0..80u32 {
6564 let seed = 42 + attempt % 40;
6565 let duration = frame_count as f64 / 25.0;
6566 let source =
6567 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
6568 let y4m = Command::new("ffmpeg")
6569 .args([
6570 "-v",
6571 "error",
6572 "-f",
6573 "lavfi",
6574 "-i",
6575 &source,
6576 "-pix_fmt",
6577 "yuv420p",
6578 "-f",
6579 "yuv4mpegpipe",
6580 "-",
6581 ])
6582 .stdin(Stdio::null())
6583 .stdout(Stdio::piped())
6584 .stderr(Stdio::piped())
6585 .output()
6586 .expect("ffmpeg failed to run");
6587 assert!(
6588 y4m.status.success(),
6589 "ffmpeg fixture: {}",
6590 String::from_utf8_lossy(&y4m.stderr)
6591 );
6592 let args: Vec<&str> = vec![
6593 "--codec=av1",
6594 "--passes=1",
6595 "--end-usage=q",
6596 "--cq-level=45",
6597 "--cpu-used=0",
6598 "--kf-max-dist=1000",
6599 "--threads=1",
6600 "--row-mt=0",
6601 "--auto-alt-ref=1",
6602 "--lag-in-frames=16",
6603 "--enable-fwd-kf=0",
6604 "--enable-order-hint=1",
6605 "--enable-warped-motion=0",
6606 "--enable-obmc=1",
6607 "--enable-masked-comp=0",
6608 "--enable-interintra-comp=0",
6609 "--enable-onesided-comp=0",
6610 "--enable-interintra-wedge=0",
6611 "--enable-smooth-interintra=0",
6612 "--enable-rect-partitions=0",
6613 "--enable-ab-partitions=0",
6614 "--enable-1to4-partitions=0",
6615 "--enable-filter-intra=0",
6616 "--enable-smooth-intra=0",
6617 "--enable-paeth-intra=0",
6618 "--enable-directional-intra=0",
6619 "--enable-angle-delta=0",
6620 "--enable-tx-size-search=0",
6621 "--enable-cdef=0",
6622 "--enable-restoration=0",
6623 "--max-partition-size=32",
6624 "--min-partition-size=32",
6625 "--enable-palette=0",
6626 "--enable-intrabc=0",
6627 "--enable-cfl-intra=0",
6628 "--enable-ref-frame-mvs=0",
6629 "--obu",
6630 "-o",
6631 "-",
6632 "-",
6633 ];
6634 let mut child = Command::new(aomenc_path())
6635 .args(&args)
6636 .stdin(Stdio::piped())
6637 .stdout(Stdio::piped())
6638 .stderr(Stdio::piped())
6639 .spawn()
6640 .expect("aomenc failed to start");
6641 child
6642 .stdin
6643 .take()
6644 .expect("aomenc stdin")
6645 .write_all(&y4m.stdout)
6646 .expect("writing y4m to aomenc");
6647 let out = child.wait_with_output().expect("aomenc failed to run");
6648 assert!(
6649 out.status.success(),
6650 "aomenc refused the fixture: {}",
6651 String::from_utf8_lossy(&out.stderr)
6652 );
6653 let stream = out.stdout;
6654 let before = decode::obmc_hits();
6655 let frames = match decode_stream(&stream) {
6656 Err(e) => {
6657 let msg = e.to_string();
6658 assert!(
6659 msg.contains("unsupported"),
6660 "{NAME} failed outright (seed {seed}): {msg}"
6661 );
6662 refusals.push(format!("seed {seed}: {msg}"));
6663 continue;
6664 }
6665 Ok(frames) => frames,
6666 };
6667 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
6668 // is ALWAYS pixel-compared below; the hit counter only decides whether
6669 // the attempt counts toward the firing total.
6670 let counted = decode::obmc_hits() != before;
6671 if !counted {
6672 never_fired += 1;
6673 }
6674 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
6675 assert_eq!(frames.len(), frame_count);
6676 let mismatched = frames
6677 .iter()
6678 .zip(&ffmpeg_frames)
6679 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
6680 if mismatched {
6681 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
6682 std::fs::write(&path, &stream).expect("writing pinned stream");
6683 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
6684 }
6685 }
6686 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6687 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
6688 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
6689 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
6690 }
6691 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
6692 // stream again, comparing EVERY decode-order frame -- the hidden
6693 // (show_frame == 0) alt-ref frames the ffmpeg compare above
6694 // cannot see, because both sides of it emit shown frames only.
6695 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
6696 eprintln!(
6697 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
6698 {hidden_n} hidden, all pixel-exact vs the oracle"
6699 );
6700 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
6701 // libaom's temporal alt-ref filter absorbs this recipe's hidden
6702 // frames, so the compare above is vacuous -- re-encode the same
6703 // fixture with --arnr-maxframes=0 and compare THOSE.
6704 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
6705 eprintln!(
6706 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
6707 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
6708 );
6709 }
6710 if counted {
6711 eprintln!(
6712 "{NAME} FIRING seed {seed}: obmc hits advanced by {}",
6713 decode::obmc_hits() - before
6714 );
6715 gate_buckets(NAME, 1, never_fired, refusals.len());
6716 return;
6717 }
6718 }
6719 gate_buckets(NAME, 0, never_fired, refusals.len());
6720 eprintln!(
6721 "SKIP {NAME}: {never_fired} attempts decoded but never fired obmc, and every \
6722 other attempt hit a named refusal:\n{}",
6723 refusals.join("\n")
6724 );
6725 }
6726
6727 /// lane-motionmode round 3: same shape as
6728 /// `a_real_aomenc_stream_with_obmc_decodes_pixel_exact`, but relaxed the
6729 /// `--min-partition-size=32 --max-partition-size=32` clamp (that other
6730 /// gate's own doc: locked to remove partition-depth choice from the
6731 /// search entirely) to `8`/`32`, to make an 8x8-leaf `OBMC_CAUSAL` pick
6732 /// possible at all. Gated on [`decode::obmc_hits_8`] specifically, not
6733 /// the aggregate [`decode::obmc_hits`]. Measured live (round 3, this
6734 /// box): 80 attempts, 0 ever called `decode_inter_block8` at all --
6735 /// `cpu-used=0`'s RD search never once splits a 16x16 down to a clean
6736 /// 4-way 8x8 leaf for this smooth `gradients` fixture (large blocks
6737 /// always win the RD cost there); the handful of named refusals seen
6738 /// are `PARTITION_SPLIT` chosen *at* 8x8 (down to 4x4, already refused
6739 /// at `decode.rs`'s `part8 != PARTITION_NONE` check) or
6740 /// `allow_screen_content_tools`, neither reaching a leaf. Kept anyway
6741 /// (mirrors this file's own `never_fired`-skip convention) as the
6742 /// honest record of the attempt; a real 8x8 OBMC fixture needs
6743 /// higher-frequency content than this gate's fixtures use, out of
6744 /// round-3 budget.
6745 #[test]
6746 fn a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact() {
6747 const NAME: &str = "a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact";
6748 let _gate_lock = lock_gate_counters();
6749 if !have_ffmpeg() {
6750 eprintln!("SKIP {NAME}: no ffmpeg");
6751 return;
6752 }
6753 if !have_aomenc() {
6754 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6755 return;
6756 }
6757 let (width, height, frame_count) = (64usize, 64usize, 24usize);
6758 let mut refusals = Vec::new();
6759 let mut never_fired = 0u32;
6760 let mut total_obmc8 = 0usize;
6761 let n_attempts: u32 = std::env::var("EC_OBMC8_ATTEMPTS")
6762 .ok()
6763 .and_then(|s| s.parse().ok())
6764 .unwrap_or(80);
6765 for attempt in 0..n_attempts {
6766 let seed = 42 + attempt % 40;
6767 let duration = frame_count as f64 / 25.0;
6768 // Recipe search hook: `gradients` is smooth, so aomenc's RD never
6769 // splits below 16x16 and this gate never fired one 8x8 OBMC block
6770 // in 45 attempts -- it "passed" by skipping (gate-blind-to-feature).
6771 // EC_AV1_OBMC8_SOURCE overrides the lavfi source so a firing recipe
6772 // can be searched for without a rebuild.
6773 let source = std::env::var("EC_AV1_OBMC8_SOURCE").unwrap_or_else(|_| {
6774 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
6775 });
6776 // A source supplied through EC_AV1_OBMC8_SOURCE need not carry its
6777 // own `duration=`; `-t` is the bound that always holds. Without it
6778 // an endless source (`testsrc2`) fills the pipe forever and the
6779 // gate hangs to its 300 s timeout.
6780 let duration_arg = format!("{duration}");
6781 let y4m = Command::new("ffmpeg")
6782 .args([
6783 "-v",
6784 "error",
6785 "-f",
6786 "lavfi",
6787 "-i",
6788 &source,
6789 "-t",
6790 &duration_arg,
6791 "-pix_fmt",
6792 "yuv420p",
6793 "-f",
6794 "yuv4mpegpipe",
6795 "-",
6796 ])
6797 .stdin(Stdio::null())
6798 .stdout(Stdio::piped())
6799 .stderr(Stdio::piped())
6800 .output()
6801 .expect("ffmpeg failed to run");
6802 assert!(
6803 y4m.status.success(),
6804 "ffmpeg fixture: {}",
6805 String::from_utf8_lossy(&y4m.stderr)
6806 );
6807 let args: Vec<&str> = vec![
6808 "--codec=av1",
6809 "--passes=1",
6810 "--end-usage=q",
6811 "--cq-level=45",
6812 "--cpu-used=0",
6813 "--kf-max-dist=1000",
6814 "--threads=1",
6815 "--row-mt=0",
6816 "--auto-alt-ref=1",
6817 "--lag-in-frames=16",
6818 "--enable-fwd-kf=0",
6819 "--enable-order-hint=1",
6820 "--enable-warped-motion=0",
6821 "--enable-obmc=1",
6822 "--enable-masked-comp=0",
6823 "--enable-interintra-comp=0",
6824 "--enable-onesided-comp=0",
6825 "--enable-interintra-wedge=0",
6826 "--enable-smooth-interintra=0",
6827 "--enable-rect-partitions=0",
6828 "--enable-ab-partitions=0",
6829 "--enable-1to4-partitions=0",
6830 "--enable-filter-intra=0",
6831 "--enable-smooth-intra=0",
6832 "--enable-paeth-intra=0",
6833 "--enable-directional-intra=0",
6834 "--enable-angle-delta=0",
6835 "--enable-tx-size-search=0",
6836 "--enable-cdef=0",
6837 "--enable-restoration=0",
6838 "--min-partition-size=8",
6839 "--max-partition-size=32",
6840 "--enable-palette=0",
6841 "--enable-intrabc=0",
6842 "--enable-cfl-intra=0",
6843 "--enable-ref-frame-mvs=0",
6844 "--obu",
6845 "-o",
6846 "-",
6847 "-",
6848 ];
6849 let mut child = Command::new(aomenc_path())
6850 .args(&args)
6851 .stdin(Stdio::piped())
6852 .stdout(Stdio::piped())
6853 .stderr(Stdio::piped())
6854 .spawn()
6855 .expect("aomenc failed to start");
6856 child
6857 .stdin
6858 .take()
6859 .expect("aomenc stdin")
6860 .write_all(&y4m.stdout)
6861 .expect("writing y4m to aomenc");
6862 let out = child.wait_with_output().expect("aomenc failed to run");
6863 assert!(
6864 out.status.success(),
6865 "aomenc refused the fixture: {}",
6866 String::from_utf8_lossy(&out.stderr)
6867 );
6868 let stream = out.stdout;
6869 let before8 = decode::obmc_hits_8();
6870 let frames = match decode_stream(&stream) {
6871 Err(e) => {
6872 let msg = e.to_string();
6873 assert!(
6874 msg.contains("unsupported"),
6875 "{NAME} failed outright (seed {seed}): {msg}"
6876 );
6877 refusals.push(format!("seed {seed}: {msg}"));
6878 continue;
6879 }
6880 Ok(frames) => frames,
6881 };
6882 let fired8 = decode::obmc_hits_8() - before8;
6883 total_obmc8 += fired8;
6884 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
6885 // is ALWAYS pixel-compared below; the hit counter only decides whether
6886 // the attempt counts toward the firing total.
6887 let counted = fired8 != 0;
6888 if !counted {
6889 never_fired += 1;
6890 }
6891 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
6892 assert_eq!(frames.len(), frame_count);
6893 let mismatched = frames
6894 .iter()
6895 .zip(&ffmpeg_frames)
6896 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
6897 if mismatched {
6898 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
6899 std::fs::write(&path, &stream).expect("writing pinned stream");
6900 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
6901 }
6902 }
6903 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6904 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
6905 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
6906 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
6907 }
6908 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
6909 // stream again, comparing EVERY decode-order frame -- the hidden
6910 // (show_frame == 0) alt-ref frames the ffmpeg compare above
6911 // cannot see, because both sides of it emit shown frames only.
6912 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
6913 eprintln!(
6914 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
6915 {hidden_n} hidden, all pixel-exact vs the oracle"
6916 );
6917 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
6918 // libaom's temporal alt-ref filter absorbs this recipe's hidden
6919 // frames, so the compare above is vacuous -- re-encode the same
6920 // fixture with --arnr-maxframes=0 and compare THOSE.
6921 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
6922 eprintln!(
6923 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
6924 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
6925 );
6926 }
6927 if counted {
6928 eprintln!(
6929 "{NAME} FIRING seed {seed}: 8x8 obmc hits {fired8} (total across attempts so far {total_obmc8})"
6930 );
6931 gate_buckets(NAME, 1, never_fired, refusals.len());
6932 return;
6933 }
6934 }
6935 gate_buckets(NAME, 0, never_fired, refusals.len());
6936 // lane-gmaffine r2: this gate fired for three rounds only as a SKIP
6937 // (gate-skips-on-its-own-failure); the 8x8 leaf is reachable now, so a
6938 // sweep that never lands one firing pixel-exact attempt is a FAILURE.
6939 panic!(
6940 "{NAME}: {never_fired} attempts decoded but never fired an 8x8 obmc block \
6941 ({total_obmc8} total 8x8 obmc hits across all attempts), and every other attempt \
6942 hit a named refusal:\n{}",
6943 refusals.join("\n")
6944 );
6945 }
6946
6947 /// lane-warp r5e (flipped from lane-motionmode r1's refuses-or-matches):
6948 /// `--enable-warped-motion=1` streams must DECODE pixel-exact --
6949 /// `av1_findSamples`/`num_proj_ref`, the 3-symbol `motion_mode` read,
6950 /// the affine projection/filter, and the WARPED_CAUSAL interp-filter
6951 /// derivation are all ported. A refusal naming warp, or any pixel
6952 /// mismatch, fails the gate; refusals for OTHER named capabilities
6953 /// (screen content tools) still skip that seed. The sweep must also
6954 /// actually exercise warp (`warp_selected_hits > 0`) so a decoder that
6955 /// silently stops selecting WARPED_CAUSAL cannot pass vacuously.
6956 #[test]
6957 fn a_real_aomenc_stream_with_warped_motion_refuses_or_matches() {
6958 const NAME: &str = "a_real_aomenc_stream_with_warped_motion_refuses_or_matches";
6959 let _gate_lock = lock_gate_counters();
6960 if !have_ffmpeg() {
6961 eprintln!("SKIP {NAME}: no ffmpeg");
6962 return;
6963 }
6964 if !have_aomenc() {
6965 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6966 return;
6967 }
6968 let (width, height, frame_count) = (64usize, 64usize, 24usize);
6969 let mut named_refusals = 0u32;
6970 let mut matched = 0u32;
6971 let n_attempts: u32 = std::env::var("EC_WARP_GATE_ATTEMPTS")
6972 .ok()
6973 .and_then(|s| s.parse().ok())
6974 .unwrap_or(40);
6975 for attempt in 0..n_attempts {
6976 let seed = 42 + attempt;
6977 let duration = frame_count as f64 / 25.0;
6978 let source =
6979 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
6980 let y4m = Command::new("ffmpeg")
6981 .args([
6982 "-v",
6983 "error",
6984 "-f",
6985 "lavfi",
6986 "-i",
6987 &source,
6988 "-pix_fmt",
6989 "yuv420p",
6990 "-f",
6991 "yuv4mpegpipe",
6992 "-",
6993 ])
6994 .stdin(Stdio::null())
6995 .stdout(Stdio::piped())
6996 .stderr(Stdio::piped())
6997 .output()
6998 .expect("ffmpeg failed to run");
6999 assert!(
7000 y4m.status.success(),
7001 "ffmpeg fixture: {}",
7002 String::from_utf8_lossy(&y4m.stderr)
7003 );
7004 let args: Vec<&str> = vec![
7005 "--codec=av1",
7006 "--passes=1",
7007 "--end-usage=q",
7008 "--cq-level=45",
7009 "--cpu-used=0",
7010 "--kf-max-dist=1000",
7011 "--threads=1",
7012 "--row-mt=0",
7013 "--auto-alt-ref=1",
7014 "--lag-in-frames=16",
7015 "--enable-fwd-kf=0",
7016 "--enable-order-hint=1",
7017 "--enable-warped-motion=1",
7018 "--enable-obmc=1",
7019 "--tune-content=default",
7020 "--enable-masked-comp=0",
7021 "--enable-interintra-comp=0",
7022 "--enable-onesided-comp=0",
7023 "--enable-interintra-wedge=0",
7024 "--enable-smooth-interintra=0",
7025 "--enable-rect-partitions=0",
7026 "--enable-ab-partitions=0",
7027 "--enable-1to4-partitions=0",
7028 "--enable-filter-intra=0",
7029 "--enable-smooth-intra=0",
7030 "--enable-paeth-intra=0",
7031 "--enable-directional-intra=0",
7032 "--enable-angle-delta=0",
7033 "--enable-tx-size-search=0",
7034 "--enable-cdef=0",
7035 "--enable-restoration=0",
7036 "--max-partition-size=32",
7037 "--min-partition-size=32",
7038 "--enable-palette=0",
7039 "--enable-intrabc=0",
7040 "--enable-cfl-intra=0",
7041 "--enable-ref-frame-mvs=0",
7042 "--obu",
7043 "-o",
7044 "-",
7045 "-",
7046 ];
7047 let mut child = Command::new(aomenc_path())
7048 .args(&args)
7049 .stdin(Stdio::piped())
7050 .stdout(Stdio::piped())
7051 .stderr(Stdio::piped())
7052 .spawn()
7053 .expect("aomenc failed to start");
7054 child
7055 .stdin
7056 .take()
7057 .expect("aomenc stdin")
7058 .write_all(&y4m.stdout)
7059 .expect("writing y4m to aomenc");
7060 let out = child.wait_with_output().expect("aomenc failed to run");
7061 assert!(
7062 out.status.success(),
7063 "aomenc refused the fixture: {}",
7064 String::from_utf8_lossy(&out.stderr)
7065 );
7066 let stream = out.stdout;
7067 let frames = match decode_stream(&stream) {
7068 Err(e) => {
7069 let msg = e.to_string();
7070 assert!(
7071 msg.contains("unsupported"),
7072 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
7073 );
7074 assert!(
7075 !msg.contains("warp"),
7076 "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \
7077 refusal must not exist: {msg}"
7078 );
7079 named_refusals += 1;
7080 eprintln!("seed {seed} refusal (non-warp capability): {msg}");
7081 continue;
7082 }
7083 Ok(frames) => frames,
7084 };
7085 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
7086 assert_eq!(frames.len(), frame_count);
7087 let mismatched = frames
7088 .iter()
7089 .zip(&ffmpeg_frames)
7090 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
7091 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
7092 std::fs::write(&path, &stream).expect("writing pinned stream");
7093 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
7094 }
7095 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
7096 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
7097 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
7098 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
7099 }
7100 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
7101 // stream again, comparing EVERY decode-order frame -- the hidden
7102 // (show_frame == 0) alt-ref frames the ffmpeg compare above
7103 // cannot see, because both sides of it emit shown frames only.
7104 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
7105 eprintln!(
7106 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
7107 {hidden_n} hidden, all pixel-exact vs the oracle"
7108 );
7109 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
7110 // libaom's temporal alt-ref filter absorbs this recipe's hidden
7111 // frames, so the compare above is vacuous -- re-encode the same
7112 // fixture with --arnr-maxframes=0 and compare THOSE.
7113 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
7114 eprintln!(
7115 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
7116 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
7117 );
7118 }
7119 matched += 1;
7120 }
7121 assert!(
7122 matched > 0,
7123 "{NAME}: every attempt refused on other capabilities; the gate never exercised warp"
7124 );
7125 assert!(
7126 crate::decode::warp_selected_hits() > 0,
7127 "{NAME}: {matched} matches but zero WARPED_CAUSAL blocks fired -- the gate decodes \
7128 warp streams without ever selecting warp, so it proves nothing about warp"
7129 );
7130 eprintln!(
7131 "{NAME}: {named_refusals} non-warp refusals, {matched} pixel-exact matches out of {n_attempts}, warp_selected_hits={}",
7132 crate::decode::warp_selected_hits()
7133 );
7134 }
7135
7136 /// lane-superres stage 3: a real aomenc `--superres-mode=1` key-frame
7137 /// sequence must decode pixel-exact vs ffmpeg/dav1d's own upscaled
7138 /// output, and must actually run [`crate::superres::upscale_picture`]
7139 /// (`superres_hits > 0`) -- a decoder that silently stopped upscaling
7140 /// would otherwise pass vacuously (class `gate-blind-to-feature`).
7141 /// `--kf-max-dist` set to the frame count keeps every frame a key
7142 /// frame: inter-frame superres (a differently-scaled reference) is a
7143 /// later stage of this lane, refused by name today.
7144 #[test]
7145 fn a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact() {
7146 const NAME: &str = "a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact";
7147 let _gate_lock = lock_gate_counters();
7148 if !have_ffmpeg() {
7149 eprintln!("SKIP {NAME}: no ffmpeg");
7150 return;
7151 }
7152 if !have_aomenc() {
7153 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7154 return;
7155 }
7156 let (width, height, frame_count) = (64usize, 64usize, 3usize);
7157 let duration = frame_count as f64 / 25.0;
7158 let source = gradients_source(7, width, height, &format!("duration={duration}:rate=25"));
7159 let y4m = Command::new("ffmpeg")
7160 .args([
7161 "-v",
7162 "error",
7163 "-f",
7164 "lavfi",
7165 "-i",
7166 &source,
7167 "-pix_fmt",
7168 "yuv420p",
7169 "-f",
7170 "yuv4mpegpipe",
7171 "-",
7172 ])
7173 .stdin(Stdio::null())
7174 .stdout(Stdio::piped())
7175 .stderr(Stdio::piped())
7176 .output()
7177 .expect("ffmpeg failed to run");
7178 assert!(
7179 y4m.status.success(),
7180 "ffmpeg fixture: {}",
7181 String::from_utf8_lossy(&y4m.stderr)
7182 );
7183 let args: Vec<&str> = vec![
7184 "--codec=av1",
7185 "--passes=1",
7186 "--end-usage=q",
7187 "--cq-level=32",
7188 "--cpu-used=0",
7189 "--kf-max-dist=0",
7190 "--threads=1",
7191 "--row-mt=0",
7192 "--superres-mode=1",
7193 "--superres-denominator=12",
7194 "--superres-kf-denominator=12",
7195 "--enable-rect-partitions=0",
7196 "--enable-ab-partitions=0",
7197 "--enable-1to4-partitions=0",
7198 "--enable-filter-intra=0",
7199 "--enable-smooth-intra=0",
7200 "--enable-paeth-intra=0",
7201 "--enable-directional-intra=0",
7202 "--enable-angle-delta=0",
7203 "--enable-tx-size-search=0",
7204 "--enable-cdef=0",
7205 "--enable-restoration=0",
7206 "--max-partition-size=32",
7207 "--min-partition-size=32",
7208 "--enable-palette=0",
7209 "--enable-intrabc=0",
7210 "--enable-cfl-intra=0",
7211 "--obu",
7212 "-o",
7213 "-",
7214 "-",
7215 ];
7216 let mut child = Command::new(aomenc_path())
7217 .args(&args)
7218 .stdin(Stdio::piped())
7219 .stdout(Stdio::piped())
7220 .stderr(Stdio::piped())
7221 .spawn()
7222 .expect("aomenc failed to start");
7223 child
7224 .stdin
7225 .take()
7226 .expect("aomenc stdin")
7227 .write_all(&y4m.stdout)
7228 .expect("writing y4m to aomenc");
7229 let out = child.wait_with_output().expect("aomenc failed to run");
7230 assert!(
7231 out.status.success(),
7232 "aomenc refused the fixture: {}",
7233 String::from_utf8_lossy(&out.stderr)
7234 );
7235 let stream = out.stdout;
7236 if let Ok(path) = std::env::var("EC_SUPERRES_STREAM_DUMP") {
7237 std::fs::write(path, &stream).expect("dump stream");
7238 }
7239 let frames =
7240 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}"));
7241 assert_eq!(frames.len(), frame_count);
7242 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
7243 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
7244 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg");
7245 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
7246 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
7247 }
7248 assert!(
7249 crate::superres::superres_hits() > 0,
7250 "{NAME}: matched but zero superres_hits -- the gate never actually exercised the \
7251 upscaler, it proves nothing"
7252 );
7253 eprintln!(
7254 "{NAME}: {frame_count} frames pixel-exact, superres_hits={}",
7255 crate::superres::superres_hits()
7256 );
7257 }
7258
7259 /// lane-superres r10: a real aomenc key+inter `--superres-mode=1`
7260 /// sequence must DECODE pixel-exact vs ffmpeg, with the frame-level
7261 /// `use_superres` refusal LIFTED for inter frames -- `mc::predict_scaled`
7262 /// (spec 7.11.3.3) is the only path this recipe can reach (warp/OBMC/
7263 /// compound/interintra/palette/intrabc/CDEF/LR are all off, matching the
7264 /// scoped refusals' own unimplemented list). A pixel match alone would
7265 /// pass just as well with an unscaled reference and prove nothing
7266 /// (class `gate-blind-to-feature`) -- hard-assert
7267 /// `crate::mc::predict_scaled_hits() > 0` so the gate can only pass if the
7268 /// scaled MC path actually ran.
7269 #[test]
7270 fn a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact() {
7271 const NAME: &str = "a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact";
7272 let _gate_lock = lock_gate_counters();
7273 if !have_ffmpeg() {
7274 eprintln!("SKIP {NAME}: no ffmpeg");
7275 return;
7276 }
7277 if !have_aomenc() {
7278 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7279 return;
7280 }
7281 let (width, height, frame_count) = (64usize, 64usize, 3usize);
7282 let duration = frame_count as f64 / 25.0;
7283 let source = gradients_source(11, width, height, &format!("duration={duration}:rate=25"));
7284 let y4m = Command::new("ffmpeg")
7285 .args([
7286 "-v",
7287 "error",
7288 "-f",
7289 "lavfi",
7290 "-i",
7291 &source,
7292 "-pix_fmt",
7293 "yuv420p",
7294 "-f",
7295 "yuv4mpegpipe",
7296 "-",
7297 ])
7298 .stdin(Stdio::null())
7299 .stdout(Stdio::piped())
7300 .stderr(Stdio::piped())
7301 .output()
7302 .expect("ffmpeg failed to run");
7303 assert!(
7304 y4m.status.success(),
7305 "ffmpeg fixture: {}",
7306 String::from_utf8_lossy(&y4m.stderr)
7307 );
7308 let args: Vec<&str> = vec![
7309 "--codec=av1",
7310 "--passes=1",
7311 "--end-usage=q",
7312 "--cq-level=32",
7313 "--cpu-used=0",
7314 // `--kf-max-dist` above `frame_count` keeps only frame 0 a key
7315 // frame -- frames 1/2 are the inter frames whose `use_superres`
7316 // refusal this round lifts.
7317 "--kf-max-dist=1000",
7318 "--lag-in-frames=0",
7319 "--auto-alt-ref=0",
7320 "--threads=1",
7321 "--row-mt=0",
7322 "--sb-size=64",
7323 "--superres-mode=1",
7324 "--superres-denominator=12",
7325 "--superres-kf-denominator=12",
7326 // Forces every inter block onto the single-ref, non-warp/OBMC/
7327 // interintra branch `decode_inter_block` threads `predict_scaled`
7328 // through -- the only branch this round's scoped refusals leave
7329 // unrefused under a scaled reference.
7330 "--enable-warped-motion=0",
7331 "--enable-obmc=0",
7332 "--enable-masked-comp=0",
7333 "--enable-interintra-comp=0",
7334 "--enable-dist-wtd-comp=0",
7335 "--enable-diff-wtd-comp=0",
7336 "--enable-onesided-comp=0",
7337 "--enable-interintra-wedge=0",
7338 "--enable-smooth-interintra=0",
7339 "--enable-order-hint=0",
7340 "--enable-ref-frame-mvs=0",
7341 "--enable-rect-partitions=0",
7342 "--enable-ab-partitions=0",
7343 "--enable-1to4-partitions=0",
7344 "--enable-filter-intra=0",
7345 "--enable-smooth-intra=0",
7346 "--enable-paeth-intra=0",
7347 "--enable-directional-intra=0",
7348 "--enable-angle-delta=0",
7349 "--enable-tx-size-search=0",
7350 "--enable-cdef=0",
7351 "--enable-restoration=0",
7352 "--max-partition-size=32",
7353 "--min-partition-size=32",
7354 "--enable-palette=0",
7355 "--enable-intrabc=0",
7356 "--enable-cfl-intra=0",
7357 "--obu",
7358 "-o",
7359 "-",
7360 "-",
7361 ];
7362 let mut child = Command::new(aomenc_path())
7363 .args(&args)
7364 .stdin(Stdio::piped())
7365 .stdout(Stdio::piped())
7366 .stderr(Stdio::piped())
7367 .spawn()
7368 .expect("aomenc failed to start");
7369 child
7370 .stdin
7371 .take()
7372 .expect("aomenc stdin")
7373 .write_all(&y4m.stdout)
7374 .expect("writing y4m to aomenc");
7375 let out = child.wait_with_output().expect("aomenc failed to run");
7376 assert!(
7377 out.status.success(),
7378 "aomenc refused the fixture: {}",
7379 String::from_utf8_lossy(&out.stderr)
7380 );
7381 let stream = out.stdout;
7382 if let Ok(path) = std::env::var("EC_SUPERRES_INTER_STREAM_DUMP") {
7383 std::fs::write(&path, &stream).expect("dump stream");
7384 }
7385 let frames =
7386 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}"));
7387 assert_eq!(frames.len(), frame_count);
7388 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
7389 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
7390 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg");
7391 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
7392 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
7393 }
7394 assert!(
7395 crate::superres::superres_hits() > 0,
7396 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
7397 );
7398 assert!(
7399 crate::mc::predict_scaled_hits() > 0,
7400 "{NAME}: matched but zero predict_scaled_hits -- every block took the unscaled MC \
7401 path, which proves nothing about the scaled-reference code this round adds \
7402 (class gate-blind-to-feature)"
7403 );
7404 eprintln!(
7405 "{NAME}: {frame_count} frames pixel-exact, superres_hits={}, predict_scaled_hits={}",
7406 crate::superres::superres_hits(),
7407 crate::mc::predict_scaled_hits()
7408 );
7409 }
7410
7411 /// lane-interintra r1: `--enable-interintra-comp=1` streams must DECODE
7412 /// pixel-exact -- the interintra flag/mode/wedge-flag syntax and the
7413 /// non-wedge smooth blend are ported. A refusal naming interintra fails
7414 /// the gate UNLESS it is the wedge refusal (`use_wedge_interintra == 1`
7415 /// is r2, and this recipe encodes with wedge off so it must not fire
7416 /// either); warp/obmc are enabled and supported; refusals for OTHER
7417 /// named capabilities (screen content tools) still skip that seed. The
7418 /// sweep must actually exercise interintra (`interintra_hits > 0`).
7419 #[test]
7420 fn a_real_aomenc_stream_with_interintra_decodes_pixel_exact() {
7421 const NAME: &str = "a_real_aomenc_stream_with_interintra_decodes_pixel_exact";
7422 let _gate_lock = lock_gate_counters();
7423 if !have_ffmpeg() {
7424 eprintln!("SKIP {NAME}: no ffmpeg");
7425 return;
7426 }
7427 if !have_aomenc() {
7428 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7429 return;
7430 }
7431 let (width, height, frame_count) = (64usize, 64usize, 24usize);
7432 let mut named_refusals = 0u32;
7433 let mut matched = 0u32;
7434 let n_attempts: u32 = std::env::var("EC_INTERINTRA_GATE_ATTEMPTS")
7435 .ok()
7436 .and_then(|s| s.parse().ok())
7437 .unwrap_or(40);
7438 for attempt in 0..n_attempts {
7439 let seed = 42 + attempt;
7440 let duration = frame_count as f64 / 25.0;
7441 let source =
7442 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
7443 let y4m = Command::new("ffmpeg")
7444 .args([
7445 "-v",
7446 "error",
7447 "-f",
7448 "lavfi",
7449 "-i",
7450 &source,
7451 "-pix_fmt",
7452 "yuv420p",
7453 "-f",
7454 "yuv4mpegpipe",
7455 "-",
7456 ])
7457 .stdin(Stdio::null())
7458 .stdout(Stdio::piped())
7459 .stderr(Stdio::piped())
7460 .output()
7461 .expect("ffmpeg failed to run");
7462 assert!(
7463 y4m.status.success(),
7464 "ffmpeg fixture: {}",
7465 String::from_utf8_lossy(&y4m.stderr)
7466 );
7467 let args: Vec<&str> = vec![
7468 "--codec=av1",
7469 "--passes=1",
7470 "--end-usage=q",
7471 "--cq-level=45",
7472 "--cpu-used=0",
7473 "--kf-max-dist=1000",
7474 "--threads=1",
7475 "--row-mt=0",
7476 "--auto-alt-ref=1",
7477 "--lag-in-frames=16",
7478 "--enable-fwd-kf=0",
7479 "--enable-order-hint=1",
7480 "--enable-warped-motion=1",
7481 "--enable-obmc=1",
7482 "--tune-content=default",
7483 "--enable-masked-comp=0",
7484 "--enable-interintra-comp=1",
7485 "--enable-onesided-comp=1",
7486 "--enable-interintra-wedge=0",
7487 "--enable-smooth-interintra=1",
7488 "--enable-rect-partitions=0",
7489 "--enable-ab-partitions=0",
7490 "--enable-1to4-partitions=0",
7491 "--enable-filter-intra=0",
7492 "--enable-smooth-intra=0",
7493 "--enable-paeth-intra=0",
7494 "--enable-directional-intra=0",
7495 "--enable-angle-delta=0",
7496 "--enable-tx-size-search=0",
7497 "--enable-cdef=0",
7498 "--enable-restoration=0",
7499 "--max-partition-size=32",
7500 "--min-partition-size=32",
7501 "--enable-palette=0",
7502 "--enable-intrabc=0",
7503 "--enable-cfl-intra=0",
7504 "--enable-ref-frame-mvs=0",
7505 "--obu",
7506 "-o",
7507 "-",
7508 "-",
7509 ];
7510 let mut child = Command::new(aomenc_path())
7511 .args(&args)
7512 .stdin(Stdio::piped())
7513 .stdout(Stdio::piped())
7514 .stderr(Stdio::piped())
7515 .spawn()
7516 .expect("aomenc failed to start");
7517 child
7518 .stdin
7519 .take()
7520 .expect("aomenc stdin")
7521 .write_all(&y4m.stdout)
7522 .expect("writing y4m to aomenc");
7523 let out = child.wait_with_output().expect("aomenc failed to run");
7524 assert!(
7525 out.status.success(),
7526 "aomenc refused the fixture: {}",
7527 String::from_utf8_lossy(&out.stderr)
7528 );
7529 let stream = out.stdout;
7530 let frames = match decode_stream(&stream) {
7531 Err(e) => {
7532 let msg = e.to_string();
7533 assert!(
7534 msg.contains("unsupported"),
7535 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
7536 );
7537 assert!(
7538 !msg.contains("warp"),
7539 "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \
7540 refusal must not exist: {msg}"
7541 );
7542 assert!(
7543 !msg.contains("interintra"),
7544 "{NAME} refused on interintra (seed {seed}) -- non-wedge interintra \
7545 is ported and this recipe encodes with wedge off: {msg}"
7546 );
7547 named_refusals += 1;
7548 eprintln!("seed {seed} refusal (non-warp capability): {msg}");
7549 continue;
7550 }
7551 Ok(frames) => frames,
7552 };
7553 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
7554 assert_eq!(frames.len(), frame_count);
7555 let mismatched = frames
7556 .iter()
7557 .zip(&ffmpeg_frames)
7558 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
7559 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
7560 std::fs::write(&path, &stream).expect("writing pinned stream");
7561 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
7562 }
7563 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
7564 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
7565 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
7566 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
7567 }
7568 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
7569 // stream again, comparing EVERY decode-order frame -- the hidden
7570 // (show_frame == 0) alt-ref frames the ffmpeg compare above
7571 // cannot see, because both sides of it emit shown frames only.
7572 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
7573 eprintln!(
7574 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
7575 {hidden_n} hidden, all pixel-exact vs the oracle"
7576 );
7577 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
7578 // libaom's temporal alt-ref filter absorbs this recipe's hidden
7579 // frames, so the compare above is vacuous -- re-encode the same
7580 // fixture with --arnr-maxframes=0 and compare THOSE.
7581 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
7582 eprintln!(
7583 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
7584 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
7585 );
7586 }
7587 matched += 1;
7588 }
7589 assert!(
7590 matched > 0,
7591 "{NAME}: every attempt refused on other capabilities; the gate never exercised warp"
7592 );
7593 assert!(
7594 crate::decode::interintra_hits() > 0,
7595 "{NAME}: {matched} matches but zero interintra blocks fired -- the gate decodes \
7596 these streams without ever taking interintra, so it proves nothing"
7597 );
7598 // lane-defon r1: `--enable-onesided-comp=1` is spelled on this
7599 // recipe, so a UNIDIR_COMP_REFERENCE pair must actually have been
7600 // read -- otherwise the on-value proves nothing.
7601 assert!(
7602 crate::decode::uni_comp_hits() > 0,
7603 "{NAME}: {matched} matches but zero UNIDIR_COMP_REFERENCE pairs read -- \
7604 --enable-onesided-comp=1 never reached the uni_comp_ref alphabet"
7605 );
7606 eprintln!(
7607 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, interintra_hits={} uni_comp_hits={}",
7608 crate::decode::interintra_hits(),
7609 crate::decode::uni_comp_hits()
7610 );
7611 }
7612
7613 /// lane-scaledref r1: a real aomenc `--superres-mode=1` sequence with
7614 /// compound, OBMC, interintra and 8x8 leaves ALL enabled must decode
7615 /// pixel-exact -- these are the combinations the three
7616 /// "... with a scaled reference (superres, unimplemented)" refusals used
7617 /// to cover. Each combination gets its OWN hard-asserted hit counter
7618 /// (`crate::decode::scaled_*_hits`), because an unscaled reference would
7619 /// pass the pixels and prove nothing (class `gate-blind-to-feature`), and
7620 /// a stream that scales but never takes compound/OBMC/interintra/8x8
7621 /// would prove nothing about the code this round adds either. A refusal
7622 /// naming a scaled reference is a hard failure: those are exactly the
7623 /// strings this round lifts. Other named capabilities skip that seed.
7624 #[test]
7625 fn a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact()
7626 {
7627 const NAME: &str = "a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact";
7628 let _gate_lock = lock_gate_counters();
7629 if !have_ffmpeg() {
7630 eprintln!("SKIP {NAME}: no ffmpeg");
7631 return;
7632 }
7633 if !have_aomenc() {
7634 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7635 return;
7636 }
7637 let (width, height, frame_count) = (64usize, 64usize, 24usize);
7638 let mut named_refusals = 0u32;
7639 let mut matched = 0u32;
7640 let n_attempts: u32 = std::env::var("EC_SCALEDREF_GATE_ATTEMPTS")
7641 .ok()
7642 .and_then(|s| s.parse().ok())
7643 .unwrap_or(12);
7644 for attempt in 0..n_attempts {
7645 let seed = 42 + attempt;
7646 let duration = frame_count as f64 / 25.0;
7647 let source =
7648 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
7649 let y4m = Command::new("ffmpeg")
7650 .args([
7651 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
7652 "yuv4mpegpipe", "-",
7653 ])
7654 .stdin(Stdio::null())
7655 .stdout(Stdio::piped())
7656 .stderr(Stdio::piped())
7657 .output()
7658 .expect("ffmpeg failed to run");
7659 assert!(
7660 y4m.status.success(),
7661 "ffmpeg fixture: {}",
7662 String::from_utf8_lossy(&y4m.stderr)
7663 );
7664 let on = |name: &str| {
7665 if std::env::var(name).as_deref() == Ok("0") { "0" } else { "1" }
7666 };
7667 // lane-scaledref r2: warp is ON. A warp-capable frame header
7668 // under a scaled reference is exactly the case r1 got wrong
7669 // (the block must read the 2-symbol `obmc_cdf`, not the
7670 // 3-symbol `motion_mode_cdf` -- libaom `motion_mode_allowed`,
7671 // blockd.h:1484), and it decoded silently wrong pixels rather
7672 // than refusing. `EC_SCALEDREF_WARP=0` turns it off for
7673 // bisecting only.
7674 let warp = format!("--enable-warped-motion={}", on("EC_SCALEDREF_WARP"));
7675 // lane-scaledref r2: `EC_SCALEDREF_MODE=3` (qthresh) lets
7676 // superres switch on and off per frame, so a compound block can
7677 // reference one scaled and one unscaled reference -- the mixed
7678 // case mode 1 (every frame scaled) never produces.
7679 let superres_mode = format!(
7680 "--superres-mode={}",
7681 std::env::var("EC_SCALEDREF_MODE").unwrap_or_else(|_| "1".into())
7682 );
7683 let obmc = format!("--enable-obmc={}", on("EC_SCALEDREF_OBMC"));
7684 let interintra = format!("--enable-interintra-comp={}", on("EC_SCALEDREF_II"));
7685 let lag = format!(
7686 "--lag-in-frames={}",
7687 if on("EC_SCALEDREF_COMP") == "0" { "0" } else { "25" }
7688 );
7689 let alt_ref = format!("--auto-alt-ref={}", on("EC_SCALEDREF_COMP"));
7690 let args: Vec<&str> = vec![
7691 "--codec=av1",
7692 "--passes=1",
7693 "--end-usage=q",
7694 "--cq-level=45",
7695 "--cpu-used=0",
7696 "--kf-max-dist=1000",
7697 "--threads=1",
7698 "--row-mt=0",
7699 "--sb-size=64",
7700 // superres on every frame, key and inter alike -- the scaled
7701 // reference this gate is about.
7702 // denominator 16 (the maximum) keeps the CODED frame
7703 // 32x64 -- a multiple of 16 both ways, so no frame-edge
7704 // 16x16 straddle forces a sub-16x16 partition this decoder
7705 // still refuses on the aligned path ("an inter partition
7706 // below 16x16"). Denominator 12 codes 43 columns and every
7707 // seed refused there.
7708 &superres_mode,
7709 "--superres-denominator=16",
7710 "--superres-kf-denominator=16",
7711 // the four combinations this round lifts (each switchable
7712 // by env for bisecting a mismatch without a rebuild)
7713 &alt_ref,
7714 &lag,
7715 "--enable-order-hint=1",
7716 &warp,
7717 &obmc,
7718 &interintra,
7719 "--enable-smooth-interintra=1",
7720 "--enable-interintra-wedge=0",
7721 "--enable-masked-comp=0",
7722 "--enable-onesided-comp=0",
7723 "--enable-fwd-kf=0",
7724 "--tune-content=default",
7725 "--max-partition-size=32",
7726 "--min-partition-size=32",
7727 // everything this decoder still refuses under any reference
7728 "--enable-rect-partitions=0",
7729 "--enable-ab-partitions=0",
7730 "--enable-1to4-partitions=0",
7731 "--enable-filter-intra=0",
7732 "--enable-smooth-intra=0",
7733 "--enable-paeth-intra=0",
7734 "--enable-directional-intra=0",
7735 "--enable-angle-delta=0",
7736 "--enable-tx-size-search=0",
7737 "--enable-cdef=0",
7738 "--enable-restoration=0",
7739 "--enable-palette=0",
7740 "--enable-intrabc=0",
7741 "--enable-cfl-intra=0",
7742 "--enable-ref-frame-mvs=0",
7743 "--obu",
7744 "-o",
7745 "-",
7746 "-",
7747 ];
7748 let mut child = Command::new(aomenc_path())
7749 .args(&args)
7750 .stdin(Stdio::piped())
7751 .stdout(Stdio::piped())
7752 .stderr(Stdio::piped())
7753 .spawn()
7754 .expect("aomenc failed to start");
7755 child
7756 .stdin
7757 .take()
7758 .expect("aomenc stdin")
7759 .write_all(&y4m.stdout)
7760 .expect("writing y4m to aomenc");
7761 let out = child.wait_with_output().expect("aomenc failed to run");
7762 assert!(
7763 out.status.success(),
7764 "aomenc refused the fixture: {}",
7765 String::from_utf8_lossy(&out.stderr)
7766 );
7767 let stream = out.stdout;
7768 let frames = match decode_stream(&stream) {
7769 Err(e) => {
7770 let msg = e.to_string();
7771 assert!(
7772 msg.contains("unsupported"),
7773 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
7774 );
7775 assert!(
7776 !msg.contains("scaled reference"),
7777 "{NAME} refused on a scaled reference (seed {seed}) -- those refusals \
7778 are exactly what this round lifts: {msg}"
7779 );
7780 named_refusals += 1;
7781 eprintln!("seed {seed} refusal (other capability): {msg}");
7782 continue;
7783 }
7784 Ok(frames) => frames,
7785 };
7786 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
7787 assert_eq!(frames.len(), frame_count);
7788 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
7789 let mismatched = frames
7790 .iter()
7791 .zip(&ffmpeg_frames)
7792 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
7793 if mismatched {
7794 std::fs::write(&path, &stream).expect("writing pinned stream");
7795 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
7796 }
7797 }
7798 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
7799 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
7800 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
7801 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
7802 }
7803 matched += 1;
7804 }
7805 eprintln!(
7806 "{NAME}: {named_refusals} other-capability refusals, {matched}/{n_attempts} pixel-exact, \
7807 superres_hits={} predict_scaled_hits={} scaled_compound={} scaled_warp_fallback={} \
7808 scaled_obmc={} scaled_interintra={} scaled_block8={} scaled_warp_suppressed={} mixed_scale_compound={}",
7809 crate::superres::superres_hits(),
7810 crate::mc::predict_scaled_hits(),
7811 crate::decode::scaled_compound_hits(),
7812 crate::decode::scaled_warp_fallback_hits(),
7813 crate::decode::scaled_obmc_hits(),
7814 crate::decode::scaled_interintra_hits(),
7815 crate::decode::scaled_block8_hits(),
7816 crate::decode::scaled_warp_suppressed_hits(),
7817 crate::decode::mixed_scale_compound_hits(),
7818 );
7819 assert!(
7820 matched > 0,
7821 "{NAME}: every attempt refused on other capabilities; the gate proves nothing"
7822 );
7823 assert!(
7824 crate::mc::predict_scaled_hits() > 0,
7825 "{NAME}: matched but zero predict_scaled_hits -- no block took the scaled MC path"
7826 );
7827 // The 8x8 leaf is NOT asserted here: it stays refused (no recipe
7828 // produced an 8x8 inter leaf at all), so its counter is a
7829 // diagnostic only -- see this gate's own doc and decode.rs.
7830 // `scaled_warp_suppressed` IS asserted: it counts the blocks whose
7831 // WARPED_CAUSAL eligibility libaom drops because the reference is
7832 // scaled, i.e. the blocks that must read `obmc_cdf`. Zero of them
7833 // would mean this gate's `--enable-warped-motion=1` never reached a
7834 // warp-eligible block and proves nothing about r2's fix.
7835 assert!(
7836 crate::decode::scaled_warp_suppressed_hits() > 0,
7837 "{NAME}: {matched} matches but no block had its warp eligibility \
7838 suppressed by a scaled reference -- the warp arm proves nothing"
7839 );
7840 for (hits, what) in [
7841 (crate::decode::scaled_compound_hits(), "compound with a scaled reference"),
7842 (crate::decode::scaled_obmc_hits(), "OBMC with a scaled reference"),
7843 (crate::decode::scaled_interintra_hits(), "interintra with a scaled reference"),
7844 ] {
7845 assert!(hits > 0, "{NAME}: {matched} matches but zero blocks took {what}");
7846 }
7847 }
7848
7849 /// lane-defon r1: the 10-bit one-sided-compound hole --
7850 /// `--enable-onesided-comp` was spelled on in no 10-bit gate (5 of the 15
7851 /// pin it off, the rest default), so the UNIDIR_COMP_REFERENCE alphabet
7852 /// was proven at 8 bits only while both of his films are 10-bit 4:2:0.
7853 /// `--enable-diff-wtd-comp=1` is deliberately NOT spelled here (a flag a
7854 /// gate turns on without asserting it fired is coverage theatre, class
7855 /// gate-blind-to-feature): measured this round, the 10-bit `gradients`
7856 /// fixture decodes 8/8 pixel-exact with `diffwtd_hits == 0` -- smooth
7857 /// gradients never win
7858 /// a difference-weighted mask (the 8-bit gate needs `mandelbrot`'s hard
7859 /// diagonal edge, and [`ten_bit_tool_gate`] has no mandelbrot source), so
7860 /// hard-asserting it here would fail on encoder choice, not on a decoder
7861 /// defect.
7862 #[test]
7863 fn a_real_aomenc_10bit_stream_with_onesided_compound_decodes_pixel_exact() {
7864 const NAME: &str = "a_real_aomenc_10bit_stream_with_onesided_compound_decodes_pixel_exact";
7865 let _gate_lock = lock_gate_counters();
7866 if !have_ffmpeg() {
7867 eprintln!("SKIP {NAME}: no ffmpeg");
7868 return;
7869 }
7870 if !have_aomenc() {
7871 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7872 return;
7873 }
7874 ten_bit_tool_gate(
7875 NAME,
7876 64,
7877 64,
7878 24,
7879 &[
7880 "--enable-onesided-comp=1",
7881 "--enable-masked-comp=1",
7882 "--enable-dist-wtd-comp=0",
7883 "--cq-level=45",
7884 "--kf-max-dist=1000",
7885 "--auto-alt-ref=1",
7886 "--lag-in-frames=16",
7887 "--enable-fwd-kf=0",
7888 "--enable-order-hint=1",
7889 "--enable-global-motion=0",
7890 "--enable-warped-motion=1",
7891 "--enable-obmc=1",
7892 "--tune-content=default",
7893 "--enable-interintra-comp=0",
7894 "--enable-interintra-wedge=0",
7895 "--enable-smooth-interintra=0",
7896 "--enable-rect-partitions=0",
7897 "--enable-ab-partitions=0",
7898 "--enable-1to4-partitions=0",
7899 "--enable-filter-intra=0",
7900 "--enable-smooth-intra=0",
7901 "--enable-paeth-intra=0",
7902 "--enable-directional-intra=0",
7903 "--enable-angle-delta=0",
7904 "--enable-tx-size-search=0",
7905 "--enable-cdef=0",
7906 "--enable-restoration=0",
7907 "--max-partition-size=32",
7908 "--min-partition-size=32",
7909 "--enable-palette=0",
7910 "--enable-intrabc=0",
7911 "--enable-cfl-intra=0",
7912 "--enable-ref-frame-mvs=0",
7913 ],
7914 &[42, 43, 44, 45, 46, 47, 48, 49],
7915 &[("uni_comp_hits", crate::decode::uni_comp_hits as fn() -> usize)],
7916 );
7917 }
7918
7919 /// lane-defon r1: the 10-bit sibling of
7920 /// [`a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact`] --
7921 /// `--enable-interintra-wedge=1` was spelled on in no 10-bit gate (5 of
7922 /// the 15 pin it off), and his two films are 10-bit, so the 8-bit
7923 /// gate alone proves nothing about the streams that matter. Same tool
7924 /// set as the 8-bit recipe (`--enable-masked-comp=0` keeps inter blocks
7925 /// off the COMPOUND_WEDGE path, fixed 32x32 partitions), driven through
7926 /// [`ten_bit_tool_gate`], which hard-asserts `wii_hits` moved and
7927 /// compares every plane against ffmpeg's own 10-bit decode.
7928 #[test]
7929 fn a_real_aomenc_10bit_stream_with_interintra_wedge_decodes_pixel_exact() {
7930 const NAME: &str = "a_real_aomenc_10bit_stream_with_interintra_wedge_decodes_pixel_exact";
7931 let _gate_lock = lock_gate_counters();
7932 if !have_ffmpeg() {
7933 eprintln!("SKIP {NAME}: no ffmpeg");
7934 return;
7935 }
7936 if !have_aomenc() {
7937 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7938 return;
7939 }
7940 ten_bit_tool_gate(
7941 NAME,
7942 64,
7943 64,
7944 24,
7945 &[
7946 "--enable-interintra-wedge=1",
7947 "--enable-interintra-comp=1",
7948 "--enable-smooth-interintra=1",
7949 "--cq-level=45",
7950 "--kf-max-dist=1000",
7951 "--auto-alt-ref=1",
7952 "--lag-in-frames=16",
7953 "--enable-fwd-kf=0",
7954 "--enable-order-hint=1",
7955 "--enable-warped-motion=1",
7956 "--enable-obmc=1",
7957 "--tune-content=default",
7958 "--enable-masked-comp=0",
7959 "--enable-onesided-comp=0",
7960 "--enable-rect-partitions=0",
7961 "--enable-ab-partitions=0",
7962 "--enable-1to4-partitions=0",
7963 "--enable-filter-intra=0",
7964 "--enable-smooth-intra=0",
7965 "--enable-paeth-intra=0",
7966 "--enable-directional-intra=0",
7967 "--enable-angle-delta=0",
7968 "--enable-tx-size-search=0",
7969 "--enable-cdef=0",
7970 "--enable-restoration=0",
7971 "--max-partition-size=32",
7972 "--min-partition-size=32",
7973 "--enable-palette=0",
7974 "--enable-intrabc=0",
7975 "--enable-cfl-intra=0",
7976 "--enable-ref-frame-mvs=0",
7977 ],
7978 &[42, 43, 44, 45, 46, 47, 48, 49],
7979 &[
7980 ("wii_hits", crate::decode::wii_hits as fn() -> usize),
7981 ("interintra_hits", crate::decode::interintra_hits as fn() -> usize),
7982 ],
7983 );
7984 }
7985
7986 /// lane-wii r2: `--enable-interintra-wedge=1` streams must DECODE
7987 /// pixel-exact -- the wedge-interintra syntax (adapting `wedge_index`
7988 /// CDF symbol, fixed sign 0) and the wedge mask blend are ported over
7989 /// the checksum-verified codebook. `--enable-masked-comp=0` stays so
7990 /// the encoder cannot route inter blocks through the still-unported
7991 /// COMPOUND_WEDGE/DIFFWTD path. A refusal naming interintra/wedge
7992 /// fails the gate; refusals for OTHER named capabilities still skip
7993 /// that seed. Zero `wii_hits` on a run means the encoder never
7994 /// selected wedge-interintra -- soft-skipped (warned), not failed:
7995 /// that is encoder choice, not a decoder bug.
7996 #[test]
7997 fn a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact() {
7998 const NAME: &str = "a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact";
7999 let _gate_lock = lock_gate_counters();
8000 if !have_ffmpeg() {
8001 eprintln!("SKIP {NAME}: no ffmpeg");
8002 return;
8003 }
8004 if !have_aomenc() {
8005 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8006 return;
8007 }
8008 let (width, height, frame_count) = (64usize, 64usize, 24usize);
8009 let mut named_refusals = 0u32;
8010 let mut matched = 0u32;
8011 let n_attempts: u32 = std::env::var("EC_WEDGE_GATE_ATTEMPTS")
8012 .ok()
8013 .and_then(|s| s.parse().ok())
8014 .unwrap_or(40);
8015 for attempt in 0..n_attempts {
8016 let seed = 42 + attempt;
8017 let duration = frame_count as f64 / 25.0;
8018 let source = if attempt % 2 == 0 {
8019 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
8020 } else {
8021 // `end_pts` does NOT bound mandelbrot (it generated 300+
8022 // frames and hung the gate for an hour); `-t` below is the
8023 // real bound, matching every other mandelbrot gate recipe.
8024 format!("mandelbrot=size={width}x{height}:rate=25")
8025 };
8026 let duration_arg = format!("{duration}");
8027 let y4m = Command::new("ffmpeg")
8028 .args([
8029 "-v",
8030 "error",
8031 "-f",
8032 "lavfi",
8033 "-i",
8034 &source,
8035 "-pix_fmt",
8036 "yuv420p",
8037 "-t",
8038 &duration_arg,
8039 "-f",
8040 "yuv4mpegpipe",
8041 "-",
8042 ])
8043 .stdin(Stdio::null())
8044 .stdout(Stdio::piped())
8045 .stderr(Stdio::piped())
8046 .output()
8047 .expect("ffmpeg failed to run");
8048 assert!(
8049 y4m.status.success(),
8050 "ffmpeg fixture: {}",
8051 String::from_utf8_lossy(&y4m.stderr)
8052 );
8053 let args: Vec<&str> = vec![
8054 "--codec=av1",
8055 "--passes=1",
8056 "--end-usage=q",
8057 "--cq-level=45",
8058 "--cpu-used=0",
8059 "--kf-max-dist=1000",
8060 "--threads=1",
8061 "--row-mt=0",
8062 "--auto-alt-ref=1",
8063 "--lag-in-frames=16",
8064 "--enable-fwd-kf=0",
8065 "--enable-order-hint=1",
8066 "--enable-warped-motion=1",
8067 "--enable-obmc=1",
8068 "--tune-content=default",
8069 "--enable-masked-comp=0",
8070 "--enable-interintra-comp=1",
8071 "--enable-onesided-comp=0",
8072 "--enable-interintra-wedge=1",
8073 "--enable-smooth-interintra=1",
8074 "--enable-rect-partitions=0",
8075 "--enable-ab-partitions=0",
8076 "--enable-1to4-partitions=0",
8077 "--enable-filter-intra=0",
8078 "--enable-smooth-intra=0",
8079 "--enable-paeth-intra=0",
8080 "--enable-directional-intra=0",
8081 "--enable-angle-delta=0",
8082 "--enable-tx-size-search=0",
8083 "--enable-cdef=0",
8084 "--enable-restoration=0",
8085 "--max-partition-size=32",
8086 "--min-partition-size=32",
8087 "--enable-palette=0",
8088 "--enable-intrabc=0",
8089 "--enable-cfl-intra=0",
8090 "--enable-ref-frame-mvs=0",
8091 "--obu",
8092 "-o",
8093 "-",
8094 "-",
8095 ];
8096 let mut child = Command::new(aomenc_path())
8097 .args(&args)
8098 .stdin(Stdio::piped())
8099 .stdout(Stdio::piped())
8100 .stderr(Stdio::piped())
8101 .spawn()
8102 .expect("aomenc failed to start");
8103 child
8104 .stdin
8105 .take()
8106 .expect("aomenc stdin")
8107 .write_all(&y4m.stdout)
8108 .expect("writing y4m to aomenc");
8109 let out = child.wait_with_output().expect("aomenc failed to run");
8110 assert!(
8111 out.status.success(),
8112 "aomenc refused the fixture: {}",
8113 String::from_utf8_lossy(&out.stderr)
8114 );
8115 let stream = out.stdout;
8116 let frames = match decode_stream(&stream) {
8117 Err(e) => {
8118 let msg = e.to_string();
8119 assert!(
8120 msg.contains("unsupported"),
8121 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
8122 );
8123 // Verifier note (lane-wii r2): no refusal string containing
8124 // "wedge"/"interintra" exists in the decoder any more, so
8125 // string-forbidding asserts here would be vacuous (class
8126 // gate-blind-to-feature). The proof this gate carries is
8127 // pixel-exact decode plus the wii_hits count printed below.
8128 named_refusals += 1;
8129 eprintln!("seed {seed} refusal (non-wedge capability): {msg}");
8130 continue;
8131 }
8132 Ok(frames) => frames,
8133 };
8134 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
8135 assert_eq!(frames.len(), frame_count);
8136 let mismatched = frames
8137 .iter()
8138 .zip(&ffmpeg_frames)
8139 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
8140 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
8141 std::fs::write(&path, &stream).expect("writing pinned stream");
8142 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
8143 }
8144 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8145 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
8146 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
8147 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
8148 }
8149 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
8150 // stream again, comparing EVERY decode-order frame -- the hidden
8151 // (show_frame == 0) alt-ref frames the ffmpeg compare above
8152 // cannot see, because both sides of it emit shown frames only.
8153 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
8154 eprintln!(
8155 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
8156 {hidden_n} hidden, all pixel-exact vs the oracle"
8157 );
8158 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
8159 // libaom's temporal alt-ref filter absorbs this recipe's hidden
8160 // frames, so the compare above is vacuous -- re-encode the same
8161 // fixture with --arnr-maxframes=0 and compare THOSE.
8162 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
8163 eprintln!(
8164 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
8165 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
8166 );
8167 }
8168 matched += 1;
8169 }
8170 assert!(
8171 matched > 0,
8172 "{NAME}: every attempt refused on other capabilities; the gate never exercised wedge-interintra"
8173 );
8174 // Hardened from a soft-note (verifier: gate-blind-to-feature): the
8175 // recipe fired wedge-interintra on EVERY one of 6 hammer runs
8176 // (wii_hits 2-7), so a zero-hit run is a regression, not sampling.
8177 assert!(
8178 crate::decode::wii_hits() > 0,
8179 "{NAME}: {matched} pixel-exact matches but zero wedge-interintra blocks fired -- \
8180 the blend is unexercised (recipe fired 2-7 hits per run when landed)"
8181 );
8182 eprintln!(
8183 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, wii_hits={}",
8184 crate::decode::wii_hits()
8185 );
8186 }
8187
8188 /// The affine-capable encoder (`scripts/build-aom-affine-oracle.sh`),
8189 /// separate from the shared oracle because stock libaom's global-motion
8190 /// model search is pinned to ROTZOOM and can never emit AFFINE.
8191 fn affine_aomenc_path() -> std::path::PathBuf {
8192 if let Some(p) = std::env::var_os("EC_AV1_AFFINE_AOMENC") {
8193 return std::path::PathBuf::from(p);
8194 }
8195 let home = std::env::var_os("HOME").unwrap_or_default();
8196 std::path::PathBuf::from(home).join(".cache/aom-affine/build/aomenc")
8197 }
8198
8199 fn have_affine_aomenc() -> bool {
8200 let present = affine_aomenc_path().is_file();
8201 assert!(
8202 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
8203 "EC_AV1_REQUIRE_AOMENC is set but no affine-capable aomenc at {} -- run \
8204 scripts/build-aom-affine-oracle.sh",
8205 affine_aomenc_path().display()
8206 );
8207 present
8208 }
8209
8210 /// lane-gmaffine r1: an inter frame whose `global_motion_params` carries a
8211 /// SIX-parameter (`AFFINE`) model for a single-reference frame -- refused
8212 /// by name since lane-gm r4 because no aomenc recipe ever reached it.
8213 /// The reason it never did is in libaom's own encoder, not in the
8214 /// content: `av1/encoder/global_motion_facade.c:24` pins the model search
8215 /// to `ROTZOOM` at both ends, so *no* `--enable-global-motion=1` command
8216 /// line over any source can produce the case. The decoder must still
8217 /// handle it (the bitstream allows it, `read_global_motion_params` reads
8218 /// params 4/5 with their own subexp references, and ffmpeg decodes it),
8219 /// so this gate widens exactly that one encoder-side search range in a
8220 /// side build and encodes with it. Everything downstream is ordinary
8221 /// libaom and the pixel oracle is still ffmpeg.
8222 ///
8223 /// Content: rotation composed with a progressive *anisotropic* stretch --
8224 /// a similarity transform plus unequal axis scaling is precisely what a
8225 /// 4-parameter ROTZOOM model cannot express, which is what makes the
8226 /// encoder's RD pick AFFINE. `affine_gm_hits()` hard-asserts that real
8227 /// blocks were predicted through the 6-parameter warp, not merely that a
8228 /// header parsed one (class `gate-blind-to-feature`).
8229 #[test]
8230 fn a_real_affine_global_motion_stream_decodes_pixel_exact() {
8231 const NAME: &str = "a_real_affine_global_motion_stream_decodes_pixel_exact";
8232 let _gate_lock = lock_gate_counters();
8233 if !have_ffmpeg() {
8234 eprintln!("SKIP {NAME}: no ffmpeg");
8235 return;
8236 }
8237 if !have_affine_aomenc() {
8238 eprintln!(
8239 "SKIP {NAME}: no affine-capable aomenc at {} (scripts/build-aom-affine-oracle.sh)",
8240 affine_aomenc_path().display()
8241 );
8242 return;
8243 }
8244 let (width, height, frame_count) = (64usize, 64usize, 24usize);
8245 let duration = frame_count as f64 / 25.0;
8246 // Both depths: his own AV1 library is yuv420p10le throughout, and a
8247 // 10-bit AFFINE warp runs the same `warp_affine` over wider samples.
8248 for depth in [8u32, 10u32] {
8249 // `-t` is the real bound on mandelbrot (it ignores `end_pts` and
8250 // has hung a gate for an hour); the 96x96 source is rotated and
8251 // then stretched horizontally only, and cropped back to 64x64.
8252 let source = format!(
8253 "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\
8254 scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}"
8255 );
8256 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
8257 let mut ff_args: Vec<&str> =
8258 vec!["-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt];
8259 // y4m has no official 10-bit tag, same as the 10-bit gate above.
8260 if depth == 10 {
8261 ff_args.extend(["-strict", "-1"]);
8262 }
8263 let duration_arg = duration.to_string();
8264 ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]);
8265 let y4m = Command::new("ffmpeg")
8266 .args(&ff_args)
8267 .stdin(Stdio::null())
8268 .stdout(Stdio::piped())
8269 .stderr(Stdio::piped())
8270 .output()
8271 .expect("ffmpeg failed to run");
8272 assert!(
8273 y4m.status.success(),
8274 "ffmpeg fixture: {}",
8275 String::from_utf8_lossy(&y4m.stderr)
8276 );
8277 let bit_depth = format!("--bit-depth={depth}");
8278 let input_bit_depth = format!("--input-bit-depth={depth}");
8279 let args: Vec<&str> = vec![
8280 "--codec=av1",
8281 "--passes=1",
8282 "--end-usage=q",
8283 "--cq-level=45",
8284 "--cpu-used=0",
8285 "--kf-max-dist=1000",
8286 "--threads=1",
8287 "--row-mt=0",
8288 "--auto-alt-ref=0",
8289 "--lag-in-frames=0",
8290 "--enable-fwd-kf=0",
8291 "--enable-order-hint=1",
8292 "--enable-global-motion=1",
8293 "--enable-warped-motion=0",
8294 "--enable-obmc=0",
8295 "--tune-content=default",
8296 "--enable-masked-comp=0",
8297 "--enable-interintra-comp=0",
8298 "--enable-onesided-comp=0",
8299 "--enable-rect-partitions=0",
8300 "--enable-ab-partitions=0",
8301 "--enable-1to4-partitions=0",
8302 "--enable-filter-intra=0",
8303 "--enable-smooth-intra=0",
8304 "--enable-paeth-intra=0",
8305 "--enable-directional-intra=0",
8306 "--enable-angle-delta=0",
8307 "--enable-tx-size-search=0",
8308 "--enable-cdef=0",
8309 "--enable-restoration=0",
8310 "--max-partition-size=32",
8311 "--min-partition-size=32",
8312 "--enable-palette=0",
8313 "--enable-intrabc=0",
8314 "--enable-cfl-intra=0",
8315 "--enable-ref-frame-mvs=0",
8316 &bit_depth,
8317 &input_bit_depth,
8318 "--obu",
8319 "-o",
8320 "-",
8321 "-",
8322 ];
8323 let mut child = Command::new(affine_aomenc_path())
8324 .args(&args)
8325 .stdin(Stdio::piped())
8326 .stdout(Stdio::piped())
8327 .stderr(Stdio::piped())
8328 .spawn()
8329 .expect("affine aomenc failed to start");
8330 child
8331 .stdin
8332 .take()
8333 .expect("aomenc stdin")
8334 .write_all(&y4m.stdout)
8335 .expect("writing y4m to aomenc");
8336 let out = child.wait_with_output().expect("aomenc failed to run");
8337 assert!(
8338 out.status.success(),
8339 "aomenc refused the fixture: {}",
8340 String::from_utf8_lossy(&out.stderr)
8341 );
8342 let stream = out.stdout;
8343 let before = crate::decode::affine_gm_hits();
8344 let frames =
8345 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} ({depth}-bit): {e}"));
8346 let ffmpeg_frames = if depth == 10 {
8347 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
8348 } else {
8349 ffmpeg_decode_sequence(&stream, width, height, frame_count)
8350 };
8351 assert_eq!(frames.len(), frame_count);
8352 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8353 assert_eq!(got.y, want.y, "{NAME} {depth}-bit frame {i} luma vs ffmpeg");
8354 assert_eq!(got.u, want.u, "{NAME} {depth}-bit frame {i} U vs ffmpeg");
8355 assert_eq!(got.v, want.v, "{NAME} {depth}-bit frame {i} V vs ffmpeg");
8356 }
8357 let hits = crate::decode::affine_gm_hits() - before;
8358 assert!(
8359 hits > 0,
8360 "{NAME} ({depth}-bit): decoded pixel-exact but no block was predicted through a \
8361 6-parameter global-motion warp -- the AFFINE path is unexercised"
8362 );
8363 eprintln!("{NAME}: {depth}-bit, {frame_count} frames pixel-exact, affine_gm_hits={hits}");
8364 }
8365 }
8366
8367 /// lane-gmaffine r1: the two 8x8-LEAF motion gates. `decode_inter_block8`
8368 /// is a separate function from [`decode_inter_block`], and until this
8369 /// round it refused both `GLOBALMV` ("GLOBALMV (round 3)") and
8370 /// `WARPED_CAUSAL` at that size while the 16x16+ leaf had implemented
8371 /// both for rounds. The reason no earlier gate caught it: the existing
8372 /// 8x8 OBMC gate clamps `--max-partition-size=32` and aomenc's RD then
8373 /// never splits down to a clean 8x8 leaf (that gate has never fired in
8374 /// 80 attempts). `--min-partition-size=8 --max-partition-size=8` removes
8375 /// the choice entirely -- every inter leaf in the stream IS an 8x8 one,
8376 /// so the leaf path is exercised by construction rather than by luck.
8377 ///
8378 /// Content is the affine gate's rotating/zooming mandelbrot (global
8379 /// motion the encoder can actually model), and the hit counters
8380 /// (`globalmv_hits_8` / `warp_hits_8`) are 8x8-leaf-specific: a
8381 /// 16x16-leaf GLOBALMV or warp cannot satisfy them.
8382 fn run_8x8_leaf_motion_gate(
8383 name: &str,
8384 global_motion: bool,
8385 counter: fn() -> usize,
8386 ) {
8387 // 72x64: `decode_inter_block8` is reached ONLY through the
8388 // true-edge-straddling 16x16 path (an interior 16x16
8389 // PARTITION_SPLIT is still refused by name), so the frame is 8
8390 // luma columns wider than its last whole superblock -- every 16x16
8391 // block in that right-hand strip is cut on ONE axis and decodes as
8392 // four 8x8 leaves by construction. `--min-partition-size=16` keeps
8393 // the interior out of the still-refused sub-16x16 case.
8394 let (width, height, frame_count) = (64usize, 64usize, 24usize);
8395 let duration = frame_count as f64 / 25.0;
8396 // The encoder's own RD still chooses WHICH 8x8 leaf codes GLOBALMV /
8397 // WARPED_CAUSAL, and at some quantisers it picks a rect partition at
8398 // 16x16 (still refused) or a non-LAST reference (still refused at the
8399 // 8x8 leaf) before ever reaching one. So sweep a few quantisers and
8400 // require at least one attempt, at each depth, that BOTH decodes
8401 // pixel-exact AND fires the counter -- a refusing attempt is recorded,
8402 // never a pass (class `gate-skips-on-its-own-failure`).
8403 let mut fired_any = [false; 2];
8404 let mut notes: Vec<String> = Vec::new();
8405 for (di, depth) in [8u32, 10u32].into_iter().enumerate() {
8406 for cq in [32u32, 45, 55] {
8407 let cq_arg = format!("--cq-level={cq}");
8408 let max_part_arg = format!(
8409 "--max-partition-size={}",
8410 std::env::var("EC_8X8_MAXPART").unwrap_or_else(|_| "8".into())
8411 );
8412 let source = format!(
8413 "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\
8414 scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}"
8415 );
8416 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
8417 let mut ff_args: Vec<&str> =
8418 vec!["-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt];
8419 if depth == 10 {
8420 ff_args.extend(["-strict", "-1"]);
8421 }
8422 let duration_arg = duration.to_string();
8423 ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]);
8424 let y4m = Command::new("ffmpeg")
8425 .args(&ff_args)
8426 .stdin(Stdio::null())
8427 .stdout(Stdio::piped())
8428 .stderr(Stdio::piped())
8429 .output()
8430 .expect("ffmpeg failed to run");
8431 assert!(
8432 y4m.status.success(),
8433 "ffmpeg fixture: {}",
8434 String::from_utf8_lossy(&y4m.stderr)
8435 );
8436 let bit_depth = format!("--bit-depth={depth}");
8437 let input_bit_depth = format!("--input-bit-depth={depth}");
8438 let gm_arg = format!("--enable-global-motion={}", u8::from(global_motion));
8439 let warp_arg = format!("--enable-warped-motion={}", u8::from(!global_motion));
8440 let args: Vec<&str> = vec![
8441 "--codec=av1",
8442 "--passes=1",
8443 "--end-usage=q",
8444 &cq_arg,
8445 "--cpu-used=0",
8446 "--kf-max-dist=1000",
8447 "--threads=1",
8448 "--row-mt=0",
8449 "--auto-alt-ref=0",
8450 "--lag-in-frames=0",
8451 "--enable-fwd-kf=0",
8452 "--enable-order-hint=1",
8453 &gm_arg,
8454 &warp_arg,
8455 "--enable-obmc=0",
8456 "--tune-content=default",
8457 "--enable-masked-comp=0",
8458 "--enable-interintra-comp=0",
8459 "--enable-onesided-comp=0",
8460 "--enable-rect-partitions=0",
8461 "--enable-ab-partitions=0",
8462 "--enable-1to4-partitions=0",
8463 "--enable-filter-intra=0",
8464 "--enable-smooth-intra=0",
8465 "--enable-paeth-intra=0",
8466 "--enable-directional-intra=0",
8467 "--enable-angle-delta=0",
8468 "--enable-tx-size-search=0",
8469 "--enable-cdef=0",
8470 "--enable-restoration=0",
8471 &max_part_arg,
8472 "--min-partition-size=8",
8473 "--enable-palette=0",
8474 "--enable-intrabc=0",
8475 "--enable-cfl-intra=0",
8476 "--enable-ref-frame-mvs=0",
8477 &bit_depth,
8478 &input_bit_depth,
8479 "--obu",
8480 "-o",
8481 "-",
8482 "-",
8483 ];
8484 let mut child = Command::new(aomenc_path())
8485 .args(&args)
8486 .stdin(Stdio::piped())
8487 .stdout(Stdio::piped())
8488 .stderr(Stdio::piped())
8489 .spawn()
8490 .expect("aomenc failed to start");
8491 child
8492 .stdin
8493 .take()
8494 .expect("aomenc stdin")
8495 .write_all(&y4m.stdout)
8496 .expect("writing y4m to aomenc");
8497 let out = child.wait_with_output().expect("aomenc failed to run");
8498 assert!(
8499 out.status.success(),
8500 "aomenc refused the fixture: {}",
8501 String::from_utf8_lossy(&out.stderr)
8502 );
8503 let stream = out.stdout;
8504 let before = counter();
8505 let frames = match decode_stream(&stream) {
8506 Ok(f) => f,
8507 Err(e) => {
8508 let msg = e.to_string();
8509 assert!(
8510 msg.contains("unsupported"),
8511 "{name} ({depth}-bit, cq {cq}) failed outright: {msg}"
8512 );
8513 notes.push(format!("{depth}-bit cq {cq}: {msg}"));
8514 continue;
8515 }
8516 };
8517 let ffmpeg_frames = if depth == 10 {
8518 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
8519 } else {
8520 ffmpeg_decode_sequence(&stream, width, height, frame_count)
8521 };
8522 assert_eq!(frames.len(), frame_count);
8523 let hits = counter() - before;
8524 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8525 assert_eq!(got.y, want.y, "{name} {depth}-bit frame {i} luma vs ffmpeg");
8526 assert_eq!(got.u, want.u, "{name} {depth}-bit frame {i} U vs ffmpeg");
8527 assert_eq!(got.v, want.v, "{name} {depth}-bit frame {i} V vs ffmpeg");
8528 }
8529 if hits == 0 {
8530 notes.push(format!(
8531 "{depth}-bit cq {cq}: {frame_count} frames pixel-exact but 0 8x8-leaf hits"
8532 ));
8533 continue;
8534 }
8535 fired_any[di] = true;
8536 eprintln!(
8537 "{name}: {depth}-bit cq {cq}, {frame_count} frames pixel-exact, 8x8 hits={hits}"
8538 );
8539 }
8540 }
8541 assert!(
8542 fired_any[0] && fired_any[1],
8543 "{name}: no attempt both decoded pixel-exact and fired the 8x8 leaf \
8544 (8-bit fired {}, 10-bit fired {}):\n{}",
8545 fired_any[0], fired_any[1], notes.join("\n")
8546 );
8547 }
8548
8549 /// lane-gmaffine r1 item (3): `GLOBALMV` at an 8x8 leaf, ROTZOOM global
8550 /// motion, warp built from the frame's own model.
8551 #[test]
8552 fn a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact() {
8553 const NAME: &str = "a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact";
8554 let _gate_lock = lock_gate_counters();
8555 if !have_ffmpeg() {
8556 eprintln!("SKIP {NAME}: no ffmpeg");
8557 return;
8558 }
8559 if !have_aomenc() {
8560 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8561 return;
8562 }
8563 run_8x8_leaf_motion_gate(NAME, true, crate::decode::globalmv_hits_8);
8564 }
8565
8566 /// lane-gmaffine r1 item (2): `WARPED_CAUSAL` at an 8x8 leaf --
8567 /// findSamples + `av1_find_projection` + the warp filter at BLOCK_8X8.
8568 #[test]
8569 fn a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact() {
8570 const NAME: &str = "a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact";
8571 let _gate_lock = lock_gate_counters();
8572 if !have_ffmpeg() {
8573 eprintln!("SKIP {NAME}: no ffmpeg");
8574 return;
8575 }
8576 if !have_aomenc() {
8577 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8578 return;
8579 }
8580 run_8x8_leaf_motion_gate(NAME, false, crate::decode::warp_hits_8);
8581 }
8582
8583 /// lane-rect16 r1/r2: a plain default-settings aomenc run over lavfi
8584 /// `mandelbrot` (`--cpu-used=4 --end-usage=q --cq-level=32`, no
8585 /// `--enable-*` flags) used to refuse frame 0 outright with "a partition
8586 /// below 16x16 other than a clean split". r1 root-caused the FIRST hit to
8587 /// a `PARTITION_VERT_B` `partition_w16` symbol at mi=(3,2) and wired it
8588 /// (left 8x16 real `decode_block_rect` strip + two stacked 8x8
8589 /// `decode_leaf8` leaves on the right). r2 re-measured after that fix
8590 /// (`decision-before-quantiser`-shaped: don't trust a stale premise) and
8591 /// found this stream's REAL first-hit blocker in z-order is earlier, at
8592 /// mi=(0,7): a plain `PARTITION_HORZ`. That arm is now wired too
8593 /// (`decode_leaf_rect`, sibling to `decode_leaf8` but real-mi-addressed
8594 /// for a non-square strip) -- `horz_vert_intra_hits` proves it fires.
8595 /// This exact stream's own HORZ block at mi=(0,7) is *coded* (real
8596 /// coefficients), which is NOT ported (same ceiling as VERT_B's own
8597 /// non-skip refusal -- no rectangular-transform coefficient tables at
8598 /// this size), so decode still stops there and `vert_b_intra_hits`
8599 /// never gets a chance to increment on this particular stream. This gate
8600 /// proves the HORZ arm fires and the OLD (now-false) two-clause refusal
8601 /// never reappears, not a pixel-exact decode of this stream.
8602 #[test]
8603 fn a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm() {
8604 const NAME: &str = "a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm";
8605 let _gate_lock = lock_gate_counters();
8606 if !have_ffmpeg() {
8607 eprintln!("SKIP {NAME}: no ffmpeg");
8608 return;
8609 }
8610 if !have_aomenc() {
8611 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8612 return;
8613 }
8614 let (width, height) = (192usize, 128usize);
8615 let y4m = Command::new("ffmpeg")
8616 .args([
8617 "-v",
8618 "error",
8619 "-f",
8620 "lavfi",
8621 "-i",
8622 &format!("mandelbrot=size={width}x{height}"),
8623 "-pix_fmt",
8624 "yuv420p",
8625 "-t",
8626 "1",
8627 "-f",
8628 "yuv4mpegpipe",
8629 "-",
8630 ])
8631 .stdin(Stdio::null())
8632 .stdout(Stdio::piped())
8633 .stderr(Stdio::piped())
8634 .output()
8635 .expect("ffmpeg failed to run");
8636 assert!(
8637 y4m.status.success(),
8638 "ffmpeg fixture: {}",
8639 String::from_utf8_lossy(&y4m.stderr)
8640 );
8641 let mut child = Command::new(aomenc_path())
8642 .args([
8643 "--threads=1",
8644 "--row-mt=0",
8645 "--sb-size=64",
8646 "--cpu-used=4",
8647 "--end-usage=q",
8648 "--cq-level=32",
8649 "--passes=1",
8650 "--obu",
8651 "-o",
8652 "-",
8653 "-",
8654 ])
8655 .stdin(Stdio::piped())
8656 .stdout(Stdio::piped())
8657 .stderr(Stdio::piped())
8658 .spawn()
8659 .expect("aomenc failed to start");
8660 child
8661 .stdin
8662 .take()
8663 .expect("aomenc stdin")
8664 .write_all(&y4m.stdout)
8665 .expect("writing y4m to aomenc");
8666 let out = child.wait_with_output().expect("aomenc failed to run");
8667 assert!(
8668 out.status.success(),
8669 "aomenc refused the fixture: {}",
8670 String::from_utf8_lossy(&out.stderr)
8671 );
8672 let stream = out.stdout;
8673 // lane-rect16 r2: the recipe above was missing `--passes=1` --
8674 // without it aomenc silently ran 2-pass and wrote nothing to stdout
8675 // on pass 1 (still exit 0), so this gate always decoded an EMPTY
8676 // stream and never actually exercised the arm it claims to gate.
8677 assert!(
8678 !stream.is_empty(),
8679 "{NAME}: aomenc wrote an empty stream (missing --passes=1?)"
8680 );
8681 let result = decode_stream(&stream);
8682 // The now-lifted false claim ("codes only the square arms below
8683 // 16x16") must never appear again.
8684 if let Err(e) = &result {
8685 let msg = e.to_string();
8686 assert!(
8687 !msg.contains("this decoder codes only the square arms below 16x16"),
8688 "{NAME}: the OLD (disproved) refusal reappeared: {msg}"
8689 );
8690 }
8691 assert!(
8692 crate::decode::horz_vert_intra_hits() > 0,
8693 "{NAME}: the plain PARTITION_HORZ/VERT arm never fired on this stream (regression -- \
8694 it fired deterministically at mi=(0,7) when this gate was written)"
8695 );
8696 eprintln!(
8697 "{NAME}: horz_vert_intra_hits={}, vert_b_intra_hits={}, decode result: {:?}",
8698 crate::decode::horz_vert_intra_hits(),
8699 crate::decode::vert_b_intra_hits(),
8700 result.as_ref().map(|f| f.len()).map_err(|e| e.to_string())
8701 );
8702 }
8703 /// lane-rectx r3: a real `aomenc` stream whose 16x16-level
8704 /// `PARTITION_HORZ`/`PARTITION_VERT` strips are CODED (non-skip), i.e.
8705 /// carry genuine `TX_16X8`/`TX_8X16` luma coefficients and their
8706 /// `TX_8X4`/`TX_4X8` chroma halves through [`decode_leaf_rect`]'s
8707 /// lane-rectx arm -- the refusal "a coded (non-skip) HORZ/VERT rect strip
8708 /// below 16x16" this round lifts. `--min-partition-size=8
8709 /// --max-partition-size=32 --enable-rect-partitions=1` is what makes
8710 /// aomenc reach for a 16x8 leaf at all; mandelbrot at `cq-level=24` is
8711 /// what makes those leaves non-skip (a gradient fixture codes them all
8712 /// away). `--reduced-tx-type-set=1` pins the five-symbol
8713 /// `EXT_TX_SET_DTT4_IDTX` alphabet: without it aomenc also writes
8714 /// `V_DCT`/`H_DCT`, whose 1D tx classes [`read_coeffs_rect`] still
8715 /// refuses by name (see the r3 report's open residue), so a `=0` run
8716 /// would prove nothing about the 2D path it does support.
8717 ///
8718 /// r2 shipped this path unproven; it was wrong. `TxbSet::LumaRect16x8`
8719 /// read its `tx_type` symbol from the 16x16 row, but libaom's
8720 /// `read_tx_type` indexes `intra_ext_tx_cdf[eset][txsize_sqr_map[tx_size]]`
8721 /// and `txsize_sqr_map[TX_16X8] == TX_8X8` -- a five-symbol CDF where a
8722 /// seven-symbol one belonged, desyncing at the FIRST coded rect leaf
8723 /// (whole frame wrong from pixel (0,0)).
8724 #[test]
8725 fn a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact() {
8726 const NAME: &str =
8727 "a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact";
8728 let _gate_lock = lock_gate_counters();
8729 if !have_ffmpeg() {
8730 eprintln!("SKIP {NAME}: no ffmpeg");
8731 return;
8732 }
8733 if !have_aomenc() {
8734 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8735 return;
8736 }
8737 let (width, height) = (64usize, 64usize);
8738 let y4m = Command::new("ffmpeg")
8739 .args([
8740 "-v",
8741 "error",
8742 "-f",
8743 "lavfi",
8744 "-i",
8745 &format!("mandelbrot=size={width}x{height}:start_x=-0.6"),
8746 "-pix_fmt",
8747 "yuv420p",
8748 "-t",
8749 "1",
8750 "-vframes",
8751 "1",
8752 "-f",
8753 "yuv4mpegpipe",
8754 "-",
8755 ])
8756 .stdin(Stdio::null())
8757 .stdout(Stdio::piped())
8758 .stderr(Stdio::piped())
8759 .output()
8760 .expect("ffmpeg failed to run");
8761 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
8762 let encode = || {
8763 let mut child = Command::new(aomenc_path())
8764 .args([
8765 "--codec=av1",
8766 "--passes=1",
8767 "--end-usage=q",
8768 "--cq-level=16",
8769 "--cpu-used=4",
8770 "--threads=1",
8771 "--row-mt=0",
8772 "--sb-size=64",
8773 "--kf-max-dist=0",
8774 "--enable-rect-partitions=1",
8775 "--enable-ab-partitions=0",
8776 "--enable-1to4-partitions=0",
8777 "--enable-tx-size-search=0",
8778 // Filter intra on a strip is a separate, still-refused
8779 // predictor (`filter intra on a HORZ/VERT strip`); this
8780 // gate is about the rect RESIDUAL path, so it is off here
8781 // and covered by the square filter-intra gate instead.
8782 "--enable-filter-intra=0",
8783 "--reduced-tx-type-set=1",
8784 "--min-partition-size=8",
8785 "--max-partition-size=32",
8786 "--obu",
8787 "-o",
8788 "-",
8789 "-",
8790 ])
8791 .stdin(Stdio::piped())
8792 .stdout(Stdio::piped())
8793 .stderr(Stdio::piped())
8794 .spawn()
8795 .expect("aomenc failed to start");
8796 child
8797 .stdin
8798 .take()
8799 .expect("aomenc stdin")
8800 .write_all(&y4m.stdout)
8801 .expect("writing y4m to aomenc");
8802 let out = child.wait_with_output().expect("aomenc failed to run");
8803 assert!(
8804 out.status.success(),
8805 "aomenc refused the fixture: {}",
8806 String::from_utf8_lossy(&out.stderr)
8807 );
8808 out.stdout
8809 };
8810 // The fixture rule: an encoder output is only a pin if it reproduces.
8811 let stream = encode();
8812 assert_eq!(stream, encode(), "{NAME}: aomenc output is not reproducible for this recipe");
8813 let before = crate::decode::rect_leaf_coeff_hits();
8814 let frames = decode_stream(&stream)
8815 .unwrap_or_else(|e| panic!("{NAME}: decode failed, not a pixel mismatch: {e}"));
8816 let fired = crate::decode::rect_leaf_coeff_hits() - before;
8817 assert!(
8818 fired > 0,
8819 "{NAME}: the stream decoded but no coded (non-skip) rect leaf fired -- \
8820 the gate proves nothing"
8821 );
8822 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
8823 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame");
8824 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
8825 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8826 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg ({fired} coded rect leaves)");
8827 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
8828 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
8829 }
8830 eprintln!("{NAME}: pixel-exact, rect_leaf_coeff_hits={fired}");
8831 }
8832
8833 /// lane-rectx r5: the same 16x8/8x16 rect leaves, but this time proving
8834 /// what a LATER, non-strip block reads from them. `decode_leaf_rect` took
8835 /// the mi-exact intra mode map in r4; `decode_block`/`decode_block_rect`/
8836 /// `decode_block_rect64` did not, so a 32x16 strip whose left neighbour was
8837 /// a 16x8 leaf still read the coarse per-16x16 `left_mode` slot -- which no
8838 /// sub-16x16 block ever writes -- and picked a DIFFERENT `kf_y_mode` CDF row
8839 /// for the same decoded mode value. The stream stayed in sync through mode
8840 /// info (`EC_TRACE_MODE_STEP` ranges match up to that symbol) and then
8841 /// diverged inside the block's own coefficients: the whole bottom-right
8842 /// 32x32 quadrant of this fixture decoded wrong (1650 bytes) while the
8843 /// three earlier quadrants were exact -- wrong pixels returned as success.
8844 /// `mode_mi_override_hits` counts exactly the reads where the mi-exact
8845 /// neighbour disagrees with the coarse slot, so a regression that drops the
8846 /// override again fails the counter as well as the pixels.
8847 #[test]
8848 fn a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact() {
8849 const NAME: &str =
8850 "a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact";
8851 let _gate_lock = lock_gate_counters();
8852 if !have_ffmpeg() {
8853 eprintln!("SKIP {NAME}: no ffmpeg");
8854 return;
8855 }
8856 if !have_aomenc() {
8857 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8858 return;
8859 }
8860 let (width, height) = (64usize, 64usize);
8861 let y4m = Command::new("ffmpeg")
8862 .args([
8863 "-v", "error", "-f", "lavfi", "-i",
8864 &format!("rgbtestsrc=size={width}x{height}"),
8865 "-pix_fmt", "yuv420p", "-t", "1", "-vframes", "1", "-f", "yuv4mpegpipe", "-",
8866 ])
8867 .stdin(Stdio::null())
8868 .stdout(Stdio::piped())
8869 .stderr(Stdio::piped())
8870 .output()
8871 .expect("ffmpeg failed to run");
8872 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
8873 // Two swept cells of the r4 sweep that decoded to completion with
8874 // WRONG pixels (1714 and 1650 bytes): `--reduced-tx-type-set` and
8875 // `--enable-filter-intra` are the two axes that move which block sizes
8876 // aomenc reaches for here; both arms are pinned.
8877 let mut total_overrides = 0usize;
8878 for (rtx, filter_intra) in [("1", "0"), ("0", "1")] {
8879 let encode = || {
8880 let mut child = Command::new(aomenc_path())
8881 .args([
8882 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32",
8883 "--cpu-used=4", "--threads=1", "--row-mt=0", "--sb-size=64",
8884 "--kf-max-dist=0", "--enable-rect-partitions=1",
8885 "--enable-ab-partitions=0", "--enable-1to4-partitions=0",
8886 "--enable-tx-size-search=0", "--enable-cdef=0",
8887 "--enable-restoration=0",
8888 &format!("--enable-filter-intra={filter_intra}"),
8889 &format!("--reduced-tx-type-set={rtx}"),
8890 "--min-partition-size=8", "--max-partition-size=32",
8891 "--obu", "-o", "-", "-",
8892 ])
8893 .stdin(Stdio::piped())
8894 .stdout(Stdio::piped())
8895 .stderr(Stdio::piped())
8896 .spawn()
8897 .expect("aomenc failed to start");
8898 child
8899 .stdin
8900 .take()
8901 .expect("aomenc stdin")
8902 .write_all(&y4m.stdout)
8903 .expect("writing y4m to aomenc");
8904 let out = child.wait_with_output().expect("aomenc failed to run");
8905 assert!(
8906 out.status.success(),
8907 "aomenc refused the fixture: {}",
8908 String::from_utf8_lossy(&out.stderr)
8909 );
8910 out.stdout
8911 };
8912 let stream = encode();
8913 assert_eq!(
8914 stream,
8915 encode(),
8916 "{NAME}: aomenc output is not reproducible (rtx={rtx} filter_intra={filter_intra})"
8917 );
8918 let before = crate::decode::mode_mi_override_hits();
8919 let frames = decode_stream(&stream).unwrap_or_else(|e| {
8920 panic!("{NAME}: decode failed (rtx={rtx} filter_intra={filter_intra}): {e}")
8921 });
8922 // Counted only on an attempt that actually decoded AND is compared
8923 // below -- a refusal never contributes to the firing assert.
8924 let overrides = crate::decode::mode_mi_override_hits() - before;
8925 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
8926 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame");
8927 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
8928 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8929 assert_eq!(
8930 got.y, want.y,
8931 "{NAME} frame {i} luma vs ffmpeg (rtx={rtx} filter_intra={filter_intra}, \
8932 {overrides} mi-exact mode overrides)"
8933 );
8934 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (rtx={rtx})");
8935 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (rtx={rtx})");
8936 }
8937 total_overrides += overrides;
8938 }
8939 assert!(
8940 total_overrides > 0,
8941 "{NAME}: no non-strip block ever read a mi-exact neighbour that disagreed with its \
8942 coarse slot -- the gate proves nothing"
8943 );
8944 eprintln!("{NAME}: pixel-exact, mode_mi_override_hits={total_overrides}");
8945 }
8946
8947 /// lane-cfl r1: the chroma intra-edge FILTER TYPE is the neighbour's
8948 /// `uv_mode` (libaom `get_filt_type`, reconintra.c: `chroma_above_mbmi`/
8949 /// `chroma_left_mbmi` -> `is_smooth` on `uv_mode`), and two whole decode
8950 /// paths passed a hardcoded `false` for it -- `decode_leaf_8x8` (every
8951 /// 8x8 leaf of a SPLIT) and `decode_leaf_rect` (every rect strip below
8952 /// 16x16), on a stale "chroma stays false (exact) until a smooth/paeth
8953 /// uv_mode can reach decode at all" comment. On top of that the coarse
8954 /// `above_uv_mode`/`left_uv_mode` cells are 16px-granular and their
8955 /// `for cell in 0..w / SUB` write runs ZERO times for any block below
8956 /// 16x16, so even the paths that DID read them saw whatever a
8957 /// 16x16-or-larger block had left there (class: context read from one
8958 /// cell / neighbour map at the wrong granularity). Result on this
8959 /// recipe: luma byte-exact, entropy ladder identical, and 40 U + 86 V
8960 /// chroma bytes wrong -- every one of them downstream of one 4x4 chroma
8961 /// block at mi(8,12) whose D135 + `angle_delta_uv=-3` left edge was
8962 /// filtered at the wrong strength (`ft=0` where the instrumented aomdec
8963 /// prints `ft=1`, left edge `95,59,30,28` vs `90,61,37,29`).
8964 ///
8965 /// Both arms hard-assert per-attempt counters for the two chroma block
8966 /// shapes involved (`UV_CFL_PRED` blocks, nonzero `angle_delta_uv`
8967 /// blocks) plus the mi-exact UV-neighbour override, and are counted only
8968 /// on an attempt that decoded AND is pixel-compared.
8969 #[test]
8970 fn a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact()
8971 {
8972 const NAME: &str = "a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact";
8973 let _gate_lock = lock_gate_counters();
8974 if !have_ffmpeg() {
8975 eprintln!("SKIP {NAME}: no ffmpeg");
8976 return;
8977 }
8978 if !have_aomenc() {
8979 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8980 return;
8981 }
8982 let mut compared = 0usize;
8983 let (width, height) = (64usize, 64usize);
8984 // 8-bit arm = the r5 residue cell ("mandfi161"); 10-bit arm = its
8985 // twin through the same recipe at `--bit-depth=10`.
8986 for depth in [8usize, 10] {
8987 let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
8988 let y4m = Command::new("ffmpeg")
8989 .args([
8990 "-v", "error", "-f", "lavfi", "-i",
8991 &format!("mandelbrot=size={width}x{height}:start_x=-0.6"),
8992 "-pix_fmt", pix, "-strict", "-1", "-t", "1", "-vframes", "1",
8993 "-f", "yuv4mpegpipe", "-",
8994 ])
8995 .stdin(Stdio::null())
8996 .stdout(Stdio::piped())
8997 .stderr(Stdio::piped())
8998 .output()
8999 .expect("ffmpeg failed to run");
9000 assert!(
9001 y4m.status.success(),
9002 "{NAME}: ffmpeg fixture (depth={depth}): {}",
9003 String::from_utf8_lossy(&y4m.stderr)
9004 );
9005 let encode = || {
9006 let mut child = Command::new(aomenc_path())
9007 .args([
9008 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=16",
9009 "--cpu-used=4", "--threads=1", "--row-mt=0", "--sb-size=64",
9010 "--kf-max-dist=0", "--enable-rect-partitions=1",
9011 "--enable-ab-partitions=0", "--enable-1to4-partitions=0",
9012 "--enable-tx-size-search=0", "--enable-filter-intra=1",
9013 "--reduced-tx-type-set=1", "--min-partition-size=8",
9014 "--max-partition-size=32",
9015 &format!("--input-bit-depth={depth}"),
9016 &format!("--bit-depth={depth}"),
9017 "--obu", "-o", "-", "-",
9018 ])
9019 .stdin(Stdio::piped())
9020 .stdout(Stdio::piped())
9021 .stderr(Stdio::piped())
9022 .spawn()
9023 .expect("aomenc failed to start");
9024 child
9025 .stdin
9026 .take()
9027 .expect("aomenc stdin")
9028 .write_all(&y4m.stdout)
9029 .expect("writing y4m to aomenc");
9030 let out = child.wait_with_output().expect("aomenc failed to run");
9031 assert!(
9032 out.status.success(),
9033 "aomenc refused the fixture (depth={depth}): {}",
9034 String::from_utf8_lossy(&out.stderr)
9035 );
9036 out.stdout
9037 };
9038 let stream = encode();
9039 assert_eq!(
9040 stream,
9041 encode(),
9042 "{NAME}: aomenc output is not reproducible (depth={depth})"
9043 );
9044 let before_cfl = crate::decode::cfl_block_hits();
9045 let before_angle = crate::decode::uv_angle_delta_hits();
9046 let before_uv = crate::decode::uv_mode_mi_override_hits();
9047 let frames = match decode_stream(&stream) {
9048 Ok(frames) => frames,
9049 // Only a NAMED refusal is tolerated (COMMON rule): the 10-bit
9050 // twin of this recipe still stops at another lane's open
9051 // sub-16 AB-partition / strip-filter-intra refusals, so it
9052 // cannot be compared yet. Any other error is a failure, and
9053 // `compared` below keeps the test from passing vacuously.
9054 Err(e) => {
9055 let msg = e.to_string();
9056 assert!(
9057 msg.contains("unsupported"),
9058 "{NAME}: decode failed (depth={depth}): {msg}"
9059 );
9060 eprintln!("{NAME}: depth={depth} arm refused (not compared): {msg}");
9061 continue;
9062 }
9063 };
9064 compared += 1;
9065 // Read only on an attempt that decoded AND is compared below.
9066 let cfl_blocks = crate::decode::cfl_block_hits() - before_cfl;
9067 let angle_blocks = crate::decode::uv_angle_delta_hits() - before_angle;
9068 let uv_overrides = crate::decode::uv_mode_mi_override_hits() - before_uv;
9069 let ffmpeg_frames = if depth == 10 {
9070 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
9071 } else {
9072 ffmpeg_decode_sequence(&stream, width, height, frames.len())
9073 };
9074 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame (depth={depth})");
9075 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
9076 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9077 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (depth={depth})");
9078 assert_eq!(
9079 got.u, want.u,
9080 "{NAME} frame {i} U vs ffmpeg (depth={depth}, {cfl_blocks} CFL blocks, \
9081 {angle_blocks} nonzero-angle_delta_uv blocks, {uv_overrides} mi-exact UV \
9082 neighbour overrides)"
9083 );
9084 assert_eq!(
9085 got.v, want.v,
9086 "{NAME} frame {i} V vs ffmpeg (depth={depth}, {cfl_blocks} CFL blocks, \
9087 {angle_blocks} nonzero-angle_delta_uv blocks, {uv_overrides} mi-exact UV \
9088 neighbour overrides)"
9089 );
9090 }
9091 assert!(
9092 cfl_blocks > 0,
9093 "{NAME}: no UV_CFL_PRED block decoded (depth={depth}) -- the gate proves nothing"
9094 );
9095 assert!(
9096 angle_blocks > 0,
9097 "{NAME}: no nonzero angle_delta_uv chroma block decoded (depth={depth}) -- \
9098 the chroma intra-edge filter path never ran"
9099 );
9100 assert!(
9101 uv_overrides > 0,
9102 "{NAME}: no chroma edge-filter read ever took a mi-exact UV neighbour that \
9103 disagreed with its coarse 16x16 slot (depth={depth}) -- the r1 defect is \
9104 not exercised"
9105 );
9106 eprintln!(
9107 "{NAME}: pixel-exact at {depth}-bit, cfl_blocks={cfl_blocks} \
9108 angle_delta_uv_blocks={angle_blocks} uv_mi_overrides={uv_overrides}"
9109 );
9110 }
9111 assert!(
9112 compared > 0,
9113 "{NAME}: every arm refused -- the gate compared no pixels at all"
9114 );
9115 }
9116
9117 /// lane-ab16 r1: real `aomenc --enable-ab-partitions=1` streams whose
9118 /// 16x16 blocks are split T-shaped (`PARTITION_HORZ_A`/`_HORZ_B`/
9119 /// `_VERT_A`/`_VERT_B`: two 8x8 squares plus one 16x8/8x16 strip), the
9120 /// refusals "a HORZ_A/HORZ_B/VERT_A partition below 16x16" and "a coded
9121 /// (non-skip) HORZ_B/VERT_B rect strip below 16x16" this round lifts.
9122 /// `--min-partition-size=8 --max-partition-size=16` pins the level so
9123 /// every AB symbol in the stream is a 16x16 one; the squares go through
9124 /// `decode_leaf8`, the strips through `decode_leaf_rect`'s non-skip
9125 /// coefficient path (lane-rectx). The per-arm counter is sampled per
9126 /// attempt and summed only over attempts that actually decoded AND were
9127 /// compared, and EACH of the four arms must have fired -- a run where
9128 /// aomenc's RD only ever picked HORZ_A cannot pass as proof of four
9129 /// ([[gate-blind-to-feature]]). 8-bit and 10-bit; `--tile-columns=1` is
9130 /// NOT among the attempts (base tile defect, reproducer in the r1
9131 /// report), and `--enable-tx-size-search` is left at aomenc's default
9132 /// (ON) -- pinning it off hid a panic in the TX4 sub-grid of an 8x8
9133 /// square inside a `PARTITION_VERT_A`/`_B` (r2).
9134 #[test]
9135 fn a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact() {
9136 const NAME: &str =
9137 "a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact";
9138 let _gate_lock = lock_gate_counters();
9139 if !have_ffmpeg() {
9140 eprintln!("SKIP {NAME}: no ffmpeg");
9141 return;
9142 }
9143 if !have_aomenc() {
9144 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9145 return;
9146 }
9147 struct Attempt {
9148 src: &'static str,
9149 w: usize,
9150 h: usize,
9151 cq: u32,
9152 ten_bit: bool,
9153 tile_cols: u32,
9154 /// Left at aomenc's default (ON) instead of pinned off: reaches
9155 /// the TX4 sub-grid of an 8x8 square inside a
9156 /// `PARTITION_VERT_A`/`_B` (r2's panic), at the cost of the
9157 /// strip-level split transform lane-rectx still refuses.
9158 tx_size_search: bool,
9159 }
9160 // Recipes chosen by a ~200-cell sweep of {source, size, cq} at this
9161 // level (r1 report): one cell per arm that is pixel-exact end to end,
9162 // plus two 10-bit cells. `--tile-columns=1` is deliberately absent --
9163 // it mismatches on blocks that are plain NONE/VERT with no AB symbol
9164 // in the failing superblock, i.e. a base tile defect this lane
9165 // neither introduced nor owns (reproducer pinned in the r1 report).
9166 let attempts = [
9167 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 22, ten_bit: false, tile_cols: 0, tx_size_search: false },
9168 Attempt { src: "rgbtestsrc=size=64x64", w: 64, h: 64, cq: 20, ten_bit: false, tile_cols: 0, tx_size_search: false },
9169 Attempt { src: "rgbtestsrc=size=64x64", w: 64, h: 64, cq: 50, ten_bit: false, tile_cols: 0, tx_size_search: false },
9170 Attempt { src: "mandelbrot=size=64x64:start_x=-1.0", w: 64, h: 64, cq: 14, ten_bit: false, tile_cols: 0, tx_size_search: false },
9171 // 10-bit: the only two cells of the sweep that are exact at this
9172 // depth (HORZ_A and VERT_A); the 10-bit HORZ_B/VERT_B cells all
9173 // trip the base chroma defect the r1 report pins, so those two
9174 // arms are proven 8-bit only.
9175 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 30, ten_bit: true, tile_cols: 0, tx_size_search: false },
9176 Attempt { src: "mandelbrot=size=64x64:start_x=0.4", w: 64, h: 64, cq: 30, ten_bit: true, tile_cols: 0, tx_size_search: false },
9177 // `--enable-tx-size-search` at aomenc's default: an 8x8 square of
9178 // a VERT_A/VERT_B resolves to a 2x2 grid of TX4 units, which is
9179 // the reach lookup that had no table row and panicked (r2). These
9180 // attempts may legitimately stop at lane-rectx's still-standing
9181 // "strip with a split transform" refusal -- an `unsupported`
9182 // message is tolerated, a panic or a pixel mismatch is not, and
9183 // at least one of them must reach a TX4 unit inside a vertical AB
9184 // partition.
9185 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 55, ten_bit: false, tile_cols: 0, tx_size_search: true },
9186 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 22, ten_bit: false, tile_cols: 0, tx_size_search: true },
9187 Attempt { src: "rgbtestsrc=size=64x64", w: 64, h: 64, cq: 20, ten_bit: false, tile_cols: 0, tx_size_search: true },
9188 Attempt { src: "mandelbrot=size=64x64:start_x=-1.0", w: 64, h: 64, cq: 14, ten_bit: false, tile_cols: 0, tx_size_search: true },
9189 ];
9190 let mut arms = [0usize; 4];
9191 let mut compared = 0usize;
9192 let mut tx4_reached = 0usize;
9193 let mut tx4_compared = 0usize;
9194 for a in &attempts {
9195 let desc =
9196 format!("{} cq={} {}bit tiles={}", a.src, a.cq, if a.ten_bit { 10 } else { 8 }, a.tile_cols);
9197 let mut ff: Vec<String> = vec![
9198 "-v".into(), "error".into(), "-f".into(), "lavfi".into(), "-i".into(), a.src.into(),
9199 "-pix_fmt".into(),
9200 if a.ten_bit { "yuv420p10le".into() } else { "yuv420p".into() },
9201 ];
9202 if a.ten_bit {
9203 ff.push("-strict".into());
9204 ff.push("-1".into());
9205 }
9206 ff.extend(["-t".into(), "1".into(), "-vframes".into(), "1".into(),
9207 "-f".into(), "yuv4mpegpipe".into(), "-".into()]);
9208 let y4m = Command::new("ffmpeg")
9209 .args(&ff)
9210 .stdin(Stdio::null())
9211 .stdout(Stdio::piped())
9212 .stderr(Stdio::piped())
9213 .output()
9214 .expect("ffmpeg failed to run");
9215 assert!(y4m.status.success(), "ffmpeg fixture {desc}: {}", String::from_utf8_lossy(&y4m.stderr));
9216 let encode = || {
9217 let mut args: Vec<String> = vec![
9218 "--codec=av1".into(), "--passes=1".into(), "--end-usage=q".into(),
9219 format!("--cq-level={}", a.cq), "--cpu-used=4".into(), "--threads=1".into(),
9220 "--row-mt=0".into(), "--sb-size=64".into(), "--kf-max-dist=0".into(),
9221 "--limit=1".into(),
9222 "--enable-rect-partitions=1".into(), "--enable-ab-partitions=1".into(),
9223 "--enable-1to4-partitions=0".into(),
9224 format!("--enable-tx-size-search={}", u8::from(a.tx_size_search)),
9225 // Filter intra ON a rect strip is a separate, still-refused
9226 // predictor; this gate is about the AB partition wiring.
9227 "--enable-filter-intra=0".into(),
9228 "--reduced-tx-type-set=1".into(),
9229 "--min-partition-size=8".into(), "--max-partition-size=16".into(),
9230 format!("--tile-columns={}", a.tile_cols),
9231 ];
9232 if a.ten_bit {
9233 args.push("--input-bit-depth=10".into());
9234 args.push("--bit-depth=10".into());
9235 }
9236 args.extend(["--obu".into(), "-o".into(), "-".into(), "-".into()]);
9237 let mut child = Command::new(aomenc_path())
9238 .args(&args)
9239 .stdin(Stdio::piped())
9240 .stdout(Stdio::piped())
9241 .stderr(Stdio::piped())
9242 .spawn()
9243 .expect("aomenc failed to start");
9244 child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("y4m to aomenc");
9245 let out = child.wait_with_output().expect("aomenc failed to run");
9246 assert!(out.status.success(), "aomenc refused {desc}: {}", String::from_utf8_lossy(&out.stderr));
9247 out.stdout
9248 };
9249 let stream = encode();
9250 assert!(!stream.is_empty(), "{NAME}: {desc}: aomenc wrote an empty stream");
9251 assert_eq!(stream, encode(), "{NAME}: {desc}: aomenc output is not reproducible");
9252 let before = crate::decode::ab16_hits_by_arm();
9253 let tx4_before = crate::decode::vert_ab_tx4_hits();
9254 let decoded = decode_stream(&stream);
9255 let tx4_this = crate::decode::vert_ab_tx4_hits() - tx4_before;
9256 // Counted even when the attempt later stops at another lane's
9257 // refusal: reaching this lookup at all is what r2 fixed.
9258 tx4_reached += tx4_this;
9259 let frames = match decoded {
9260 Ok(frames) => frames,
9261 // Only lane-rectx's split-transform strip refusal may stop a
9262 // tx-size-search attempt; a panic never reaches here at all.
9263 Err(e) if a.tx_size_search => {
9264 let msg = e.to_string();
9265 assert!(
9266 msg.contains("unsupported"),
9267 "{NAME}: {desc}: decode failed with a non-refusal error: {msg}"
9268 );
9269 eprintln!("{NAME}: {desc} refused after {tx4_this} vert-AB TX4 units: {msg}");
9270 continue;
9271 }
9272 Err(e) => panic!("{NAME}: {desc}: decode failed, not a pixel mismatch: {e}"),
9273 };
9274 let after = crate::decode::ab16_hits_by_arm();
9275 let this: Vec<usize> = (0..4).map(|i| after[i] - before[i]).collect();
9276 eprintln!("{NAME}: {desc} decoded, arms this attempt={this:?}");
9277 let want = if a.ten_bit {
9278 ffmpeg_decode_sequence_10bit(&stream, a.w, a.h, frames.len())
9279 } else {
9280 ffmpeg_decode_sequence(&stream, a.w, a.h, frames.len())
9281 };
9282 assert_eq!(want.len(), frames.len(), "{NAME}: {desc}: ffmpeg frame count");
9283 for (i, (got, w)) in frames.iter().zip(&want).enumerate() {
9284 assert_eq!(got.y, w.y, "{NAME}: {desc} frame {i} luma vs ffmpeg");
9285 assert_eq!(got.u, w.u, "{NAME}: {desc} frame {i} U vs ffmpeg");
9286 assert_eq!(got.v, w.v, "{NAME}: {desc} frame {i} V vs ffmpeg");
9287 }
9288 // Counted only now: the attempt decoded AND compared exact.
9289 if a.tx_size_search {
9290 tx4_compared += 1;
9291 eprintln!("{NAME}: {desc} pixel-exact, vert-AB TX4 units={tx4_this}");
9292 continue;
9293 }
9294 for i in 0..4 {
9295 arms[i] += after[i] - before[i];
9296 }
9297 compared += 1;
9298 eprintln!("{NAME}: {desc} pixel-exact");
9299 }
9300 assert_eq!(
9301 compared,
9302 attempts.iter().filter(|a| !a.tx_size_search).count(),
9303 "{NAME}: every fixed-transform attempt must decode and compare"
9304 );
9305 // The tx-size-search attempts cannot be compared pixel by pixel yet:
9306 // every 16x16 AB partition contains a strip, and with a free
9307 // transform size aomenc splits at least one of them in every stream
9308 // of a 40-cell {source, cq} sweep (r2 report), so they all stop at
9309 // lane-rectx's "strip with a split transform" refusal (or the 1:4 /
9310 // sub-8x8 ones) before the frame is done. What they DO prove is that
9311 // the TX4 sub-grid of an 8x8 square inside a VERT_A/VERT_B is reached
9312 // on a real stream and answers -- it used to panic there, and a panic
9313 // cannot be tolerated by the `unsupported` arm above. The values it
9314 // answers are pinned separately against libaom in
9315 // `of_tu_keeps_the_ordinary_answer_and_uses_the_block_row_under_vert_ab`.
9316 let _ = tx4_compared;
9317 assert!(
9318 tx4_reached > 0,
9319 "{NAME}: no --enable-tx-size-search=1 attempt reached a TX4 unit inside a \
9320 vertical AB partition -- the r2 panic path is unproven"
9321 );
9322 for (i, arm) in ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"].iter().enumerate() {
9323 assert!(arms[i] > 0, "{NAME}: PARTITION_{arm} at 16x16 never fired across {compared} \
9324 compared streams -- the gate proves nothing about that arm (arms={arms:?})");
9325 }
9326 eprintln!("{NAME}: pixel-exact on {compared} streams, ab16 arms(HORZ_A,HORZ_B,VERT_A,VERT_B)={arms:?}");
9327 }
9328
9329 #[test]
9330 #[ignore = "lane-rectx r3 scratch sweep"]
9331 fn sweep_rectx_recipes() {
9332 let _gate_lock = lock_gate_counters();
9333 let srcs: Vec<String> = vec![
9334 "mandelbrot=size=64x64:start_x=0.4".into(),
9335 "mandelbrot=size=64x64:start_x=-0.6".into(),
9336 "mandelbrot=size=64x64:start_x=0.1".into(),
9337 "mandelbrot=size=128x128:start_x=0.4".into(),
9338 "mandelbrot=size=128x128:start_x=-0.6".into(),
9339 "testsrc2=size=64x64".into(),
9340 "testsrc2=size=128x128".into(),
9341 "rgbtestsrc=size=64x64".into(),
9342 "smptebars=size=128x128".into(),
9343 ];
9344 for start_x in srcs {
9345 let y4m = Command::new("ffmpeg")
9346 .args([
9347 "-v", "error", "-f", "lavfi", "-i",
9348 &start_x,
9349 "-pix_fmt", "yuv420p", "-t", "1", "-vframes", "1", "-f", "yuv4mpegpipe", "-",
9350 ])
9351 .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped())
9352 .output().expect("ffmpeg");
9353 assert!(y4m.status.success());
9354 let (width, height) = if start_x.contains("128x128") { (128usize, 128usize) } else { (64usize, 64usize) };
9355 for cq in [16u32, 20, 24, 28, 32, 40, 50] {
9356 for rtx in ["0", "1"] {
9357 let mut child = Command::new(aomenc_path())
9358 .args([
9359 "--codec=av1", "--passes=1", "--end-usage=q",
9360 &format!("--cq-level={cq}"), "--cpu-used=4", "--threads=1",
9361 "--row-mt=0", "--sb-size=64", "--kf-max-dist=0",
9362 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
9363 "--enable-1to4-partitions=0", "--enable-tx-size-search=0",
9364 "--enable-cdef=0", "--enable-restoration=0",
9365 &format!("--reduced-tx-type-set={rtx}"),
9366 "--min-partition-size=8", "--max-partition-size=32",
9367 "--obu", "-o", "-", "-",
9368 ])
9369 .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
9370 .spawn().expect("aomenc");
9371 child.stdin.take().unwrap().write_all(&y4m.stdout).unwrap();
9372 let out = child.wait_with_output().unwrap();
9373 assert!(out.status.success());
9374 let stream = out.stdout;
9375 let before = crate::decode::rect_leaf_coeff_hits();
9376 let res = decode_stream(&stream);
9377 let fired = crate::decode::rect_leaf_coeff_hits() - before;
9378 match res {
9379 Err(e) => eprintln!("x={start_x} cq={cq} rtx={rtx} fired={fired} REFUSED {e}"),
9380 Ok(frames) => {
9381 let want = ffmpeg_decode_sequence(&stream, width, height, frames.len());
9382 let bad = frames.iter().zip(&want)
9383 .filter(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v).count();
9384 eprintln!("x={start_x} cq={cq} rtx={rtx} fired={fired} frames={} mismatched={bad}", frames.len());
9385 if bad == 0 { continue; }
9386 let (g, w) = (&frames[0], &want[0]);
9387 for br in 0..height / 8 {
9388 let mut line = String::new();
9389 for bc in 0..width / 8 {
9390 let mut n = 0;
9391 for row in br * 8..br * 8 + 8 {
9392 for col in bc * 8..bc * 8 + 8 {
9393 if g.y[row * width + col] != w.y[row * width + col] {
9394 n += 1;
9395 }
9396 }
9397 }
9398 line.push_str(&format!("{n:4}"));
9399 }
9400 eprintln!(" blk8 row{br}: {line}");
9401 }
9402 }
9403 }
9404 }
9405 }
9406 }
9407 }
9408
9409 /// lane-rectgate r1: every prior gate pins `--enable-rect-partitions=0
9410 /// --enable-ab-partitions=0 --min/max-partition-size=32` so aomenc never
9411 /// gets to choose a real rect/ab split. This charter's premise ("rect
9412 /// HORZ/VERT + HORZ_A/HORZ_B/VERT_A/VERT_B landed during the warp lane")
9413 /// does NOT hold: `decode_frame`'s inter-tile `match part32` only has
9414 /// arms for `PARTITION_NONE`/`SPLIT`/`HORZ_B` -- `HORZ`, `VERT`,
9415 /// `HORZ_A`, `VERT_A`, `VERT_B`, `HORZ_4`, `VERT_4` all fall into the
9416 /// generic "a partition type this encoder never writes" `_` arm. Two
9417 /// recipes were swept empirically (40 attempts each) to characterize the
9418 /// gap:
9419 /// - `--enable-rect-partitions=1 --enable-ab-partitions=1`, no
9420 /// min/max clamp: 0/40 matched -- every attempt hit either the
9421 /// screen-content refusal or a genuinely-unimplemented partition value
9422 /// (1/2/6/7/9 all observed), always somewhere in the 24-frame stream.
9423 /// - Same, but `--enable-1to4-partitions=0` explicit and
9424 /// `--min-partition-size=16`: still 0/40, `value=9` (`VERT_4`)
9425 /// dominates -- this build's `--enable-1to4-partitions=0` does NOT
9426 /// suppress `VERT_4` selection (aomenc-side, confirmed by direct flag
9427 /// toggle; outside this decoder). This recipe (below) restores the
9428 /// `--enable-rect-partitions=0 --min/max-partition-size=32` pin every
9429 /// other gate uses, flipping only `--enable-ab-partitions=1`: matches
9430 /// cleanly (33/40, rest screen-content refusals) but
9431 /// `extended_partition_hits` stayed 0 -- confirmed with the same probe
9432 /// wired into the already-green warp gate too (144 `warp_selected_hits`,
9433 /// 0 `extended_partition_hits`), so `PARTITION_HORZ_B` itself is
9434 /// apparently never chosen by aomenc for this small gradient fixture at
9435 /// `cq-level=45` regardless of clamp. No decode defect (crash or pixel
9436 /// mismatch) was found in any sweep -- every refusal is a correctly
9437 /// named, non-silent "unsupported" error. A refusal or mismatch naming
9438 /// any OTHER already-ported capability (warp, obmc, interintra) still
9439 /// fails the gate outright.
9440 #[test]
9441 fn a_real_aomenc_stream_with_free_partitions_decodes_pixel_exact() {
9442 const NAME: &str = "a_real_aomenc_stream_with_free_partitions_decodes_pixel_exact";
9443 let _gate_lock = lock_gate_counters();
9444 if !have_ffmpeg() {
9445 eprintln!("SKIP {NAME}: no ffmpeg");
9446 return;
9447 }
9448 if !have_aomenc() {
9449 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9450 return;
9451 }
9452 let (width, height, frame_count) = (64usize, 64usize, 24usize);
9453 let mut named_refusals = 0u32;
9454 let mut matched = 0u32;
9455 let n_attempts: u32 = std::env::var("EC_RECTGATE_ATTEMPTS")
9456 .ok()
9457 .and_then(|s| s.parse().ok())
9458 .unwrap_or(40);
9459 for attempt in 0..n_attempts {
9460 let seed = 42 + attempt;
9461 let duration = frame_count as f64 / 25.0;
9462 let source =
9463 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
9464 let y4m = Command::new("ffmpeg")
9465 .args([
9466 "-v",
9467 "error",
9468 "-f",
9469 "lavfi",
9470 "-i",
9471 &source,
9472 "-pix_fmt",
9473 "yuv420p",
9474 "-f",
9475 "yuv4mpegpipe",
9476 "-",
9477 ])
9478 .stdin(Stdio::null())
9479 .stdout(Stdio::piped())
9480 .stderr(Stdio::piped())
9481 .output()
9482 .expect("ffmpeg failed to run");
9483 assert!(
9484 y4m.status.success(),
9485 "ffmpeg fixture: {}",
9486 String::from_utf8_lossy(&y4m.stderr)
9487 );
9488 let args: Vec<&str> = vec![
9489 "--codec=av1",
9490 "--passes=1",
9491 "--end-usage=q",
9492 "--cq-level=45",
9493 "--cpu-used=0",
9494 "--kf-max-dist=1000",
9495 "--threads=1",
9496 "--row-mt=0",
9497 "--auto-alt-ref=1",
9498 "--lag-in-frames=16",
9499 "--enable-fwd-kf=0",
9500 "--enable-order-hint=1",
9501 "--enable-warped-motion=1",
9502 "--enable-obmc=1",
9503 "--tune-content=default",
9504 "--enable-masked-comp=0",
9505 "--enable-interintra-comp=0",
9506 "--enable-onesided-comp=0",
9507 "--enable-interintra-wedge=0",
9508 "--enable-smooth-interintra=0",
9509 // lane-rect r2: HORZ/VERT decode for real (rect-flake-1
9510 // byte-exact: size_h + warp dims + OBMC overlap + tx height)
9511 // -- free recipe restored; remaining partition kinds refuse
9512 // by name and skip their seeds.
9513 "--enable-rect-partitions=1",
9514 "--enable-ab-partitions=1",
9515 "--enable-1to4-partitions=0",
9516 "--enable-filter-intra=0",
9517 "--enable-smooth-intra=0",
9518 "--enable-paeth-intra=0",
9519 "--enable-directional-intra=0",
9520 "--enable-angle-delta=0",
9521 "--enable-tx-size-search=0",
9522 "--enable-cdef=0",
9523 "--enable-restoration=0",
9524 "--max-partition-size=32",
9525 "--min-partition-size=16",
9526 "--enable-palette=0",
9527 "--enable-intrabc=0",
9528 "--enable-cfl-intra=0",
9529 "--enable-ref-frame-mvs=0",
9530 "--obu",
9531 "-o",
9532 "-",
9533 "-",
9534 ];
9535 let mut child = Command::new(aomenc_path())
9536 .args(&args)
9537 .stdin(Stdio::piped())
9538 .stdout(Stdio::piped())
9539 .stderr(Stdio::piped())
9540 .spawn()
9541 .expect("aomenc failed to start");
9542 child
9543 .stdin
9544 .take()
9545 .expect("aomenc stdin")
9546 .write_all(&y4m.stdout)
9547 .expect("writing y4m to aomenc");
9548 let out = child.wait_with_output().expect("aomenc failed to run");
9549 assert!(
9550 out.status.success(),
9551 "aomenc refused the fixture: {}",
9552 String::from_utf8_lossy(&out.stderr)
9553 );
9554 let stream = out.stdout;
9555 let frames = match decode_stream(&stream) {
9556 Err(e) => {
9557 let msg = e.to_string();
9558 assert!(
9559 msg.contains("unsupported"),
9560 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
9561 );
9562 for banned in ["warp", "obmc", "interintra"] {
9563 assert!(
9564 !msg.contains(banned),
9565 "{NAME} refused on {banned} (seed {seed}) -- that capability is \
9566 ported and this recipe does not need it: {msg}"
9567 );
9568 }
9569 named_refusals += 1;
9570 eprintln!("seed {seed} refusal: {msg}");
9571 continue;
9572 }
9573 Ok(frames) => frames,
9574 };
9575 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
9576 assert_eq!(frames.len(), frame_count);
9577 let mismatched = frames
9578 .iter()
9579 .zip(&ffmpeg_frames)
9580 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
9581 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
9582 std::fs::write(&path, &stream).expect("writing pinned stream");
9583 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
9584 }
9585 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9586 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
9587 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
9588 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
9589 }
9590 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
9591 // stream again, comparing EVERY decode-order frame -- the hidden
9592 // (show_frame == 0) alt-ref frames the ffmpeg compare above
9593 // cannot see, because both sides of it emit shown frames only.
9594 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
9595 eprintln!(
9596 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
9597 {hidden_n} hidden, all pixel-exact vs the oracle"
9598 );
9599 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
9600 // libaom's temporal alt-ref filter absorbs this recipe's hidden
9601 // frames, so the compare above is vacuous -- re-encode the same
9602 // fixture with --arnr-maxframes=0 and compare THOSE.
9603 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
9604 eprintln!(
9605 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
9606 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
9607 );
9608 }
9609 matched += 1;
9610 }
9611 assert!(
9612 matched > 0,
9613 "{NAME}: every attempt refused; the gate never decoded a free-partition stream"
9614 );
9615 // lane-partitions r1: HORZ/VERT arms landed, so the diversity probe
9616 // graduates from rectgate r1's eprintln to a report line on
9617 // `rect_partition_hits`; a zero-hit run SOFT-reports (aomenc RD may
9618 // legitimately never pick a rect split in a small window -- same
9619 // sampling caveat as the masked-compound gate's zero-hit runs).
9620 // `extended_partition_hits` (HORZ_B) stays unasserted per rectgate r1.
9621 if crate::decode::rect_partition_hits() == 0 {
9622 eprintln!(
9623 "{NAME}: SOFT-NOTE -- zero HORZ/VERT strips fired this run \
9624 ({matched} matches, {named_refusals} refusals); sampling, not a regression"
9625 );
9626 } else {
9627 // r5: the desync was the tx-depth symbol being read
9628 // unconditionally where both square paths gate it on `tx_select`
9629 // -- with --enable-tx-size-search=0 the encoder writes no such
9630 // symbol and the decoder consumed one that was never there. With
9631 // that fixed the real coefficient decode is pixel-exact, so this
9632 // is a HARD assert again: strips fired but no coefficients read
9633 // would mean the coded path silently stopped being exercised.
9634 assert!(
9635 crate::decode::rect_coeff_hits() > 0,
9636 "{NAME}: {} HORZ/VERT strips fired but rect_coeff_hits==0 -- the \
9637 coded rect path is no longer exercised",
9638 crate::decode::rect_partition_hits()
9639 );
9640 }
9641 eprintln!(
9642 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of {n_attempts}, rect_partition_hits={} rect_coeff_hits={} extended_partition_hits={} partab_hits={}",
9643 crate::decode::rect_partition_hits(),
9644 crate::decode::rect_coeff_hits(),
9645 crate::decode::extended_partition_hits(),
9646 crate::decode::partab_hits()
9647 );
9648 }
9649
9650 /// lane-partab r1: `--enable-ab-partitions=1` (aomenc default-on) INTER
9651 /// streams must consume PARTITION_HORZ_A/VERT_A/VERT_B entropy-exact AND
9652 /// decode pixel-exact -- `partab_hits() > 0` is soft-skipped on a
9653 /// zero-hit run (aomenc RD may legitimately never pick an AB split in a
9654 /// small window, same sampling caveat as wedge/rect). The INTER AB
9655 /// refusal is FORBIDDEN (decode.rs names it "an INTER 32x32 partition
9656 /// ..."); intra-frame AB refusals stay accepted named refusals -- the
9657 /// intra dispatch is a later lane. Recipe = the free-partition gate's,
9658 /// which fires AB live (r1: partab_hits 6/2/4/3/1/5 over six
9659 /// 40-attempt runs).
9660 #[test]
9661 fn a_real_aomenc_stream_with_ab_partitions_decodes_pixel_exact() {
9662 const NAME: &str = "a_real_aomenc_stream_with_ab_partitions_decodes_pixel_exact";
9663 let _gate_lock = lock_gate_counters();
9664 if !have_ffmpeg() {
9665 eprintln!("SKIP {NAME}: no ffmpeg");
9666 return;
9667 }
9668 if !have_aomenc() {
9669 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9670 return;
9671 }
9672 let (width, height, frame_count) = (64usize, 64usize, 24usize);
9673 let mut named_refusals = 0u32;
9674 let mut matched = 0u32;
9675 let n_attempts: u32 = std::env::var("EC_RECTGATE_ATTEMPTS")
9676 .ok()
9677 .and_then(|s| s.parse().ok())
9678 .unwrap_or(40);
9679 for attempt in 0..n_attempts {
9680 let seed = 42 + attempt;
9681 let duration = frame_count as f64 / 25.0;
9682 let source =
9683 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
9684 let y4m = Command::new("ffmpeg")
9685 .args([
9686 "-v",
9687 "error",
9688 "-f",
9689 "lavfi",
9690 "-i",
9691 &source,
9692 "-pix_fmt",
9693 "yuv420p",
9694 "-f",
9695 "yuv4mpegpipe",
9696 "-",
9697 ])
9698 .stdin(Stdio::null())
9699 .stdout(Stdio::piped())
9700 .stderr(Stdio::piped())
9701 .output()
9702 .expect("ffmpeg failed to run");
9703 assert!(
9704 y4m.status.success(),
9705 "ffmpeg fixture: {}",
9706 String::from_utf8_lossy(&y4m.stderr)
9707 );
9708 let args: Vec<&str> = vec![
9709 "--codec=av1",
9710 "--passes=1",
9711 "--end-usage=q",
9712 "--cq-level=45",
9713 "--cpu-used=0",
9714 "--kf-max-dist=1000",
9715 "--threads=1",
9716 "--row-mt=0",
9717 "--auto-alt-ref=1",
9718 "--lag-in-frames=16",
9719 "--enable-fwd-kf=0",
9720 "--enable-order-hint=1",
9721 "--enable-warped-motion=1",
9722 "--enable-obmc=1",
9723 "--tune-content=default",
9724 "--enable-masked-comp=0",
9725 "--enable-interintra-comp=0",
9726 "--enable-onesided-comp=0",
9727 "--enable-interintra-wedge=0",
9728 "--enable-smooth-interintra=0",
9729 // lane-rect r2 recipe, kept byte-identical by lane-partab
9730 // r1: free partition search, 1to4 off, intra tools off.
9731 "--enable-rect-partitions=1",
9732 "--enable-ab-partitions=1",
9733 "--enable-1to4-partitions=0",
9734 "--enable-filter-intra=0",
9735 "--enable-smooth-intra=0",
9736 "--enable-paeth-intra=0",
9737 "--enable-directional-intra=0",
9738 "--enable-angle-delta=0",
9739 "--enable-tx-size-search=0",
9740 "--enable-cdef=0",
9741 "--enable-restoration=0",
9742 "--max-partition-size=32",
9743 "--min-partition-size=16",
9744 "--enable-palette=0",
9745 "--enable-intrabc=0",
9746 "--enable-cfl-intra=0",
9747 "--enable-ref-frame-mvs=0",
9748 "--obu",
9749 "-o",
9750 "-",
9751 "-",
9752 ];
9753 let mut child = Command::new(aomenc_path())
9754 .args(&args)
9755 .stdin(Stdio::piped())
9756 .stdout(Stdio::piped())
9757 .stderr(Stdio::piped())
9758 .spawn()
9759 .expect("aomenc failed to start");
9760 child
9761 .stdin
9762 .take()
9763 .expect("aomenc stdin")
9764 .write_all(&y4m.stdout)
9765 .expect("writing y4m to aomenc");
9766 let out = child.wait_with_output().expect("aomenc failed to run");
9767 assert!(
9768 out.status.success(),
9769 "aomenc refused the fixture: {}",
9770 String::from_utf8_lossy(&out.stderr)
9771 );
9772 let stream = out.stdout;
9773 let frames = match decode_stream(&stream) {
9774 Err(e) => {
9775 let msg = e.to_string();
9776 assert!(
9777 msg.contains("unsupported"),
9778 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
9779 );
9780 for banned in ["warp", "obmc", "interintra"] {
9781 assert!(
9782 !msg.contains(banned),
9783 "{NAME} refused on {banned} (seed {seed}) -- that capability is \
9784 ported and this recipe does not need it: {msg}"
9785 );
9786 }
9787 for v in [4, 6, 7] {
9788 assert!(
9789 !msg.contains(&format!(
9790 "an INTER 32x32 partition type this encoder never writes \
9791 (value={v})"
9792 )),
9793 "{NAME} refused an INTER AB partition (value={v}, seed {seed}) -- \
9794 all three AB arms are ported, this refusal is forbidden: {msg}"
9795 );
9796 }
9797 named_refusals += 1;
9798 eprintln!("seed {seed} refusal: {msg}");
9799 continue;
9800 }
9801 Ok(frames) => frames,
9802 };
9803 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
9804 assert_eq!(frames.len(), frame_count);
9805 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9806 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
9807 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
9808 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
9809 }
9810 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
9811 // stream again, comparing EVERY decode-order frame -- the hidden
9812 // (show_frame == 0) alt-ref frames the ffmpeg compare above
9813 // cannot see, because both sides of it emit shown frames only.
9814 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
9815 eprintln!(
9816 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
9817 {hidden_n} hidden, all pixel-exact vs the oracle"
9818 );
9819 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
9820 // libaom's temporal alt-ref filter absorbs this recipe's hidden
9821 // frames, so the compare above is vacuous -- re-encode the same
9822 // fixture with --arnr-maxframes=0 and compare THOSE.
9823 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
9824 eprintln!(
9825 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
9826 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
9827 );
9828 }
9829 matched += 1;
9830 }
9831 assert!(
9832 matched > 0,
9833 "{NAME}: every attempt refused; the gate never decoded a stream"
9834 );
9835 if crate::decode::partab_hits() == 0 {
9836 eprintln!(
9837 "{NAME}: SOFT-NOTE -- zero AB partitions fired this run \
9838 ({matched} matches, {named_refusals} refusals); sampling, not a regression"
9839 );
9840 }
9841 eprintln!(
9842 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of {n_attempts}, partab_hits={}",
9843 crate::decode::partab_hits()
9844 );
9845 }
9846
9847 /// lane-ab32 r1: the 32x32-level AB arms (`PARTITION_HORZ_A`/`_HORZ_B`/
9848 /// `_VERT_A`/`_VERT_B` -- two 16x16 squares plus one 32x16/16x32 strip)
9849 /// are decoded on the INTRA path (decode.rs `PARTITION_HORZ_A` .. the
9850 /// 32x32 refusal) but nothing asserted they fire: the INTER AB gate above
9851 /// only SOFT-notes `partab_hits`, and the four per-arm counters
9852 /// lane-part32 added had no consumer at all (class
9853 /// `refusal-lifted-without-a-gate`). This drives a real key-frame-only
9854 /// aomenc at `--enable-ab-partitions=1 --enable-rect-partitions=1
9855 /// --sb-size=64 --min-partition-size=16 --max-partition-size=32`, so every
9856 /// AB split aomenc picks is a 32-level one, pixel-compares every
9857 /// successful decode against ffmpeg's decode of the same bytes, and
9858 /// hard-asserts each arm fired at least once over the seed sweep --
9859 /// counting deltas only from attempts that decoded AND compared (class
9860 /// `counter-from-refused-stream`).
9861 #[test]
9862 fn a_real_aomenc_stream_with_a_32_level_ab_partition_decodes_pixel_exact() {
9863 const NAME: &str = "a_real_aomenc_stream_with_a_32_level_ab_partition_decodes_pixel_exact";
9864 let _gate_lock = lock_gate_counters();
9865 if !have_ffmpeg() {
9866 eprintln!("SKIP {NAME}: no ffmpeg");
9867 return;
9868 }
9869 if !have_aomenc() {
9870 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9871 return;
9872 }
9873 let (width, height) = (256usize, 256usize);
9874 let arms: [(&str, fn() -> usize); 4] = [
9875 ("HORZ_A_32", crate::decode::intra_horz_a_hits),
9876 ("HORZ_B_32", crate::decode::intra_horz_b_hits),
9877 ("VERT_A_32", crate::decode::intra_vert_a_hits),
9878 ("VERT_B_32", crate::decode::intra_vert_b_hits),
9879 ];
9880 let mut totals = [0usize; 4];
9881 let mut refusals: Vec<String> = Vec::new();
9882 let mut compared = 0usize;
9883 for &seed in &LR_SEEDS {
9884 // Smooth gradients code as PARTITION_NONE everywhere (r1: 16/16
9885 // attempts decoded pixel-exact with zero AB hits), so the fixture
9886 // carries seeded noise to give the intra RD a reason to split.
9887 let source = format!(
9888 "{},noise=alls=40:all_seed={seed}",
9889 gradients_source(seed, width, height, "duration=0.04:rate=25")
9890 );
9891 let y4m = Command::new("ffmpeg")
9892 .args([
9893 "-v",
9894 "error",
9895 "-f",
9896 "lavfi",
9897 "-i",
9898 &source,
9899 "-frames:v",
9900 "1",
9901 "-pix_fmt",
9902 "yuv420p",
9903 "-f",
9904 "yuv4mpegpipe",
9905 "-",
9906 ])
9907 .stdin(Stdio::null())
9908 .stdout(Stdio::piped())
9909 .stderr(Stdio::piped())
9910 .output()
9911 .expect("ffmpeg failed to run");
9912 assert!(
9913 y4m.status.success(),
9914 "{NAME}: ffmpeg fixture (seed {seed}): {}",
9915 String::from_utf8_lossy(&y4m.stderr)
9916 );
9917 // The flags under test come LAST: aomenc keeps the LAST
9918 // occurrence of a repeated flag (measured 2026-09-02 by md5 of
9919 // four orderings), so an override appended after the base recipe
9920 // is the one that lands. Nothing here is repeated, and each of the
9921 // four arm counters below proves the AB flag actually arrived.
9922 let args: Vec<&str> = vec![
9923 "--codec=av1",
9924 "--passes=1",
9925 "--end-usage=q",
9926 "--cq-level=45",
9927 "--cpu-used=0",
9928 "--limit=1",
9929 "--kf-max-dist=0",
9930 "--lag-in-frames=0",
9931 "--threads=1",
9932 "--row-mt=0",
9933 "--enable-1to4-partitions=0",
9934 "--enable-filter-intra=0",
9935 "--enable-smooth-intra=0",
9936 "--enable-paeth-intra=0",
9937 "--enable-directional-intra=0",
9938 "--enable-angle-delta=0",
9939 "--enable-tx-size-search=0",
9940 "--enable-cdef=0",
9941 "--enable-restoration=0",
9942 "--enable-palette=0",
9943 "--enable-intrabc=0",
9944 "--enable-cfl-intra=0",
9945 "--enable-ref-frame-mvs=0",
9946 "--sb-size=64",
9947 "--enable-rect-partitions=1",
9948 "--enable-ab-partitions=1",
9949 "--min-partition-size=16",
9950 "--max-partition-size=32",
9951 "--obu",
9952 "-o",
9953 "-",
9954 "-",
9955 ];
9956 let mut child = Command::new(aomenc_path())
9957 .args(&args)
9958 .stdin(Stdio::piped())
9959 .stdout(Stdio::piped())
9960 .stderr(Stdio::piped())
9961 .spawn()
9962 .expect("aomenc failed to start");
9963 child
9964 .stdin
9965 .take()
9966 .expect("aomenc stdin")
9967 .write_all(&y4m.stdout)
9968 .expect("writing y4m to aomenc");
9969 let out = child.wait_with_output().expect("aomenc failed to run");
9970 assert!(
9971 out.status.success(),
9972 "aomenc refused the fixture (seed {seed}): {}",
9973 String::from_utf8_lossy(&out.stderr)
9974 );
9975 let stream = out.stdout;
9976 let before: Vec<usize> = arms.iter().map(|(_, f)| f()).collect();
9977 let frames = match decode_stream(&stream) {
9978 Err(e) => {
9979 let msg = e.to_string();
9980 assert!(
9981 msg.contains("unsupported"),
9982 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
9983 );
9984 for v in [4, 5, 6, 7] {
9985 assert!(
9986 !msg.contains(&format!(
9987 "a 32x32 partition type this decoder does not code (value={v})"
9988 )),
9989 "{NAME} refused a 32-level AB partition (value={v}, seed {seed}) -- \
9990 all four arms are ported, this refusal is forbidden: {msg}"
9991 );
9992 }
9993 refusals.push(format!("seed {seed}: {msg}"));
9994 continue;
9995 }
9996 Ok(frames) => frames,
9997 };
9998 let deltas: Vec<usize> = arms
9999 .iter()
10000 .zip(before.iter())
10001 .map(|((_, f), b)| f() - b)
10002 .collect();
10003 let fired: Vec<String> = arms
10004 .iter()
10005 .zip(deltas.iter())
10006 .map(|((label, _), d)| format!("{label}={d}"))
10007 .collect();
10008 let fired = fired.join(" ");
10009 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
10010 assert_eq!(
10011 frames.len(),
10012 ffmpeg_frames.len(),
10013 "{NAME}: seed {seed}: shown-frame count vs ffmpeg"
10014 );
10015 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10016 assert_eq!(
10017 got.y, want.y,
10018 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) [{fired}]"
10019 );
10020 assert_eq!(
10021 got.u, want.u,
10022 "{NAME} frame {i} U vs ffmpeg (seed {seed}) [{fired}]"
10023 );
10024 assert_eq!(
10025 got.v, want.v,
10026 "{NAME} frame {i} V vs ffmpeg (seed {seed}) [{fired}]"
10027 );
10028 }
10029 compared += 1;
10030 for (i, d) in deltas.iter().enumerate() {
10031 totals[i] += d;
10032 }
10033 }
10034 assert!(
10035 compared > 0,
10036 "{NAME}: every attempt hit a named refusal:\n{}",
10037 refusals.join("\n")
10038 );
10039 for (i, (label, _)) in arms.iter().enumerate() {
10040 assert!(
10041 totals[i] > 0,
10042 "{NAME}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
10043 the gate would prove nothing about that arm. refusals:\n{}",
10044 refusals.join("\n")
10045 );
10046 }
10047 eprintln!(
10048 "{NAME}: {compared}/{} attempts pixel-exact, HORZ_A_32={} HORZ_B_32={} \
10049 VERT_A_32={} VERT_B_32={}, {} named refusals",
10050 LR_SEEDS.len(),
10051 totals[0],
10052 totals[1],
10053 totals[2],
10054 totals[3],
10055 refusals.len()
10056 );
10057 }
10058
10059 /// lane-ab32 r1: the 10-bit twin of the gate above -- his two films are
10060 /// yuv420p10le, so an 8-bit-only AB gate proves nothing about the streams
10061 /// that matter. Same recipe through [`ten_bit_tool_gate`], which sums the
10062 /// per-arm counters only over attempts that decoded and pixel-compared.
10063 #[test]
10064 fn a_real_aomenc_10bit_stream_with_a_32_level_ab_partition_decodes_pixel_exact() {
10065 const NAME: &str =
10066 "a_real_aomenc_10bit_stream_with_a_32_level_ab_partition_decodes_pixel_exact";
10067 if !have_ffmpeg() {
10068 eprintln!("SKIP {NAME}: no ffmpeg");
10069 return;
10070 }
10071 if !have_aomenc() {
10072 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10073 return;
10074 }
10075 ten_bit_tool_gate(
10076 NAME,
10077 256,
10078 256,
10079 1,
10080 &[
10081 "--ec-fixture-noise",
10082 "--cq-level=45",
10083 "--limit=1",
10084 "--kf-max-dist=0",
10085 "--enable-1to4-partitions=0",
10086 "--enable-filter-intra=0",
10087 "--enable-smooth-intra=0",
10088 "--enable-paeth-intra=0",
10089 "--enable-directional-intra=0",
10090 "--enable-angle-delta=0",
10091 "--enable-tx-size-search=0",
10092 "--enable-cdef=0",
10093 "--enable-restoration=0",
10094 "--enable-palette=0",
10095 "--enable-intrabc=0",
10096 "--enable-cfl-intra=0",
10097 "--enable-ref-frame-mvs=0",
10098 // last wins: the flags under test go after the base recipe
10099 "--enable-rect-partitions=1",
10100 "--enable-ab-partitions=1",
10101 "--min-partition-size=16",
10102 "--max-partition-size=32",
10103 ],
10104 &LR_SEEDS,
10105 &[
10106 ("HORZ_A_32", crate::decode::intra_horz_a_hits),
10107 ("HORZ_B_32", crate::decode::intra_horz_b_hits),
10108 ("VERT_A_32", crate::decode::intra_vert_a_hits),
10109 ("VERT_B_32", crate::decode::intra_vert_b_hits),
10110 ],
10111 );
10112 }
10113
10114 /// lane-cwarp r1: a real `--enable-global-motion=1 --enable-dist-wtd-comp=1`
10115 /// stream over a rotating/zooming source, so a `GLOBAL_GLOBALMV` compound
10116 /// block lands under a ROTZOOM/AFFINE model and each of its two references
10117 /// is predicted through its OWN global warp
10118 /// (`crate::warp::warp_affine_compound`, libaom `av1_warp_plane` with
10119 /// `conv_params->is_compound`) rather than translationally. Before r1 that
10120 /// path was SILENTLY WRONG -- no refusal named it, both taps went through
10121 /// `mc::predict_compound_intermediate`. `compound_warp_hits() > 0` is a
10122 /// hard assert: a run where the encoder never emitted one proves nothing.
10123 /// A decode error or a pixel mismatch is a FAILURE, never a skip.
10124 fn run_compound_global_warp_gate(name: &str, ten_bit: bool) {
10125 let _gate_lock = lock_gate_counters();
10126 assert!(have_ffmpeg(), "{name}: ffmpeg required");
10127 assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
10128 let (width, height, frame_count) = (64usize, 64usize, 24usize);
10129 let before = crate::decode::compound_warp_hits();
10130 let mut matched = 0u32;
10131 let mut named_refusals = 0u32;
10132 let mut attempts = 0u32;
10133 for cq in [32u32, 45, 55] {
10134 for (i, rate) in [0.010f64, 0.022].iter().enumerate() {
10135 attempts += 1;
10136 let duration = frame_count as f64 / 25.0;
10137 // A rotation about the frame centre plus a slow zoom is what
10138 // aomenc's global-motion search fits a ROTZOOM/AFFINE model to;
10139 // mandelbrot gives it real, non-flat texture to track.
10140 let source = format!(
10141 "mandelbrot=size={w}x{h}:rate=25:start_x={sx}:start_y=-0.4,\
10142 rotate=a={rate}*n:ow={w}:oh={h}:c=black,scale={width}:{height}",
10143 w = width * 2,
10144 h = height * 2,
10145 sx = -0.6 + 0.01 * (i as f64),
10146 );
10147 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
10148 let y4m = Command::new("ffmpeg")
10149 .args([
10150 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
10151 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
10152 "-f", "yuv4mpegpipe", "-",
10153 ])
10154 .stdin(Stdio::null())
10155 .stdout(Stdio::piped())
10156 .stderr(Stdio::piped())
10157 .output()
10158 .expect("ffmpeg failed to run");
10159 assert!(
10160 y4m.status.success(),
10161 "ffmpeg fixture: {}",
10162 String::from_utf8_lossy(&y4m.stderr)
10163 );
10164 let cq_arg = format!("--cq-level={cq}");
10165 let mut args: Vec<&str> = vec![
10166 "--codec=av1",
10167 "--passes=1",
10168 "--end-usage=q",
10169 &cq_arg,
10170 "--cpu-used=0",
10171 "--kf-max-dist=1000",
10172 "--threads=1",
10173 "--row-mt=0",
10174 "--auto-alt-ref=1",
10175 "--lag-in-frames=25",
10176 "--enable-fwd-kf=0",
10177 "--enable-order-hint=1",
10178 // the two tools this gate exists for
10179 "--enable-global-motion=1",
10180 "--enable-dist-wtd-comp=1",
10181 "--enable-warped-motion=1",
10182 "--enable-obmc=1",
10183 "--enable-masked-comp=1",
10184 "--enable-onesided-comp=0",
10185 "--enable-interintra-comp=1",
10186 "--enable-interintra-wedge=0",
10187 "--enable-smooth-interintra=1",
10188 "--tune-content=default",
10189 // partition/intra tools this decoder does not code yet --
10190 // same exclusion list every compound gate carries.
10191 "--enable-rect-partitions=0",
10192 "--enable-ab-partitions=0",
10193 "--enable-1to4-partitions=0",
10194 "--enable-filter-intra=0",
10195 "--enable-smooth-intra=0",
10196 "--enable-paeth-intra=0",
10197 "--enable-directional-intra=0",
10198 "--enable-angle-delta=0",
10199 "--enable-tx-size-search=0",
10200 "--enable-cdef=0",
10201 "--enable-restoration=0",
10202 "--max-partition-size=32",
10203 "--min-partition-size=32",
10204 "--enable-palette=0",
10205 "--enable-intrabc=0",
10206 "--enable-cfl-intra=0",
10207 "--enable-ref-frame-mvs=0",
10208 ];
10209 if ten_bit {
10210 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
10211 }
10212 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
10213 let mut child = Command::new(aomenc_path())
10214 .args(&args)
10215 .stdin(Stdio::piped())
10216 .stdout(Stdio::piped())
10217 .stderr(Stdio::piped())
10218 .spawn()
10219 .expect("aomenc failed to start");
10220 child
10221 .stdin
10222 .take()
10223 .expect("aomenc stdin")
10224 .write_all(&y4m.stdout)
10225 .expect("writing y4m to aomenc");
10226 let out = child.wait_with_output().expect("aomenc failed to run");
10227 assert!(
10228 out.status.success(),
10229 "aomenc refused the fixture: {}",
10230 String::from_utf8_lossy(&out.stderr)
10231 );
10232 let stream = out.stdout;
10233 let frames = match decode_stream(&stream) {
10234 Err(e) => {
10235 let msg = e.to_string();
10236 assert!(
10237 msg.contains("unsupported"),
10238 "{name} failed outright, not a named refusal (cq {cq}): {msg}"
10239 );
10240 assert!(
10241 !msg.contains("warp"),
10242 "{name} refused on warp (cq {cq}) -- warp decode is ported: {msg}"
10243 );
10244 named_refusals += 1;
10245 eprintln!("{name} cq {cq} rate {rate} refusal: {msg}");
10246 continue;
10247 }
10248 Ok(frames) => frames,
10249 };
10250 let want = if ten_bit {
10251 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
10252 } else {
10253 ffmpeg_decode_sequence(&stream, width, height, frame_count)
10254 };
10255 assert_eq!(frames.len(), frame_count);
10256 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
10257 && frames
10258 .iter()
10259 .zip(&want)
10260 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
10261 {
10262 std::fs::write(&path, &stream).expect("writing pinned stream");
10263 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
10264 }
10265 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
10266 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq})");
10267 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq})");
10268 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq})");
10269 }
10270 matched += 1;
10271 }
10272 }
10273 let hits = crate::decode::compound_warp_hits() - before;
10274 eprintln!(
10275 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
10276 compound_warp_hits={hits}"
10277 );
10278 assert!(
10279 hits > 0,
10280 "{name}: no compound block was predicted through a per-ref global warp \
10281 ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous"
10282 );
10283 assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran");
10284 }
10285
10286 /// lane-fimv r1 (class `wrong-alphabet-same-value`): libaom
10287 /// `motion_mode_allowed` (blockd.h ~1484) only returns `WARPED_CAUSAL`
10288 /// when `!xd->cur_frame_force_integer_mv`, so on a frame whose header set
10289 /// `force_integer_mv` an otherwise warp-eligible block reads the 2-symbol
10290 /// `obmc_cdf`, not the 3-symbol `motion_mode_cdf`. This decoder read the
10291 /// 3-symbol alphabet there (silent tile desync, no refusal named it).
10292 ///
10293 /// The fixture is screen content that is mostly static with only
10294 /// whole-pixel motion, which is exactly what aomenc's own
10295 /// `av1_is_integer_mv` (`encoder_utils.c:1357`, >=80% of blocks matching
10296 /// their collocated block) needs to set `cur_frame_force_integer_mv`
10297 /// under `--tune-content=screen` (seq `force_integer_mv == 2`, adaptive:
10298 /// `encoder.c:4171`). Two hard asserts, both class
10299 /// `gate-blind-to-feature`: at least one decoded frame header carried
10300 /// `force_integer_mv = 1`, and at least one block took the 2-symbol
10301 /// alphabet where `allow_warped_motion = 1` and `num_proj_ref >= 1` would
10302 /// have picked the 3-symbol one. A decode error or a pixel mismatch is a
10303 /// FAILURE, never a skip.
10304 #[track_caller]
10305 fn run_fimv_motion_mode_gate(name: &str, ten_bit: bool) {
10306 let _gate_lock = lock_gate_counters();
10307 assert!(have_ffmpeg(), "{name}: ffmpeg required");
10308 assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
10309 let (width, height, frame_count) = (64usize, 64usize, 20usize);
10310 let fimv_frames_before = crate::decode::fimv_frame_hits();
10311 let alphabet_before = crate::decode::fimv_alphabet_hits();
10312 let mut matched = 0u32;
10313 let mut named_refusals = 0u32;
10314 let mut attempts = 0u32;
10315 let mut refusals = Vec::new();
10316 for cq in [32u32, 45, 55] {
10317 for step in [4u32, 8] {
10318 attempts += 1;
10319 // lane-fimv r1: per-attempt snapshots. The aggregate
10320 // assertions below are satisfied by a single lucky cq/step
10321 // cell; these prove EVERY attempt that decoded and
10322 // pixel-compared really carried the header state and the
10323 // forced alphabet under test (class gate-blind-to-feature).
10324 let attempt_fimv_before = crate::decode::fimv_frame_hits();
10325 let attempt_alphabet_before = crate::decode::fimv_alphabet_hits();
10326 let duration = frame_count as f64 / 25.0;
10327 // Flat screen-content tiles with hard edges, translating by a
10328 // whole number of pixels per frame: static enough for
10329 // `av1_is_integer_mv`, moving enough for a real inter block
10330 // with overlappable neighbours.
10331 let source = format!(
10332 "color=c=black:s={width}x{height}:r=25,\
10333 drawbox=x='8+{step}*mod(trunc(t*25)\\,3)':y=8:w=20:h=20:color=white:t=fill,\
10334 drawbox=x=36:y='6+{step}*mod(trunc(t*25)+1\\,3)':w=16:h=16:color=0x808080:t=fill,\
10335 drawbox=x=4:y=44:w=56:h=12:color=0xC0C0C0:t=fill"
10336 );
10337 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
10338 let y4m = Command::new("ffmpeg")
10339 .args([
10340 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
10341 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
10342 "-f", "yuv4mpegpipe", "-",
10343 ])
10344 .stdin(Stdio::null())
10345 .stdout(Stdio::piped())
10346 .stderr(Stdio::piped())
10347 .output()
10348 .expect("ffmpeg failed to run");
10349 assert!(
10350 y4m.status.success(),
10351 "ffmpeg fixture: {}",
10352 String::from_utf8_lossy(&y4m.stderr)
10353 );
10354 let cq_arg = format!("--cq-level={cq}");
10355 let mut args: Vec<&str> = vec![
10356 "--codec=av1",
10357 "--passes=1",
10358 "--end-usage=q",
10359 &cq_arg,
10360 "--cpu-used=0",
10361 "--kf-max-dist=1000",
10362 "--threads=1",
10363 "--row-mt=0",
10364 // single reference only: the 10-bit compound MC defect
10365 // (see `a_real_compound_global_warp_10bit_stream_...`)
10366 // is unrelated to this lane and would mask it.
10367 "--auto-alt-ref=0",
10368 "--lag-in-frames=0",
10369 "--enable-fwd-kf=0",
10370 "--enable-order-hint=1",
10371 // the flag combination this gate exists for: warp allowed
10372 // by the header, OBMC available, global motion off (so the
10373 // GLOBALMV suppression is not what picks the alphabet).
10374 "--tune-content=screen",
10375 "--enable-warped-motion=1",
10376 "--enable-obmc=1",
10377 "--enable-global-motion=0",
10378 "--enable-masked-comp=0",
10379 "--enable-onesided-comp=0",
10380 "--enable-interintra-comp=0",
10381 "--enable-interintra-wedge=0",
10382 "--enable-smooth-interintra=0",
10383 "--enable-dist-wtd-comp=0",
10384 // partition/intra tools this decoder does not code yet --
10385 // the same exclusion list every inter gate here carries.
10386 "--enable-rect-partitions=0",
10387 "--enable-ab-partitions=0",
10388 "--enable-1to4-partitions=0",
10389 "--enable-filter-intra=0",
10390 "--enable-smooth-intra=0",
10391 "--enable-paeth-intra=0",
10392 "--enable-directional-intra=0",
10393 "--enable-angle-delta=0",
10394 "--enable-tx-size-search=0",
10395 "--enable-cdef=0",
10396 "--enable-restoration=0",
10397 "--max-partition-size=32",
10398 "--min-partition-size=32",
10399 "--enable-palette=0",
10400 "--enable-intrabc=0",
10401 "--enable-cfl-intra=0",
10402 "--enable-ref-frame-mvs=0",
10403 ];
10404 if ten_bit {
10405 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
10406 }
10407 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
10408 let mut child = Command::new(aomenc_path())
10409 .args(&args)
10410 .stdin(Stdio::piped())
10411 .stdout(Stdio::piped())
10412 .stderr(Stdio::piped())
10413 .spawn()
10414 .expect("aomenc failed to start");
10415 child
10416 .stdin
10417 .take()
10418 .expect("aomenc stdin")
10419 .write_all(&y4m.stdout)
10420 .expect("writing y4m to aomenc");
10421 let out = child.wait_with_output().expect("aomenc failed to run");
10422 assert!(
10423 out.status.success(),
10424 "aomenc refused the fixture: {}",
10425 String::from_utf8_lossy(&out.stderr)
10426 );
10427 let stream = out.stdout;
10428 let frames = match decode_stream(&stream) {
10429 Err(e) => {
10430 let msg = e.to_string();
10431 assert!(
10432 msg.contains("unsupported"),
10433 "{name} failed outright (cq {cq} step {step}): {msg}"
10434 );
10435 named_refusals += 1;
10436 refusals.push(format!("cq {cq} step {step}: {msg}"));
10437 continue;
10438 }
10439 Ok(frames) => frames,
10440 };
10441 let want = if ten_bit {
10442 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
10443 } else {
10444 ffmpeg_decode_sequence(&stream, width, height, frame_count)
10445 };
10446 assert_eq!(frames.len(), frame_count);
10447 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
10448 && frames
10449 .iter()
10450 .zip(&want)
10451 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
10452 {
10453 std::fs::write(&path, &stream).expect("writing pinned stream");
10454 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
10455 }
10456 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
10457 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq} step {step})");
10458 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq} step {step})");
10459 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq} step {step})");
10460 }
10461 assert!(
10462 crate::decode::fimv_frame_hits() > attempt_fimv_before,
10463 "{name} (cq {cq} step {step}): decoded and compared all \
10464 frames but no frame header had force_integer_mv=1 -- \
10465 this attempt is vacuous"
10466 );
10467 assert!(
10468 crate::decode::fimv_alphabet_hits() > attempt_alphabet_before,
10469 "{name} (cq {cq} step {step}): no block was forced onto the \
10470 2-symbol obmc alphabet by force_integer_mv while \
10471 allow_warped_motion=1 and num_proj_ref>=1 -- this attempt \
10472 is vacuous"
10473 );
10474 matched += 1;
10475 }
10476 }
10477 let fimv_frames = crate::decode::fimv_frame_hits() - fimv_frames_before;
10478 let alphabet = crate::decode::fimv_alphabet_hits() - alphabet_before;
10479 eprintln!(
10480 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
10481 force_integer_mv frames={fimv_frames}, forced-2-symbol blocks={alphabet}\n{}",
10482 refusals.join("\n")
10483 );
10484 assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran");
10485 assert!(
10486 fimv_frames > 0,
10487 "{name}: no decoded frame header had force_integer_mv=1 \
10488 ({matched} matches of {attempts}) -- gate vacuous"
10489 );
10490 assert!(
10491 alphabet > 0,
10492 "{name}: no block read the 2-symbol obmc alphabet where \
10493 allow_warped_motion=1 and num_proj_ref>=1 would have picked the \
10494 3-symbol motion_mode alphabet -- gate vacuous"
10495 );
10496 }
10497
10498 /// 8-bit arm of [`run_fimv_motion_mode_gate`].
10499 #[test]
10500 fn a_real_force_integer_mv_warp_stream_decodes_pixel_exact() {
10501 run_fimv_motion_mode_gate("a_real_force_integer_mv_warp_stream_decodes_pixel_exact", false);
10502 }
10503
10504 /// 10-bit arm of [`run_fimv_motion_mode_gate`] -- both of his films are
10505 /// `yuv420p10le`.
10506 #[test]
10507 fn a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact() {
10508 run_fimv_motion_mode_gate(
10509 "a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact",
10510 true,
10511 );
10512 }
10513
10514 /// 8-bit arm of [`run_compound_global_warp_gate`].
10515 #[test]
10516 fn a_real_compound_global_warp_stream_decodes_pixel_exact() {
10517 run_compound_global_warp_gate("a_real_compound_global_warp_stream_decodes_pixel_exact", false);
10518 }
10519
10520 /// 10-bit arm of [`run_compound_global_warp_gate`] -- both of his films are
10521 /// `yuv420p10le`, and `warp_affine`'s `bd` was hardcoded 8 before r1.
10522 ///
10523 /// IGNORED, blocked by a PRE-EXISTING 10-bit COMPOUND defect this lane did
10524 /// not introduce and does not own. Ablation run by lane-cwarp r1 on this
10525 /// very recipe: with `--enable-global-motion=0 --enable-warped-motion=0`
10526 /// (no warp of any kind reachable) the 10-bit stream STILL mismatches at
10527 /// frame 1 luma, cq 32; with `--auto-alt-ref=0 --lag-in-frames=0
10528 /// --enable-dist-wtd-comp=0` (single-reference 10-bit inter only) the same
10529 /// recipe is 6/6 pixel-exact. So: 10-bit single-ref inter is exact, 10-bit
10530 /// compound is not. `mc::diffwtd_mask`'s missing `(bd - 8)` round term was
10531 /// found and fixed while bisecting this, but is NOT the whole defect.
10532 /// Un-ignore the moment the 10-bit compound path is fixed -- the warp
10533 /// wiring under test here is bit-depth generic already.
10534 #[test]
10535 #[ignore = "blocked by a pre-existing 10-bit compound MC defect (see doc comment)"]
10536 fn a_real_compound_global_warp_10bit_stream_decodes_pixel_exact() {
10537 run_compound_global_warp_gate(
10538 "a_real_compound_global_warp_10bit_stream_decodes_pixel_exact",
10539 true,
10540 );
10541 }
10542
10543 /// lane-mcomp64 r1: at 64x64 `av1_is_wedge_used` is false
10544 /// (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`), so libaom's
10545 /// `read_compound_type` codes NO `compound_type` symbol and INFERS
10546 /// `COMPOUND_DIFFWTD`; only the 1-bit `mask_type` literal follows. This
10547 /// decoder used to refuse such a block by name ("a masked compound 64x64
10548 /// inter block..."), because reading the symbol would have desynced.
10549 ///
10550 /// The recipe pins every block to 64x64 (`--sb-size=64
10551 /// --max-partition-size=64 --min-partition-size=64`) with masked compound
10552 /// on and distance-weighted compound off, so the only way a
10553 /// `comp_group_idx == 1` block can be coded is through the inferred arm.
10554 /// `diffwtd_inferred_hits` is snapshotted PER ATTEMPT and only accumulated
10555 /// for attempts that decoded AND pixel-compared (class
10556 /// `counter-from-refused-stream`), and is hard-asserted at the end. A
10557 /// decode error or a pixel mismatch is a FAILURE, never a skip.
10558 #[track_caller]
10559 fn run_diffwtd_inferred_64x64_gate(name: &str, ten_bit: bool) {
10560 let _gate_lock = lock_gate_counters();
10561 assert!(have_ffmpeg(), "{name}: ffmpeg required");
10562 assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
10563 let (width, height, frame_count) = (128usize, 128usize, 16usize);
10564 let mut matched = 0u32;
10565 let mut named_refusals = 0u32;
10566 let mut attempts = 0u32;
10567 let mut fired = 0usize;
10568 let mut refusals: Vec<String> = Vec::new();
10569 for cq in [32u32, 45, 55] {
10570 for (i, zoom) in [0.004f64, 0.010].iter().enumerate() {
10571 attempts += 1;
10572 let attempt_before = crate::decode::diffwtd_inferred_hits();
10573 let duration = frame_count as f64 / 25.0;
10574 // Hard-edged, moving content: a difference-weighted mask only
10575 // wins where the two references genuinely disagree over part
10576 // of a 64x64 block (a smooth `gradients` source measured
10577 // diffwtd_hits == 0, memory `gate-blind-to-feature`).
10578 let source = format!(
10579 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y=-0.4:\
10580 end_scale=0.3:maxiter=200,\
10581 noise=alls=6:allf=t+u:all_seed={seed}",
10582 sx = -0.6 + zoom * (i as f64 + 1.0),
10583 seed = 1000 + cq,
10584 );
10585 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
10586 let y4m = Command::new("ffmpeg")
10587 .args([
10588 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
10589 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
10590 "-f", "yuv4mpegpipe", "-",
10591 ])
10592 .stdin(Stdio::null())
10593 .stdout(Stdio::piped())
10594 .stderr(Stdio::piped())
10595 .output()
10596 .expect("ffmpeg failed to run");
10597 assert!(
10598 y4m.status.success(),
10599 "ffmpeg fixture: {}",
10600 String::from_utf8_lossy(&y4m.stderr)
10601 );
10602 let cq_arg = format!("--cq-level={cq}");
10603 let mut args: Vec<&str> = vec![
10604 "--codec=av1",
10605 "--passes=1",
10606 "--end-usage=q",
10607 &cq_arg,
10608 "--cpu-used=0",
10609 "--kf-max-dist=1000",
10610 "--threads=1",
10611 "--row-mt=0",
10612 "--auto-alt-ref=1",
10613 "--lag-in-frames=16",
10614 "--enable-fwd-kf=0",
10615 "--enable-order-hint=1",
10616 // the tools this gate exists for: masked compound on, the
10617 // difference-weighted arm on, the distance-weighted
10618 // competitor off so comp_group_idx==1 is the encoder's
10619 // only masked choice at a size where wedge does not exist.
10620 "--enable-masked-comp=1",
10621 "--enable-diff-wtd-comp=1",
10622 "--enable-dist-wtd-comp=0",
10623 "--enable-onesided-comp=0",
10624 "--enable-interintra-comp=0",
10625 "--enable-global-motion=0",
10626 "--enable-warped-motion=1",
10627 "--enable-obmc=1",
10628 "--tune-content=default",
10629 // partition/intra tools this decoder does not code yet --
10630 // same exclusion list every compound gate carries.
10631 "--enable-rect-partitions=0",
10632 "--enable-ab-partitions=0",
10633 "--enable-1to4-partitions=0",
10634 "--enable-filter-intra=0",
10635 "--enable-smooth-intra=0",
10636 "--enable-paeth-intra=0",
10637 "--enable-directional-intra=0",
10638 "--enable-angle-delta=0",
10639 "--enable-tx-size-search=0",
10640 "--enable-cdef=0",
10641 "--enable-restoration=0",
10642 "--enable-palette=0",
10643 "--enable-intrabc=0",
10644 "--enable-cfl-intra=0",
10645 "--enable-ref-frame-mvs=0",
10646 // every block is a whole 64x64 superblock: the ONLY size
10647 // where compound_type is inferred rather than coded.
10648 "--sb-size=64",
10649 "--max-partition-size=64",
10650 "--min-partition-size=64",
10651 ];
10652 if ten_bit {
10653 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
10654 }
10655 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
10656 let mut child = Command::new(aomenc_path())
10657 .args(&args)
10658 .stdin(Stdio::piped())
10659 .stdout(Stdio::piped())
10660 .stderr(Stdio::piped())
10661 .spawn()
10662 .expect("aomenc failed to start");
10663 child
10664 .stdin
10665 .take()
10666 .expect("aomenc stdin")
10667 .write_all(&y4m.stdout)
10668 .expect("writing y4m to aomenc");
10669 let out = child.wait_with_output().expect("aomenc failed to run");
10670 assert!(
10671 out.status.success(),
10672 "aomenc refused the fixture: {}",
10673 String::from_utf8_lossy(&out.stderr)
10674 );
10675 let stream = out.stdout;
10676 let frames = match decode_stream(&stream) {
10677 Err(e) => {
10678 let msg = e.to_string();
10679 assert!(
10680 msg.contains("unsupported"),
10681 "{name} failed outright, not a named refusal (cq {cq}): {msg}"
10682 );
10683 assert!(
10684 !msg.contains("masked compound 64x64"),
10685 "{name} refused the inferred-DIFFWTD 64x64 block (cq {cq}) -- \
10686 that refusal is lifted, this is forbidden: {msg}"
10687 );
10688 named_refusals += 1;
10689 refusals.push(msg.clone());
10690 eprintln!("{name} cq {cq} variant {i} refusal: {msg}");
10691 continue;
10692 }
10693 Ok(frames) => frames,
10694 };
10695 let want = if ten_bit {
10696 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
10697 } else {
10698 ffmpeg_decode_sequence(&stream, width, height, frame_count)
10699 };
10700 assert_eq!(frames.len(), frame_count);
10701 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
10702 && frames
10703 .iter()
10704 .zip(&want)
10705 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
10706 {
10707 std::fs::write(&path, &stream).expect("writing pinned stream");
10708 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
10709 }
10710 for (f, (got, want)) in frames.iter().zip(&want).enumerate() {
10711 assert_eq!(got.y, want.y, "{name} frame {f} luma vs ffmpeg (cq {cq})");
10712 assert_eq!(got.u, want.u, "{name} frame {f} U vs ffmpeg (cq {cq})");
10713 assert_eq!(got.v, want.v, "{name} frame {f} V vs ffmpeg (cq {cq})");
10714 }
10715 // decoded AND compared: only now does this attempt's own
10716 // inferred-DIFFWTD count mean anything.
10717 fired += crate::decode::diffwtd_inferred_hits() - attempt_before;
10718 matched += 1;
10719 }
10720 }
10721 eprintln!(
10722 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
10723 diffwtd_inferred_hits (decoded+compared attempts only)={fired}"
10724 );
10725 assert!(matched > 0, "{name}: every attempt refused ({refusals:?}) -- no pixel compare ran");
10726 assert!(
10727 fired > 0,
10728 "{name}: no inferred-DIFFWTD 64x64 block fired on a compared attempt \
10729 ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous"
10730 );
10731 }
10732
10733 /// 8-bit arm of [`run_diffwtd_inferred_64x64_gate`].
10734 #[test]
10735 fn a_real_aomenc_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact() {
10736 run_diffwtd_inferred_64x64_gate(
10737 "a_real_aomenc_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact",
10738 false,
10739 );
10740 }
10741
10742 /// 10-bit arm of [`run_diffwtd_inferred_64x64_gate`] -- both of his films
10743 /// are `yuv420p10le`.
10744 #[test]
10745 fn a_real_aomenc_10bit_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact() {
10746 run_diffwtd_inferred_64x64_gate(
10747 "a_real_aomenc_10bit_stream_with_a_diffwtd_compound_64x64_block_decodes_pixel_exact",
10748 true,
10749 );
10750 }
10751
10752 /// lane-maskcomp r2 / lane-wedge r3: `--enable-masked-comp=1` streams
10753 /// must consume `compound_type`/`wedge_idx`/`wedge_sign`/`mask_type`
10754 /// entropy-exact AND build the real blend, DIFFWTD or WEDGE --
10755 /// `masked_compound_hits() > 0` is a hard assert and BOTH
10756 /// `COMPOUND_DIFFWTD` and `COMPOUND_WEDGE` refusals are now FORBIDDEN
10757 /// (matches interintra's own gate). r3: `--enable-dist-wtd-comp=0`
10758 /// (forces the masked choice toward wedge when comp_group_idx==1) plus
10759 /// a hard-diagonal-edge `geq` source (wedge's OBLIQUE directions favor
10760 /// a real diagonal edge over the r2 gradients content) to fire
10761 /// COMPOUND_WEDGE live; `wedge_hits()` is soft-skipped (not hard
10762 /// asserted) on a zero-hit run -- the recipe search is not proven to
10763 /// converge every run, see charter's "if no recipe fires" fallback.
10764 #[test]
10765 fn a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact() {
10766 const NAME: &str = "a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact";
10767 let _gate_lock = lock_gate_counters();
10768 if !have_ffmpeg() {
10769 eprintln!("SKIP {NAME}: no ffmpeg");
10770 return;
10771 }
10772 if !have_aomenc() {
10773 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10774 return;
10775 }
10776 let (width, height, frame_count) = (64usize, 64usize, 24usize);
10777 let mut named_refusals = 0u32;
10778 let mut matched = 0u32;
10779 let n_attempts: u32 = std::env::var("EC_MASKCOMP_GATE_ATTEMPTS")
10780 .ok()
10781 .and_then(|s| s.parse().ok())
10782 .unwrap_or(80);
10783 for attempt in 0..n_attempts {
10784 let seed = 42 + attempt;
10785 let duration = frame_count as f64 / 25.0;
10786 // lane-wedge r3: a hard diagonal edge (not a smooth gradient)
10787 // is the content wedge's OBLIQUE master masks are shaped for --
10788 // `mandelbrot`'s pan position varies the edge angle/position
10789 // across attempts the way the r2 gradients seed did.
10790 let source = format!(
10791 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
10792 sx = -0.6 + 0.005 * (attempt as f64),
10793 sy = -0.4 + 0.005 * (attempt as f64)
10794 );
10795 let y4m = Command::new("ffmpeg")
10796 .args([
10797 "-v",
10798 "error",
10799 "-f",
10800 "lavfi",
10801 "-i",
10802 &source,
10803 "-t",
10804 &duration.to_string(),
10805 "-pix_fmt",
10806 "yuv420p",
10807 "-f",
10808 "yuv4mpegpipe",
10809 "-",
10810 ])
10811 .stdin(Stdio::null())
10812 .stdout(Stdio::piped())
10813 .stderr(Stdio::piped())
10814 .output()
10815 .expect("ffmpeg failed to run");
10816 assert!(
10817 y4m.status.success(),
10818 "ffmpeg fixture: {}",
10819 String::from_utf8_lossy(&y4m.stderr)
10820 );
10821 let args: Vec<&str> = vec![
10822 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
10823 // occurrence, so overrides go before the base list).
10824 "--enable-diff-wtd-comp=1",
10825 "--codec=av1",
10826 "--passes=1",
10827 "--end-usage=q",
10828 "--cq-level=45",
10829 "--cpu-used=0",
10830 "--kf-max-dist=1000",
10831 "--threads=1",
10832 "--row-mt=0",
10833 "--auto-alt-ref=1",
10834 "--lag-in-frames=16",
10835 "--enable-fwd-kf=0",
10836 "--enable-order-hint=1",
10837 "--enable-warped-motion=1",
10838 // r3: mandelbrot's pan/zoom triggers aomenc's single-ref
10839 // GLOBALMV global-motion search (a capability distinct from
10840 // and outside this lane's scope) -- off, matching this
10841 // gate's own goal of exercising masked compound, not GM.
10842 "--enable-global-motion=0",
10843 "--enable-obmc=1",
10844 "--tune-content=default",
10845 "--enable-masked-comp=1",
10846 // r3: force the masked choice toward wedge (r2 always set
10847 // this =1; distance-weighted compound competes with the
10848 // wedge/diffwtd choice for the same comp_group_idx==1 slot).
10849 "--enable-dist-wtd-comp=0",
10850 "--enable-interintra-comp=1",
10851 "--enable-onesided-comp=0",
10852 "--enable-interintra-wedge=0",
10853 "--enable-smooth-interintra=1",
10854 "--enable-rect-partitions=0",
10855 "--enable-ab-partitions=0",
10856 "--enable-1to4-partitions=0",
10857 "--enable-filter-intra=0",
10858 "--enable-smooth-intra=0",
10859 "--enable-paeth-intra=0",
10860 "--enable-directional-intra=0",
10861 "--enable-angle-delta=0",
10862 "--enable-tx-size-search=0",
10863 "--enable-cdef=0",
10864 "--enable-restoration=0",
10865 "--max-partition-size=32",
10866 "--min-partition-size=32",
10867 "--enable-palette=0",
10868 "--enable-intrabc=0",
10869 "--enable-cfl-intra=0",
10870 "--enable-ref-frame-mvs=0",
10871 "--obu",
10872 "-o",
10873 "-",
10874 "-",
10875 ];
10876 let mut child = Command::new(aomenc_path())
10877 .args(&args)
10878 .stdin(Stdio::piped())
10879 .stdout(Stdio::piped())
10880 .stderr(Stdio::piped())
10881 .spawn()
10882 .expect("aomenc failed to start");
10883 child
10884 .stdin
10885 .take()
10886 .expect("aomenc stdin")
10887 .write_all(&y4m.stdout)
10888 .expect("writing y4m to aomenc");
10889 let out = child.wait_with_output().expect("aomenc failed to run");
10890 assert!(
10891 out.status.success(),
10892 "aomenc refused the fixture: {}",
10893 String::from_utf8_lossy(&out.stderr)
10894 );
10895 let stream = out.stdout;
10896 let frames = match decode_stream(&stream) {
10897 Err(e) => {
10898 let msg = e.to_string();
10899 assert!(
10900 msg.contains("unsupported"),
10901 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
10902 );
10903 assert!(
10904 !msg.contains("warp"),
10905 "{NAME} refused on warp (seed {seed}) -- warp decode is ported: {msg}"
10906 );
10907 assert!(
10908 !msg.contains("masked COMPOUND_REFERENCE"),
10909 "{NAME} refused a masked-compound block (seed {seed}) -- both DIFFWTD \
10910 and WEDGE blends are ported, this refusal is forbidden: {msg}"
10911 );
10912 assert!(
10913 !msg.contains("interintra"),
10914 "{NAME} refused on interintra (seed {seed}) -- non-wedge \
10915 interintra is ported: {msg}"
10916 );
10917 named_refusals += 1;
10918 eprintln!("seed {seed} refusal: {msg}");
10919 if std::env::var_os("EC_AV1_GATE_DUMP").is_some() {
10920 // r1's self-pin is armed via EC_AV1_GATE_DUMP=<path>
10921 // only for a real pixel MISMATCH below, not for this
10922 // still-expected named refusal.
10923 }
10924 continue;
10925 }
10926 Ok(frames) => frames,
10927 };
10928 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
10929 assert_eq!(frames.len(), frame_count);
10930 let mismatched = frames
10931 .iter()
10932 .zip(&ffmpeg_frames)
10933 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
10934 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
10935 std::fs::write(&path, &stream).expect("writing pinned stream");
10936 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
10937 }
10938 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
10939 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
10940 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
10941 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
10942 }
10943 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
10944 // stream again, comparing EVERY decode-order frame -- the hidden
10945 // (show_frame == 0) alt-ref frames the ffmpeg compare above
10946 // cannot see, because both sides of it emit shown frames only.
10947 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
10948 eprintln!(
10949 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
10950 {hidden_n} hidden, all pixel-exact vs the oracle"
10951 );
10952 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
10953 // libaom's temporal alt-ref filter absorbs this recipe's hidden
10954 // frames, so the compare above is vacuous -- re-encode the same
10955 // fixture with --arnr-maxframes=0 and compare THOSE.
10956 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
10957 eprintln!(
10958 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
10959 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
10960 );
10961 }
10962 matched += 1;
10963 }
10964 // r1: observed flaky at 40 attempts -- aomenc's cpu-used=0 RD is
10965 // run-to-run nondeterministic in whether it ever picks
10966 // comp_group_idx == 1 for this synthetic gradients content, and
10967 // allow_screen_content_tools sometimes eats most of a small seed
10968 // window (class gate-recipe-confound / never-fired-gate, memory).
10969 // 80 attempts is the mitigation, not a fix; a still-zero run here
10970 // is that sampling flake, not a decode regression -- check
10971 // masked_compound_hits/named_refusals in the panic message before
10972 // assuming a real bug.
10973 // r2: DIFFWTD is ported and gated, so a zero-hit run is no longer
10974 // soft-skipped -- hard assert, matching the interintra gate.
10975 assert!(
10976 crate::decode::masked_compound_hits() > 0,
10977 "{NAME}: zero masked-compound blocks fired ({matched} matches, {named_refusals} \
10978 other refusals out of {n_attempts}) -- gate proved nothing this run"
10979 );
10980 // lane-defon r1: `--enable-diff-wtd-comp=1` is now spelled on this
10981 // recipe, so the DIFFWTD half of MASKED_COMPOUND_HITS must fire.
10982 assert!(
10983 crate::decode::diffwtd_hits() > 0,
10984 "{NAME}: zero COMPOUND_DIFFWTD blends ({matched} matches, {named_refusals} \
10985 other refusals out of {n_attempts}) -- --enable-diff-wtd-comp=1 proved nothing"
10986 );
10987 // r3: wedge_hits() is soft-skipped, not hard-asserted -- the recipe
10988 // search (dist-wtd-comp=0 + diagonal mandelbrot content) is not
10989 // proven to fire wedge on every run; charter's fallback is to land
10990 // the checksum-verified codebook + blend with this soft path.
10991 if crate::decode::wedge_hits() == 0 {
10992 eprintln!(
10993 "{NAME}: WARNING wedge_hits()==0 this run -- COMPOUND_WEDGE never fired \
10994 ({matched} matches, {named_refusals} refusals out of {n_attempts}); codebook \
10995 is checksum-verified but unexercised live this run"
10996 );
10997 }
10998 eprintln!(
10999 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
11000 out of {n_attempts}, masked_compound_hits={} wedge_hits={}",
11001 crate::decode::masked_compound_hits(),
11002 crate::decode::wedge_hits()
11003 );
11004 }
11005
11006
11007 /// lane-lr r3: proves stage 1/2's exit criterion -- a real
11008 /// `--enable-restoration=1` aomenc stream must survive the whole
11009 /// partition walk (every symbol read entropy-exact) and land on the
11010 /// NEW, narrowed refusal ("read but not applied"), never desync into
11011 /// some other named refusal or an outright decode panic. Multi-superblock
11012 /// fixture (192x128 = 3x2 SBs of 64px) per the charter's own trap
11013 /// warning -- a single-SB fixture can never re-enter `read_lr` a second
11014 /// time and would leave `SWITCHABLE_HITS`/etc. proving only one call
11015 /// site, not the per-SB loop.
11016 #[test]
11017 fn a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly() {
11018 const NAME: &str = "a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly";
11019 let _gate_lock = lock_gate_counters();
11020 if !have_ffmpeg() {
11021 eprintln!("SKIP {NAME}: no ffmpeg");
11022 return;
11023 }
11024 if !have_aomenc() {
11025 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11026 return;
11027 }
11028 let (width, height) = (192usize, 128usize);
11029 let n_attempts: u32 = std::env::var("EC_LR_GATE_ATTEMPTS")
11030 .ok()
11031 .and_then(|s| s.parse().ok())
11032 .unwrap_or(40);
11033 let mut lr_refusals = 0u32;
11034 let mut other_refusals = Vec::new();
11035 for attempt in 0..n_attempts {
11036 let seed = 42 + attempt;
11037 // Diagnosis knob: which content makes RD pick an 8x16/16x8 strip
11038 // AND filter intra on it is a search (see lanes/fistrip-r1.report.md).
11039 let source = match std::env::var("EC_FISTRIP_SRC").unwrap_or_default().as_str() {
11040 "bars" => format!("smptebars=size={width}x{height}:duration=0.04:rate=25"),
11041 "src2" => format!("testsrc2=size={width}x{height}:duration=0.04:rate=25"),
11042 "noise" => format!(
11043 "nullsrc=size={width}x{height}:duration=0.04:rate=25,geq=random(1)*255:128:128"
11044 ),
11045 _ => gradients_source(seed, width, height, "duration=0.04:rate=25"),
11046 };
11047 let y4m = Command::new("ffmpeg")
11048 .args(["-v", "error", "-f", "lavfi", "-i"])
11049 .arg(&source)
11050 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
11051 .stdin(Stdio::null())
11052 .stdout(Stdio::piped())
11053 .stderr(Stdio::piped())
11054 .output()
11055 .expect("ffmpeg failed to run");
11056 assert!(
11057 y4m.status.success(),
11058 "ffmpeg fixture: {}",
11059 String::from_utf8_lossy(&y4m.stderr)
11060 );
11061 let mut child = Command::new(aomenc_path())
11062 .args([
11063 "--codec=av1",
11064 "--passes=1",
11065 "--end-usage=q",
11066 // r3: a low cq-level (high quality/bitrate) is load-bearing --
11067 // sampled live (2026-08-30) that aomenc's RD only ever picks a
11068 // non-`RESTORE_NONE` frame_restoration_type at cq-level<=20 for
11069 // this fixture; cq-level=45 (this gate's sibling gates' usual
11070 // value) landed `uses_lr=false` on every attempt.
11071 "--cq-level=15",
11072 "--cpu-used=0",
11073 "--threads=1",
11074 "--row-mt=0",
11075 // r3: this decoder always assumes 64px superblocks
11076 // (`decode.rs` hardcodes `SB_MI=16`, ledger `lane-sb128`
11077 // dead-ends) -- force aomenc to match rather than risk
11078 // the unrelated sb128 gap eating this gate's own window.
11079 "--sb-size=64",
11080 "--enable-restoration=1",
11081 "--enable-cdef=0",
11082 "--enable-rect-partitions=0",
11083 "--enable-ab-partitions=0",
11084 "--enable-1to4-partitions=0",
11085 "--enable-filter-intra=0",
11086 "--enable-smooth-intra=0",
11087 "--enable-paeth-intra=0",
11088 "--enable-tx-size-search=0",
11089 "--max-partition-size=32",
11090 "--min-partition-size=16",
11091 "--enable-palette=0",
11092 "--enable-intrabc=0",
11093 "--enable-cfl-intra=0",
11094 "--enable-ref-frame-mvs=0",
11095 "--enable-warped-motion=0",
11096 "--enable-global-motion=0",
11097 "--enable-masked-comp=0",
11098 "--enable-interintra-comp=0",
11099 "--enable-obmc=0",
11100 "--obu",
11101 "-o",
11102 "-",
11103 "-",
11104 ])
11105 .stdin(Stdio::piped())
11106 .stdout(Stdio::piped())
11107 .stderr(Stdio::piped())
11108 .spawn()
11109 .expect("aomenc failed to start");
11110 child
11111 .stdin
11112 .take()
11113 .expect("aomenc stdin")
11114 .write_all(&y4m.stdout)
11115 .expect("writing y4m to aomenc");
11116 let out = child.wait_with_output().expect("aomenc failed to run");
11117 assert!(
11118 out.status.success(),
11119 "aomenc refused the fixture: {}",
11120 String::from_utf8_lossy(&out.stderr)
11121 );
11122 let stream = out.stdout;
11123 match decode_stream(&stream) {
11124 Ok(pics) => {
11125 // r4: the pixel filters are wired -- every `uses_lr`
11126 // frame must now decode Ok AND match an independent
11127 // decoder pixel-exact, not just refuse cleanly.
11128 let reference = ffmpeg_decode_sequence(&stream, width, height, pics.len());
11129 let mismatched = pics
11130 .iter()
11131 .zip(&reference)
11132 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
11133 // r7: pin a mismatching stream the same way the
11134 // masked-compound gate does -- lets a follow-up round
11135 // decode this exact seed's bytes directly instead of
11136 // re-deriving them from a live 40-attempt sweep.
11137 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
11138 std::fs::write(&path, &stream).expect("writing pinned stream");
11139 eprintln!(
11140 "EC_AV1_GATE_DUMP: wrote mismatching LR stream (seed {seed}) to {path}"
11141 );
11142 }
11143 for (i, (pic, refpic)) in pics.iter().zip(reference.iter()).enumerate() {
11144 assert_eq!(pic.y, refpic.y, "{NAME}: luma mismatch (seed {seed} frame {i})");
11145 assert_eq!(pic.u, refpic.u, "{NAME}: U mismatch (seed {seed} frame {i})");
11146 assert_eq!(pic.v, refpic.v, "{NAME}: V mismatch (seed {seed} frame {i})");
11147 }
11148 lr_refusals += 1; // reused below as "attempts that actually exercised LR pixels"
11149 }
11150 Err(e) => {
11151 let msg = e.to_string();
11152 other_refusals.push(format!("seed {seed}: {msg}"));
11153 }
11154 }
11155 }
11156 assert!(
11157 other_refusals.is_empty(),
11158 "{NAME}: {} attempts failed outright instead of decoding:\n{}",
11159 other_refusals.len(),
11160 other_refusals.join("\n")
11161 );
11162 assert!(
11163 lr_refusals > 0,
11164 "{NAME}: no attempt ever decoded pixel-exact ({n_attempts} attempts)"
11165 );
11166 // Any real (non-`RESTORE_NONE`) filter kind is acceptable proof --
11167 // aomenc's RD picks the frame-level `restoration_type` itself (not
11168 // always `Switchable`; observed `Sgrproj` live at cq-level=15 for
11169 // this fixture), so hard-requiring one specific arm would be the
11170 // gate-recipe-confound class (ledger).
11171 let total_hits = crate::restoration::wiener_hits()
11172 + crate::restoration::sgrproj_hits()
11173 + crate::restoration::switchable_hits();
11174 assert!(
11175 total_hits > 0,
11176 "{NAME}: {lr_refusals} LR refusals fired but read_lr_unit never decoded a real \
11177 (non-None) filter -- gate proved nothing about the symbol path"
11178 );
11179 eprintln!(
11180 "{NAME}: {lr_refusals} LR refusals, {} other refusals out of {n_attempts}, \
11181 wiener_hits={} sgrproj_hits={} switchable_hits={}",
11182 other_refusals.len(),
11183 crate::restoration::wiener_hits(),
11184 crate::restoration::sgrproj_hits(),
11185 crate::restoration::switchable_hits()
11186 );
11187 }
11188
11189 /// r8: decode the ONE pinned stream `EC_AV1_GATE_DUMP` captured in r7
11190 /// (`fixtures/lr-sgr-r7.obu`, seed 46) directly -- not the live
11191 /// 40-attempt sweep, which reuses `v_start` coordinates across unrelated
11192 /// seeds/frames and made r6's captured 9 bytes unprovable. Run with
11193 /// `EC_LR_CALL_DUMP=1` set (see `restoration.rs`'s `apply_sgrproj_stripe`)
11194 /// to get the real window on stderr, call-uniquely keyed to `xqd ==
11195 /// [-16,-32]` rather than any coordinate.
11196 #[test]
11197 #[ignore = "reads a pinned fixture under the gitignored fixtures dir; run manually with EC_LR_CALL_DUMP=1"]
11198 fn pinned_lr_sgr_stream_call_unique_dump() {
11199 let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/lr-sgr-r7.obu");
11200 let stream = std::fs::read(path).expect("reading pinned lr-sgr-r7.obu");
11201 let pics = decode_stream(&stream).expect("pinned lr-sgr-r7.obu must decode");
11202 if have_ffmpeg() {
11203 let reference = ffmpeg_decode_sequence(&stream, 192, 128, pics.len());
11204 for (i, (got, want)) in pics.iter().zip(&reference).enumerate() {
11205 let y_mismatch = got.y != want.y;
11206 let u_mismatch = got.u != want.u;
11207 let v_mismatch = got.v != want.v;
11208 eprintln!(
11209 "frame {i}: y_mismatch={y_mismatch} u_mismatch={u_mismatch} v_mismatch={v_mismatch}"
11210 );
11211 if y_mismatch {
11212 let n = got.y.iter().zip(&want.y).filter(|(a, b)| a != b).count();
11213 eprintln!(" {n} luma bytes differ / {}", got.y.len());
11214 }
11215 if v_mismatch {
11216 let w = 96usize; // chroma plane width (192/2)
11217 for (idx, (a, b)) in got.v.iter().zip(&want.v).enumerate() {
11218 if a != b {
11219 eprintln!(" V[{},{}] got={a} want={b}", idx / w, idx % w);
11220 }
11221 }
11222 }
11223 }
11224 }
11225 }
11226
11227 /// lane-realworld r2: `read_cdef` (spec 5.11.56) ported -- per-superblock
11228 /// `cdef_idx`, wired at all five `skip`-decode sites, `apply_cdef` looks
11229 /// up strength through the grid instead of a hardcoded `[0]`. Structure
11230 /// copied from `a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact`
11231 /// but `--enable-cdef=1` (the one thing that gate turns off) and every
11232 /// *other* filter/mode feature this lane doesn't touch disabled, so a
11233 /// mismatch here can only be attributed to CDEF. `cdef_idx_hits()` is a
11234 /// hard assert -- a run that never reads a real cdef_idx symbol proves
11235 /// nothing (class `gate-blind-to-feature`).
11236 #[test]
11237 fn a_real_aomenc_stream_with_cdef_decodes_pixel_exact() {
11238 const NAME: &str = "a_real_aomenc_stream_with_cdef_decodes_pixel_exact";
11239 let _gate_lock = lock_gate_counters();
11240 if !have_ffmpeg() {
11241 eprintln!("SKIP {NAME}: no ffmpeg");
11242 return;
11243 }
11244 if !have_aomenc() {
11245 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11246 return;
11247 }
11248 // cdef_bits selects among PER-SUPERBLOCK strengths -- a single-SB
11249 // 64x64 frame (the other gates' size) gives aomenc nothing to
11250 // differentiate, so it always writes bits=0 and cdef_idx is never
11251 // read. 128x64 = 2 SBs is the minimum that lets aomenc's RD ever
11252 // pick bits > 0. Multi-SB content at --cpu-used=0 (every other
11253 // gate's setting) makes aomenc pick PARTITION_HORZ_4/VERT_B etc.
11254 // at the top SB level regardless of the ab/1to4-partitions=0
11255 // flags below (a real gap: this decoder's intra part64 match only
11256 // covers NONE/SPLIT, and the inter path blindly assumes SPLIT --
11257 // both pre-existing, out of this lane's scope); --cpu-used=4
11258 // avoids that RD path entirely and needs --aq-mode=0
11259 // --deltaq-mode=0 to keep delta_q/delta_lf (next lane step) off.
11260 let (width, height, frame_count) = (128usize, 64usize, 24usize);
11261 let mut named_refusals = 0u32;
11262 let mut matched = 0u32;
11263 let n_attempts: u32 = std::env::var("EC_CDEF_GATE_ATTEMPTS")
11264 .ok()
11265 .and_then(|s| s.parse().ok())
11266 .unwrap_or(40);
11267 for attempt in 0..n_attempts {
11268 let seed = 42 + attempt;
11269 let duration = frame_count as f64 / 25.0;
11270 // mandelbrot's ringing-prone hard edges are what CDEF's RD
11271 // search targets; flat gradients (charter's first guess) may
11272 // never make aomenc choose cdef_bits > 0.
11273 let source = format!(
11274 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
11275 sx = -0.6 + 0.005 * (attempt as f64),
11276 sy = -0.4 + 0.005 * (attempt as f64)
11277 );
11278 let y4m = Command::new("ffmpeg")
11279 .args([
11280 "-v",
11281 "error",
11282 "-f",
11283 "lavfi",
11284 "-i",
11285 &source,
11286 "-t",
11287 &duration.to_string(),
11288 "-pix_fmt",
11289 "yuv420p",
11290 "-f",
11291 "yuv4mpegpipe",
11292 "-",
11293 ])
11294 .stdin(Stdio::null())
11295 .stdout(Stdio::piped())
11296 .stderr(Stdio::piped())
11297 .output()
11298 .expect("ffmpeg failed to run");
11299 assert!(
11300 y4m.status.success(),
11301 "ffmpeg fixture: {}",
11302 String::from_utf8_lossy(&y4m.stderr)
11303 );
11304 let args: Vec<&str> = vec![
11305 "--codec=av1",
11306 "--passes=1",
11307 "--end-usage=q",
11308 "--cq-level=45",
11309 "--cpu-used=4",
11310 "--aq-mode=0",
11311 "--deltaq-mode=0",
11312 "--kf-max-dist=1000",
11313 "--threads=1",
11314 "--row-mt=0",
11315 "--auto-alt-ref=1",
11316 "--lag-in-frames=16",
11317 "--enable-fwd-kf=0",
11318 "--enable-order-hint=1",
11319 // r2: a starved inter toolset (everything below off) pushes
11320 // aomenc's RD toward exotic partition shapes (HORZ_4/VERT_B
11321 // etc.) at the SB(64) level even with those partition
11322 // flags off -- this decoder's part64 8/9/10-way arms and
11323 // the inter path's blind SPLIT assumption don't cover that;
11324 // keeping the same rich toolset the (working, ab/1to4-off)
11325 // masked-compound gate uses avoids it.
11326 "--enable-warped-motion=1",
11327 "--enable-global-motion=0",
11328 "--enable-obmc=1",
11329 "--tune-content=default",
11330 "--enable-masked-comp=1",
11331 "--enable-dist-wtd-comp=0",
11332 "--enable-interintra-comp=1",
11333 "--enable-onesided-comp=0",
11334 "--enable-interintra-wedge=0",
11335 "--enable-smooth-interintra=1",
11336 "--enable-rect-partitions=0",
11337 "--enable-ab-partitions=0",
11338 "--enable-1to4-partitions=0",
11339 "--enable-filter-intra=0",
11340 "--enable-smooth-intra=0",
11341 "--enable-paeth-intra=0",
11342 "--enable-directional-intra=0",
11343 "--enable-angle-delta=0",
11344 "--enable-tx-size-search=0",
11345 "--enable-cdef=1",
11346 "--enable-restoration=0",
11347 "--max-partition-size=32",
11348 "--min-partition-size=32",
11349 "--enable-palette=0",
11350 "--enable-intrabc=0",
11351 "--enable-cfl-intra=0",
11352 "--enable-ref-frame-mvs=0",
11353 "--obu",
11354 "-o",
11355 "-",
11356 "-",
11357 ];
11358 let mut child = Command::new(aomenc_path())
11359 .args(&args)
11360 .stdin(Stdio::piped())
11361 .stdout(Stdio::piped())
11362 .stderr(Stdio::piped())
11363 .spawn()
11364 .expect("aomenc failed to start");
11365 child
11366 .stdin
11367 .take()
11368 .expect("aomenc stdin")
11369 .write_all(&y4m.stdout)
11370 .expect("writing y4m to aomenc");
11371 let out = child.wait_with_output().expect("aomenc failed to run");
11372 assert!(
11373 out.status.success(),
11374 "aomenc refused the fixture: {}",
11375 String::from_utf8_lossy(&out.stderr)
11376 );
11377 let stream = out.stdout;
11378 let frames = match decode_stream(&stream) {
11379 Err(e) => {
11380 let msg = e.to_string();
11381 assert!(
11382 msg.contains("unsupported"),
11383 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
11384 );
11385 assert!(
11386 !msg.contains("cdef"),
11387 "{NAME} refused on cdef (seed {seed}) -- cdef_idx decode is ported: {msg}"
11388 );
11389 named_refusals += 1;
11390 eprintln!("seed {seed} refusal: {msg}");
11391 continue;
11392 }
11393 Ok(frames) => frames,
11394 };
11395 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
11396 assert_eq!(frames.len(), frame_count);
11397 let mismatched = frames
11398 .iter()
11399 .zip(&ffmpeg_frames)
11400 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
11401 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
11402 std::fs::write(&path, &stream).expect("writing pinned stream");
11403 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
11404 }
11405 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11406 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
11407 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
11408 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
11409 }
11410 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
11411 // stream again, comparing EVERY decode-order frame -- the hidden
11412 // (show_frame == 0) alt-ref frames the ffmpeg compare above
11413 // cannot see, because both sides of it emit shown frames only.
11414 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
11415 eprintln!(
11416 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
11417 {hidden_n} hidden, all pixel-exact vs the oracle"
11418 );
11419 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
11420 // libaom's temporal alt-ref filter absorbs this recipe's hidden
11421 // frames, so the compare above is vacuous -- re-encode the same
11422 // fixture with --arnr-maxframes=0 and compare THOSE.
11423 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
11424 eprintln!(
11425 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
11426 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
11427 );
11428 }
11429 matched += 1;
11430 }
11431 assert!(
11432 crate::decode::cdef_idx_hits() > 0,
11433 "{NAME}: zero cdef_idx blocks fired ({matched} matches, {named_refusals} other \
11434 refusals out of {n_attempts}) -- gate proved nothing this run"
11435 );
11436 eprintln!(
11437 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
11438 out of {n_attempts}, cdef_idx_hits={}",
11439 crate::decode::cdef_idx_hits()
11440 );
11441 }
11442 /// lane-tiny r4 GATE (was r1's `#[ignore]`d probe): every tiny key-frame
11443 /// size real aomenc will encode, decoded pixel-exact against ffmpeg.
11444 /// Tiny frames are where every edge/partial-superblock corner case is
11445 /// forced, and this sweep is what found both r3's filter-intra tx_type
11446 /// CDF row and r4's chroma-transform-size deblock defect -- so it
11447 /// hard-asserts now: a decode error, a refusal, or one differing sample
11448 /// at any size/seed fails. Only a genuinely absent oracle skips, and
11449 /// `EC_AV1_REQUIRE_AOMENC=1` turns that into a failure too.
11450 #[test]
11451 fn a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact() {
11452 if !have_ffmpeg() || !have_aomenc() {
11453 eprintln!("SKIP: no ffmpeg/aomenc");
11454 return;
11455 }
11456 let sizes: &[(usize, usize)] =
11457 &[(8, 8), (16, 16), (32, 32), (16, 32), (32, 16), (64, 64), (48, 48), (24, 24)];
11458 let mut total_exact = 0u32;
11459 for &(width, height) in sizes {
11460 let mut ok = 0u32;
11461 let mut bad = 0u32;
11462 let mut refused = 0u32;
11463 let n = 10u32;
11464 for attempt in 0..n {
11465 let seed = 42 + attempt;
11466 let source = format!(
11467 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
11468 sx = -0.6 + 0.005 * (attempt as f64),
11469 sy = -0.4 + 0.005 * (attempt as f64)
11470 );
11471 let y4m = Command::new("ffmpeg")
11472 .args([
11473 "-v", "error", "-f", "lavfi", "-i", &source, "-t", "0.04", "-pix_fmt",
11474 "yuv420p", "-f", "yuv4mpegpipe", "-",
11475 ])
11476 .stdin(Stdio::null())
11477 .stdout(Stdio::piped())
11478 .stderr(Stdio::piped())
11479 .output()
11480 .expect("ffmpeg failed to run");
11481 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
11482 let max_part = width.max(height).min(64).next_power_of_two();
11483 let min_part = width.min(height).next_power_of_two().max(8).min(max_part);
11484 let max_part_arg = format!("--max-partition-size={max_part}");
11485 let min_part_arg = format!("--min-partition-size={min_part}");
11486 let args: Vec<&str> = vec![
11487 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32",
11488 "--cpu-used=4", "--kf-max-dist=0", "--limit=1", "--threads=1",
11489 "--row-mt=0", "--enable-rect-partitions=0", "--enable-ab-partitions=0",
11490 "--enable-1to4-partitions=0",
11491 &max_part_arg, &min_part_arg,
11492 "--obu", "-o", "-", "-",
11493 ];
11494 let mut child = Command::new(aomenc_path())
11495 .args(&args)
11496 .stdin(Stdio::piped())
11497 .stdout(Stdio::piped())
11498 .stderr(Stdio::piped())
11499 .spawn()
11500 .expect("aomenc failed to start");
11501 child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("write y4m");
11502 let out = child.wait_with_output().expect("aomenc failed to run");
11503 assert!(out.status.success(), "aomenc refused: {}", String::from_utf8_lossy(&out.stderr));
11504 let stream = out.stdout;
11505 let frames = match decode_stream(&stream) {
11506 Err(e) => {
11507 // A NAMED refusal is the only non-exact outcome this
11508 // gate tolerates (8x8 still needs a rectangular
11509 // transform); anything else is a hard failure, and
11510 // the floor assert below keeps that from going
11511 // vacuous.
11512 let msg = e.to_string();
11513 assert!(
11514 msg.contains("unsupported"),
11515 "{width}x{height} seed {seed}: failed outright, not a named \
11516 refusal: {msg}"
11517 );
11518 eprintln!(" {width}x{height} seed {seed}: REFUSED {msg}");
11519 refused += 1;
11520 continue;
11521 }
11522 Ok(f) => f,
11523 };
11524 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
11525 if frames.len() == 1
11526 && frames[0].y == ffmpeg_frames[0].y
11527 && frames[0].u == ffmpeg_frames[0].u
11528 && frames[0].v == ffmpeg_frames[0].v
11529 {
11530 ok += 1;
11531 } else {
11532 bad += 1;
11533 let nd = |a: &[u16], b: &[u16]| a.iter().zip(b).filter(|(x, y)| x != y).count();
11534 let (ndy, ndu, ndv) = (
11535 nd(&frames[0].y, &ffmpeg_frames[0].y),
11536 nd(&frames[0].u, &ffmpeg_frames[0].u),
11537 nd(&frames[0].v, &ffmpeg_frames[0].v),
11538 );
11539 let mut first = None;
11540 for row in 0..height {
11541 for col in 0..width {
11542 let i = row * width + col;
11543 if frames[0].y[i] != ffmpeg_frames[0].y[i] {
11544 first = Some((row, col, frames[0].y[i], ffmpeg_frames[0].y[i]));
11545 break;
11546 }
11547 }
11548 if first.is_some() {
11549 break;
11550 }
11551 }
11552 let ndiff = frames[0]
11553 .y
11554 .iter()
11555 .zip(&ffmpeg_frames[0].y)
11556 .filter(|(a, b)| a != b)
11557 .count();
11558 eprintln!(
11559 " {width}x{height} seed {seed}: MISMATCH first_diff={first:?} \
11560 ndiff_luma={ndiff}/{} ndiff y/u/v={ndy}/{ndu}/{ndv}",
11561 width * height
11562 );
11563 }
11564 }
11565 assert_eq!(
11566 bad, 0,
11567 "{width}x{height}: {bad} of {n} seeds decoded to WRONG PIXELS ({ok} exact, \
11568 {refused} named refusals)"
11569 );
11570 eprintln!("{width}x{height}: {ok}/{n} pixel-exact, {refused} named refusals");
11571 total_exact += ok;
11572 }
11573 // Hit counter: the sweep proved nothing unless every size x seed
11574 // attempt really ran end to end (aomenc -> us -> ffmpeg compare).
11575 // Floor (hit counter): 7 of the 8 sizes must decode all 10 seeds
11576 // pixel-exact -- only 8x8 is allowed to refuse outright today. If a
11577 // future change makes sizes refuse instead of decode, this fails
11578 // rather than passing on refusals alone.
11579 assert!(
11580 total_exact >= 70,
11581 "tiny sweep only reached {total_exact} pixel-exact attempts (floor 70) -- \
11582 refusals cannot substitute for decodes"
11583 );
11584 eprintln!("tiny frame sweep: {total_exact} pixel-exact attempts");
11585 }
11586
11587 /// lane-tiny r1: re-decodes the known-failing 32x32 seed 45 fixture with
11588 /// `EC_AV1_TRACE` on to inspect what mode/tx this single-block frame
11589 /// picked. Diagnostic only, `#[ignore]`d, run manually with --nocapture.
11590 #[test]
11591 #[ignore = "diagnostic, run manually with --nocapture"]
11592 fn probe_tiny_32x32_trace() {
11593 if !have_ffmpeg() || !have_aomenc() {
11594 eprintln!("SKIP: no ffmpeg/aomenc");
11595 return;
11596 }
11597 let (width, height) = (32usize, 32usize);
11598 let attempt = 3u32; // seed 45
11599 let source = format!(
11600 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
11601 sx = -0.6 + 0.005 * (attempt as f64),
11602 sy = -0.4 + 0.005 * (attempt as f64)
11603 );
11604 let y4m = Command::new("ffmpeg")
11605 .args([
11606 "-v", "error", "-f", "lavfi", "-i", &source, "-t", "0.04", "-pix_fmt", "yuv420p",
11607 "-f", "yuv4mpegpipe", "-",
11608 ])
11609 .stdin(Stdio::null())
11610 .stdout(Stdio::piped())
11611 .stderr(Stdio::piped())
11612 .output()
11613 .expect("ffmpeg failed to run");
11614 assert!(y4m.status.success());
11615 let args: Vec<&str> = vec![
11616 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32", "--cpu-used=4",
11617 "--kf-max-dist=0", "--limit=1", "--threads=1", "--row-mt=0",
11618 "--enable-rect-partitions=0", "--enable-ab-partitions=0",
11619 "--enable-1to4-partitions=0", "--max-partition-size=32", "--min-partition-size=32",
11620 "--enable-filter-intra=0",
11621 "--obu", "-o", "-", "-",
11622 ];
11623 let mut child = Command::new(aomenc_path())
11624 .args(&args)
11625 .stdin(Stdio::piped())
11626 .stdout(Stdio::piped())
11627 .stderr(Stdio::piped())
11628 .spawn()
11629 .expect("aomenc failed to start");
11630 child.stdin.take().unwrap().write_all(&y4m.stdout).unwrap();
11631 let out = child.wait_with_output().unwrap();
11632 assert!(out.status.success());
11633 let stream = out.stdout;
11634 let frames = decode_stream(&stream).expect("decode");
11635 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
11636 let mismatched = frames[0].y != ffmpeg_frames[0].y;
11637 eprintln!("mismatched={mismatched}");
11638 }
11639
11640 /// lane-tiny r2: decodes a raw OBU stream at `EC_TINY_FIXTURE_PATH` --
11641 /// no ffmpeg/aomenc invocation -- so a range ladder can be run
11642 /// (`EC_TRACE_MODE_STEP=1`) against the exact same bytes fed to the
11643 /// oracle aomdec, byte for byte. `#[ignore]`d diagnostic, no assertion.
11644 #[test]
11645 #[ignore = "diagnostic, run manually with --nocapture and EC_TINY_FIXTURE_PATH set"]
11646 fn probe_tiny_fixture_trace() {
11647 let path = std::env::var("EC_TINY_FIXTURE_PATH")
11648 .expect("set EC_TINY_FIXTURE_PATH to an .obu file");
11649 let stream = std::fs::read(&path).expect("reading fixture");
11650 match decode_stream(&stream) {
11651 Ok(frames) => {
11652 eprintln!("decoded {} frame(s)", frames.len());
11653 if let Ok(dump) = std::env::var("EC_TINY_FIXTURE_Y_DUMP") {
11654 let bytes: Vec<u8> = frames[0].y.iter().map(|&v| v as u8).collect();
11655 std::fs::write(&dump, &bytes).expect("dump y plane");
11656 }
11657 }
11658 Err(e) => eprintln!("REFUSED: {e}"),
11659 }
11660 }
11661 /// Pinned streams captured by `EC_AV1_GATE_DUMP` off
11662 /// `a_real_aomenc_stream_with_warped_motion_refuses_or_matches` -- each
11663 /// one is a former mismatch, kept as a regression pin (warp-mismatch:
11664 /// the WARPED_CAUSAL interp-read suppression; warp-flake-7: the same
11665 /// suppression for skip_mode blocks; warp-flake-5: mvstack entry
11666 /// clamping; ii-flake-1..8: interintra neighbours excluded from
11667 /// warp-sample gathering, ref_frame[1] == INTRA_FRAME in the mi grid).
11668 /// `EC_AV1_GATE_DUMP_PIN` overrides to a single stream.
11669 /// Deterministic and static -- `#[ignore]`d because the gitignored
11670 /// fixtures dir may be absent; run manually.
11671 #[test]
11672 #[ignore = "reads pinned fixture paths under the gitignored fixtures dir; run manually"]
11673 fn pinned_warp_stream_decodes_pixel_exact() {
11674 if !have_ffmpeg() {
11675 eprintln!("SKIP pinned_warp_stream_decodes_pixel_exact: no ffmpeg");
11676 return;
11677 }
11678 let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");
11679 let paths: Vec<String> = match std::env::var("EC_AV1_GATE_DUMP_PIN") {
11680 Ok(p) => vec![p],
11681 Err(_) => [
11682 "warp-mismatch",
11683 "warp-flake-5",
11684 "warp-flake-7",
11685 "ii-flake-1",
11686 "ii-flake-2",
11687 "ii-flake-3",
11688 "ii-flake-5",
11689 "ii-flake-6",
11690 "ii-flake-7",
11691 "ii-flake-8",
11692 // switchable_interp missing from reset_counts (counter
11693 // saturation slowed the adaptation rate) -- unrelated to
11694 // interintra, caught by the same gate.
11695 "ii-flake-9",
11696 // lane-rect r2: HORZ strip rect defects (mvstack size_h,
11697 // warp sample/projection dims, OBMC overlap, deblock tx-h).
11698 "rect-flake-1",
11699 // scan_row/scan_col weight `inc` min'd by the wrong candidate
11700 // axis (width vs height) -- ties reordered DRL entry 1 for a
11701 // block under a 32x16 strip, and suppressed the -5 extended
11702 // row scan.
11703 "rect-flake-2",
11704 // overlappable_left stepped the vertical walk by the
11705 // neighbour's WIDTH: a 32x16 left strip swallowed the strip
11706 // below it, blending the wrong OBMC prediction there.
11707 "rect-flake-3",
11708 ]
11709 .iter()
11710 .map(|n| format!("{fixtures}/{n}.obu"))
11711 .collect(),
11712 };
11713 for path in paths {
11714 eprintln!("pin: {path}");
11715 check_pinned_warp_stream(&path);
11716 }
11717 }
11718
11719 fn check_pinned_warp_stream(path: &str) {
11720 use crate::decode::warp_selected_hits;
11721 let stream = std::fs::read(path).expect("reading pinned stream");
11722 let before = warp_selected_hits();
11723 let frames = decode_stream(&stream).expect("pinned stream must decode");
11724 eprintln!(
11725 "warp_selected_hits before={before} after={}",
11726 warp_selected_hits()
11727 );
11728 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 24);
11729 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11730 if got.y != want.y {
11731 for row in 0..64 {
11732 let mut line = String::new();
11733 for col in 0..64 {
11734 let d = got.y[row * 64 + col] as i32 - want.y[row * 64 + col] as i32;
11735 line.push(if d == 0 {
11736 '.'
11737 } else if d.abs() < 4 {
11738 'o'
11739 } else {
11740 'X'
11741 });
11742 }
11743 eprintln!("{line}");
11744 }
11745 }
11746 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
11747 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
11748 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
11749 }
11750 }
11751
11752 /// `LAST2_FRAME`/`LAST3_FRAME` are just older slots in the same forward
11753 /// reference-buffer ring `LAST_FRAME`/`GOLDEN_FRAME` already prove --
11754 /// dropping the golden gate's `--max-reference-frames=3
11755 /// --reduced-reference-set=1` narrowing (which suppresses exactly these)
11756 /// and running long enough for aomenc's own buffer rotation to reach
11757 /// past the first 2 frames is the whole difference.
11758 #[test]
11759 fn a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact() {
11760 a_real_aomenc_single_ref_gate(
11761 "a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact",
11762 crate::mvstack::LAST2_FRAME,
11763 "LAST2_FRAME",
11764 &["--auto-alt-ref=0", "--lag-in-frames=0"],
11765 64,
11766 64,
11767 8,
11768 120,
11769 );
11770 }
11771
11772 #[test]
11773 fn a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact() {
11774 a_real_aomenc_single_ref_gate(
11775 "a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact",
11776 crate::mvstack::LAST3_FRAME,
11777 "LAST3_FRAME",
11778 &["--auto-alt-ref=0", "--lag-in-frames=0"],
11779 64,
11780 64,
11781 8,
11782 120,
11783 );
11784 }
11785
11786 /// `BWDREF`/`ALTREF2`/`ALTREF` are all backward (display-order-forward)
11787 /// references that only exist once aomenc builds a hierarchical GOP --
11788 /// `--auto-alt-ref=1 --lag-in-frames` (need at least one full mini-GOP
11789 /// of lookahead) is what makes aomenc code them at all; without it
11790 /// every attempt would hit this decoder's own real, still-open
11791 /// per-block sign-bias gap by never drawing the reference in the first
11792 /// place, not by proving it correct.
11793 #[test]
11794 fn a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact() {
11795 a_real_aomenc_single_ref_gate(
11796 "a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact",
11797 crate::mvstack::BWDREF_FRAME,
11798 "BWDREF_FRAME",
11799 &[
11800 "--auto-alt-ref=1",
11801 "--lag-in-frames=16",
11802 "--enable-fwd-kf=0",
11803 ],
11804 64,
11805 64,
11806 16,
11807 120,
11808 );
11809 }
11810
11811 /// lane-altref2 r1: 16 frames was too short for aomenc to ever build a
11812 /// second-level alt-ref pyramid, so this gate ran 86 attempts and fired
11813 /// ALTREF2 exactly zero times (class `gate-blind-to-feature`) -- the
11814 /// flags were already right, only the clip length was wrong. A 64-frame
11815 /// clip at the same `--lag-in-frames=16` gives aomenc enough lookahead
11816 /// to schedule a 2-level GF pyramid and reliably codes ALTREF2 (4/4
11817 /// hits on a plain seed-42 direct-aomenc probe; see
11818 /// lanes/altref2-r1.report.md for the recipe search table). Firing is
11819 /// now HARD-asserted below: the gate fails rather than skips if
11820 /// `ref_hits(ALTREF2_FRAME)` does not advance.
11821 #[test]
11822 fn a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact() {
11823 let before = decode::ref_hits(crate::mvstack::ALTREF2_FRAME);
11824 a_real_aomenc_single_ref_gate(
11825 "a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact",
11826 crate::mvstack::ALTREF2_FRAME,
11827 "ALTREF2_FRAME",
11828 &[
11829 "--auto-alt-ref=1",
11830 "--lag-in-frames=16",
11831 "--enable-fwd-kf=0",
11832 ],
11833 64,
11834 64,
11835 64,
11836 120,
11837 );
11838 let after = decode::ref_hits(crate::mvstack::ALTREF2_FRAME);
11839 assert!(
11840 after > before,
11841 "a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact: \
11842 ALTREF2_FRAME never fired across 120 attempts -- the gate is vacuous \
11843 again (class gate-blind-to-feature); see lanes/altref2-r1.report.md \
11844 for the recipe that is supposed to make this fire"
11845 );
11846 }
11847
11848 #[test]
11849 fn a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact() {
11850 a_real_aomenc_single_ref_gate(
11851 "a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact",
11852 crate::mvstack::ALTREF_FRAME,
11853 "ALTREF_FRAME",
11854 &[
11855 "--auto-alt-ref=1",
11856 "--lag-in-frames=16",
11857 "--enable-fwd-kf=0",
11858 ],
11859 64,
11860 64,
11861 16,
11862 120,
11863 );
11864 }
11865
11866 /// lane-av1tmvp: the temporal-MV gate -- unlike every `_single_ref_gate`
11867 /// attempt above, this one leaves `--enable-ref-frame-mvs` at aomenc's
11868 /// own default (on) instead of pinning it off, so `use_ref_frame_mvs`
11869 /// actually fires and `decode::tmv_hits()` (this gate's own capability
11870 /// proof, not just `non_last_ref_hits`) has to advance for the run to
11871 /// count as a real pass rather than a `never_fired` skip.
11872 fn a_real_aomenc_temporal_mv_gate(seed_base: u32, attempts: u32) {
11873 let gate_name = "a_real_aomenc_temporal_mv_gate";
11874 let _gate_lock = lock_gate_counters();
11875 if !have_ffmpeg() {
11876 eprintln!("SKIP {gate_name}: no ffmpeg");
11877 return;
11878 }
11879 if !have_aomenc() {
11880 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
11881 return;
11882 }
11883 let (width, height, frame_count) = (64usize, 64usize, 16usize);
11884 let mut never_fired = 0u32;
11885 let mut refusals = Vec::new();
11886 for attempt in 0..attempts {
11887 let seed = seed_base + attempt;
11888 let duration = frame_count as f64 / 25.0;
11889 let source =
11890 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
11891 let y4m = Command::new("ffmpeg")
11892 .args([
11893 "-v",
11894 "error",
11895 "-f",
11896 "lavfi",
11897 "-i",
11898 &source,
11899 "-pix_fmt",
11900 "yuv420p",
11901 "-f",
11902 "yuv4mpegpipe",
11903 "-",
11904 ])
11905 .stdin(Stdio::null())
11906 .stdout(Stdio::piped())
11907 .stderr(Stdio::piped())
11908 .output()
11909 .expect("ffmpeg failed to run");
11910 assert!(
11911 y4m.status.success(),
11912 "ffmpeg fixture: {}",
11913 String::from_utf8_lossy(&y4m.stderr)
11914 );
11915 // Same envelope as `a_real_aomenc_single_ref_gate`, minus its
11916 // `--enable-ref-frame-mvs=0` pin -- everything else this decoder
11917 // still cannot code stays refused the same way.
11918 let args: Vec<&str> = vec![
11919 "--codec=av1",
11920 "--passes=1",
11921 "--end-usage=q",
11922 "--cq-level=55",
11923 "--cpu-used=0",
11924 "--kf-max-dist=1000",
11925 "--threads=1",
11926 "--row-mt=0",
11927 "--auto-alt-ref=1",
11928 "--lag-in-frames=16",
11929 "--enable-fwd-kf=0",
11930 "--enable-warped-motion=0",
11931 "--enable-obmc=0",
11932 "--enable-masked-comp=0",
11933 "--enable-interintra-comp=0",
11934 "--enable-dist-wtd-comp=0",
11935 "--enable-diff-wtd-comp=0",
11936 "--enable-onesided-comp=0",
11937 "--enable-interintra-wedge=0",
11938 "--enable-smooth-interintra=0",
11939 "--enable-rect-partitions=0",
11940 "--enable-ab-partitions=0",
11941 "--enable-1to4-partitions=0",
11942 "--enable-filter-intra=0",
11943 "--enable-smooth-intra=0",
11944 "--enable-paeth-intra=0",
11945 "--enable-directional-intra=0",
11946 "--enable-angle-delta=0",
11947 "--enable-tx-size-search=0",
11948 "--enable-cdef=0",
11949 "--enable-restoration=0",
11950 "--max-partition-size=32",
11951 "--min-partition-size=32",
11952 "--enable-palette=0",
11953 "--enable-intrabc=0",
11954 "--enable-cfl-intra=0",
11955 "--obu",
11956 "-o",
11957 "-",
11958 "-",
11959 ];
11960 let mut child = Command::new(aomenc_path())
11961 .args(&args)
11962 .stdin(Stdio::piped())
11963 .stdout(Stdio::piped())
11964 .stderr(Stdio::piped())
11965 .spawn()
11966 .expect("aomenc failed to start");
11967 child
11968 .stdin
11969 .take()
11970 .expect("aomenc stdin")
11971 .write_all(&y4m.stdout)
11972 .expect("writing y4m to aomenc");
11973 let out = child.wait_with_output().expect("aomenc failed to run");
11974 assert!(
11975 out.status.success(),
11976 "aomenc refused the fixture: {}",
11977 String::from_utf8_lossy(&out.stderr)
11978 );
11979 let stream = out.stdout;
11980 let before = decode::tmv_hits();
11981 let frames = match decode_stream(&stream) {
11982 Err(e) => {
11983 let msg = e.to_string();
11984 assert!(
11985 msg.contains("unsupported"),
11986 "{gate_name} failed outright (seed {seed}): {msg}"
11987 );
11988 refusals.push(format!("seed {seed}: {msg}"));
11989 continue;
11990 }
11991 Ok(frames) => frames,
11992 };
11993 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
11994 // is ALWAYS pixel-compared below; the hit counter only decides whether
11995 // the attempt counts toward the firing total.
11996 let counted = decode::tmv_hits() != before;
11997 if !counted {
11998 never_fired += 1;
11999 }
12000 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
12001 assert_eq!(frames.len(), frame_count);
12002 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
12003 let mismatched = frames
12004 .iter()
12005 .zip(&ffmpeg_frames)
12006 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
12007 if mismatched {
12008 std::fs::write(&path, &stream).expect("writing pinned stream");
12009 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
12010 }
12011 }
12012 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12013 assert_eq!(
12014 got.y, want.y,
12015 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
12016 );
12017 assert_eq!(
12018 got.u, want.u,
12019 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
12020 );
12021 assert_eq!(
12022 got.v, want.v,
12023 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
12024 );
12025 }
12026 if counted {
12027 eprintln!(
12028 "{gate_name} FIRING seed {seed}: tmv_hits advanced by {}",
12029 decode::tmv_hits() - before
12030 );
12031 gate_buckets(gate_name, 1, never_fired, refusals.len());
12032 return;
12033 }
12034 }
12035 gate_buckets(gate_name, 0, never_fired, refusals.len());
12036 eprintln!(
12037 "SKIP {gate_name}: {never_fired} attempts decoded but never fired a temporal MV \
12038 candidate, and every other attempt hit a named refusal:\n{}",
12039 refusals.join("\n")
12040 );
12041 }
12042
12043 #[test]
12044 fn a_real_aomenc_stream_with_temporal_mvs_decodes_pixel_exact() {
12045 a_real_aomenc_temporal_mv_gate(42, 40);
12046 }
12047
12048 /// bisect scratch: decode a pinned stream exactly once -- generic
12049 /// pin-repro tool, kept for manual use.
12050 #[test]
12051 #[ignore]
12052 fn scratch_decode_pinned_stream_once() {
12053 let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path");
12054 let stream = std::fs::read(&path).expect("read pinned stream");
12055 match decode_stream(&stream) {
12056 Ok(frames) => eprintln!("OK: {} frames", frames.len()),
12057 Err(e) => eprintln!("ERR: {e}"),
12058 }
12059 }
12060
12061 /// scratch: isolate a pinned mismatching stream's first divergent pixel.
12062 #[test]
12063 #[ignore]
12064 fn scratch_isolate_pinned_mismatch() {
12065 let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path");
12066 let stream = std::fs::read(&path).expect("read pinned stream");
12067 {
12068 let mut p = Av1Parser::new();
12069 let mut pos = 0usize;
12070 while pos < stream.len() {
12071 let obu = p.parse_obu(&stream[pos..]).expect("parse");
12072 pos += obu.total_size;
12073 if let ObuKind::Frame(header, _) = obu.kind {
12074 eprintln!("interpolation_filter: {:?}", header.interpolation_filter);
12075 eprintln!("cdef: {:?}", header.cdef);
12076 eprintln!("quantization: {:?}", header.quantization);
12077 eprintln!(
12078 "coded_lossless: {:?} tx_mode: {:?}",
12079 header.coded_lossless, header.tx_mode
12080 );
12081 eprintln!("delta: {:?}", header.delta);
12082 eprintln!("segmentation: {:?}", header.segmentation);
12083 eprintln!("loop_restoration: {:?}", header.loop_restoration);
12084 eprintln!(
12085 "use_128x128_superblock: {:?} disable_cdf_update: {:?} disable_frame_end_update_cdf: {:?} primary_ref_frame: {:?} allow_high_precision_mv: {:?} force_integer_mv: {:?}",
12086 p.sequence_header().map(|s| s.use_128x128_superblock),
12087 header.disable_cdf_update,
12088 header.disable_frame_end_update_cdf,
12089 header.primary_ref_frame,
12090 header.allow_high_precision_mv,
12091 header.force_integer_mv,
12092 );
12093 }
12094 }
12095 }
12096 let width = std::env::var("EC_AV1_PIN_W")
12097 .map(|s| s.parse().unwrap())
12098 .unwrap_or(64);
12099 let height = std::env::var("EC_AV1_PIN_H")
12100 .map(|s| s.parse().unwrap())
12101 .unwrap_or(64);
12102 let frame_count = std::env::var("EC_AV1_PIN_N")
12103 .map(|s| s.parse().unwrap())
12104 .unwrap_or(4);
12105 let frames = decode_stream(&stream).expect("our decode");
12106 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
12107 for f in 0..frame_count.min(frames.len()).min(ffmpeg_frames.len()) {
12108 let ours = &frames[f];
12109 let theirs = &ffmpeg_frames[f];
12110 for (plane_name, a, b, w) in [
12111 ("y", &ours.y, &theirs.y, width),
12112 ("u", &ours.u, &theirs.u, width / 2),
12113 ("v", &ours.v, &theirs.v, width / 2),
12114 ] {
12115 let mut first = None;
12116 let mut count = 0;
12117 let mut worst = 0i32;
12118 for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
12119 if x != y {
12120 count += 1;
12121 if first.is_none() {
12122 first = Some(i);
12123 }
12124 worst = worst.max((*x as i32 - *y as i32).abs());
12125 }
12126 }
12127 if let Some(i) = first {
12128 eprintln!(
12129 "frame {f} plane {plane_name}: {count} mismatches (worst delta {worst}), first at offset {i} (row {}, col {}) ours={} theirs={}",
12130 i / w,
12131 i % w,
12132 a[i],
12133 b[i]
12134 );
12135 } else {
12136 eprintln!("frame {f} plane {plane_name}: MATCH");
12137 }
12138 }
12139 }
12140 }
12141
12142 /// Final round of the TX4/tx-class lane's own gate: `--min-partition-size=8
12143 /// --max-partition-size=8` pins every leaf to exactly 8x8 (spec
12144 /// 5.11.4's own boundary carve-out aside, which a multiple-of-8 frame
12145 /// never triggers), so a real `aomenc` stream from this recipe can only
12146 /// legitimately read `PARTITION_NONE` at every `bsize=3` node -- any
12147 /// other value this decoder sees there is a genuine desync, not a
12148 /// "partition below 8x8" the encoder actually wrote (traced live against
12149 /// a debug `aomdec` 2026-08-27: the true bitstream's own 8x8 partition
12150 /// reads are all `NONE`; the mismatch was `base_ctx`'s DC-position
12151 /// short-circuit firing for `TX_CLASS_HORIZ`/`VERT` too, off by one
12152 /// `BR` read into a spurious extra Golomb call). The sinusoidal-stripe
12153 /// `geq` source (a smooth luma ramp, not the sharp two-tone stripes that
12154 /// tripped `aomenc`'s screen-content-tools auto-detect) is what actually
12155 /// resolves `V_DCT`/`H_DCT` (`TxClass::of`) on some 8x8 TUs at this
12156 /// content's frequency; the attempt loop moves on from named refusals
12157 /// (`allow_screen_content_tools`, angle-delta) same as every other
12158 /// multi-seed recipe in this file, and only counts a run as a genuine
12159 /// firing when [`decode::tx_class1_hits`] actually moved.
12160 #[test]
12161 fn a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact() {
12162 if !have_ffmpeg() {
12163 eprintln!(
12164 "SKIP a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact: no ffmpeg"
12165 );
12166 return;
12167 }
12168 if !have_aomenc() {
12169 eprintln!(
12170 "SKIP a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact: no aomenc at {}",
12171 aomenc_path().display()
12172 );
12173 return;
12174 }
12175 let (width, height) = (64usize, 64usize);
12176 let mut refusals = Vec::new();
12177 let mut fired_runs = 0u32;
12178 let mut uncounted_exact = 0u32;
12179 for attempt in 0..60u32 {
12180 let cq = 20 + (attempt % 5) * 10;
12181 let period = [4u32, 6, 8, 12, 16][(attempt as usize / 5) % 5];
12182 let y4m = Command::new("ffmpeg")
12183 .args([
12184 "-v",
12185 "error",
12186 "-f",
12187 "lavfi",
12188 "-i",
12189 "testsrc2=size=64x64:rate=25",
12190 "-vf",
12191 &format!(
12192 "geq=lum='128+80*sin(2*PI*Y/{period})':cb=128:cr=128,noise=alls=6:allf=t"
12193 ),
12194 "-pix_fmt",
12195 "yuv420p",
12196 "-t",
12197 "0.04",
12198 "-f",
12199 "yuv4mpegpipe",
12200 "-",
12201 ])
12202 .stdin(Stdio::null())
12203 .stdout(Stdio::piped())
12204 .stderr(Stdio::piped())
12205 .output()
12206 .expect("ffmpeg failed to run");
12207 assert!(
12208 y4m.status.success(),
12209 "ffmpeg fixture: {}",
12210 String::from_utf8_lossy(&y4m.stderr)
12211 );
12212 let mut child = Command::new(aomenc_path())
12213 .args([
12214 "--codec=av1",
12215 "--passes=1",
12216 "--end-usage=q",
12217 &format!("--cq-level={cq}"),
12218 "--cpu-used=0",
12219 "--enable-directional-intra=0",
12220 "--enable-smooth-intra=0",
12221 "--enable-paeth-intra=0",
12222 "--enable-rect-partitions=0",
12223 "--enable-angle-delta=0",
12224 "--enable-palette=0",
12225 "--reduced-tx-type-set=0",
12226 "--enable-restoration=0",
12227 "--enable-cdef=0",
12228 "--loopfilter-control=0",
12229 "--min-partition-size=8",
12230 "--max-partition-size=8",
12231 "--enable-ab-partitions=0",
12232 "--enable-1to4-partitions=0",
12233 "--enable-filter-intra=0",
12234 "--enable-intrabc=0",
12235 "--enable-cfl-intra=0",
12236 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
12237 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
12238 "--enable-ref-frame-mvs=0",
12239 "--tune-content=default",
12240 "--obu",
12241 "-o",
12242 "-",
12243 "-",
12244 ])
12245 .stdin(Stdio::piped())
12246 .stdout(Stdio::piped())
12247 .stderr(Stdio::piped())
12248 .spawn()
12249 .expect("aomenc failed to start");
12250 child
12251 .stdin
12252 .take()
12253 .expect("aomenc stdin")
12254 .write_all(&y4m.stdout)
12255 .expect("writing y4m to aomenc");
12256 let out = child.wait_with_output().expect("aomenc failed to run");
12257 if !out.status.success() {
12258 refusals.push(format!(
12259 "cq={cq} period={period}: aomenc itself refused the fixture"
12260 ));
12261 continue;
12262 }
12263 let stream = out.stdout;
12264 let before = decode::tx_class1_hits();
12265 let frames = match decode_stream(&stream) {
12266 Ok(frames) => frames,
12267 Err(e) => {
12268 refusals.push(format!("cq={cq} period={period}: {e}"));
12269 continue;
12270 }
12271 };
12272 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
12273 // is ALWAYS pixel-compared below; the hit counter only decides whether
12274 // the attempt counts toward the firing total.
12275 let counted = decode::tx_class1_hits() != before;
12276 if !counted {
12277 uncounted_exact += 1;
12278 refusals.push(format!(
12279 "cq={cq} period={period}: decoded and pixel-compared, but no block read a \
12280 V_DCT/H_DCT tx_type"
12281 ));
12282 }
12283 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
12284 assert_eq!(
12285 frames[0].y, ffmpeg_frames[0].y,
12286 "luma vs ffmpeg (cq={cq} period={period})"
12287 );
12288 assert_eq!(
12289 frames[0].u, ffmpeg_frames[0].u,
12290 "U vs ffmpeg (cq={cq} period={period})"
12291 );
12292 assert_eq!(
12293 frames[0].v, ffmpeg_frames[0].v,
12294 "V vs ffmpeg (cq={cq} period={period})"
12295 );
12296 if counted {
12297 fired_runs += 1;
12298 if fired_runs >= 4 {
12299 gate_buckets(
12300 "a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact",
12301 fired_runs,
12302 uncounted_exact,
12303 refusals.len() - uncounted_exact as usize,
12304 );
12305 return;
12306 }
12307 }
12308 }
12309 gate_buckets(
12310 "a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact",
12311 fired_runs,
12312 uncounted_exact,
12313 refusals.len() - uncounted_exact as usize,
12314 );
12315 panic!(
12316 "fewer than 4 firing+pixel-exact runs out of 60 attempts:\n{}",
12317 refusals.join("\n")
12318 );
12319 }
12320
12321 /// lane-sub8 r1: `--min-partition-size=4` on fine-detail noisy gradients
12322 /// at low cq reliably makes aomenc split an 8x8 block all the way to
12323 /// four `BLOCK_4X4` leaves (`PARTITION_SPLIT` below 8x8, spec
12324 /// `decode_partition`'s recursion bottom) -- confirmed with
12325 /// `EC_AV1_TRACE=1` against `examples/decode_probe` before this gate was
12326 /// written (`partition_w8 ... value=3` at mi=(0,0) on the very first
12327 /// block). [`decode::sub8_split_hits`] hard-asserts the path actually
12328 /// ran rather than every attempt landing on `PARTITION_NONE`.
12329 #[test]
12330 fn a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact() {
12331 if !have_ffmpeg() {
12332 eprintln!("SKIP a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact: no ffmpeg");
12333 return;
12334 }
12335 if !have_aomenc() {
12336 let msg = format!(
12337 "no aomenc at {}",
12338 aomenc_path().display()
12339 );
12340 assert!(
12341 std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
12342 "EC_AV1_REQUIRE_AOMENC is set but {msg}"
12343 );
12344 eprintln!("SKIP a_real_aomenc_stream_with_a_sub8_split_decodes_pixel_exact: {msg}");
12345 return;
12346 }
12347 // round 2: `--enable-rect-partitions=0` was added below to keep
12348 // aomenc off HORZ/VERT-below-8x8 elsewhere in the same tile, but it
12349 // is NOT sufficient alone -- see the round-2 report
12350 // (lanes/sub8-r1.report.md) for the live finding: 0/160 attempts
12351 // across both 64x64 and a spatially-isolated single-16x16-leaf
12352 // fixture passed, and every SPLIT that fires is immediately
12353 // followed by a spurious HORZ/VERT read on the very next sibling
12354 // 8x8 leaf, which reads as a real desync left behind by
12355 // `decode_leaf_split4`/`read_intra_mode_sub8`, not an encoder
12356 // choice this recipe can dodge. Tried and rejected: shrinking the
12357 // frame to 16x16 (single 16x16 leaf, at most 4 candidate 8x8s) --
12358 // that surfaces an UNRELATED pre-existing tiny-frame edge-straddle
12359 // defect (reproduces with zero sub8 code involved, `--min-partition
12360 // -size`/`--max-partition-size` absent entirely), so it is not a
12361 // safe way to isolate the leaf count. Left red; do not "fix" this
12362 // gate by picking fixture parameters that dodge the desync without
12363 // finding it.
12364 // lane-sub8 r6: three arms. The mi-granular mode maps
12365 // (`sub8_mode_col`/`uv_mode_col` and their row twins) are per TILE --
12366 // the verifier's repro was a 128x64 `--tile-columns=1` stream (seeds
12367 // 207/228) whose every mismatching luma pixel sat at x>=64, the tile
12368 // boundary -- so one arm per tile axis is part of this gate.
12369 for (width, height, tile_args) in [
12370 (64usize, 64usize, &[][..]),
12371 (128usize, 64usize, &["--tile-columns=1"][..]),
12372 (64usize, 128usize, &["--tile-rows=1"][..]),
12373 ] {
12374 let mut refusals = Vec::new();
12375 let mut fired_runs = 0u32;
12376 for attempt in 0..40u32 {
12377 let seed = 100 + attempt;
12378 let cq = 6 + (attempt % 4) * 2;
12379 let y4m = Command::new("ffmpeg")
12380 .args([
12381 "-v",
12382 "error",
12383 "-f",
12384 "lavfi",
12385 "-i",
12386 &gradients_source(seed, width, height, "rate=25"),
12387 "-vf",
12388 // `noise` without `all_seed` re-renders differently on
12389 // every run (seeded-fixture-not-reproducible); pinning it
12390 // makes (seed, cq) name one exact stream.
12391 &format!("noise=alls=40:allf=t:all_seed={seed},format=yuv420p"),
12392 "-t",
12393 "0.04",
12394 "-f",
12395 "yuv4mpegpipe",
12396 "-",
12397 ])
12398 .stdin(Stdio::null())
12399 .stdout(Stdio::piped())
12400 .stderr(Stdio::piped())
12401 .output()
12402 .expect("ffmpeg failed to run");
12403 assert!(
12404 y4m.status.success(),
12405 "ffmpeg fixture: {}",
12406 String::from_utf8_lossy(&y4m.stderr)
12407 );
12408 let mut child = Command::new(aomenc_path())
12409 .args([
12410 "--codec=av1",
12411 "--passes=1",
12412 "--end-usage=q",
12413 &format!("--cq-level={cq}"),
12414 "--cpu-used=0",
12415 "--threads=1",
12416 "--row-mt=0",
12417 "--sb-size=64",
12418 "--min-partition-size=4",
12419 "--max-partition-size=8",
12420 // Below 8x8 only PARTITION_NONE/SPLIT are decodable (HORZ/VERT
12421 // need a real rectangular transform, see the module doc above);
12422 // disabling rect partitions entirely -- not just AB -- keeps
12423 // aomenc from picking the still-refused HORZ/VERT arms almost
12424 // every attempt (round 2 measured ~90% HORZ/VERT-below-8x8
12425 // refusals with --enable-ab-partitions=0 alone).
12426 "--enable-rect-partitions=0",
12427 "--enable-ab-partitions=0",
12428 "--enable-1to4-partitions=1",
12429 "--enable-palette=0",
12430 "--enable-intrabc=0",
12431 "--enable-restoration=0",
12432 "--enable-cdef=0",
12433 "--loopfilter-control=0",
12434 // use_ref_frame_mvs (temporal MV projection) is unimplemented in
12435 // mvstack; this is a key-frame-only fixture, but keep it off for
12436 // safety against a run that emits a second frame.
12437 "--enable-ref-frame-mvs=0",
12438 "--limit=1",
12439 "--obu",
12440 "-o",
12441 "-",
12442 "-",
12443 ])
12444 .args(tile_args)
12445 .stdin(Stdio::piped())
12446 .stdout(Stdio::piped())
12447 .stderr(Stdio::piped())
12448 .spawn()
12449 .expect("aomenc failed to start");
12450 child
12451 .stdin
12452 .take()
12453 .expect("aomenc stdin")
12454 .write_all(&y4m.stdout)
12455 .expect("writing y4m to aomenc");
12456 let out = child.wait_with_output().expect("aomenc failed to run");
12457 if !out.status.success() {
12458 refusals.push(format!(
12459 "seed={seed} cq={cq}: aomenc itself refused the fixture"
12460 ));
12461 continue;
12462 }
12463 let stream = out.stdout;
12464 let before = decode::sub8_split_hits();
12465 let tiles_before = decode::tile_hits();
12466 let frames = match decode_stream(&stream) {
12467 Ok(frames) => frames,
12468 Err(e) => {
12469 // Only a named refusal ("unsupported: ...") is a skip
12470 // reason; any other decode error is this decoder failing.
12471 let msg = e.to_string();
12472 assert!(
12473 msg.starts_with("unsupported: "),
12474 "decode error that is not a named refusal \
12475 (seed={seed} cq={cq} tiles={tile_args:?}): {msg}"
12476 );
12477 refusals.push(format!("seed={seed} cq={cq}: {msg}"));
12478 continue;
12479 }
12480 };
12481 // gate-blind-to-feature: a tile arm must actually decode more
12482 // than one tile, not merely carry `tile_info.cols > 1`.
12483 assert!(
12484 tile_args.is_empty() || decode::tile_hits() - tiles_before >= 2,
12485 "tiles={tile_args:?} decoded only {} tile(s) (seed={seed} cq={cq})",
12486 decode::tile_hits() - tiles_before
12487 );
12488 if decode::sub8_split_hits() == before {
12489 refusals.push(format!(
12490 "seed={seed} cq={cq}: decoded, but no block read a real PARTITION_SPLIT below 8x8"
12491 ));
12492 continue;
12493 }
12494 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
12495 assert_eq!(
12496 frames[0].y, ffmpeg_frames[0].y,
12497 "luma vs ffmpeg (seed={seed} cq={cq})"
12498 );
12499 assert_eq!(
12500 frames[0].u, ffmpeg_frames[0].u,
12501 "U vs ffmpeg (seed={seed} cq={cq})"
12502 );
12503 assert_eq!(
12504 frames[0].v, ffmpeg_frames[0].v,
12505 "V vs ffmpeg (seed={seed} cq={cq})"
12506 );
12507 fired_runs += 1;
12508 if fired_runs >= 4 {
12509 break;
12510 }
12511 }
12512 assert!(
12513 fired_runs >= 4,
12514 "fewer than 4 firing+pixel-exact runs out of 40 attempts \
12515 ({width}x{height} tiles={tile_args:?}):\n{}",
12516 refusals.join("\n")
12517 );
12518 }
12519 }
12520
12521 /// lane-tx4x8: `--enable-rect-partitions=1` with `--min-partition-size=4
12522 /// --max-partition-size=8` on fine-detail noisy gradients makes aomenc
12523 /// pick `PARTITION_VERT`/`PARTITION_HORZ` at the 8x8 level -- two
12524 /// `BLOCK_4X8`/`BLOCK_8X4` leaves, the last sub-8x8 shape this decoder
12525 /// refused (it needed a real `TX_4X8`/`TX_8X4`: rect scan, 32-position
12526 /// `eob_pt`, `TX_4X4` `tx_type` row over `TX_8X8` coefficient tables).
12527 /// Both [`decode::tx4x8_coded_hits`] and [`decode::tx8x4_coded_hits`] are
12528 /// hard-asserted per firing attempt so neither orientation can ride along
12529 /// on the other ([[gate-blind-to-feature]]), and only leaves that coded
12530 /// REAL coefficients count -- a skipped leaf never runs the transform.
12531 /// Arms: 8-bit 16x16, an 8-bit `--tile-columns=1` 128x16 (the mi-granular
12532 /// mode maps are per tile), and a 10-bit 16x16 -- 16-pixel fixtures, for
12533 /// the reason the comment inside the loop gives.
12534 #[test]
12535 fn a_real_aomenc_stream_with_a_sub8_rect_leaf_decodes_pixel_exact() {
12536 const NAME: &str = "a_real_aomenc_stream_with_a_sub8_rect_leaf_decodes_pixel_exact";
12537 if !have_ffmpeg() {
12538 eprintln!("SKIP {NAME}: no ffmpeg");
12539 return;
12540 }
12541 if !have_aomenc() {
12542 let msg = format!("no aomenc at {}", aomenc_path().display());
12543 assert!(
12544 std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
12545 "EC_AV1_REQUIRE_AOMENC is set but {msg}"
12546 );
12547 eprintln!("SKIP {NAME}: {msg}");
12548 return;
12549 }
12550 // 16-pixel-tall/wide fixtures on purpose: at 64x64 EVERY attempt
12551 // dies on a 16x16-LEVEL rect refusal belonging to other lanes
12552 // ("a HORZ/VERT intra strip with a split transform", "a coded
12553 // (non-skip) HORZ/VERT rect strip below 16x16", "a HORZ_A/HORZ_B/
12554 // VERT_A partition below 16x16") -- `--max-partition-size=8` does
12555 // NOT stop aomenc coding a 16x16 as two 16x8 strips, measured
12556 // 39/40 attempts refused. A 16x16 frame is one 16x16 block, so the
12557 // encoder either splits it to 8x8s (this lane's path) or codes it
12558 // whole; measured 12/12 attempts decoding, 3/12 with BOTH
12559 // orientations coded.
12560 for (width, height, tile_args, bit_depth) in [
12561 (16usize, 16usize, &[][..], 8u8),
12562 (128usize, 16usize, &["--tile-columns=1"][..], 8u8),
12563 (16usize, 16usize, &[][..], 10u8),
12564 ] {
12565 let mut refusals = Vec::new();
12566 let mut fired_runs = 0u32;
12567 let mut split_tx = 0usize;
12568 for attempt in 0..40u32 {
12569 let seed = 300 + attempt;
12570 let cq = 6 + (attempt % 4) * 2;
12571 let pix_fmt = if bit_depth == 10 {
12572 "yuv420p10le"
12573 } else {
12574 "yuv420p"
12575 };
12576 let y4m = Command::new("ffmpeg")
12577 .args([
12578 "-v",
12579 "error",
12580 "-f",
12581 "lavfi",
12582 "-i",
12583 &format!("testsrc2=size={width}x{height}:rate=25"),
12584 "-vf",
12585 &format!("noise=alls=40:allf=t:all_seed={seed},format={pix_fmt}"),
12586 "-strict",
12587 "-1",
12588 "-t",
12589 "0.04",
12590 "-f",
12591 "yuv4mpegpipe",
12592 "-",
12593 ])
12594 .stdin(Stdio::null())
12595 .stdout(Stdio::piped())
12596 .stderr(Stdio::piped())
12597 .output()
12598 .expect("ffmpeg failed to run");
12599 assert!(
12600 y4m.status.success(),
12601 "ffmpeg fixture: {}",
12602 String::from_utf8_lossy(&y4m.stderr)
12603 );
12604 let mut child = Command::new(aomenc_path())
12605 .args([
12606 "--codec=av1",
12607 "--passes=1",
12608 "--end-usage=q",
12609 &format!("--cq-level={cq}"),
12610 "--cpu-used=0",
12611 "--threads=1",
12612 "--row-mt=0",
12613 "--sb-size=64",
12614 "--min-partition-size=4",
12615 "--max-partition-size=8",
12616 // The tool under test: rect partitions ON, at a size
12617 // where the only rect shapes are 4x8 and 8x4.
12618 "--enable-rect-partitions=1",
12619 "--enable-ab-partitions=0",
12620 "--enable-1to4-partitions=0",
12621 "--enable-palette=0",
12622 "--enable-intrabc=0",
12623 "--enable-restoration=0",
12624 "--enable-cdef=0",
12625 "--loopfilter-control=0",
12626 "--enable-ref-frame-mvs=0",
12627 // Filter intra on a 4x8/8x4 leaf is refused by name
12628 // (`predict_filter_intra` is square-only in this
12629 // decoder, the same refusal the 16x16-level strips
12630 // carry); with it on, that refusal -- not this
12631 // lane's path -- is what most attempts hit.
12632 "--enable-filter-intra=0",
12633 "--limit=1",
12634 "--obu",
12635 "-o",
12636 "-",
12637 "-",
12638 ])
12639 .args(if bit_depth == 10 {
12640 &["--input-bit-depth=10", "--bit-depth=10"][..]
12641 } else {
12642 &[][..]
12643 })
12644 .args(tile_args)
12645 .stdin(Stdio::piped())
12646 .stdout(Stdio::piped())
12647 .stderr(Stdio::piped())
12648 .spawn()
12649 .expect("aomenc failed to start");
12650 child
12651 .stdin
12652 .take()
12653 .expect("aomenc stdin")
12654 .write_all(&y4m.stdout)
12655 .expect("writing y4m to aomenc");
12656 let out = child.wait_with_output().expect("aomenc failed to run");
12657 if !out.status.success() {
12658 refusals.push(format!(
12659 "seed={seed} cq={cq}: aomenc itself refused the fixture"
12660 ));
12661 continue;
12662 }
12663 let stream = out.stdout;
12664 let vert_before = decode::tx4x8_coded_hits();
12665 let horz_before = decode::tx8x4_coded_hits();
12666 let split_before = decode::rect8_split_tx_hits();
12667 let tiles_before = decode::tile_hits();
12668 let frames = match decode_stream(&stream) {
12669 Ok(frames) => frames,
12670 Err(e) => {
12671 let msg = e.to_string();
12672 assert!(
12673 msg.starts_with("unsupported: "),
12674 "decode error that is not a named refusal \
12675 (seed={seed} cq={cq} depth={bit_depth} tiles={tile_args:?}): {msg}"
12676 );
12677 refusals.push(format!("seed={seed} cq={cq}: {msg}"));
12678 continue;
12679 }
12680 };
12681 assert!(
12682 tile_args.is_empty() || decode::tile_hits() - tiles_before >= 2,
12683 "tiles={tile_args:?} decoded only {} tile(s) (seed={seed} cq={cq})",
12684 decode::tile_hits() - tiles_before
12685 );
12686 let vert = decode::tx4x8_coded_hits() - vert_before;
12687 let horz = decode::tx8x4_coded_hits() - horz_before;
12688 if vert == 0 || horz == 0 {
12689 refusals.push(format!(
12690 "seed={seed} cq={cq}: decoded, but coded 4x8={vert} 8x4={horz} leaves"
12691 ));
12692 continue;
12693 }
12694 let ffmpeg_frames = if bit_depth == 10 {
12695 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
12696 } else {
12697 ffmpeg_decode_sequence(&stream, width, height, 1)
12698 };
12699 assert_eq!(
12700 frames[0].y, ffmpeg_frames[0].y,
12701 "luma vs ffmpeg (seed={seed} cq={cq} depth={bit_depth} tiles={tile_args:?})"
12702 );
12703 assert_eq!(
12704 frames[0].u, ffmpeg_frames[0].u,
12705 "U vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})"
12706 );
12707 assert_eq!(
12708 frames[0].v, ffmpeg_frames[0].v,
12709 "V vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})"
12710 );
12711 fired_runs += 1;
12712 split_tx += decode::rect8_split_tx_hits() - split_before;
12713 if fired_runs >= 4 {
12714 break;
12715 }
12716 }
12717 assert!(
12718 fired_runs >= 4,
12719 "fewer than 4 firing+pixel-exact runs out of 40 attempts \
12720 ({width}x{height} depth={bit_depth} tiles={tile_args:?}):\n{}",
12721 refusals.join("\n")
12722 );
12723 // aomenc's default `--enable-tx-size-search=1` makes TX_MODE_SELECT
12724 // the frame's tx mode, so every sub-8x8 rect leaf carries a
12725 // `tx_depth` symbol; depth 1 (two 4x4 transform units predicted one
12726 // after the other) is the half of that path a whole-leaf transform
12727 // would silently get wrong, so the gate proves it fired.
12728 assert!(
12729 split_tx > 0,
12730 "no sub-8x8 rect leaf used a split (depth-1) transform in the \
12731 {fired_runs} pixel-exact runs ({width}x{height} depth={bit_depth})"
12732 );
12733 }
12734 }
12735
12736 /// lane-fi8 r1: the sub8 rect-leaf gate above with the tool under test
12737 /// turned ON (`--enable-filter-intra=1`, appended AFTER the base recipe
12738 /// -- aomenc takes the FIRST occurrence of a repeated flag, so the base
12739 /// recipe below carries no `--enable-filter-intra` at all). A DC_PRED
12740 /// `BLOCK_4X8`/`BLOCK_8X4` leaf carries a `use_filter_intra` flag
12741 /// (`av1_filter_intra_allowed_bsize` is "both sides <= 32"), which this
12742 /// decoder read from `BLOCK_4X4`'s CDF row until this round -- the same
12743 /// VALUE, a different interval, so it desynced a block or two later
12744 /// ([[wrong-alphabet-same-value]]) -- and then refused the prediction by
12745 /// name. Per attempt, only runs whose [`decode::filter_intra_rect_sub8_hits`]
12746 /// delta is nonzero AND whose three planes match ffmpeg count; the wider
12747 /// `filter_intra_rect_hits` would be satisfied by a 16x8 strip and prove
12748 /// nothing about these shapes. Arms cover both transform depths
12749 /// (`--enable-tx-size-search=1`, where a leaf may split into two 4x4
12750 /// units each predicted from the previous one's reconstruction, and `=0`,
12751 /// one whole-leaf transform) and both bit depths.
12752 #[test]
12753 fn a_real_aomenc_stream_with_filter_intra_on_a_sub8_rect_leaf_decodes_pixel_exact() {
12754 const NAME: &str =
12755 "a_real_aomenc_stream_with_filter_intra_on_a_sub8_rect_leaf_decodes_pixel_exact";
12756 if !have_ffmpeg() {
12757 eprintln!("SKIP {NAME}: no ffmpeg");
12758 return;
12759 }
12760 if !have_aomenc() {
12761 let msg = format!("no aomenc at {}", aomenc_path().display());
12762 assert!(
12763 std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
12764 "EC_AV1_REQUIRE_AOMENC is set but {msg}"
12765 );
12766 eprintln!("SKIP {NAME}: {msg}");
12767 return;
12768 }
12769 let (width, height) = (16usize, 16usize);
12770 for (tx_search, bit_depth) in [("1", 8u8), ("0", 8u8), ("1", 10u8)] {
12771 let mut refusals = Vec::new();
12772 let mut fired_runs = 0u32;
12773 let mut fi_leaves = 0usize;
12774 let mut split_tx = 0usize;
12775 for attempt in 0..80u32 {
12776 let seed = 300 + attempt;
12777 let cq = 6 + (attempt % 8) * 6;
12778 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
12779 let y4m = Command::new("ffmpeg")
12780 .args([
12781 "-v", "error", "-f", "lavfi", "-i",
12782 &format!("testsrc2=size={width}x{height}:rate=25"),
12783 "-vf",
12784 &format!("noise=alls=40:allf=t:all_seed={seed},format={pix_fmt}"),
12785 "-strict", "-1", "-t", "0.04", "-f", "yuv4mpegpipe", "-",
12786 ])
12787 .stdin(Stdio::null())
12788 .stdout(Stdio::piped())
12789 .stderr(Stdio::piped())
12790 .output()
12791 .expect("ffmpeg failed to run");
12792 assert!(
12793 y4m.status.success(),
12794 "ffmpeg fixture: {}",
12795 String::from_utf8_lossy(&y4m.stderr)
12796 );
12797 let mut child = Command::new(aomenc_path())
12798 .args([
12799 "--codec=av1",
12800 "--passes=1",
12801 "--end-usage=q",
12802 &format!("--cq-level={cq}"),
12803 "--cpu-used=0",
12804 "--threads=1",
12805 "--row-mt=0",
12806 "--sb-size=64",
12807 "--min-partition-size=4",
12808 "--max-partition-size=8",
12809 "--enable-rect-partitions=1",
12810 "--enable-ab-partitions=0",
12811 "--enable-1to4-partitions=0",
12812 "--enable-palette=0",
12813 "--enable-intrabc=0",
12814 "--enable-restoration=0",
12815 "--enable-cdef=0",
12816 "--loopfilter-control=0",
12817 "--enable-ref-frame-mvs=0",
12818 // The tools under test, first occurrence in the
12819 // command line (aomenc keeps the first).
12820 "--enable-filter-intra=1",
12821 &format!("--enable-tx-size-search={tx_search}"),
12822 "--limit=1",
12823 "--obu",
12824 "-o",
12825 "-",
12826 "-",
12827 ])
12828 .args(if bit_depth == 10 {
12829 &["--input-bit-depth=10", "--bit-depth=10"][..]
12830 } else {
12831 &[][..]
12832 })
12833 .stdin(Stdio::piped())
12834 .stdout(Stdio::piped())
12835 .stderr(Stdio::piped())
12836 .spawn()
12837 .expect("aomenc failed to start");
12838 child
12839 .stdin
12840 .take()
12841 .expect("aomenc stdin")
12842 .write_all(&y4m.stdout)
12843 .expect("writing y4m to aomenc");
12844 let out = child.wait_with_output().expect("aomenc failed to run");
12845 if !out.status.success() {
12846 refusals.push(format!("seed={seed} cq={cq}: aomenc itself refused"));
12847 continue;
12848 }
12849 let stream = out.stdout;
12850 let fi_before = decode::filter_intra_rect_sub8_hits();
12851 let split_before = decode::rect8_split_tx_hits();
12852 let frames = match decode_stream(&stream) {
12853 Ok(frames) => frames,
12854 Err(e) => {
12855 let msg = e.to_string();
12856 assert!(
12857 msg.starts_with("unsupported: "),
12858 "decode error that is not a named refusal \
12859 (seed={seed} cq={cq} depth={bit_depth} txs={tx_search}): {msg}"
12860 );
12861 refusals.push(format!("seed={seed} cq={cq}: {msg}"));
12862 continue;
12863 }
12864 };
12865 let fi = decode::filter_intra_rect_sub8_hits() - fi_before;
12866 if fi == 0 {
12867 refusals.push(format!(
12868 "seed={seed} cq={cq}: decoded, but no 4x8/8x4 leaf used filter intra"
12869 ));
12870 continue;
12871 }
12872 let ffmpeg_frames = if bit_depth == 10 {
12873 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
12874 } else {
12875 ffmpeg_decode_sequence(&stream, width, height, 1)
12876 };
12877 assert_eq!(
12878 frames[0].y, ffmpeg_frames[0].y,
12879 "luma vs ffmpeg (seed={seed} cq={cq} depth={bit_depth} txs={tx_search})"
12880 );
12881 assert_eq!(
12882 frames[0].u, ffmpeg_frames[0].u,
12883 "U vs ffmpeg (seed={seed} cq={cq} depth={bit_depth} txs={tx_search})"
12884 );
12885 assert_eq!(
12886 frames[0].v, ffmpeg_frames[0].v,
12887 "V vs ffmpeg (seed={seed} cq={cq} depth={bit_depth} txs={tx_search})"
12888 );
12889 fired_runs += 1;
12890 fi_leaves += fi;
12891 split_tx += decode::rect8_split_tx_hits() - split_before;
12892 if fired_runs >= 3 {
12893 break;
12894 }
12895 }
12896 assert!(
12897 fired_runs >= 3,
12898 "{NAME}: fewer than 3 firing+pixel-exact runs out of 80 attempts \
12899 (depth={bit_depth} txs={tx_search}), {fi_leaves} filter-intra sub8 leaves \
12900 seen:\n{}",
12901 refusals.join("\n")
12902 );
12903 if tx_search == "1" {
12904 assert!(
12905 split_tx > 0,
12906 "{NAME}: no sub-8x8 rect leaf used a split (depth-1) transform in the \
12907 {fired_runs} pixel-exact runs (depth={bit_depth})"
12908 );
12909 }
12910 eprintln!(
12911 "{NAME}: depth={bit_depth} txs={tx_search} {fired_runs} pixel-exact runs, \
12912 {fi_leaves} filter-intra 4x8/8x4 leaves, split_tx={split_tx}"
12913 );
12914 }
12915 }
12916
12917 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
12918 /// a 16x8/8x16 intra strip whose DIRECTIONAL mode reads above-right or
12919 /// below-left samples. Which of those the decoder may read is
12920 /// `Reach::of_rect`'s answer, and until this round `rect_reach_tables`
12921 /// had no 16x8 row at all -- every 16x8 strip read libaom's `has_tr_32x16`
12922 /// row instead of `has_tr_16x8`, wrong at 10 of the 21 reachable
12923 /// superblock positions for above-right and 7 for below-left. No gate saw
12924 /// it: the sibling strip gate (`coded_rect_strip_below_16x16`) runs with
12925 /// smooth/paeth/DC modes, which never read past the block, so the wrong
12926 /// bit changed no pixel there.
12927 ///
12928 /// So this gate turns every non-directional intra tool OFF
12929 /// (`--enable-smooth-intra=0 --enable-paeth-intra=0
12930 /// --enable-filter-intra=0`) at `--min-partition-size=8
12931 /// --max-partition-size=16 --enable-rect-partitions=1`, and counts, per
12932 /// attempt, the 16x8/8x16 strips whose prediction actually reached past
12933 /// their own width or height ([`decode::rect_strip_reach_hits`], recorded
12934 /// in the predictor's edge fetch). An attempt only counts when that
12935 /// counter moved AND the frame is pixel-exact against ffmpeg.
12936 ///
12937 /// BLOCKED, and `#[ignore]`d for it, not skipped from inside
12938 /// ([[gate-skips-on-its-own-failure]]): the 16x16-level strip decoder
12939 /// refuses every NON-SKIP 16x8/8x16 strip ("a coded (non-skip) HORZ/VERT
12940 /// rect strip below 16x16", `decode.rs`), and that is what real streams
12941 /// contain -- measured on this exact recipe, 38 of 40 attempts died on
12942 /// that refusal and 2 on a sub-16x16 AB partition, at cq 30/45/58 and at
12943 /// `--min-partition-size=16` (which yields no 16x8 at all, aomenc bounds a
12944 /// rect shape by its smaller side). What unblocks it: the lane that ports
12945 /// the coded 16x16-level strip; then drop this attribute. Until then the
12946 /// table routing is pinned by the domain test
12947 /// `encode::tests::every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock`
12948 /// against libaom's own `has_tr_*`/`has_bl_*` arrays.
12949 #[test]
12950 #[ignore = "the coded 16x8/8x16 strip is a live refusal; see the doc above"]
12951 fn a_directional_16x8_strip_reads_the_right_above_right_samples() {
12952 const NAME: &str = "a_directional_16x8_strip_reads_the_right_above_right_samples";
12953 if !have_ffmpeg() {
12954 eprintln!("SKIP {NAME}: no ffmpeg");
12955 return;
12956 }
12957 if !have_aomenc() {
12958 let msg = format!("no aomenc at {}", aomenc_path().display());
12959 assert!(
12960 std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
12961 "EC_AV1_REQUIRE_AOMENC is set but {msg}"
12962 );
12963 eprintln!("SKIP {NAME}: {msg}");
12964 return;
12965 }
12966 // 64x16, not 64x64: a 16-tall frame is a single row of 16x16 blocks,
12967 // so a HORZ arm is a 16x8 strip at column 0..3 of the superblock --
12968 // exactly the positions whose `has_tr_16x8`/`has_bl_16x8` bit the old
12969 // routing got wrong -- while the frame is too short for aomenc to
12970 // build the deep sub-16x16 partitions other lanes still refuse. It
12971 // must also be WIDER than one block: at width 16 the block is the
12972 // frame, and `x + bw < width` kills above-right before any table.
12973 for (width, height, bit_depth) in [(64usize, 16usize, 8u8), (64, 16, 10u8)] {
12974 let mut refusals = Vec::new();
12975 let mut fired_runs = 0u32;
12976 let mut reach_hits = 0usize;
12977 for attempt in 0..40u32 {
12978 let seed = 700 + attempt;
12979 // Coarse quantisers on lightly-dithered content: fine detail
12980 // at low cq makes aomenc build the sub-16x16 partitions other
12981 // lanes refuse, and 40/40 attempts died there.
12982 let cq = 45 + (attempt % 4);
12983 let half = height / 2;
12984 let pix_fmt = if bit_depth == 10 {
12985 "yuv420p10le"
12986 } else {
12987 "yuv420p"
12988 };
12989 let y4m = Command::new("ffmpeg")
12990 .args([
12991 "-v",
12992 "error",
12993 "-f",
12994 "lavfi",
12995 "-i",
12996 &format!("testsrc2=size={width}x{half}:rate=25"),
12997 "-f",
12998 "lavfi",
12999 "-i",
13000 &format!("color=c=gray:s={width}x{half}:rate=25"),
13001 "-filter_complex",
13002 &format!(
13003 "[0]noise=alls=8:allf=t:all_seed={seed}[t];[t][1]vstack,\
13004 format={pix_fmt}"
13005 ),
13006 "-strict",
13007 "-1",
13008 "-t",
13009 "0.04",
13010 "-f",
13011 "yuv4mpegpipe",
13012 "-",
13013 ])
13014 .stdin(Stdio::null())
13015 .stdout(Stdio::piped())
13016 .stderr(Stdio::piped())
13017 .output()
13018 .expect("ffmpeg failed to run");
13019 assert!(
13020 y4m.status.success(),
13021 "ffmpeg fixture: {}",
13022 String::from_utf8_lossy(&y4m.stderr)
13023 );
13024 let mut child = Command::new(aomenc_path())
13025 .args([
13026 "--codec=av1",
13027 "--passes=1",
13028 "--end-usage=q",
13029 &format!("--cq-level={cq}"),
13030 "--cpu-used=0",
13031 "--threads=1",
13032 "--row-mt=0",
13033 "--sb-size=64",
13034 // The tool under test: 16x8/8x16 strips, predicted by
13035 // a mode that reads beyond the block.
13036 // aomenc bounds a RECT shape by its smaller side, so
13037 // `--min-partition-size=16` yields no 16x8 at all
13038 // (measured: 0 strips in 40 attempts); 8 is the
13039 // smallest value that lets a 16x16 split HORZ/VERT.
13040 "--min-partition-size=8",
13041 "--max-partition-size=16",
13042 // Largest transform per block: a split (depth-1) rect
13043 // strip is a named refusal of another lane, and it
13044 // ate every attempt while it was on.
13045 "--enable-tx-size-search=0",
13046 "--enable-rect-partitions=1",
13047 "--enable-directional-intra=1",
13048 "--enable-smooth-intra=0",
13049 "--enable-paeth-intra=0",
13050 "--enable-filter-intra=0",
13051 "--enable-ab-partitions=0",
13052 "--enable-1to4-partitions=0",
13053 "--enable-palette=0",
13054 "--enable-intrabc=0",
13055 "--enable-restoration=0",
13056 "--enable-cdef=0",
13057 "--loopfilter-control=0",
13058 "--enable-ref-frame-mvs=0",
13059 "--limit=1",
13060 "--obu",
13061 "-o",
13062 "-",
13063 "-",
13064 ])
13065 .args(if bit_depth == 10 {
13066 &["--input-bit-depth=10", "--bit-depth=10"][..]
13067 } else {
13068 &[][..]
13069 })
13070 .stdin(Stdio::piped())
13071 .stdout(Stdio::piped())
13072 .stderr(Stdio::piped())
13073 .spawn()
13074 .expect("aomenc failed to start");
13075 child
13076 .stdin
13077 .take()
13078 .expect("aomenc stdin")
13079 .write_all(&y4m.stdout)
13080 .expect("writing y4m to aomenc");
13081 let out = child.wait_with_output().expect("aomenc failed to run");
13082 if !out.status.success() {
13083 refusals.push(format!(
13084 "seed={seed} cq={cq}: aomenc itself refused the fixture"
13085 ));
13086 continue;
13087 }
13088 let stream = out.stdout;
13089 let reach_before = decode::rect_strip_reach_hits();
13090 let pred_before = decode::rect_strip_pred_hits();
13091 let frames = match decode_stream(&stream) {
13092 Ok(frames) => frames,
13093 Err(e) => {
13094 let msg = e.to_string();
13095 assert!(
13096 msg.starts_with("unsupported: "),
13097 "decode error that is not a named refusal \
13098 (seed={seed} cq={cq} depth={bit_depth}): {msg}"
13099 );
13100 refusals.push(format!("seed={seed} cq={cq}: {msg}"));
13101 continue;
13102 }
13103 };
13104 let reached = decode::rect_strip_reach_hits() - reach_before;
13105 let predicted = decode::rect_strip_pred_hits() - pred_before;
13106 if predicted == 0 {
13107 refusals.push(format!(
13108 "seed={seed} cq={cq}: decoded, but no 16x8/8x16 strip in the frame"
13109 ));
13110 continue;
13111 }
13112 let ffmpeg_frames = if bit_depth == 10 {
13113 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
13114 } else {
13115 ffmpeg_decode_sequence(&stream, width, height, 1)
13116 };
13117 assert_eq!(
13118 frames[0].y, ffmpeg_frames[0].y,
13119 "luma vs ffmpeg (seed={seed} cq={cq} depth={bit_depth}, {predicted} strips, \
13120 {reached} of them reaching)"
13121 );
13122 assert_eq!(
13123 frames[0].u, ffmpeg_frames[0].u,
13124 "U vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})"
13125 );
13126 assert_eq!(
13127 frames[0].v, ffmpeg_frames[0].v,
13128 "V vs ffmpeg (seed={seed} cq={cq} depth={bit_depth})"
13129 );
13130 fired_runs += 1;
13131 reach_hits += reached;
13132 if fired_runs >= 4 {
13133 break;
13134 }
13135 }
13136 assert!(
13137 fired_runs >= 4,
13138 "fewer than 4 firing+pixel-exact runs out of 40 attempts \
13139 ({width}x{height} depth={bit_depth}, {reach_hits} reaching strips):\n{}",
13140 refusals.join("\n")
13141 );
13142 }
13143 }
13144
13145 /// lane-av1golden7 r9's decisive fixture: a real aomenc stream (seed 59,
13146 /// `--tune-content=film`, GOLDEN_FRAME firing downstream) whose frame-0
13147 /// *intra keyframe* mismatched ffmpeg on 3855/4096 luma pixels -- traced
13148 /// to `apply_grain=true` (spec 7.18.3 grain synthesis, now implemented in
13149 /// `crate::film_grain`), entirely unrelated to GOLDEN_FRAME or frame
13150 /// ordering. Frames beyond 0 in this fixture hit an unrelated, pre-existing
13151 /// gap (`decode_inter_block`'s GOLDEN_FRAME MC path, lane-av1golden7's own
13152 /// `golden7-forwarding-mismatch.obu`), so this test truncates the stream to
13153 /// the sequence header + frame-0 OBUs only -- exactly the span the
13154 /// mismatch was traced to -- rather than reaching into `decode.rs`/`mc.rs`
13155 /// to widen MC support, which is out of this lane's scope.
13156 #[test]
13157 fn a_real_aomenc_stream_with_film_grain_decodes_pixel_exact() {
13158 if !have_ffmpeg() {
13159 eprintln!("SKIP a_real_aomenc_stream_with_film_grain_decodes_pixel_exact: no ffmpeg");
13160 return;
13161 }
13162 let data = std::fs::read(concat!(
13163 env!("CARGO_MANIFEST_DIR"),
13164 "/../../fixtures/golden6-mismatch.obu"
13165 ))
13166 .unwrap();
13167 // Truncate right after the first `Frame` OBU (the key frame): every
13168 // byte up to there is sequence header + frame-0, which is a complete,
13169 // independently decodable single-frame stream.
13170 let mut parser = Av1Parser::new();
13171 let mut pos = 0usize;
13172 let mut frame0_end = None;
13173 while pos < data.len() {
13174 let obu = parser.parse_obu(&data[pos..]).unwrap();
13175 pos += obu.total_size;
13176 if matches!(obu.kind, ObuKind::Frame(..)) {
13177 frame0_end = Some(pos);
13178 break;
13179 }
13180 }
13181 let data = &data[..frame0_end.expect("fixture has at least one frame OBU")];
13182 let (width, height) = (64usize, 64usize);
13183 let ffmpeg_frames = ffmpeg_decode_sequence(data, width, height, 1);
13184 let decoded = decode_stream(data).unwrap();
13185 assert_eq!(decoded.len(), 1);
13186 let (got, want) = (&decoded[0], &ffmpeg_frames[0]);
13187 assert_eq!(got.y, want.y, "frame 0 luma vs ffmpeg (film grain)");
13188 assert_eq!(got.u, want.u, "frame 0 U vs ffmpeg (film grain)");
13189 assert_eq!(got.v, want.v, "frame 0 V vs ffmpeg (film grain)");
13190 }
13191
13192 /// A real-encoder sweep, not just the one pinned fixture above
13193 /// (fixture-proves-symbol-not-signal class): several fresh
13194 /// `--tune-content=film` draws at different seeds/content, each decoded
13195 /// pixel-exact against ffmpeg's own AV1 decoder (which synthesizes grain
13196 /// by default -- confirmed via `ffmpeg -h decoder=av1`, no
13197 /// `-export_side_data`/grain-disable flag is passed anywhere in this
13198 /// file).
13199 #[test]
13200 fn real_aomenc_film_grain_streams_decode_pixel_exact() {
13201 if !have_ffmpeg() {
13202 eprintln!("SKIP real_aomenc_film_grain_streams_decode_pixel_exact: no ffmpeg");
13203 return;
13204 }
13205 if !have_aomenc() {
13206 eprintln!("SKIP real_aomenc_film_grain_streams_decode_pixel_exact: no aomenc");
13207 return;
13208 }
13209 let (width, height) = (64usize, 64usize);
13210 for seed in [1u64, 2, 3] {
13211 let dir = std::env::temp_dir().join(format!(
13212 "ec-av1-filmgrain-gate-{}-{seed}",
13213 std::process::id()
13214 ));
13215 std::fs::create_dir_all(&dir).unwrap();
13216 let yuv_path = dir.join("in.yuv");
13217 let obu_path = dir.join("out.obu");
13218 let frames = 3usize;
13219 let luma = width * height;
13220 let chroma = luma / 4;
13221 let mut yuv = Vec::with_capacity((luma + 2 * chroma) * frames);
13222 for f in 0..frames {
13223 let card = panned_test_card(width, height, ((f as i32 + seed as i32) * 5) as i64);
13224 yuv.extend(card.y.iter().map(|&v| v as u8));
13225 yuv.extend(card.u.iter().map(|&v| v as u8));
13226 yuv.extend(card.v.iter().map(|&v| v as u8));
13227 }
13228 std::fs::write(&yuv_path, &yuv).unwrap();
13229 let status = Command::new(aomenc_path())
13230 .args([
13231 &format!("--width={width}"),
13232 &format!("--height={height}"),
13233 "--input-bit-depth=8",
13234 "--bit-depth=8",
13235 "--fps=25/1",
13236 &format!("--limit={frames}"),
13237 // The full constraint set of the forwarding/golden gates,
13238 // so the streams stay inside this decoder's supported
13239 // envelope and the gate isolates grain synthesis alone;
13240 // `--tune-content=film` is the one flag under test (it
13241 // enables apply_grain).
13242 "--codec=av1",
13243 "--passes=1",
13244 "--end-usage=q",
13245 "--cq-level=32",
13246 "--cpu-used=0",
13247 "--lag-in-frames=0",
13248 "--auto-alt-ref=0",
13249 "--kf-max-dist=1000",
13250 "--threads=1",
13251 "--row-mt=0",
13252 "--max-reference-frames=3",
13253 "--reduced-reference-set=1",
13254 "--enable-warped-motion=0",
13255 "--enable-obmc=0",
13256 "--enable-masked-comp=0",
13257 "--enable-interintra-comp=0",
13258 "--enable-dist-wtd-comp=0",
13259 "--enable-diff-wtd-comp=0",
13260 "--enable-onesided-comp=0",
13261 "--enable-interintra-wedge=0",
13262 "--enable-smooth-interintra=0",
13263 "--enable-rect-partitions=0",
13264 "--enable-ab-partitions=0",
13265 "--enable-1to4-partitions=0",
13266 "--enable-filter-intra=0",
13267 "--enable-smooth-intra=0",
13268 "--enable-paeth-intra=0",
13269 "--enable-directional-intra=0",
13270 "--enable-angle-delta=0",
13271 "--enable-tx-size-search=0",
13272 "--enable-cdef=0",
13273 "--enable-restoration=0",
13274 "--max-partition-size=32",
13275 "--min-partition-size=32",
13276 "--enable-palette=0",
13277 "--enable-intrabc=0",
13278 "--enable-cfl-intra=0",
13279 // Temporal MV projection (`use_ref_frame_mvs`) has no
13280 // decode path here (`mvstack.rs`'s documented corner-cut:
13281 // `zero_mv_ctx` and the mode-context GLOBALMV_OFFSET bit
13282 // are always computed as if it were off) -- this gate
13283 // isolates grain synthesis, so it must stay inside that
13284 // envelope like every other feature disabled above, not
13285 // silently decode a wrong mode context. Root cause of
13286 // this test's frame-1 mismatch: aomenc turns
13287 // `use_ref_frame_mvs` on by default once order hints are
13288 // enabled, unrelated to `--tune-content=film`.
13289 "--enable-ref-frame-mvs=0",
13290 "--tune-content=film",
13291 "--obu",
13292 "-o",
13293 ])
13294 .arg(&obu_path)
13295 .arg(&yuv_path)
13296 .stdout(Stdio::null())
13297 .stderr(Stdio::null())
13298 .status()
13299 .expect("aomenc failed to start");
13300 assert!(status.success(), "aomenc failed for seed {seed}");
13301 let encoded = std::fs::read(&obu_path).unwrap();
13302 let _ = std::fs::remove_dir_all(&dir);
13303
13304 let mut parser = ec_av1_syntax::Av1Parser::new();
13305 let mut pos = 0usize;
13306 let mut saw_grain = false;
13307 while pos < encoded.len() {
13308 let obu = parser.parse_obu(&encoded[pos..]).unwrap();
13309 pos += obu.total_size;
13310 if let ec_av1_syntax::ObuKind::Frame(header, _) = obu.kind
13311 && header.film_grain.apply_grain
13312 {
13313 saw_grain = true;
13314 }
13315 }
13316 assert!(saw_grain, "seed {seed}: aomenc did not turn on apply_grain");
13317
13318 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded, width, height, frames);
13319 let decoded = decode_stream(&encoded).unwrap();
13320 assert_eq!(decoded.len(), frames, "seed {seed}");
13321 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
13322 assert_eq!(got.y, want.y, "seed {seed} frame {i} luma vs ffmpeg");
13323 assert_eq!(got.u, want.u, "seed {seed} frame {i} U vs ffmpeg");
13324 assert_eq!(got.v, want.v, "seed {seed} frame {i} V vs ffmpeg");
13325 }
13326 }
13327 }
13328
13329 /// lane-tiles r3/r7: a real two-tile-column aomenc key frame, decoded
13330 /// through [`decode_key_frame_tile_with_cdfs`] directly with the whole
13331 /// `tiles: &[&[u8]]` list -- `decode_stream`'s `cols > 1 || rows > 1`
13332 /// refusal (this file, ~line 292) still fires for any stream this wide,
13333 /// so this gate bypasses it on purpose to prove the per-tile loop r2
13334 /// landed (fresh `SymbolDecoder`/CDF copy per tile, `Neighbours::start_tile`,
13335 /// `PlaneBuf::set_tile_origin`) actually decodes both tiles pixel-exact
13336 /// before that refusal is lifted. 128x64 is exactly two 64x64
13337 /// superblocks wide with `--tile-columns=1` (`TileCols=2`), so tile 1 is
13338 /// also the frame's own right edge -- the known gap (`PlaneBuf`'s
13339 /// tile_x0/tile_y0 only clip left/top reach, not a non-last column's
13340 /// right-edge reach) does not apply to this fixture; it would to a
13341 /// 3+-column one, proven separately by the four-tile-column gate below.
13342 /// r7: `--loopfilter-control=0` REMOVED per the charter -- `PlaneBuf`'s
13343 /// `tile_x1`/`tile_y1` clamps now receive real values at every call site
13344 /// (r6's `set_tile_origin` sweep), so this gate now proves real
13345 /// deblocking across the tile boundary too, not just decode with it off.
13346 /// Tile count itself is a structural aomenc param, not
13347 /// RD-dependent content, but this decoder's chroma smooth/paeth gap
13348 /// (`decode.rs` "a smooth or paeth chroma mode (round 2)", unrelated to
13349 /// tiles, pre-dating this lane) is content-dependent -- no aomenc flag
13350 /// disables UV-only smooth/paeth search, so a small seed sweep is
13351 /// needed the same way the sibling `a_real_aomenc_stream_with_*` gates
13352 /// retry past unrelated named refusals (every refusal in this crate is
13353 /// prefixed `"AV1 tile"` regardless of category, so unlike the sibling
13354 /// gates' `warp`/`obmc`/`interintra` banned lists there is no
13355 /// tile-specific substring to forbid here -- `matched > 0` plus the
13356 /// hard `tile_hits > 1`/pixel-exact asserts on any actual decode are
13357 /// the real proof).
13358 #[test]
13359 fn a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact() {
13360 const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact";
13361 if !have_ffmpeg() {
13362 eprintln!("SKIP {NAME}: no ffmpeg");
13363 return;
13364 }
13365 if !have_aomenc() {
13366 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13367 return;
13368 }
13369 let (width, height) = (128usize, 64usize);
13370 let mut matched = 0u32;
13371 let mut named_refusals = 0u32;
13372 for attempt in 0..20u32 {
13373 let seed = 42 + attempt;
13374 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
13375 let y4m = Command::new("ffmpeg")
13376 .args([
13377 "-v",
13378 "error",
13379 "-f",
13380 "lavfi",
13381 "-i",
13382 &source,
13383 "-pix_fmt",
13384 "yuv420p",
13385 "-f",
13386 "yuv4mpegpipe",
13387 "-",
13388 ])
13389 .stdin(Stdio::null())
13390 .stdout(Stdio::piped())
13391 .stderr(Stdio::piped())
13392 .output()
13393 .expect("ffmpeg failed to run");
13394 assert!(
13395 y4m.status.success(),
13396 "ffmpeg fixture: {}",
13397 String::from_utf8_lossy(&y4m.stderr)
13398 );
13399 let mut child = Command::new(aomenc_path())
13400 .args([
13401 "--codec=av1",
13402 "--passes=1",
13403 "--end-usage=q",
13404 "--cq-level=45",
13405 "--cpu-used=0",
13406 "--limit=1",
13407 "--kf-max-dist=1000",
13408 "--threads=1",
13409 "--row-mt=0",
13410 "--tile-columns=1",
13411 "--tile-rows=0",
13412 // This decoder hardcodes SB_MI=16 (64px) superblocks
13413 // everywhere (`decode.rs`'s sb128 dead-end, ledger
13414 // `av1-superblock-contexts`) -- without this, aomenc's
13415 // own default 128x128 superblock makes 128x64 exactly
13416 // ONE superblock wide, so `--tile-columns=1` has nothing
13417 // to split and `cols` comes back 1.
13418 "--sb-size=64",
13419 // Deblocking crosses tile boundaries by default (spec
13420 // `loop_filter_across_tiles_enabled`); `PlaneBuf`'s
13421 // tile_x0/tile_y0 origin only ever clips a tile's own
13422 // left/top reach (r2/r3's documented known gap), so a
13423 // non-last tile column's right-edge deblock would read
13424 // into the next tile's still-undecoded/differently-
13425 // origined samples. Off here since deblocking itself is
13426 // not what this gate is proving.
13427 "--enable-rect-partitions=0",
13428 "--enable-ab-partitions=0",
13429 "--enable-1to4-partitions=0",
13430 "--enable-filter-intra=0",
13431 "--enable-smooth-intra=0",
13432 "--enable-paeth-intra=0",
13433 "--enable-directional-intra=0",
13434 "--enable-angle-delta=0",
13435 "--enable-tx-size-search=0",
13436 "--enable-cdef=0",
13437 "--enable-restoration=0",
13438 "--max-partition-size=32",
13439 "--min-partition-size=32",
13440 "--enable-palette=0",
13441 "--enable-intrabc=0",
13442 "--enable-cfl-intra=0",
13443 "--obu",
13444 "-o",
13445 "-",
13446 "-",
13447 ])
13448 .stdin(Stdio::piped())
13449 .stdout(Stdio::piped())
13450 .stderr(Stdio::piped())
13451 .spawn()
13452 .expect("aomenc failed to start");
13453 child
13454 .stdin
13455 .take()
13456 .expect("aomenc stdin")
13457 .write_all(&y4m.stdout)
13458 .expect("writing y4m to aomenc");
13459 let out = child.wait_with_output().expect("aomenc failed to run");
13460 assert!(
13461 out.status.success(),
13462 "aomenc refused the fixture: {}",
13463 String::from_utf8_lossy(&out.stderr)
13464 );
13465 let stream = out.stdout;
13466
13467 // Parse the stream ourselves (rather than `decode_stream`, whose
13468 // multi-tile refusal is exactly what this gate exists to run
13469 // ahead of) to reach the real `Frame` OBU's `tile_info` and its
13470 // full `Vec<Tile>` -- `Av1Parser::parse_obu` already locates
13471 // every tile in a multi-tile tile group (`parse_tile_group`), it
13472 // is only `decode_stream` that ever narrows this to
13473 // `tiles.first()`.
13474 let mut parser = Av1Parser::new();
13475 let mut pos = 0usize;
13476 let mut frame = None;
13477 while pos < stream.len() {
13478 let obu_offset = pos;
13479 let obu = parser.parse_obu(&stream[pos..]).unwrap();
13480 pos += obu.total_size;
13481 if let ObuKind::Frame(header, tiles) = obu.kind {
13482 frame = Some((header, tiles, obu_offset));
13483 break;
13484 }
13485 }
13486 let (header, tiles, obu_offset) = frame.expect("stream has a Frame OBU");
13487 assert!(
13488 header.tile_info.cols > 1,
13489 "{NAME}: aomenc did not actually split into >1 tile column (cols={}, seed {seed})",
13490 header.tile_info.cols
13491 );
13492 assert_eq!(
13493 tiles.len(),
13494 header.tile_info.cols as usize,
13495 "{NAME}: expected one tile per column (seed {seed})"
13496 );
13497 // `Tile::offset` is relative to the buffer `parse_obu` was
13498 // handed (`&stream[pos..]` at the time this OBU was parsed), so
13499 // it needs `obu_offset` added back -- the same adjustment
13500 // `decode_stream` makes for its own single-tile slice above.
13501 let tile_bufs: Vec<&[u8]> = tiles
13502 .iter()
13503 .map(|t| &stream[obu_offset + t.offset..obu_offset + t.offset + t.size])
13504 .collect();
13505
13506 let enable_filter_intra = parser
13507 .sequence_header()
13508 .is_some_and(|seq| seq.enable_filter_intra);
13509 let enable_edge_filter = parser
13510 .sequence_header()
13511 .is_some_and(|seq| seq.enable_intra_edge_filter);
13512
13513 let before = crate::decode::tile_hits();
13514 let picture = match decode_key_frame_tile_with_cdfs(
13515 &tile_bufs,
13516 &header.tile_info,
13517 header.mi_cols,
13518 header.mi_rows,
13519 header.quantization.base_q_idx,
13520 crate::quant::QuantDeltas {
13521 y_dc: i32::from(header.quantization.delta_q_y_dc),
13522 u_dc: i32::from(header.quantization.delta_q_u_dc),
13523 u_ac: i32::from(header.quantization.delta_q_u_ac),
13524 v_dc: i32::from(header.quantization.delta_q_v_dc),
13525 v_ac: i32::from(header.quantization.delta_q_v_ac),
13526 },
13527 header.frame_width,
13528 header.frame_height,
13529 enable_filter_intra,
13530 enable_edge_filter,
13531 &header.cdef,
13532 &header.loop_filter,
13533 &header.loop_restoration,
13534 None,
13535 header.tx_mode == TxMode::Select,
13536 header.reduced_tx_set,
13537 header.allow_screen_content_tools,
13538 header.allow_intrabc,
13539 header.delta,
13540 ) {
13541 Err(e) => {
13542 let msg = e.to_string();
13543 assert!(
13544 msg.contains("unsupported"),
13545 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
13546 );
13547 named_refusals += 1;
13548 eprintln!("seed {seed} refusal: {msg}");
13549 continue;
13550 }
13551 Ok((picture, _end_cdfs)) => picture,
13552 };
13553 let hits = crate::decode::tile_hits() - before;
13554 assert!(
13555 hits > 1,
13556 "{NAME}: tile_hits delta was {hits}, expected >1 -- both tiles must actually \
13557 decode, not just tile 0 (seed {seed})"
13558 );
13559
13560 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
13561 assert_eq!(picture.y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
13562 assert_eq!(picture.u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
13563 assert_eq!(picture.v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
13564 matched += 1;
13565 }
13566 assert!(
13567 matched > 0,
13568 "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \
13569 a two-tile-column stream"
13570 );
13571 eprintln!(
13572 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
13573 );
13574 }
13575
13576 /// lane-tiles r8 stage 1: the same bypass-the-refusal pattern as the
13577 /// two-tile-column gate above, this time for tile ROWS -- `decode_stream`
13578 /// still refuses any `tile_info.rows > 1` stream, so this gate calls
13579 /// [`decode_key_frame_tile_with_cdfs`] directly to prove the underlying
13580 /// per-tile loop (already row/col-generic: `tile_num / tile_info.cols`
13581 /// gives the row, `mi_row_starts`/`set_tile_origin`'s `y0`/`y1` are
13582 /// exactly symmetric with the column gate's `x0`/`x1`) actually decodes
13583 /// both tile rows pixel-exact before the refusal is lifted. 64x128 is
13584 /// one 64px superblock wide and two tall with `--tile-rows=1`
13585 /// (`TileRows=2`, `--tile-columns=0` keeps `cols=1` so only the row axis
13586 /// is under test). Loop filter is left ON (no
13587 /// `--loopfilter-control=0`) per the charter -- deblocking crosses tile
13588 /// row boundaries by spec default exactly as it crosses column ones, and
13589 /// `deblock_plane` runs once over the whole decoded picture after every
13590 /// tile is in, with no tile-axis distinction, so there is no reason to
13591 /// expect the row boundary to behave differently from the column one r7
13592 /// already proved -- this gate is what actually proves it either way.
13593 #[test]
13594 fn a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact() {
13595 const NAME: &str = "a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact";
13596 if !have_ffmpeg() {
13597 eprintln!("SKIP {NAME}: no ffmpeg");
13598 return;
13599 }
13600 if !have_aomenc() {
13601 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13602 return;
13603 }
13604 let (width, height) = (64usize, 128usize);
13605 let mut matched = 0u32;
13606 let mut named_refusals = 0u32;
13607 for attempt in 0..20u32 {
13608 let seed = 42 + attempt;
13609 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
13610 let y4m = Command::new("ffmpeg")
13611 .args([
13612 "-v",
13613 "error",
13614 "-f",
13615 "lavfi",
13616 "-i",
13617 &source,
13618 "-pix_fmt",
13619 "yuv420p",
13620 "-f",
13621 "yuv4mpegpipe",
13622 "-",
13623 ])
13624 .stdin(Stdio::null())
13625 .stdout(Stdio::piped())
13626 .stderr(Stdio::piped())
13627 .output()
13628 .expect("ffmpeg failed to run");
13629 assert!(
13630 y4m.status.success(),
13631 "ffmpeg fixture: {}",
13632 String::from_utf8_lossy(&y4m.stderr)
13633 );
13634 let mut child = Command::new(aomenc_path())
13635 .args([
13636 "--codec=av1",
13637 "--passes=1",
13638 "--end-usage=q",
13639 "--cq-level=45",
13640 "--cpu-used=0",
13641 "--limit=1",
13642 "--kf-max-dist=1000",
13643 "--threads=1",
13644 "--row-mt=0",
13645 "--tile-columns=0",
13646 "--tile-rows=1",
13647 // This decoder hardcodes SB_MI=16 (64px) superblocks
13648 // everywhere; without this aomenc's own default 128x128
13649 // superblock makes 64x128 exactly ONE superblock tall,
13650 // so `--tile-rows=1` has nothing to split.
13651 "--sb-size=64",
13652 "--enable-rect-partitions=0",
13653 "--enable-ab-partitions=0",
13654 "--enable-1to4-partitions=0",
13655 "--enable-filter-intra=0",
13656 "--enable-smooth-intra=0",
13657 "--enable-paeth-intra=0",
13658 "--enable-directional-intra=0",
13659 "--enable-angle-delta=0",
13660 "--enable-tx-size-search=0",
13661 "--enable-cdef=0",
13662 "--enable-restoration=0",
13663 "--max-partition-size=32",
13664 "--min-partition-size=32",
13665 "--enable-palette=0",
13666 "--enable-intrabc=0",
13667 "--enable-cfl-intra=0",
13668 "--obu",
13669 "-o",
13670 "-",
13671 "-",
13672 ])
13673 .stdin(Stdio::piped())
13674 .stdout(Stdio::piped())
13675 .stderr(Stdio::piped())
13676 .spawn()
13677 .expect("aomenc failed to start");
13678 child
13679 .stdin
13680 .take()
13681 .expect("aomenc stdin")
13682 .write_all(&y4m.stdout)
13683 .expect("writing y4m to aomenc");
13684 let out = child.wait_with_output().expect("aomenc failed to run");
13685 assert!(
13686 out.status.success(),
13687 "aomenc refused the fixture: {}",
13688 String::from_utf8_lossy(&out.stderr)
13689 );
13690 let stream = out.stdout;
13691
13692 let mut parser = Av1Parser::new();
13693 let mut pos = 0usize;
13694 let mut frame = None;
13695 while pos < stream.len() {
13696 let obu_offset = pos;
13697 let obu = parser.parse_obu(&stream[pos..]).unwrap();
13698 pos += obu.total_size;
13699 if let ObuKind::Frame(header, tiles) = obu.kind {
13700 frame = Some((header, tiles, obu_offset));
13701 break;
13702 }
13703 }
13704 let (header, tiles, obu_offset) = frame.expect("stream has a Frame OBU");
13705 assert!(
13706 header.tile_info.rows > 1,
13707 "{NAME}: aomenc did not actually split into >1 tile row (rows={}, seed {seed})",
13708 header.tile_info.rows
13709 );
13710 assert_eq!(
13711 tiles.len(),
13712 header.tile_info.rows as usize,
13713 "{NAME}: expected one tile per row (cols=1, seed {seed})"
13714 );
13715 let tile_bufs: Vec<&[u8]> = tiles
13716 .iter()
13717 .map(|t| &stream[obu_offset + t.offset..obu_offset + t.offset + t.size])
13718 .collect();
13719
13720 let enable_filter_intra = parser
13721 .sequence_header()
13722 .is_some_and(|seq| seq.enable_filter_intra);
13723 let enable_edge_filter = parser
13724 .sequence_header()
13725 .is_some_and(|seq| seq.enable_intra_edge_filter);
13726
13727 let before = crate::decode::tile_hits();
13728 let picture = match decode_key_frame_tile_with_cdfs(
13729 &tile_bufs,
13730 &header.tile_info,
13731 header.mi_cols,
13732 header.mi_rows,
13733 header.quantization.base_q_idx,
13734 crate::quant::QuantDeltas {
13735 y_dc: i32::from(header.quantization.delta_q_y_dc),
13736 u_dc: i32::from(header.quantization.delta_q_u_dc),
13737 u_ac: i32::from(header.quantization.delta_q_u_ac),
13738 v_dc: i32::from(header.quantization.delta_q_v_dc),
13739 v_ac: i32::from(header.quantization.delta_q_v_ac),
13740 },
13741 header.frame_width,
13742 header.frame_height,
13743 enable_filter_intra,
13744 enable_edge_filter,
13745 &header.cdef,
13746 &header.loop_filter,
13747 &header.loop_restoration,
13748 None,
13749 header.tx_mode == TxMode::Select,
13750 header.reduced_tx_set,
13751 header.allow_screen_content_tools,
13752 header.allow_intrabc,
13753 header.delta,
13754 ) {
13755 Err(e) => {
13756 let msg = e.to_string();
13757 assert!(
13758 msg.contains("unsupported"),
13759 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
13760 );
13761 named_refusals += 1;
13762 eprintln!("seed {seed} refusal: {msg}");
13763 continue;
13764 }
13765 Ok((picture, _end_cdfs)) => picture,
13766 };
13767 let hits = crate::decode::tile_hits() - before;
13768 assert!(
13769 hits > 1,
13770 "{NAME}: tile_hits delta was {hits}, expected >1 -- both tile rows must actually \
13771 decode, not just tile 0 (seed {seed})"
13772 );
13773
13774 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
13775 assert_eq!(picture.y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
13776 assert_eq!(picture.u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
13777 assert_eq!(picture.v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
13778 matched += 1;
13779 }
13780 assert!(
13781 matched > 0,
13782 "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \
13783 a two-tile-row stream"
13784 );
13785 eprintln!(
13786 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
13787 );
13788 }
13789
13790 /// lane-tiles r8 stage 2/3: the same two-tile-row stream as the bypass
13791 /// gate above, this time through `decode_stream` itself -- the entry
13792 /// point real callers use, with the `rows > 1` refusal lifted (same
13793 /// commit) so this actually reaches the tile decode instead of
13794 /// refusing by name. Loop filter ON, no `--loopfilter-control=0`.
13795 #[test]
13796 fn a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_stream() {
13797 const NAME: &str = "a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_stream";
13798 if !have_ffmpeg() {
13799 eprintln!("SKIP {NAME}: no ffmpeg");
13800 return;
13801 }
13802 if !have_aomenc() {
13803 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13804 return;
13805 }
13806 let (width, height) = (64usize, 128usize);
13807 let mut matched = 0u32;
13808 let mut named_refusals = 0u32;
13809 for attempt in 0..20u32 {
13810 let seed = 42 + attempt;
13811 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
13812 let y4m = Command::new("ffmpeg")
13813 .args([
13814 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
13815 "yuv4mpegpipe", "-",
13816 ])
13817 .stdin(Stdio::null())
13818 .stdout(Stdio::piped())
13819 .stderr(Stdio::piped())
13820 .output()
13821 .expect("ffmpeg failed to run");
13822 assert!(
13823 y4m.status.success(),
13824 "ffmpeg fixture: {}",
13825 String::from_utf8_lossy(&y4m.stderr)
13826 );
13827 let mut child = Command::new(aomenc_path())
13828 .args([
13829 "--codec=av1",
13830 "--passes=1",
13831 "--end-usage=q",
13832 "--cq-level=45",
13833 "--cpu-used=0",
13834 "--limit=1",
13835 "--kf-max-dist=1000",
13836 "--threads=1",
13837 "--row-mt=0",
13838 "--tile-columns=0",
13839 "--tile-rows=1",
13840 "--sb-size=64",
13841 "--enable-rect-partitions=0",
13842 "--enable-ab-partitions=0",
13843 "--enable-1to4-partitions=0",
13844 "--enable-filter-intra=0",
13845 "--enable-smooth-intra=0",
13846 "--enable-paeth-intra=0",
13847 "--enable-directional-intra=0",
13848 "--enable-angle-delta=0",
13849 "--enable-tx-size-search=0",
13850 "--enable-cdef=0",
13851 "--enable-restoration=0",
13852 "--max-partition-size=32",
13853 "--min-partition-size=32",
13854 "--enable-palette=0",
13855 "--enable-intrabc=0",
13856 "--enable-cfl-intra=0",
13857 "--obu",
13858 "-o",
13859 "-",
13860 "-",
13861 ])
13862 .stdin(Stdio::piped())
13863 .stdout(Stdio::piped())
13864 .stderr(Stdio::piped())
13865 .spawn()
13866 .expect("aomenc failed to start");
13867 child
13868 .stdin
13869 .take()
13870 .expect("aomenc stdin")
13871 .write_all(&y4m.stdout)
13872 .expect("writing y4m to aomenc");
13873 let out = child.wait_with_output().expect("aomenc failed to run");
13874 assert!(
13875 out.status.success(),
13876 "aomenc refused the fixture: {}",
13877 String::from_utf8_lossy(&out.stderr)
13878 );
13879 let stream = out.stdout;
13880
13881 let before = crate::decode::tile_hits();
13882 let pictures = match decode_stream(&stream) {
13883 Err(e) => {
13884 let msg = e.to_string();
13885 assert!(
13886 msg.contains("unsupported"),
13887 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
13888 );
13889 named_refusals += 1;
13890 eprintln!("seed {seed} refusal: {msg}");
13891 continue;
13892 }
13893 Ok(pictures) => pictures,
13894 };
13895 let hits = crate::decode::tile_hits() - before;
13896 assert!(
13897 hits > 1,
13898 "{NAME}: tile_hits delta was {hits}, expected >1 -- both tile rows must actually \
13899 decode, not just tile 0 (seed {seed})"
13900 );
13901 assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})");
13902
13903 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
13904 assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
13905 assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
13906 assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
13907 matched += 1;
13908 }
13909 assert!(
13910 matched > 0,
13911 "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
13912 decoded a two-tile-row stream"
13913 );
13914 eprintln!(
13915 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
13916 );
13917 }
13918
13919 /// lane-tiles r7: the `>2 tile columns` refusal's own capability, proven
13920 /// separately from the 2-column gate above -- `--tile-columns=2` gives
13921 /// aomenc `TileCols=4` (log2), a real non-last-column right-edge case the
13922 /// 2-column fixture cannot exercise (there tile 1 IS the frame's right
13923 /// edge). 256x64 is four 64x64 superblocks wide with `--sb-size=64`, so
13924 /// each tile column is exactly one superblock. Loop filtering stays ON
13925 /// (no `--loopfilter-control=0`) to prove the same reach-bound fix also
13926 /// covers deblocking across an *interior* tile boundary, not just the
13927 /// 2-column case's boundary-that-is-also-the-frame-edge.
13928 #[test]
13929 fn a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact() {
13930 const NAME: &str = "a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact";
13931 if !have_ffmpeg() {
13932 eprintln!("SKIP {NAME}: no ffmpeg");
13933 return;
13934 }
13935 if !have_aomenc() {
13936 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13937 return;
13938 }
13939 let (width, height) = (256usize, 64usize);
13940 let mut matched = 0u32;
13941 let mut named_refusals = 0u32;
13942 for attempt in 0..20u32 {
13943 let seed = 42 + attempt;
13944 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
13945 let y4m = Command::new("ffmpeg")
13946 .args([
13947 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
13948 "yuv4mpegpipe", "-",
13949 ])
13950 .stdin(Stdio::null())
13951 .stdout(Stdio::piped())
13952 .stderr(Stdio::piped())
13953 .output()
13954 .expect("ffmpeg failed to run");
13955 assert!(
13956 y4m.status.success(),
13957 "ffmpeg fixture: {}",
13958 String::from_utf8_lossy(&y4m.stderr)
13959 );
13960 let mut child = Command::new(aomenc_path())
13961 .args([
13962 "--codec=av1",
13963 "--passes=1",
13964 "--end-usage=q",
13965 "--cq-level=45",
13966 "--cpu-used=0",
13967 "--limit=1",
13968 "--kf-max-dist=1000",
13969 "--threads=1",
13970 "--row-mt=0",
13971 "--tile-columns=2",
13972 "--tile-rows=0",
13973 "--sb-size=64",
13974 "--enable-rect-partitions=0",
13975 "--enable-ab-partitions=0",
13976 "--enable-1to4-partitions=0",
13977 "--enable-filter-intra=0",
13978 "--enable-smooth-intra=0",
13979 "--enable-paeth-intra=0",
13980 "--enable-directional-intra=0",
13981 "--enable-angle-delta=0",
13982 "--enable-tx-size-search=0",
13983 "--enable-cdef=0",
13984 "--enable-restoration=0",
13985 "--max-partition-size=32",
13986 "--min-partition-size=32",
13987 "--enable-palette=0",
13988 "--enable-intrabc=0",
13989 "--enable-cfl-intra=0",
13990 "--obu",
13991 "-o",
13992 "-",
13993 "-",
13994 ])
13995 .stdin(Stdio::piped())
13996 .stdout(Stdio::piped())
13997 .stderr(Stdio::piped())
13998 .spawn()
13999 .expect("aomenc failed to start");
14000 child
14001 .stdin
14002 .take()
14003 .expect("aomenc stdin")
14004 .write_all(&y4m.stdout)
14005 .expect("writing y4m to aomenc");
14006 let out = child.wait_with_output().expect("aomenc failed to run");
14007 assert!(
14008 out.status.success(),
14009 "aomenc refused the fixture: {}",
14010 String::from_utf8_lossy(&out.stderr)
14011 );
14012 let stream = out.stdout;
14013
14014 let mut parser = Av1Parser::new();
14015 let mut pos = 0usize;
14016 let mut frame = None;
14017 while pos < stream.len() {
14018 let obu_offset = pos;
14019 let obu = parser.parse_obu(&stream[pos..]).unwrap();
14020 pos += obu.total_size;
14021 if let ObuKind::Frame(header, tiles) = obu.kind {
14022 frame = Some((header, tiles, obu_offset));
14023 break;
14024 }
14025 }
14026 let (header, tiles, obu_offset) = frame.expect("stream has a Frame OBU");
14027 assert!(
14028 header.tile_info.cols > 2,
14029 "{NAME}: aomenc did not actually split into >2 tile columns (cols={}, seed {seed})",
14030 header.tile_info.cols
14031 );
14032 assert_eq!(
14033 tiles.len(),
14034 header.tile_info.cols as usize,
14035 "{NAME}: expected one tile per column (seed {seed})"
14036 );
14037 let tile_bufs: Vec<&[u8]> = tiles
14038 .iter()
14039 .map(|t| &stream[obu_offset + t.offset..obu_offset + t.offset + t.size])
14040 .collect();
14041
14042 let enable_filter_intra = parser
14043 .sequence_header()
14044 .is_some_and(|seq| seq.enable_filter_intra);
14045 let enable_edge_filter = parser
14046 .sequence_header()
14047 .is_some_and(|seq| seq.enable_intra_edge_filter);
14048
14049 let before = crate::decode::tile_hits();
14050 let picture = match decode_key_frame_tile_with_cdfs(
14051 &tile_bufs,
14052 &header.tile_info,
14053 header.mi_cols,
14054 header.mi_rows,
14055 header.quantization.base_q_idx,
14056 crate::quant::QuantDeltas {
14057 y_dc: i32::from(header.quantization.delta_q_y_dc),
14058 u_dc: i32::from(header.quantization.delta_q_u_dc),
14059 u_ac: i32::from(header.quantization.delta_q_u_ac),
14060 v_dc: i32::from(header.quantization.delta_q_v_dc),
14061 v_ac: i32::from(header.quantization.delta_q_v_ac),
14062 },
14063 header.frame_width,
14064 header.frame_height,
14065 enable_filter_intra,
14066 enable_edge_filter,
14067 &header.cdef,
14068 &header.loop_filter,
14069 &header.loop_restoration,
14070 None,
14071 header.tx_mode == TxMode::Select,
14072 header.reduced_tx_set,
14073 header.allow_screen_content_tools,
14074 header.allow_intrabc,
14075 header.delta,
14076 ) {
14077 Err(e) => {
14078 let msg = e.to_string();
14079 assert!(
14080 msg.contains("unsupported"),
14081 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
14082 );
14083 named_refusals += 1;
14084 eprintln!("seed {seed} refusal: {msg}");
14085 continue;
14086 }
14087 Ok((picture, _end_cdfs)) => picture,
14088 };
14089 let hits = crate::decode::tile_hits() - before;
14090 assert!(
14091 hits > 2,
14092 "{NAME}: tile_hits delta was {hits}, expected >2 -- all four tiles must actually \
14093 decode, not just a subset (seed {seed})"
14094 );
14095
14096 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
14097 assert_eq!(picture.y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
14098 assert_eq!(picture.u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
14099 assert_eq!(picture.v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
14100 matched += 1;
14101 }
14102 assert!(
14103 matched > 0,
14104 "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \
14105 a four-tile-column stream"
14106 );
14107 eprintln!(
14108 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
14109 );
14110 }
14111
14112 /// lane-tiles r8: the tile-*row* analogue of the four-tile-column gate
14113 /// above -- `--tile-rows=2` gives aomenc `TileRows=4` (log2; uniform
14114 /// tile spacing is always a power of two, so this is the smallest count
14115 /// that has an interior row neither the top nor bottom frame edge,
14116 /// mirroring why the column gate needed 4 columns rather than 3). 64x256
14117 /// is four 64x64 superblocks tall with `--sb-size=64`, one per tile row.
14118 /// Loop filter ON, run through `decode_stream` itself since the
14119 /// `rows > 1` refusal is already lifted by this commit. Also settles a
14120 /// stale documentation claim found while writing this gate: the old
14121 /// comment above `decode_stream`'s multi-tile block said
14122 /// `context_update_tile_id != 0` was refused "further down" -- no such
14123 /// refusal exists (`decode.rs` reads `tile_info.context_update_tile_id`
14124 /// generically, never hardcoded to tile 0), and this fixture's own
14125 /// aomenc runs pick 1/2/3 as often as 0 (RD-driven tile-size heuristic),
14126 /// all 20/20 pixel-exact -- so the capability was already there,
14127 /// undocumented and unproven; hard-asserted here so the proof can't go
14128 /// unnoticed if it stops firing.
14129 #[test]
14130 fn a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact() {
14131 const NAME: &str = "a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact";
14132 if !have_ffmpeg() {
14133 eprintln!("SKIP {NAME}: no ffmpeg");
14134 return;
14135 }
14136 if !have_aomenc() {
14137 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14138 return;
14139 }
14140 let (width, height) = (64usize, 256usize);
14141 let mut matched = 0u32;
14142 let mut named_refusals = 0u32;
14143 let mut saw_nonzero_context_update_tile_id = false;
14144 for attempt in 0..20u32 {
14145 let seed = 42 + attempt;
14146 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
14147 let y4m = Command::new("ffmpeg")
14148 .args([
14149 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
14150 "yuv4mpegpipe", "-",
14151 ])
14152 .stdin(Stdio::null())
14153 .stdout(Stdio::piped())
14154 .stderr(Stdio::piped())
14155 .output()
14156 .expect("ffmpeg failed to run");
14157 assert!(
14158 y4m.status.success(),
14159 "ffmpeg fixture: {}",
14160 String::from_utf8_lossy(&y4m.stderr)
14161 );
14162 let mut child = Command::new(aomenc_path())
14163 .args([
14164 "--codec=av1",
14165 "--passes=1",
14166 "--end-usage=q",
14167 "--cq-level=45",
14168 "--cpu-used=0",
14169 "--limit=1",
14170 "--kf-max-dist=1000",
14171 "--threads=1",
14172 "--row-mt=0",
14173 "--tile-columns=0",
14174 "--tile-rows=2",
14175 "--sb-size=64",
14176 "--enable-rect-partitions=0",
14177 "--enable-ab-partitions=0",
14178 "--enable-1to4-partitions=0",
14179 "--enable-filter-intra=0",
14180 "--enable-smooth-intra=0",
14181 "--enable-paeth-intra=0",
14182 "--enable-directional-intra=0",
14183 "--enable-angle-delta=0",
14184 "--enable-tx-size-search=0",
14185 "--enable-cdef=0",
14186 "--enable-restoration=0",
14187 "--max-partition-size=32",
14188 "--min-partition-size=32",
14189 "--enable-palette=0",
14190 "--enable-intrabc=0",
14191 "--enable-cfl-intra=0",
14192 "--obu",
14193 "-o",
14194 "-",
14195 "-",
14196 ])
14197 .stdin(Stdio::piped())
14198 .stdout(Stdio::piped())
14199 .stderr(Stdio::piped())
14200 .spawn()
14201 .expect("aomenc failed to start");
14202 child
14203 .stdin
14204 .take()
14205 .expect("aomenc stdin")
14206 .write_all(&y4m.stdout)
14207 .expect("writing y4m to aomenc");
14208 let out = child.wait_with_output().expect("aomenc failed to run");
14209 assert!(
14210 out.status.success(),
14211 "aomenc refused the fixture: {}",
14212 String::from_utf8_lossy(&out.stderr)
14213 );
14214 let stream = out.stdout;
14215
14216 let mut parser = Av1Parser::new();
14217 let mut pos = 0usize;
14218 let mut rows_seen = 0u32;
14219 while pos < stream.len() {
14220 let obu = parser.parse_obu(&stream[pos..]).unwrap();
14221 pos += obu.total_size;
14222 if let ObuKind::Frame(header, _) = &obu.kind {
14223 rows_seen = header.tile_info.rows;
14224 if header.tile_info.context_update_tile_id != 0 {
14225 saw_nonzero_context_update_tile_id = true;
14226 }
14227 }
14228 }
14229 assert!(
14230 rows_seen > 2,
14231 "{NAME}: aomenc did not actually split into >2 tile rows (rows={rows_seen}, seed {seed})"
14232 );
14233
14234 let before = crate::decode::tile_hits();
14235 let pictures = match decode_stream(&stream) {
14236 Err(e) => {
14237 let msg = e.to_string();
14238 assert!(
14239 msg.contains("unsupported"),
14240 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
14241 );
14242 named_refusals += 1;
14243 eprintln!("seed {seed} refusal: {msg}");
14244 continue;
14245 }
14246 Ok(pictures) => pictures,
14247 };
14248 let hits = crate::decode::tile_hits() - before;
14249 assert!(
14250 hits > 2,
14251 "{NAME}: tile_hits delta was {hits}, expected >2 -- all four tile rows must \
14252 actually decode, not just a subset (seed {seed})"
14253 );
14254 assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})");
14255
14256 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
14257 assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
14258 assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
14259 assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
14260 matched += 1;
14261 }
14262 assert!(
14263 matched > 0,
14264 "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \
14265 a four-tile-row stream"
14266 );
14267 assert!(
14268 saw_nonzero_context_update_tile_id,
14269 "{NAME}: every attempt named context_update_tile_id=0 -- this sweep proves nothing \
14270 about the != 0 case (see the stale-refusal note above `decode_stream`'s multi-tile \
14271 comment: aomenc's own tile-size heuristic picks it, seen 1/2/3 live in a prior probe \
14272 run of this exact fixture, so a 20-attempt window not seeing it is the gate's own bug)"
14273 );
14274 eprintln!(
14275 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
14276 );
14277 }
14278
14279 /// lane-tiles r4/r7: the same real two-tile-column stream as the
14280 /// bypass gate above, this time run through `decode_stream` itself --
14281 /// the entry point real callers use. Proves the `cols > 1` refusal is
14282 /// actually lifted (not just that the underlying per-tile loop works)
14283 /// for a key frame; `--loopfilter-control=0` stays here for its own
14284 /// sake (isolating the entry-point wiring from deblocking), but r7's
14285 /// `a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact`
14286 /// bypass gate now proves loop filtering ON across a tile boundary too,
14287 /// and the `cols > 1 && loop_filter_on` / `cols > 2` refusals this
14288 /// comment used to describe are gone from `decode_stream`.
14289 #[test]
14290 fn a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream() {
14291 const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream";
14292 if !have_ffmpeg() {
14293 eprintln!("SKIP {NAME}: no ffmpeg");
14294 return;
14295 }
14296 if !have_aomenc() {
14297 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14298 return;
14299 }
14300 let (width, height) = (128usize, 64usize);
14301 let mut matched = 0u32;
14302 let mut named_refusals = 0u32;
14303 for attempt in 0..20u32 {
14304 let seed = 42 + attempt;
14305 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
14306 let y4m = Command::new("ffmpeg")
14307 .args([
14308 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
14309 "yuv4mpegpipe", "-",
14310 ])
14311 .stdin(Stdio::null())
14312 .stdout(Stdio::piped())
14313 .stderr(Stdio::piped())
14314 .output()
14315 .expect("ffmpeg failed to run");
14316 assert!(
14317 y4m.status.success(),
14318 "ffmpeg fixture: {}",
14319 String::from_utf8_lossy(&y4m.stderr)
14320 );
14321 let mut child = Command::new(aomenc_path())
14322 .args([
14323 "--codec=av1",
14324 "--passes=1",
14325 "--end-usage=q",
14326 "--cq-level=45",
14327 "--cpu-used=0",
14328 "--limit=1",
14329 "--kf-max-dist=1000",
14330 "--threads=1",
14331 "--row-mt=0",
14332 "--tile-columns=1",
14333 "--tile-rows=0",
14334 "--sb-size=64",
14335 "--loopfilter-control=0",
14336 "--enable-rect-partitions=0",
14337 "--enable-ab-partitions=0",
14338 "--enable-1to4-partitions=0",
14339 "--enable-filter-intra=0",
14340 "--enable-smooth-intra=0",
14341 "--enable-paeth-intra=0",
14342 "--enable-directional-intra=0",
14343 "--enable-angle-delta=0",
14344 "--enable-tx-size-search=0",
14345 "--enable-cdef=0",
14346 "--enable-restoration=0",
14347 "--max-partition-size=32",
14348 "--min-partition-size=32",
14349 "--enable-palette=0",
14350 "--enable-intrabc=0",
14351 "--enable-cfl-intra=0",
14352 "--obu",
14353 "-o",
14354 "-",
14355 "-",
14356 ])
14357 .stdin(Stdio::piped())
14358 .stdout(Stdio::piped())
14359 .stderr(Stdio::piped())
14360 .spawn()
14361 .expect("aomenc failed to start");
14362 child
14363 .stdin
14364 .take()
14365 .expect("aomenc stdin")
14366 .write_all(&y4m.stdout)
14367 .expect("writing y4m to aomenc");
14368 let out = child.wait_with_output().expect("aomenc failed to run");
14369 assert!(
14370 out.status.success(),
14371 "aomenc refused the fixture: {}",
14372 String::from_utf8_lossy(&out.stderr)
14373 );
14374 let stream = out.stdout;
14375
14376 let before = crate::decode::tile_hits();
14377 let pictures = match decode_stream(&stream) {
14378 Err(e) => {
14379 let msg = e.to_string();
14380 assert!(
14381 msg.contains("unsupported"),
14382 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
14383 );
14384 named_refusals += 1;
14385 eprintln!("seed {seed} refusal: {msg}");
14386 continue;
14387 }
14388 Ok(pictures) => pictures,
14389 };
14390 let hits = crate::decode::tile_hits() - before;
14391 assert!(
14392 hits > 1,
14393 "{NAME}: tile_hits delta was {hits}, expected >1 -- both tiles must actually \
14394 decode, not just tile 0 (seed {seed})"
14395 );
14396 assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})");
14397
14398 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
14399 assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
14400 assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
14401 assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
14402 matched += 1;
14403 }
14404 assert!(
14405 matched > 0,
14406 "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
14407 decoded a two-tile-column stream"
14408 );
14409 eprintln!(
14410 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
14411 );
14412 }
14413 /// lane-realworld r6: r5 ported `maybe_read_delta_q`/`maybe_read_delta_lf`
14414 /// and removed the whole-frame refusal, but no fixture anywhere set
14415 /// `delta_lf_present` -- the removal was unproven. `--deltaq-mode=2`
14416 /// (`DELTA_Q_PERCEPTUAL`, checked against libaom's own
14417 /// `encodeframe.c:2192-2225`) sets `delta_q_present_flag` unconditionally
14418 /// once `base_qindex > 0` (unlike the default `--deltaq-mode=1`
14419 /// `DELTA_Q_OBJECTIVE`, which additionally requires an alt-ref-eligible
14420 /// frame and `allow_deltaq_mode`'s own RD search); `--delta-lf-mode=1`
14421 /// then ANDs `delta_lf_present_flag` on top
14422 /// (`tool_cfg->enable_deltalf_mode`, `av1_cx_iface.c:1269-1270`). 128x64
14423 /// (2 SBs; this decoder hardcodes 64px SBs) is the charter's minimum for
14424 /// a per-superblock symbol to have somewhere to differ; `--cpu-used=4`
14425 /// (not the other gates' `=0`) sidesteps the multi-SB
14426 /// HORZ_4/VERT_B-at-part64 gap the cdef gate's own comment documents
14427 /// (lane-realworld r2 dead-end, part64 only covers NONE/SPLIT). Note:
14428 /// libaom hardcodes `delta_lf_multi = DEFAULT_DELTA_LF_MULTI == 0`
14429 /// (`enums.h:73`) with no CLI flag to set it -- this gate cannot and
14430 /// does not claim to exercise this decoder's `delta_lf_multi` branch;
14431 /// only the single-plane path is gate-proven.
14432 #[test]
14433 fn a_real_aomenc_stream_with_delta_q_and_delta_lf_decodes_pixel_exact() {
14434 const NAME: &str = "a_real_aomenc_stream_with_delta_q_and_delta_lf_decodes_pixel_exact";
14435 let _gate_lock = lock_gate_counters();
14436 if !have_ffmpeg() {
14437 eprintln!("SKIP {NAME}: no ffmpeg");
14438 return;
14439 }
14440 if !have_aomenc() {
14441 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14442 return;
14443 }
14444 let (width, height, frame_count) = (128usize, 64usize, 24usize);
14445 let mut named_refusals = 0u32;
14446 let mut matched = 0u32;
14447 let n_attempts: u32 = std::env::var("EC_DELTAQ_GATE_ATTEMPTS")
14448 .ok()
14449 .and_then(|s| s.parse().ok())
14450 .unwrap_or(40);
14451 for attempt in 0..n_attempts {
14452 let seed = 42 + attempt;
14453 let duration = frame_count as f64 / 25.0;
14454 // Mandelbrot's varying local contrast is what gives
14455 // DELTA_Q_PERCEPTUAL's per-superblock RD something to
14456 // differentiate; flat gradients risk every superblock
14457 // resolving the same delta.
14458 let source = format!(
14459 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
14460 sx = -0.6 + 0.005 * (attempt as f64),
14461 sy = -0.4 + 0.005 * (attempt as f64)
14462 );
14463 let y4m = Command::new("ffmpeg")
14464 .args([
14465 "-v",
14466 "error",
14467 "-f",
14468 "lavfi",
14469 "-i",
14470 &source,
14471 "-t",
14472 &duration.to_string(),
14473 "-pix_fmt",
14474 "yuv420p",
14475 "-f",
14476 "yuv4mpegpipe",
14477 "-",
14478 ])
14479 .stdin(Stdio::null())
14480 .stdout(Stdio::piped())
14481 .stderr(Stdio::piped())
14482 .output()
14483 .expect("ffmpeg failed to run");
14484 assert!(
14485 y4m.status.success(),
14486 "ffmpeg fixture: {}",
14487 String::from_utf8_lossy(&y4m.stderr)
14488 );
14489 let args: Vec<&str> = vec![
14490 "--codec=av1",
14491 "--passes=1",
14492 "--end-usage=q",
14493 "--cq-level=45",
14494 "--cpu-used=4",
14495 "--aq-mode=0",
14496 "--deltaq-mode=2",
14497 "--delta-lf-mode=1",
14498 "--kf-max-dist=1000",
14499 "--threads=1",
14500 "--row-mt=0",
14501 "--sb-size=64",
14502 "--auto-alt-ref=1",
14503 "--lag-in-frames=16",
14504 "--enable-fwd-kf=0",
14505 "--enable-order-hint=1",
14506 "--enable-warped-motion=1",
14507 "--enable-global-motion=0",
14508 "--enable-obmc=1",
14509 "--tune-content=default",
14510 "--enable-masked-comp=1",
14511 "--enable-dist-wtd-comp=0",
14512 "--enable-interintra-comp=1",
14513 "--enable-onesided-comp=0",
14514 "--enable-interintra-wedge=0",
14515 "--enable-smooth-interintra=1",
14516 "--enable-rect-partitions=0",
14517 "--enable-ab-partitions=0",
14518 "--enable-1to4-partitions=0",
14519 "--enable-filter-intra=0",
14520 "--enable-smooth-intra=0",
14521 "--enable-paeth-intra=0",
14522 "--enable-directional-intra=0",
14523 "--enable-angle-delta=0",
14524 "--enable-tx-size-search=0",
14525 "--enable-cdef=1",
14526 "--enable-restoration=0",
14527 "--max-partition-size=32",
14528 "--min-partition-size=32",
14529 "--enable-palette=0",
14530 "--enable-intrabc=0",
14531 "--enable-cfl-intra=0",
14532 "--enable-ref-frame-mvs=0",
14533 "--obu",
14534 "-o",
14535 "-",
14536 "-",
14537 ];
14538 let mut child = Command::new(aomenc_path())
14539 .args(&args)
14540 .stdin(Stdio::piped())
14541 .stdout(Stdio::piped())
14542 .stderr(Stdio::piped())
14543 .spawn()
14544 .expect("aomenc failed to start");
14545 child
14546 .stdin
14547 .take()
14548 .expect("aomenc stdin")
14549 .write_all(&y4m.stdout)
14550 .expect("writing y4m to aomenc");
14551 let out = child.wait_with_output().expect("aomenc failed to run");
14552 assert!(
14553 out.status.success(),
14554 "aomenc refused the fixture: {}",
14555 String::from_utf8_lossy(&out.stderr)
14556 );
14557 let stream = out.stdout;
14558 let frames = match decode_stream(&stream) {
14559 Err(e) => {
14560 let msg = e.to_string();
14561 assert!(
14562 msg.contains("unsupported"),
14563 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
14564 );
14565 assert!(
14566 !msg.contains("delta_q") && !msg.contains("delta_lf"),
14567 "{NAME} refused on delta_q/delta_lf (seed {seed}) -- that read is ported: {msg}"
14568 );
14569 named_refusals += 1;
14570 eprintln!("seed {seed} refusal: {msg}");
14571 continue;
14572 }
14573 Ok(frames) => frames,
14574 };
14575 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
14576 assert_eq!(frames.len(), frame_count);
14577 let mismatched = frames
14578 .iter()
14579 .zip(&ffmpeg_frames)
14580 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
14581 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
14582 std::fs::write(&path, &stream).expect("writing pinned stream");
14583 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
14584 }
14585 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14586 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
14587 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
14588 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
14589 }
14590 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
14591 // stream again, comparing EVERY decode-order frame -- the hidden
14592 // (show_frame == 0) alt-ref frames the ffmpeg compare above
14593 // cannot see, because both sides of it emit shown frames only.
14594 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
14595 eprintln!(
14596 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
14597 {hidden_n} hidden, all pixel-exact vs the oracle"
14598 );
14599 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
14600 // libaom's temporal alt-ref filter absorbs this recipe's hidden
14601 // frames, so the compare above is vacuous -- re-encode the same
14602 // fixture with --arnr-maxframes=0 and compare THOSE.
14603 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
14604 eprintln!(
14605 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
14606 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
14607 );
14608 }
14609 matched += 1;
14610 }
14611 assert!(
14612 matched > 0,
14613 "{NAME}: every attempt refused on other capabilities ({named_refusals} refusals); \
14614 the gate never exercised delta_q/delta_lf"
14615 );
14616 assert!(
14617 crate::decode::delta_q_hits() > 0,
14618 "{NAME}: {matched} pixel-exact matches but zero delta_q symbol groups fired -- \
14619 the reader is unexercised"
14620 );
14621 assert!(
14622 crate::decode::delta_lf_hits() > 0,
14623 "{NAME}: {matched} pixel-exact matches but zero delta_lf symbol groups fired -- \
14624 the reader is unexercised"
14625 );
14626 eprintln!(
14627 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
14628 out of {n_attempts}, delta_q_hits={}, delta_lf_hits={}",
14629 crate::decode::delta_q_hits(),
14630 crate::decode::delta_lf_hits()
14631 );
14632 }
14633
14634 /// lane-seg: a real `aomenc` stream with SEGMENTATION genuinely active.
14635 /// `--aq-mode=1` (variance AQ) / `--aq-mode=2` (complexity AQ) are the two
14636 /// paths libaom uses to switch `segmentation_enabled` on by itself
14637 /// (`av1_vaq_frame_setup`/`av1_setup_in_frame_q_adj`, both of which only
14638 /// ever set `SEG_LVL_ALT_Q`); `--deltaq-mode=0` keeps the per-superblock
14639 /// delta-q reader out of the picture so a mismatch points at the segment
14640 /// map, not at `CurrentQIndex`. Mandelbrot's varying local contrast is
14641 /// what gives variance/complexity AQ different segments to assign --
14642 /// a flat gradient collapses every block onto one segment, which the
14643 /// `segment_ids_seen() >= 2` assert below would catch as a vacuous run.
14644 /// The rest of the recipe is the delta-q gate's own feature-disable
14645 /// envelope, so this gate isolates the segmentation reader.
14646 fn run_segmentation_gate(
14647 name: &str,
14648 aq_mode: &str,
14649 bit_depth: usize,
14650 frame_count: usize,
14651 rate_args: &[&str],
14652 ) {
14653 let _gate_lock = lock_gate_counters();
14654 if !have_ffmpeg() {
14655 eprintln!("SKIP {name}: no ffmpeg");
14656 return;
14657 }
14658 if !have_aomenc() {
14659 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
14660 return;
14661 }
14662 crate::decode::reset_segment_hits();
14663 let (width, height) = (128usize, 64usize);
14664 let mut named_refusals = 0u32;
14665 let mut matched = 0u32;
14666 let n_attempts: u32 = std::env::var("EC_SEG_GATE_ATTEMPTS")
14667 .ok()
14668 .and_then(|s| s.parse().ok())
14669 .unwrap_or(10);
14670 for attempt in 0..n_attempts {
14671 let seed = 42 + attempt;
14672 let duration = frame_count as f64 / 25.0;
14673 let source = format!(
14674 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
14675 sx = -0.6 + 0.005 * (attempt as f64),
14676 sy = -0.4 + 0.005 * (attempt as f64)
14677 );
14678 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
14679 let y4m = Command::new("ffmpeg")
14680 .args([
14681 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
14682 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
14683 ])
14684 .stdin(Stdio::null())
14685 .stdout(Stdio::piped())
14686 .stderr(Stdio::piped())
14687 .output()
14688 .expect("ffmpeg failed to run");
14689 assert!(
14690 y4m.status.success(),
14691 "ffmpeg fixture: {}",
14692 String::from_utf8_lossy(&y4m.stderr)
14693 );
14694 let depth_args: Vec<String> = if bit_depth == 10 {
14695 vec!["--input-bit-depth=10".to_owned(), "--bit-depth=10".to_owned()]
14696 } else {
14697 Vec::new()
14698 };
14699 let aq = format!("--aq-mode={aq_mode}");
14700 let mut args: Vec<&str> = vec![
14701 "--codec=av1",
14702 "--passes=1",
14703 "--cpu-used=4",
14704 &aq,
14705 "--deltaq-mode=0",
14706 "--kf-max-dist=1000",
14707 "--threads=1",
14708 "--row-mt=0",
14709 "--sb-size=64",
14710 "--auto-alt-ref=1",
14711 "--lag-in-frames=16",
14712 "--enable-fwd-kf=0",
14713 "--enable-order-hint=1",
14714 "--enable-warped-motion=1",
14715 "--enable-global-motion=0",
14716 "--enable-obmc=1",
14717 "--tune-content=default",
14718 "--enable-masked-comp=1",
14719 "--enable-dist-wtd-comp=0",
14720 "--enable-interintra-comp=1",
14721 "--enable-onesided-comp=0",
14722 "--enable-interintra-wedge=0",
14723 "--enable-smooth-interintra=1",
14724 "--enable-rect-partitions=0",
14725 "--enable-ab-partitions=0",
14726 "--enable-1to4-partitions=0",
14727 "--enable-filter-intra=0",
14728 "--enable-smooth-intra=0",
14729 "--enable-paeth-intra=0",
14730 "--enable-directional-intra=0",
14731 "--enable-angle-delta=0",
14732 "--enable-tx-size-search=0",
14733 "--enable-cdef=1",
14734 "--enable-restoration=0",
14735 "--max-partition-size=32",
14736 "--min-partition-size=32",
14737 "--enable-palette=0",
14738 "--enable-intrabc=0",
14739 "--enable-cfl-intra=0",
14740 "--enable-ref-frame-mvs=0",
14741 ];
14742 args.extend(rate_args.iter().copied());
14743 args.extend(depth_args.iter().map(String::as_str));
14744 args.extend(["--obu", "-o", "-", "-"]);
14745 let mut child = Command::new(aomenc_path())
14746 .args(&args)
14747 .stdin(Stdio::piped())
14748 .stdout(Stdio::piped())
14749 .stderr(Stdio::piped())
14750 .spawn()
14751 .expect("aomenc failed to start");
14752 child
14753 .stdin
14754 .take()
14755 .expect("aomenc stdin")
14756 .write_all(&y4m.stdout)
14757 .expect("writing y4m to aomenc");
14758 let out = child.wait_with_output().expect("aomenc failed to run");
14759 assert!(
14760 out.status.success(),
14761 "aomenc refused the fixture: {}",
14762 String::from_utf8_lossy(&out.stderr)
14763 );
14764 let stream = out.stdout;
14765 // The stream must really carry `segmentation_enabled`, or the
14766 // gate proves nothing about the reader.
14767 let mut seg_frames = 0u32;
14768 {
14769 let mut probe = Av1Parser::new();
14770 let mut pos = 0usize;
14771 while pos < stream.len() {
14772 let obu = probe.parse_obu(&stream[pos..]).expect("parsing the gate stream");
14773 pos += obu.total_size;
14774 match &obu.kind {
14775 ObuKind::Frame(h, _) => {
14776 if h.segmentation.enabled {
14777 seg_frames += 1;
14778 }
14779 }
14780 ObuKind::FrameHeader(h) => {
14781 if h.segmentation.enabled {
14782 seg_frames += 1;
14783 }
14784 }
14785 _ => {}
14786 }
14787 }
14788 }
14789 if seg_frames == 0 {
14790 eprintln!("seed {seed}: aomenc wrote no segmentation-enabled frame, skipping attempt");
14791 continue;
14792 }
14793 let frames = match decode_stream(&stream) {
14794 Err(e) => {
14795 let msg = e.to_string();
14796 assert!(
14797 msg.contains("unsupported"),
14798 "{name} failed outright, not a named refusal (seed {seed}): {msg}"
14799 );
14800 assert!(
14801 !msg.contains("segment_id symbol"),
14802 "{name} refused on the segmentation reader itself (seed {seed}): {msg}"
14803 );
14804 named_refusals += 1;
14805 eprintln!("seed {seed} refusal: {msg}");
14806 continue;
14807 }
14808 Ok(frames) => frames,
14809 };
14810 let ffmpeg_frames = if bit_depth == 10 {
14811 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14812 } else {
14813 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14814 };
14815 assert_eq!(frames.len(), frame_count);
14816 let mismatched = frames
14817 .iter()
14818 .zip(&ffmpeg_frames)
14819 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
14820 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
14821 std::fs::write(&path, &stream).expect("writing pinned stream");
14822 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
14823 }
14824 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14825 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (seed {seed})");
14826 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (seed {seed})");
14827 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (seed {seed})");
14828 }
14829 matched += 1;
14830 }
14831 assert!(
14832 matched > 0,
14833 "{name}: every attempt refused on other capabilities ({named_refusals} refusals); \
14834 the gate never exercised segmentation"
14835 );
14836 assert!(
14837 crate::decode::segment_id_hits() > 0,
14838 "{name}: {matched} pixel-exact matches but zero segment_id symbols fired -- \
14839 the reader is unexercised"
14840 );
14841 assert!(
14842 crate::decode::segment_ids_seen() >= 2,
14843 "{name}: {matched} pixel-exact matches but only {} distinct segment id(s) -- \
14844 every block landed in one segment, so nothing was actually segmented",
14845 crate::decode::segment_ids_seen()
14846 );
14847 // An inter-frame run must also have exercised the TEMPORAL path
14848 // (`seg_id_predicted` against the primary reference's saved map);
14849 // the key-frame-only run has no previous map by construction.
14850 if frame_count > 1 {
14851 assert!(
14852 crate::decode::segment_pred_hits() > 0,
14853 "{name}: {matched} pixel-exact matches over {frame_count} frames but zero \
14854 seg_id_predicted symbols -- the temporal_update path is unexercised"
14855 );
14856 }
14857 eprintln!(
14858 "{name}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
14859 out of {n_attempts}, segment_id_hits={}, distinct segment ids={}, \
14860 seg_id_predicted symbols={}",
14861 crate::decode::segment_id_hits(),
14862 crate::decode::segment_ids_seen(),
14863 crate::decode::segment_pred_hits()
14864 );
14865 }
14866
14867 #[test]
14868 fn a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact() {
14869 run_segmentation_gate(
14870 "a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact",
14871 "1",
14872 8,
14873 16,
14874 &["--end-usage=q", "--cq-level=45"],
14875 );
14876 }
14877
14878 // lane-seg r1 DEFERRED: an `--aq-mode=2` (complexity AQ) twin of the gate
14879 // above. libaom only switches segmentation on for complexity AQ once the
14880 // target bits per 64x64 superblock clear `sb64_target_rate >= 256`
14881 // (`aq_complexity.c:is_sb_aq_enabled`), which needs `--end-usage=vbr`;
14882 // every VBR recipe tried (cpu-used 0 and 4, 32x32 and 64x64 fixed
14883 // partitions) makes aomenc pick partition shapes OTHER lanes still refuse
14884 // (AB below 16x16, SB-level HORZ/VERT, part32 values 4/6), so 10/10
14885 // attempts refuse before a pixel is compared. The syntax exercised would
14886 // be identical to variance AQ's (both features only ever set
14887 // `SEG_LVL_ALT_Q` via `update_map`), so this is coverage, not capability.
14888 // Unblocked by the sub-16x16 rect/AB partition lanes.
14889
14890 /// His two AV1 films are both `yuv420p10le`, so every capability lands
14891 /// with a 10-bit twin (memory `his-av1-library-is-10-bit`). KEY FRAME
14892 /// ONLY (`frame_count = 1`): a 10-bit INTER frame does not decode
14893 /// pixel-exact in this crate yet, segmentation or not -- lane-seg r1 ran
14894 /// this same recipe with `--aq-mode=0` (segmentation off entirely) and it
14895 /// still mismatched at frame 2, so the 16-frame 10-bit variant would be
14896 /// gating an unrelated pre-existing gap. Variance AQ segments the key
14897 /// frame too (`aq_variance.c`, `is_frame_aq_enabled` includes
14898 /// `frame_is_intra_only`), so this still proves the 10-bit segment-id
14899 /// read and the per-segment 10-bit dequant.
14900 #[test]
14901 fn a_real_aomenc_10bit_stream_with_aq_segmentation_decodes_pixel_exact() {
14902 run_segmentation_gate(
14903 "a_real_aomenc_10bit_stream_with_aq_segmentation_decodes_pixel_exact",
14904 "1",
14905 10,
14906 1,
14907 &["--end-usage=q", "--cq-level=45"],
14908 );
14909 }
14910
14911 /// lane-tiles r7: the gate stage 2 (r6, commit 8899fc1) shipped without
14912 /// -- a real >1-tile-column stream with a genuine INTER frame (not just
14913 /// the key-frame-only two-column gate above), decoded through
14914 /// `decode_stream` itself. Same recipe as the key-frame gate
14915 /// (`--sb-size=64`, `--tile-columns=1`, `--loopfilter-control=0`, the
14916 /// same feature-disable envelope so the gate isolates the tile loop, not
14917 /// an unrelated unimplemented mode) plus `--limit=2 --kf-max-dist=1000`
14918 /// so frame 1 is a real inter frame, and `gradients_source`'s default
14919 /// `speed=0.01` rotation (undisturbed -- not overridden by the tail)
14920 /// gives it genuine motion against frame 0, so `decode_inter_frame_tile_
14921 /// with_cdfs`'s new per-tile loop and `MiGrid`'s per-tile bound actually
14922 /// have to walk a live MV stack across the tile-column boundary, not
14923 /// just replay skip/zero-mv blocks. Bounded with `duration=0.08` (2
14924 /// frames at rate=25) per the class in ledger
14925 /// `refusal-claim-disproved-by-its-own-gate`/`gate-loader-slurps-whole-
14926 /// file` (never leave an ffmpeg/lavfi generate unbounded).
14927 #[test]
14928 fn a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact() {
14929 const NAME: &str =
14930 "a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact";
14931 if !have_ffmpeg() {
14932 eprintln!("SKIP {NAME}: no ffmpeg");
14933 return;
14934 }
14935 if !have_aomenc() {
14936 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14937 return;
14938 }
14939 let (width, height) = (128usize, 64usize);
14940 let frames = 2usize;
14941 let mut matched = 0u32;
14942 let mut named_refusals = 0u32;
14943 for attempt in 0..20u32 {
14944 let seed = 42 + attempt;
14945 let source = gradients_source(seed, width, height, "duration=0.08:rate=25");
14946 let y4m = Command::new("ffmpeg")
14947 .args([
14948 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
14949 "yuv4mpegpipe", "-",
14950 ])
14951 .stdin(Stdio::null())
14952 .stdout(Stdio::piped())
14953 .stderr(Stdio::piped())
14954 .output()
14955 .expect("ffmpeg failed to run");
14956 assert!(
14957 y4m.status.success(),
14958 "ffmpeg fixture: {}",
14959 String::from_utf8_lossy(&y4m.stderr)
14960 );
14961 let mut child = Command::new(aomenc_path())
14962 .args([
14963 "--codec=av1",
14964 "--passes=1",
14965 "--end-usage=q",
14966 "--cq-level=45",
14967 "--cpu-used=0",
14968 &format!("--limit={frames}"),
14969 "--kf-max-dist=1000",
14970 "--lag-in-frames=0",
14971 "--auto-alt-ref=0",
14972 "--threads=1",
14973 "--row-mt=0",
14974 "--tile-columns=1",
14975 "--tile-rows=0",
14976 "--sb-size=64",
14977 "--loopfilter-control=0",
14978 "--max-reference-frames=3",
14979 "--reduced-reference-set=1",
14980 "--enable-warped-motion=0",
14981 "--enable-obmc=0",
14982 "--enable-masked-comp=0",
14983 "--enable-interintra-comp=0",
14984 "--enable-dist-wtd-comp=0",
14985 "--enable-diff-wtd-comp=0",
14986 "--enable-onesided-comp=0",
14987 "--enable-interintra-wedge=0",
14988 "--enable-smooth-interintra=0",
14989 "--enable-ref-frame-mvs=0",
14990 "--enable-rect-partitions=0",
14991 "--enable-ab-partitions=0",
14992 "--enable-1to4-partitions=0",
14993 "--enable-filter-intra=0",
14994 "--enable-smooth-intra=0",
14995 "--enable-paeth-intra=0",
14996 "--enable-directional-intra=0",
14997 "--enable-angle-delta=0",
14998 "--enable-tx-size-search=0",
14999 "--enable-cdef=0",
15000 "--enable-restoration=0",
15001 "--max-partition-size=32",
15002 "--min-partition-size=32",
15003 "--enable-palette=0",
15004 "--enable-intrabc=0",
15005 "--enable-cfl-intra=0",
15006 "--obu",
15007 "-o",
15008 "-",
15009 "-",
15010 ])
15011 .stdin(Stdio::piped())
15012 .stdout(Stdio::piped())
15013 .stderr(Stdio::piped())
15014 .spawn()
15015 .expect("aomenc failed to start");
15016 child
15017 .stdin
15018 .take()
15019 .expect("aomenc stdin")
15020 .write_all(&y4m.stdout)
15021 .expect("writing y4m to aomenc");
15022 let out = child.wait_with_output().expect("aomenc failed to run");
15023 assert!(
15024 out.status.success(),
15025 "aomenc refused the fixture: {}",
15026 String::from_utf8_lossy(&out.stderr)
15027 );
15028 let stream = out.stdout;
15029
15030 // Confirm aomenc actually split into >1 tile column and that
15031 // frame 1 is a real inter frame before trusting a pixel match --
15032 // otherwise a match could mean "tiles collapsed to 1" or "frame
15033 // 1 fell back to key", not "the inter tile loop ran".
15034 let mut parser = Av1Parser::new();
15035 let mut pos = 0usize;
15036 let mut saw_multi_tile_inter = false;
15037 while pos < stream.len() {
15038 let obu = parser.parse_obu(&stream[pos..]).unwrap();
15039 pos += obu.total_size;
15040 if let ObuKind::Frame(header, _) = obu.kind
15041 && header.frame_type != FrameType::Key
15042 && header.tile_info.cols > 1
15043 {
15044 saw_multi_tile_inter = true;
15045 }
15046 }
15047 assert!(
15048 saw_multi_tile_inter,
15049 "{NAME}: seed {seed} never produced a >1-tile-column inter frame (aomenc \
15050 collapsed tiling or coded frame 1 as key)"
15051 );
15052
15053 let before = crate::decode::tile_hits();
15054 let pictures = match decode_stream(&stream) {
15055 Err(e) => {
15056 let msg = e.to_string();
15057 assert!(
15058 msg.contains("unsupported"),
15059 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
15060 );
15061 named_refusals += 1;
15062 eprintln!("seed {seed} refusal: {msg}");
15063 continue;
15064 }
15065 Ok(pictures) => pictures,
15066 };
15067 let hits = crate::decode::tile_hits() - before;
15068 assert!(
15069 hits > frames,
15070 "{NAME}: tile_hits delta was {hits}, expected > {frames} -- both tiles of both \
15071 frames must actually decode (seed {seed})"
15072 );
15073 assert_eq!(pictures.len(), frames, "{NAME}: expected {frames} pictures (seed {seed})");
15074
15075 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames);
15076 for (i, (got, want)) in pictures.iter().zip(&ffmpeg_frames).enumerate() {
15077 assert_eq!(got.y, want.y, "{NAME}: seed {seed} frame {i} luma vs ffmpeg");
15078 assert_eq!(got.u, want.u, "{NAME}: seed {seed} frame {i} U vs ffmpeg");
15079 assert_eq!(got.v, want.v, "{NAME}: seed {seed} frame {i} V vs ffmpeg");
15080 }
15081 matched += 1;
15082 }
15083 assert!(
15084 matched > 0,
15085 "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
15086 decoded a two-tile-column inter frame"
15087 );
15088 eprintln!(
15089 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
15090 );
15091 }
15092
15093 /// lane-tiles r9: `--num-tile-groups` makes aomenc split one frame's
15094 /// tiles across several `OBU_TILE_GROUP`s instead of folding them into
15095 /// the single `OBU_FRAME` every other gate in this file relies on --
15096 /// verified live (`scratch_probe_num_tile_groups`, this round) to emit a
15097 /// standalone `OBU_FRAME_HEADER` (`show_existing_frame == false`)
15098 /// followed by two `OBU_TILE_GROUP` OBUs, one tile each. Before this
15099 /// round `decode_stream` had no arm for `ObuKind::TileGroup` at all (it
15100 /// fell through the catch-all `continue`, silently dropping the frame),
15101 /// and its `ObuKind::FrameHeader` arm matched *every* frame header
15102 /// unconditionally, so a standalone header was misrouted into the
15103 /// `show_existing_frame` slot lookup and returned the wrong named error
15104 /// ("a show_existing_frame header naming an empty reference slot") for a
15105 /// frame that was never a show_existing_frame header. Both are fixed
15106 /// above: the `FrameHeader` arm now checks `show_existing_frame`, and a
15107 /// `pending_header`/`pending_tiles` accumulator collects tile groups
15108 /// until the frame's `cols * rows` tiles have all arrived.
15109 #[test]
15110 fn a_real_aomenc_stream_with_several_tile_group_obus_decodes_pixel_exact() {
15111 const NAME: &str = "a_real_aomenc_stream_with_several_tile_group_obus_decodes_pixel_exact";
15112 if !have_ffmpeg() {
15113 eprintln!("SKIP {NAME}: no ffmpeg");
15114 return;
15115 }
15116 if !have_aomenc() {
15117 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15118 return;
15119 }
15120 let (width, height) = (64usize, 128usize);
15121 let mut matched = 0u32;
15122 let mut named_refusals = 0u32;
15123 let mut saw_multiple_tile_group_obus = false;
15124 for attempt in 0..20u32 {
15125 let seed = 42 + attempt;
15126 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
15127 let y4m = Command::new("ffmpeg")
15128 .args([
15129 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
15130 "yuv4mpegpipe", "-",
15131 ])
15132 .stdin(Stdio::null())
15133 .stdout(Stdio::piped())
15134 .stderr(Stdio::piped())
15135 .output()
15136 .expect("ffmpeg failed to run");
15137 assert!(
15138 y4m.status.success(),
15139 "ffmpeg fixture: {}",
15140 String::from_utf8_lossy(&y4m.stderr)
15141 );
15142 let mut child = Command::new(aomenc_path())
15143 .args([
15144 "--codec=av1",
15145 "--passes=1",
15146 "--end-usage=q",
15147 "--cq-level=45",
15148 "--cpu-used=0",
15149 "--limit=1",
15150 "--kf-max-dist=1000",
15151 "--threads=1",
15152 "--row-mt=0",
15153 "--tile-columns=0",
15154 "--tile-rows=1",
15155 "--sb-size=64",
15156 "--num-tile-groups=4",
15157 "--loopfilter-control=0",
15158 "--enable-rect-partitions=0",
15159 "--enable-ab-partitions=0",
15160 "--enable-1to4-partitions=0",
15161 "--enable-filter-intra=0",
15162 "--enable-smooth-intra=0",
15163 "--enable-paeth-intra=0",
15164 "--enable-directional-intra=0",
15165 "--enable-angle-delta=0",
15166 "--enable-tx-size-search=0",
15167 "--enable-cdef=0",
15168 "--enable-restoration=0",
15169 "--max-partition-size=32",
15170 "--min-partition-size=32",
15171 "--enable-palette=0",
15172 "--enable-intrabc=0",
15173 "--enable-cfl-intra=0",
15174 "--obu",
15175 "-o",
15176 "-",
15177 "-",
15178 ])
15179 .stdin(Stdio::piped())
15180 .stdout(Stdio::piped())
15181 .stderr(Stdio::piped())
15182 .spawn()
15183 .expect("aomenc failed to start");
15184 child
15185 .stdin
15186 .take()
15187 .expect("aomenc stdin")
15188 .write_all(&y4m.stdout)
15189 .expect("writing y4m to aomenc");
15190 let out = child.wait_with_output().expect("aomenc failed to run");
15191 assert!(
15192 out.status.success(),
15193 "aomenc refused the fixture: {}",
15194 String::from_utf8_lossy(&out.stderr)
15195 );
15196 let stream = out.stdout;
15197
15198 let mut probe = Av1Parser::new();
15199 let mut pos = 0usize;
15200 let mut tile_group_obus = 0u32;
15201 while pos < stream.len() {
15202 let obu = probe.parse_obu(&stream[pos..]).unwrap();
15203 pos += obu.total_size;
15204 if matches!(obu.kind, ObuKind::TileGroup(_)) {
15205 tile_group_obus += 1;
15206 }
15207 }
15208 if tile_group_obus > 1 {
15209 saw_multiple_tile_group_obus = true;
15210 }
15211
15212 let before = crate::decode::tile_hits();
15213 let pictures = match decode_stream(&stream) {
15214 Err(e) => {
15215 let msg = e.to_string();
15216 assert!(
15217 msg.contains("unsupported"),
15218 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
15219 );
15220 named_refusals += 1;
15221 eprintln!("seed {seed} refusal: {msg}");
15222 continue;
15223 }
15224 Ok(pictures) => pictures,
15225 };
15226 let hits = crate::decode::tile_hits() - before;
15227 assert!(
15228 hits > 0,
15229 "{NAME}: tile_hits delta was {hits}, expected >0 (seed {seed})"
15230 );
15231 assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})");
15232
15233 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
15234 assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
15235 assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
15236 assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
15237 matched += 1;
15238 }
15239 assert!(
15240 matched > 0,
15241 "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
15242 decoded a several-tile-group-OBUs stream"
15243 );
15244 assert!(
15245 saw_multiple_tile_group_obus,
15246 "{NAME}: no attempt actually split into more than one OBU_TILE_GROUP -- this sweep \
15247 proves nothing about the multi-tile-group case (aomenc's --num-tile-groups is \
15248 RD/heuristic-driven, same as tile sizing)"
15249 );
15250 eprintln!(
15251 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
15252 );
15253 }
15254
15255 /// lane-tiles r10: non-uniform tile spacing (`uniform_spacing_flag == 0`,
15256 /// spec 5.9.15). aomenc never sets this from `--tile-columns`/
15257 /// `--tile-rows` (those always take the `uniform_spacing = 1` branch in
15258 /// `set_tile_info`, libaom `encoder.c`), and `--auto-tiles` only takes
15259 /// the non-uniform balancing path when `g_threads >= 2` -- this charter's
15260 /// `--threads=1` rules that out. The only CLI surface that reaches
15261 /// libaom's `else { tiles->uniform_spacing = 0; ... }` arm is the
15262 /// explicit per-tile size lists `--tile-width=<sb-list>`/
15263 /// `--tile-height=<sb-list>` (`av1_cx_iface.c` `set_tile_info`, argument
15264 /// parsing at `arg_defs.c`'s `.tile_width`/`.tile_height` -- present in
15265 /// the binary, just not printed by `--help`). Probed live with
15266 /// `aomenc --tile-width=1,3 --tile-height=1 --sb-size=64` on a 256x64
15267 /// source (4 SB columns, 1 SB row): confirmed by hand this round to
15268 /// produce a real OBU stream aomdec/ffmpeg both decode.
15269 ///
15270 /// `decode.rs`'s tile loop was already generic over spacing before this
15271 /// gate existed -- it walks `tile_info.mi_col_starts`/`mi_row_starts`
15272 /// (populated identically by `read_tile_info` for both the uniform and
15273 /// non-uniform branches, spec 5.9.15) and never recomputes tile bounds
15274 /// from `cols_log2`/`rows_log2`. The only place in this crate that ever
15275 /// refused non-uniform spacing is `frame.rs`'s OBU *writer*
15276 /// (`"non-uniform tile spacing is not written"`), an unrelated encode
15277 /// path this gate does not touch. So this is a staleness check, not new
15278 /// machinery: prove the already-generic decode path live and pin it.
15279 #[test]
15280 fn a_real_aomenc_stream_with_non_uniform_tile_spacing_decodes_pixel_exact() {
15281 const NAME: &str = "a_real_aomenc_stream_with_non_uniform_tile_spacing_decodes_pixel_exact";
15282 if !have_ffmpeg() {
15283 eprintln!("SKIP {NAME}: no ffmpeg");
15284 return;
15285 }
15286 if !have_aomenc() {
15287 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15288 return;
15289 }
15290 let (width, height) = (256usize, 64usize);
15291 let mut matched = 0u32;
15292 let mut named_refusals = 0u32;
15293 let mut saw_non_uniform_spacing = false;
15294 for attempt in 0..20u32 {
15295 let seed = 42 + attempt;
15296 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
15297 let y4m = Command::new("ffmpeg")
15298 .args([
15299 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
15300 "yuv4mpegpipe", "-",
15301 ])
15302 .stdin(Stdio::null())
15303 .stdout(Stdio::piped())
15304 .stderr(Stdio::piped())
15305 .output()
15306 .expect("ffmpeg failed to run");
15307 assert!(
15308 y4m.status.success(),
15309 "ffmpeg fixture: {}",
15310 String::from_utf8_lossy(&y4m.stderr)
15311 );
15312 let mut child = Command::new(aomenc_path())
15313 .args([
15314 "--codec=av1",
15315 "--passes=1",
15316 "--end-usage=q",
15317 "--cq-level=45",
15318 "--cpu-used=0",
15319 "--limit=1",
15320 "--kf-max-dist=1000",
15321 "--threads=1",
15322 "--row-mt=0",
15323 "--sb-size=64",
15324 "--tile-width=1,3",
15325 "--tile-height=1",
15326 "--loopfilter-control=0",
15327 "--enable-rect-partitions=0",
15328 "--enable-ab-partitions=0",
15329 "--enable-1to4-partitions=0",
15330 "--enable-filter-intra=0",
15331 "--enable-smooth-intra=0",
15332 "--enable-paeth-intra=0",
15333 "--enable-directional-intra=0",
15334 "--enable-angle-delta=0",
15335 "--enable-tx-size-search=0",
15336 "--enable-cdef=0",
15337 "--enable-restoration=0",
15338 "--max-partition-size=32",
15339 "--min-partition-size=32",
15340 "--enable-palette=0",
15341 "--enable-intrabc=0",
15342 "--enable-cfl-intra=0",
15343 "--obu",
15344 "-o",
15345 "-",
15346 "-",
15347 ])
15348 .stdin(Stdio::piped())
15349 .stdout(Stdio::piped())
15350 .stderr(Stdio::piped())
15351 .spawn()
15352 .expect("aomenc failed to start");
15353 child
15354 .stdin
15355 .take()
15356 .expect("aomenc stdin")
15357 .write_all(&y4m.stdout)
15358 .expect("writing y4m to aomenc");
15359 let out = child.wait_with_output().expect("aomenc failed to run");
15360 assert!(
15361 out.status.success(),
15362 "aomenc refused the fixture: {}",
15363 String::from_utf8_lossy(&out.stderr)
15364 );
15365 let stream = out.stdout;
15366
15367 let mut probe = Av1Parser::new();
15368 let mut pos = 0usize;
15369 while pos < stream.len() {
15370 let obu = probe.parse_obu(&stream[pos..]).unwrap();
15371 pos += obu.total_size;
15372 let tile_info = match &obu.kind {
15373 ObuKind::Frame(header, _) => Some(&header.tile_info),
15374 ObuKind::FrameHeader(header) if !header.show_existing_frame => {
15375 Some(&header.tile_info)
15376 }
15377 _ => None,
15378 };
15379 if let Some(info) = tile_info {
15380 if !info.uniform_spacing {
15381 saw_non_uniform_spacing = true;
15382 }
15383 assert!(
15384 info.cols > 1 || info.rows > 1,
15385 "{NAME}: --tile-width=1,3 --tile-height=1 produced only 1 tile \
15386 (cols={} rows={}, seed {seed}) -- fixture stopped exercising the case",
15387 info.cols,
15388 info.rows
15389 );
15390 }
15391 }
15392
15393 let before = crate::decode::tile_hits();
15394 let pictures = match decode_stream(&stream) {
15395 Err(e) => {
15396 let msg = e.to_string();
15397 assert!(
15398 msg.contains("unsupported"),
15399 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
15400 );
15401 named_refusals += 1;
15402 eprintln!("seed {seed} refusal: {msg}");
15403 continue;
15404 }
15405 Ok(pictures) => pictures,
15406 };
15407 let hits = crate::decode::tile_hits() - before;
15408 assert!(
15409 hits > 0,
15410 "{NAME}: tile_hits delta was {hits}, expected >0 (seed {seed})"
15411 );
15412 assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})");
15413
15414 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
15415 assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
15416 assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
15417 assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
15418 matched += 1;
15419 }
15420 assert!(
15421 matched > 0,
15422 "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
15423 decoded a non-uniform-tile-spacing stream"
15424 );
15425 assert!(
15426 saw_non_uniform_spacing,
15427 "{NAME}: no attempt actually set uniform_spacing_flag == 0 -- this sweep proves \
15428 nothing about the non-uniform case"
15429 );
15430 eprintln!(
15431 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
15432 );
15433 }
15434
15435 /// lane-sb128 r1 gate: a real `aomenc --sb-size=128` stream (the size his
15436 /// ReelC encode uses -- `EC_TRACE=1 aomdec reelc-head.obu` prints
15437 /// `EC_PART mi_row=0 mi_col=0 bsize=15` = `BLOCK_128X128`) must decode
15438 /// pixel-exact. `--max-partition-size=64` keeps the RD search from ever
15439 /// choosing a 128-level NONE/HORZ/VERT/AB arm, so every 128 root here is
15440 /// genuinely `PARTITION_SPLIT` -- the one arm
15441 /// `decode_key_frame_tile_with_cdfs` codes; the other seven refuse by
15442 /// name (`PART128_NON_SPLIT_REFUSAL`) and stay refused after this round.
15443 ///
15444 /// What the 128 root actually changes, and what this gate therefore
15445 /// proves: the 8-symbol `partition_w128` CDF and its forced-split gather
15446 /// at the frame edge, the quadrant VISIT ORDER (TL, TR, BL, BR inside one
15447 /// superblock, not raster over 64x64 superblocks), one loop-restoration
15448 /// read per 128x128 instead of per 64x64, `delta_q`/`delta_lf` once per
15449 /// 128x128, and the per-64x64 `cdef_idx` read inside the 128 superblock.
15450 /// 256x192 gives a 2x2 grid of 128 superblocks whose bottom row is a
15451 /// partial superblock (the gathered forced-split read); 384x384 gives a
15452 /// 3x3 grid of whole ones. 8-bit sweep plus one 10-bit stream (his films
15453 /// are `yuv420p10le`). Only a missing tool SKIPs.
15454 #[test]
15455 fn a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact() {
15456 const NAME: &str = "a_real_aomenc_stream_with_128x128_superblocks_decodes_pixel_exact";
15457 let _gate_lock = lock_gate_counters();
15458 if !have_ffmpeg() {
15459 eprintln!("SKIP {NAME}: no ffmpeg");
15460 return;
15461 }
15462 if !have_aomenc() {
15463 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15464 return;
15465 }
15466 let base: Vec<&str> = vec![
15467 "--codec=av1",
15468 "--passes=1",
15469 "--end-usage=q",
15470 "--cq-level=40",
15471 "--cpu-used=0",
15472 "--threads=1",
15473 "--row-mt=0",
15474 "--sb-size=128",
15475 "--max-partition-size=64",
15476 "--enable-rect-partitions=1",
15477 "--enable-ab-partitions=0",
15478 "--enable-1to4-partitions=0",
15479 // aomenc emits PARTITION_HORZ_4/VERT_4 below 16x16 even with the
15480 // flag off (ledger, lane-modectx r1), so bound the search instead.
15481 "--min-partition-size=16",
15482 "--enable-restoration=1",
15483 "--enable-palette=0",
15484 "--deltaq-mode=0",
15485 "--enable-intrabc=0",
15486 "--enable-tx-size-search=0",
15487 "--limit=1",
15488 ];
15489 let encode = |y4m: &[u8], extra: &[&str]| -> Vec<u8> {
15490 let mut args = base.clone();
15491 args.extend_from_slice(extra);
15492 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
15493 let mut child = Command::new(aomenc_path())
15494 .args(&args)
15495 .stdin(Stdio::piped())
15496 .stdout(Stdio::piped())
15497 .stderr(Stdio::piped())
15498 .spawn()
15499 .expect("aomenc failed to start");
15500 child
15501 .stdin
15502 .take()
15503 .expect("aomenc stdin")
15504 .write_all(y4m)
15505 .expect("writing y4m to aomenc");
15506 let out = child.wait_with_output().expect("aomenc failed to run");
15507 assert!(
15508 out.status.success(),
15509 "aomenc refused the fixture: {}",
15510 String::from_utf8_lossy(&out.stderr)
15511 );
15512 out.stdout
15513 };
15514 let render = |seed: u32, width: usize, height: usize, ten_bit: bool| -> Vec<u8> {
15515 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
15516 let out = Command::new("ffmpeg")
15517 .args([
15518 "-v",
15519 "error",
15520 "-f",
15521 "lavfi",
15522 "-i",
15523 &gradients_source(seed, width, height, "duration=0.04:rate=25"),
15524 "-pix_fmt",
15525 pix,
15526 "-strict",
15527 "-1",
15528 "-t",
15529 "0.04",
15530 "-f",
15531 "yuv4mpegpipe",
15532 "-",
15533 ])
15534 .stdin(Stdio::null())
15535 .stdout(Stdio::piped())
15536 .stderr(Stdio::piped())
15537 .output()
15538 .expect("ffmpeg failed to run");
15539 assert!(
15540 out.status.success(),
15541 "ffmpeg fixture: {}",
15542 String::from_utf8_lossy(&out.stderr)
15543 );
15544 out.stdout
15545 };
15546 let mut matched = 0u32;
15547 let mut named_refusals = 0u32;
15548 // (seed, width, height, 10-bit): 256x192 = 2x2 superblocks with a
15549 // partial bottom row; 384x384 = 3x3 whole ones.
15550 let arms: Vec<(u32, usize, usize, bool)> = vec![
15551 (42, 256, 192, false),
15552 (43, 256, 192, false),
15553 (44, 256, 192, false),
15554 (45, 384, 384, false),
15555 (46, 256, 192, true),
15556 (47, 384, 384, true),
15557 ];
15558 for (seed, width, height, ten_bit) in arms {
15559 let y4m = render(seed, width, height, ten_bit);
15560 let extra: Vec<&str> = if ten_bit {
15561 vec!["--input-bit-depth=10", "--bit-depth=10"]
15562 } else {
15563 vec![]
15564 };
15565 let stream = encode(&y4m, &extra);
15566 let parsed = {
15567 let mut parser = ec_av1_syntax::Av1Parser::new();
15568 let mut pos = 0usize;
15569 while let Ok(obu) = parser.parse_obu(&stream[pos..]) {
15570 pos += obu.total_size;
15571 if pos >= stream.len() {
15572 break;
15573 }
15574 }
15575 parser
15576 .sequence_header()
15577 .map(|q| (q.use_128x128_superblock, q.color_config.bit_depth))
15578 };
15579 assert_eq!(
15580 parsed,
15581 Some((true, if ten_bit { 10 } else { 8 })),
15582 "{NAME} (seed {seed}): the encoder did not write a 128x128-superblock \
15583 sequence header at the requested bit depth -- the flag never arrived"
15584 );
15585 let frames = match decode_stream(&stream) {
15586 Err(e) => {
15587 let msg = e.to_string();
15588 assert!(
15589 msg.contains("unsupported"),
15590 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
15591 );
15592 named_refusals += 1;
15593 eprintln!("seed {seed} refusal: {msg}");
15594 continue;
15595 }
15596 Ok(frames) => frames,
15597 };
15598 let want = if ten_bit {
15599 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
15600 } else {
15601 ffmpeg_decode_sequence(&stream, width, height, 1)
15602 };
15603 assert_eq!(frames.len(), 1);
15604 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
15605 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
15606 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
15607 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
15608 }
15609 matched += 1;
15610 }
15611 assert!(
15612 matched > 0,
15613 "{NAME}: every attempt refused; the gate never decoded a stream"
15614 );
15615 // 256x192 codes 3 whole + 1 partial superblock, 384x384 codes 9 whole
15616 // ones, so a run that decoded anything at all must have read real 128
15617 // partition symbols and split every one of them.
15618 assert!(
15619 crate::decode::part128_symbols() >= 3 * matched as usize,
15620 "{NAME}: only {} 128-level partition symbols over {matched} decoded streams -- \
15621 the 128 root never fired",
15622 crate::decode::part128_symbols()
15623 );
15624 assert!(
15625 crate::decode::part128_split_hits() >= 4 * matched as usize,
15626 "{NAME}: only {} 128 superblocks split",
15627 crate::decode::part128_split_hits()
15628 );
15629 eprintln!(
15630 "{NAME}: {matched} pixel-exact, {named_refusals} named refusals, \
15631 part128_symbols={} part128_split_hits={}",
15632 crate::decode::part128_symbols(),
15633 crate::decode::part128_split_hits()
15634 );
15635 }
15636
15637 /// lane-sb128 r1: the inter half of a `--sb-size=128` stream is refused by
15638 /// NAME (the inter tile path still recurses a 64x64 root only), never
15639 /// silently decoded at the wrong superblock size the way this decoder did
15640 /// before this round -- which is what made every earlier ReelC "stop" a
15641 /// desync artefact rather than a real capability gap.
15642 #[test]
15643 fn a_real_aomenc_128x128_inter_stream_refuses_by_name() {
15644 const NAME: &str = "a_real_aomenc_128x128_inter_stream_refuses_by_name";
15645 let _gate_lock = lock_gate_counters();
15646 if !have_ffmpeg() || !have_aomenc() {
15647 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
15648 return;
15649 }
15650 let (width, height) = (256usize, 192usize);
15651 let y4m = Command::new("ffmpeg")
15652 .args([
15653 "-v",
15654 "error",
15655 "-f",
15656 "lavfi",
15657 "-i",
15658 &gradients_source(51, width, height, "duration=0.24:rate=25"),
15659 "-pix_fmt",
15660 "yuv420p",
15661 "-t",
15662 "0.24",
15663 "-f",
15664 "yuv4mpegpipe",
15665 "-",
15666 ])
15667 .stdin(Stdio::null())
15668 .stdout(Stdio::piped())
15669 .stderr(Stdio::piped())
15670 .output()
15671 .expect("ffmpeg failed to run");
15672 assert!(y4m.status.success(), "ffmpeg fixture");
15673 let mut child = Command::new(aomenc_path())
15674 .args([
15675 "--codec=av1",
15676 "--passes=1",
15677 "--end-usage=q",
15678 "--cq-level=40",
15679 "--cpu-used=1",
15680 "--threads=1",
15681 "--row-mt=0",
15682 "--sb-size=128",
15683 "--max-partition-size=64",
15684 "--deltaq-mode=0",
15685 "--limit=6",
15686 "--lag-in-frames=0",
15687 "--obu",
15688 "-o",
15689 "-",
15690 "-",
15691 ])
15692 .stdin(Stdio::piped())
15693 .stdout(Stdio::piped())
15694 .stderr(Stdio::piped())
15695 .spawn()
15696 .expect("aomenc failed to start");
15697 child
15698 .stdin
15699 .take()
15700 .expect("aomenc stdin")
15701 .write_all(&y4m.stdout)
15702 .expect("writing y4m to aomenc");
15703 let out = child.wait_with_output().expect("aomenc failed to run");
15704 assert!(out.status.success(), "aomenc refused the fixture");
15705 let err = decode_stream(&out.stdout)
15706 .err()
15707 .map(|e| e.to_string())
15708 .unwrap_or_default();
15709 assert!(
15710 err.contains("an inter frame under a 128x128 superblock"),
15711 "{NAME}: expected the scoped inter refusal, got: {err:?}"
15712 );
15713 eprintln!("{NAME}: {err}");
15714 }
15715
15716 /// lane-sbpart r2: a real `aomenc` stream whose superblock-level
15717 /// partition decision is genuinely HORZ/VERT (not NONE/SPLIT) must
15718 /// decode pixel-exact through [`crate::decode::decode_block_rect64`] --
15719 /// `sb_rect_hits() > 0` is a HARD assert (this round's rule: a removed
15720 /// refusal needs a firing gate in the same commit, not a green suite
15721 /// that never took the new path). Recipe = the charter's own, verified
15722 /// live by r1: `--min/max-partition-size=32/64` keeps the RD search
15723 /// from ever recursing below 32x32, so every SB-level decision is
15724 /// genuinely NONE/SPLIT/HORZ/VERT; a `gradients` source blended with
15725 /// `testsrc2` (lavfi `blend=all_mode=average`) keeps the content from
15726 /// being flat enough that the search stops at NONE every time.
15727 #[test]
15728 fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact() {
15729 const NAME: &str =
15730 "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact";
15731 let _gate_lock = lock_gate_counters();
15732 if !have_ffmpeg() {
15733 eprintln!("SKIP {NAME}: no ffmpeg");
15734 return;
15735 }
15736 if !have_aomenc() {
15737 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15738 return;
15739 }
15740 let (width, height, frame_count) = (192usize, 128usize, 1usize);
15741 let mut named_refusals = 0u32;
15742 let mut matched = 0u32;
15743 let n_attempts: u32 = std::env::var("EC_SBPART_GATE_ATTEMPTS")
15744 .ok()
15745 .and_then(|s| s.parse().ok())
15746 .unwrap_or(40);
15747 for attempt in 0..n_attempts {
15748 let seed = 42 + attempt;
15749 let duration = frame_count as f64 / 25.0;
15750 let source =
15751 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
15752 let y4m = Command::new("ffmpeg")
15753 .args([
15754 "-v",
15755 "error",
15756 "-f",
15757 "lavfi",
15758 "-i",
15759 &source,
15760 "-pix_fmt",
15761 "yuv420p",
15762 "-f",
15763 "yuv4mpegpipe",
15764 "-",
15765 ])
15766 .stdin(Stdio::null())
15767 .stdout(Stdio::piped())
15768 .stderr(Stdio::piped())
15769 .output()
15770 .expect("ffmpeg failed to run");
15771 assert!(
15772 y4m.status.success(),
15773 "ffmpeg fixture: {}",
15774 String::from_utf8_lossy(&y4m.stderr)
15775 );
15776 let args: Vec<&str> = vec![
15777 "--codec=av1",
15778 "--passes=1",
15779 "--end-usage=q",
15780 "--cq-level=45",
15781 "--cpu-used=0",
15782 "--threads=1",
15783 "--row-mt=0",
15784 "--sb-size=64",
15785 "--enable-rect-partitions=1",
15786 "--enable-ab-partitions=0",
15787 "--enable-1to4-partitions=0",
15788 "--min-partition-size=32",
15789 "--max-partition-size=64",
15790 "--enable-restoration=0",
15791 "--enable-palette=0",
15792 "--deltaq-mode=0",
15793 "--enable-filter-intra=0",
15794 "--enable-cfl-intra=0",
15795 "--enable-intrabc=0",
15796 "--enable-tx-size-search=0",
15797 "--obu",
15798 "-o",
15799 "-",
15800 "-",
15801 ];
15802 let mut child = Command::new(aomenc_path())
15803 .args(&args)
15804 .stdin(Stdio::piped())
15805 .stdout(Stdio::piped())
15806 .stderr(Stdio::piped())
15807 .spawn()
15808 .expect("aomenc failed to start");
15809 child
15810 .stdin
15811 .take()
15812 .expect("aomenc stdin")
15813 .write_all(&y4m.stdout)
15814 .expect("writing y4m to aomenc");
15815 let out = child.wait_with_output().expect("aomenc failed to run");
15816 assert!(
15817 out.status.success(),
15818 "aomenc refused the fixture: {}",
15819 String::from_utf8_lossy(&out.stderr)
15820 );
15821 let stream = out.stdout;
15822 let frames = match decode_stream(&stream) {
15823 Err(e) => {
15824 let msg = e.to_string();
15825 assert!(
15826 msg.contains("unsupported"),
15827 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
15828 );
15829 // r5: the four SB-level AB arms (`partition_w64` 4-7)
15830 // decode since this round, so the only partition refusal
15831 // left at 64x64 is the 1:4 pair (values 8/9, four
15832 // 64x16/16x64 strips, whose luma TX_64X16 this decoder
15833 // has no transform for); the refusals this loop actually
15834 // counts on these fixtures are the pre-existing
15835 // screen-content-palette strip one. Every refusal is
15836 // named, so a genuine decode failure still fails the
15837 // assert above rather than skipping.
15838 named_refusals += 1;
15839 eprintln!("seed {seed} refusal: {msg}");
15840 continue;
15841 }
15842 Ok(frames) => frames,
15843 };
15844 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
15845 assert_eq!(frames.len(), frame_count);
15846 let mismatched = frames
15847 .iter()
15848 .zip(&ffmpeg_frames)
15849 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
15850 if mismatched {
15851 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
15852 std::fs::write(&path, &stream).expect("writing pinned stream");
15853 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
15854 }
15855 }
15856 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15857 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
15858 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
15859 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
15860 }
15861 matched += 1;
15862 }
15863 assert!(
15864 matched > 0,
15865 "{NAME}: every attempt refused; the gate never decoded a stream"
15866 );
15867 assert!(
15868 crate::decode::sb_rect_hits() > 0,
15869 "{NAME}: zero superblock-level HORZ/VERT blocks fired ({matched} matches, \
15870 {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run"
15871 );
15872 eprintln!(
15873 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
15874 {n_attempts}, sb_rect_hits={}",
15875 crate::decode::sb_rect_hits()
15876 );
15877 }
15878
15879 /// lane-sqchroma r1 gate: a plain SQUARE-partition intra key frame with
15880 /// REAL chroma (no `hue=s=0` guard) and aomenc's tx-size search left at
15881 /// its own DEFAULT (on) -- the combination the user's films hit
15882 /// everywhere and that no gate in this file covered: every older recipe
15883 /// pins `--enable-tx-size-search=0`, and the one that does not
15884 /// (`a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact`)
15885 /// desaturates its fixture. With the search on, RD gives a square block a
15886 /// luma transform smaller than its own side while chroma keeps the
15887 /// block's single `side/2` transform and its own `uv_mode`-derived
15888 /// `tx_type` -- the pair [`crate::decode::sq_chroma_tx_hits`] counts and
15889 /// this gate hard-asserts, so a stream whose split-transform blocks all
15890 /// landed on `DC_PRED` chroma cannot pass for free.
15891 ///
15892 /// Sweeps seeds 8-bit and finishes with one 10-bit stream of the same
15893 /// recipe (his films are `yuv420p10le`), whose sequence header's
15894 /// `bit_depth` is asserted before any pixel is compared. Only a missing
15895 /// tool SKIPs: a decode error that is not a named refusal, and every
15896 /// pixel mismatch, FAIL.
15897 #[test]
15898 fn a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact() {
15899 const NAME: &str =
15900 "a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact";
15901 let _gate_lock = lock_gate_counters();
15902 if !have_ffmpeg() {
15903 eprintln!("SKIP {NAME}: no ffmpeg");
15904 return;
15905 }
15906 if !have_aomenc() {
15907 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15908 return;
15909 }
15910 let (width, height) = (192usize, 128usize);
15911 // NOTE: no `--enable-tx-size-search=0` (the point of this gate), and
15912 // no chroma filter on the fixture (the other point). Square
15913 // partitions only: rect/AB/1to4 all off.
15914 let base_args: Vec<&str> = vec![
15915 "--codec=av1",
15916 "--passes=1",
15917 "--end-usage=q",
15918 "--cpu-used=0",
15919 "--threads=1",
15920 "--row-mt=0",
15921 "--sb-size=64",
15922 "--enable-rect-partitions=0",
15923 "--enable-ab-partitions=0",
15924 "--enable-1to4-partitions=0",
15925 "--min-partition-size=16",
15926 "--max-partition-size=32",
15927 "--enable-restoration=0",
15928 "--enable-palette=0",
15929 "--deltaq-mode=0",
15930 "--enable-intrabc=0",
15931 "--limit=1",
15932 ];
15933 let encode = |y4m: &[u8], extra: &[&str]| -> Vec<u8> {
15934 let mut args = base_args.clone();
15935 args.extend_from_slice(extra);
15936 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
15937 let mut child = Command::new(aomenc_path())
15938 .args(&args)
15939 .stdin(Stdio::piped())
15940 .stdout(Stdio::piped())
15941 .stderr(Stdio::piped())
15942 .spawn()
15943 .expect("aomenc failed to start");
15944 child
15945 .stdin
15946 .take()
15947 .expect("aomenc stdin")
15948 .write_all(y4m)
15949 .expect("writing y4m to aomenc");
15950 let out = child.wait_with_output().expect("aomenc failed to run");
15951 assert!(
15952 out.status.success(),
15953 "aomenc refused the fixture: {}",
15954 String::from_utf8_lossy(&out.stderr)
15955 );
15956 assert!(!out.stdout.is_empty(), "{NAME}: aomenc wrote an empty stream");
15957 out.stdout
15958 };
15959 let render = |source: &str, pix_fmt: &str| -> Vec<u8> {
15960 let y4m = Command::new("ffmpeg")
15961 .args([
15962 "-v", "error", "-f", "lavfi", "-i", source, "-t", "0.04", "-pix_fmt", pix_fmt,
15963 "-strict", "-1", "-f", "yuv4mpegpipe", "-",
15964 ])
15965 .stdin(Stdio::null())
15966 .stdout(Stdio::piped())
15967 .stderr(Stdio::piped())
15968 .output()
15969 .expect("ffmpeg failed to run");
15970 assert!(
15971 y4m.status.success(),
15972 "ffmpeg fixture: {}",
15973 String::from_utf8_lossy(&y4m.stderr)
15974 );
15975 y4m.stdout
15976 };
15977 let mut named_refusals = 0u32;
15978 let mut matched = 0u32;
15979 // Hits counted ONLY over attempts that decoded AND pixel-compared:
15980 // a stream that later refuses must not lend its firings to the
15981 // assertion below (class refusal-hides-a-defect).
15982 let mut firing = 0usize;
15983 let n_attempts: u32 = std::env::var("EC_SQCHROMA_GATE_ATTEMPTS")
15984 .ok()
15985 .and_then(|s| s.parse().ok())
15986 .unwrap_or(10);
15987 for attempt in 0..n_attempts {
15988 let seed = 42 + attempt;
15989 // Two quantisers per seed: the coarse one keeps most blocks on
15990 // one transform, the fine one is what actually splits them.
15991 let cq = if attempt % 2 == 0 { "--cq-level=20" } else { "--cq-level=40" };
15992 let y4m = render(
15993 &gradients_source(seed, width, height, "duration=0.04:rate=25"),
15994 "yuv420p",
15995 );
15996 let stream = encode(&y4m, &[cq]);
15997 let before = crate::decode::sq_chroma_tx_hits();
15998 let frames = match decode_stream(&stream) {
15999 Err(e) => {
16000 let msg = e.to_string();
16001 assert!(
16002 msg.contains("unsupported"),
16003 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
16004 );
16005 named_refusals += 1;
16006 continue;
16007 }
16008 Ok(frames) => frames,
16009 };
16010 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
16011 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
16012 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME} luma vs ffmpeg (seed {seed})");
16013 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME} U vs ffmpeg (seed {seed})");
16014 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME} V vs ffmpeg (seed {seed})");
16015 firing += crate::decode::sq_chroma_tx_hits() - before;
16016 matched += 1;
16017 }
16018 // Same recipe, 10-bit: his two films are both yuv420p10le, so the
16019 // square+tx-search+chroma claim is only worth anything if it holds
16020 // at their bit depth too.
16021 let y4m10 = render(
16022 &gradients_source(42, width, height, "duration=0.04:rate=25"),
16023 "yuv420p10le",
16024 );
16025 let stream10 = encode(&y4m10, &["--cq-level=20", "--input-bit-depth=10", "--bit-depth=10"]);
16026 let mut probe = Av1Parser::new();
16027 let mut pos = 0usize;
16028 while pos < stream10.len() && probe.sequence_header().is_none() {
16029 let obu = probe.parse_obu(&stream10[pos..]).unwrap();
16030 pos += obu.total_size;
16031 }
16032 assert_eq!(
16033 probe
16034 .sequence_header()
16035 .expect("stream has a sequence header OBU")
16036 .color_config
16037 .bit_depth,
16038 10,
16039 "{NAME}: aomenc did not actually write a 10-bit sequence header"
16040 );
16041 let before10 = crate::decode::sq_chroma_tx_hits();
16042 let frames10 = match decode_stream(&stream10) {
16043 Ok(frames) => frames,
16044 Err(e) => panic!("{NAME}: decode_stream refused the 10-bit stream: {e}"),
16045 };
16046 let ffmpeg10 = ffmpeg_decode_sequence_10bit(&stream10, width, height, 1);
16047 assert_eq!(frames10[0].y, ffmpeg10[0].y, "{NAME} luma vs ffmpeg (10-bit)");
16048 assert_eq!(frames10[0].u, ffmpeg10[0].u, "{NAME} U vs ffmpeg (10-bit)");
16049 assert_eq!(frames10[0].v, ffmpeg10[0].v, "{NAME} V vs ffmpeg (10-bit)");
16050 let firing10 = crate::decode::sq_chroma_tx_hits() - before10;
16051 firing += firing10;
16052 matched += 1;
16053 assert!(
16054 matched > 1,
16055 "{NAME}: every 8-bit attempt refused; the gate decoded only the 10-bit stream"
16056 );
16057 assert!(
16058 firing > 0,
16059 "{NAME}: zero square blocks split their luma transform under a non-DC chroma mode \
16060 ({matched} matches, {named_refusals} refusals) -- gate proved nothing this run"
16061 );
16062 eprintln!(
16063 "{NAME}: {matched} pixel-exact decodes ({named_refusals} named refusals out of \
16064 {n_attempts} 8-bit attempts), split-tx-with-chroma blocks: {firing} \
16065 (10-bit stream: {firing10})"
16066 );
16067 }
16068
16069 /// lane-rectsplit r1 gate (a): a real `aomenc` key frame whose 32x32
16070 /// quadrants split HORZ/VERT into true 32x16/16x32 strips, with the
16071 /// tx-size search left at aomenc's own default (ON) -- every sibling
16072 /// recipe in this file pins `--enable-tx-size-search=0`, which is exactly
16073 /// why the split-transform strip was never exercised. RD is then free to
16074 /// give a strip a transform smaller than its own size, the case
16075 /// [`crate::decode::decode_block_rect`] refused by name ("a HORZ/VERT
16076 /// intra strip with a split transform (per-unit rect prediction is not
16077 /// ported)") until this round ported the per-transform-unit predict-and-
16078 /// reconstruct loop. Hard-asserts a nonzero `rect_split_tx_hits()` delta:
16079 /// without it a stream that resolved every `tx_depth` to 0 would
16080 /// pixel-match by construction and prove nothing. A decode error that is
16081 /// not a named refusal, and any pixel mismatch, FAIL -- only a missing
16082 /// tool skips.
16083 #[test]
16084 fn a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact() {
16085 const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact";
16086 let _gate_lock = lock_gate_counters();
16087 if !have_ffmpeg() {
16088 eprintln!("SKIP {NAME}: no ffmpeg");
16089 return;
16090 }
16091 if !have_aomenc() {
16092 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16093 return;
16094 }
16095 let (width, height) = (192usize, 128usize);
16096 let before = crate::decode::rect_split_tx_hits();
16097 let mut named_refusals = 0u32;
16098 let mut matched = 0u32;
16099 // lane-rectsplit r2 (verifier finding): the feature counter is
16100 // sampled PER ATTEMPT and folded in only after that attempt was
16101 // decoded AND pixel-compared. One delta across the whole sweep
16102 // counted strips decoded by attempts that went on to hit a named
16103 // refusal, so the gate could pass with every COMPARED stream
16104 // containing none of the feature at all.
16105 let mut compared_hits = 0usize;
16106 let mut split_so_far = 0usize;
16107 // Bounded sweep: see this gate's own doc for the seed-77 residue and
16108 // why extending it is a diagnosis knob, not a pass/fail one.
16109 let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
16110 .ok()
16111 .and_then(|s| s.parse().ok())
16112 .unwrap_or(20);
16113 for attempt in 0..n_attempts {
16114 let seed = 42 + attempt;
16115 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
16116 let y4m = Command::new("ffmpeg")
16117 .args([
16118 "-v", "error", "-f", "lavfi", "-i", &source,
16119 // REAL chroma (lane-sqchroma r1 dropped the `hue=s=0`
16120 // guard this recipe carried): the "PRE-EXISTING square-path
16121 // chroma defect" that guard named does not reproduce at
16122 // HEAD -- seeds 42..61, cq 12/20/32/45, plus testsrc2 and
16123 // mandelbrot, all decode pixel-exact with
16124 // `--enable-rect-partitions=0`, and this gate is green with
16125 // the filter gone. Its own gate is
16126 // `a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact`.
16127 "-pix_fmt", "yuv420p", "-f",
16128 "yuv4mpegpipe", "-",
16129 ])
16130 .stdin(Stdio::null())
16131 .stdout(Stdio::piped())
16132 .stderr(Stdio::piped())
16133 .output()
16134 .expect("ffmpeg failed to run");
16135 assert!(
16136 y4m.status.success(),
16137 "ffmpeg fixture: {}",
16138 String::from_utf8_lossy(&y4m.stderr)
16139 );
16140 // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's
16141 // own default (search ON) is the entire point of this gate.
16142 let args: Vec<&str> = vec![
16143 "--codec=av1",
16144 "--passes=1",
16145 "--end-usage=q",
16146 "--cq-level=45",
16147 "--cpu-used=0",
16148 "--threads=1",
16149 "--row-mt=0",
16150 "--sb-size=64",
16151 "--enable-rect-partitions=1",
16152 "--enable-ab-partitions=0",
16153 "--enable-1to4-partitions=0",
16154 "--min-partition-size=16",
16155 "--max-partition-size=32",
16156 "--enable-restoration=0",
16157 "--enable-palette=0",
16158 "--deltaq-mode=0",
16159 "--enable-filter-intra=0",
16160 "--enable-cfl-intra=0",
16161 "--enable-intrabc=0",
16162 "--obu",
16163 "-o",
16164 "-",
16165 "-",
16166 ];
16167 let mut child = Command::new(aomenc_path())
16168 .args(&args)
16169 .stdin(Stdio::piped())
16170 .stdout(Stdio::piped())
16171 .stderr(Stdio::piped())
16172 .spawn()
16173 .expect("aomenc failed to start");
16174 child
16175 .stdin
16176 .take()
16177 .expect("aomenc stdin")
16178 .write_all(&y4m.stdout)
16179 .expect("writing y4m to aomenc");
16180 let out = child.wait_with_output().expect("aomenc failed to run");
16181 assert!(
16182 out.status.success(),
16183 "aomenc refused the fixture: {}",
16184 String::from_utf8_lossy(&out.stderr)
16185 );
16186 let stream = out.stdout;
16187 assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})");
16188 let attempt_before = crate::decode::rect_split_tx_hits();
16189 let frames = match decode_stream(&stream) {
16190 Err(e) => {
16191 let msg = e.to_string();
16192 assert!(
16193 msg.contains("unsupported"),
16194 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
16195 );
16196 named_refusals += 1;
16197 continue;
16198 }
16199 Ok(frames) => frames,
16200 };
16201 let after = crate::decode::rect_split_tx_hits();
16202 eprintln!(
16203 "{NAME}: seed {seed} decoded, split-tx strips this stream: {}",
16204 after - before - split_so_far
16205 );
16206 split_so_far = after - before;
16207 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
16208 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
16209 if let Some(i) = frames[0]
16210 .y
16211 .iter()
16212 .zip(&ffmpeg_frames[0].y)
16213 .position(|(a, b)| a != b)
16214 {
16215 let diffs: Vec<usize> = frames[0]
16216 .y
16217 .iter()
16218 .zip(&ffmpeg_frames[0].y)
16219 .enumerate()
16220 .filter(|(_, (a, b))| a != b)
16221 .map(|(j, _)| j)
16222 .collect();
16223 let (x0, x1) = (
16224 diffs.iter().map(|j| j % width).min().unwrap(),
16225 diffs.iter().map(|j| j % width).max().unwrap(),
16226 );
16227 let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width);
16228 eprintln!(
16229 "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \
16230 -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}",
16231 i % width,
16232 i / width,
16233 frames[0].y[i],
16234 ffmpeg_frames[0].y[i],
16235 diffs.len(),
16236 );
16237 }
16238 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
16239 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
16240 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
16241 compared_hits += crate::decode::rect_split_tx_hits() - attempt_before;
16242 matched += 1;
16243 }
16244 let split_hits = compared_hits;
16245 assert!(
16246 matched > 0,
16247 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
16248 );
16249 assert!(
16250 split_hits > 0,
16251 "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \
16252 matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \
16253 this run"
16254 );
16255 eprintln!(
16256 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
16257 rect_split_tx_hits delta={split_hits} out of {n_attempts} attempts"
16258 );
16259 }
16260
16261 /// lane-rectsplit r1 gate (c): gate (a)'s recipe with
16262 /// `--enable-filter-intra=1` (every sibling gate here pins it to 0), so
16263 /// aomenc's RD is free to pick `use_filter_intra` on a 32x16/16x32 strip
16264 /// -- the case [`crate::decode::decode_block_rect`] refused by name
16265 /// ("filter intra on a HORZ/VERT strip (this decoder predicts
16266 /// square-only)") until this round gave `predict_filter_intra` its own
16267 /// `bw`x`bh`. Hard-asserts a nonzero `filter_intra_rect_hits()` delta:
16268 /// a stream where RD never picked filter intra on a strip would
16269 /// pixel-match by construction and prove nothing.
16270 #[test]
16271 fn a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact() {
16272 const NAME: &str =
16273 "a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact";
16274 let _gate_lock = lock_gate_counters();
16275 if !have_ffmpeg() {
16276 eprintln!("SKIP {NAME}: no ffmpeg");
16277 return;
16278 }
16279 if !have_aomenc() {
16280 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16281 return;
16282 }
16283 let (width, height) = (192usize, 128usize);
16284 let rect_before = crate::decode::rect_partition_hits();
16285 let fi_square_before = crate::decode::filter_intra_hits();
16286 let mut named_refusals = 0u32;
16287 let mut matched = 0u32;
16288 // lane-rectsplit r2 (verifier finding): the feature counter is
16289 // sampled PER ATTEMPT and folded in only after that attempt was
16290 // decoded AND pixel-compared. One delta across the whole sweep
16291 // counted strips decoded by attempts that went on to hit a named
16292 // refusal, so the gate could pass with every COMPARED stream
16293 // containing none of the feature at all.
16294 let mut compared_hits = 0usize;
16295 let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
16296 .ok()
16297 .and_then(|s| s.parse().ok())
16298 .unwrap_or(40);
16299 for attempt in 0..n_attempts {
16300 let seed = 42 + attempt;
16301 // Diagnosis knob: which content makes RD pick a HORZ/VERT strip
16302 // AND filter intra on it is a search (see this round's report).
16303 let source = match std::env::var("EC_RECTSPLIT_SRC").unwrap_or_default().as_str() {
16304 "bars" => format!("smptebars=size={width}x{height}:duration=0.04:rate=25"),
16305 "src2" => format!("testsrc2=size={width}x{height}:duration=0.04:rate=25"),
16306 _ => gradients_source(seed, width, height, "duration=0.04:rate=25"),
16307 };
16308 let y4m = Command::new("ffmpeg")
16309 .args([
16310 "-v", "error", "-f", "lavfi", "-i", &source,
16311 // Real chroma: the `hue=s=0` guard gate (a) carried is
16312 // gone (lane-sqchroma r1 -- the square-path chroma defect
16313 // it named does not reproduce at HEAD).
16314 "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-",
16315 ])
16316 .stdin(Stdio::null())
16317 .stdout(Stdio::piped())
16318 .stderr(Stdio::piped())
16319 .output()
16320 .expect("ffmpeg failed to run");
16321 assert!(
16322 y4m.status.success(),
16323 "ffmpeg fixture: {}",
16324 String::from_utf8_lossy(&y4m.stderr)
16325 );
16326 // Diagnosis knob only (default is the gate's pinned recipe):
16327 // which `--cq-level` makes aomenc's RD reach for filter intra on
16328 // a strip is a search, and the sweep that found this one is in
16329 // lanes/rectsplit-r1.report.md.
16330 let cq = format!(
16331 "--cq-level={}",
16332 // Pinned by the sweep in lanes/rectsplit-r1.report.md: at
16333 // cq 45 aomenc's RD picks a strip 18 times in 100 seeds and
16334 // filter intra on none of them; at cq 25 strips are common
16335 // (130/100 seeds) and filter intra lands on one every ~13
16336 // seeds.
16337 std::env::var("EC_RECTSPLIT_CQ").unwrap_or_else(|_| "25".into())
16338 );
16339 let args: Vec<&str> = vec![
16340 "--codec=av1",
16341 "--passes=1",
16342 "--end-usage=q",
16343 &cq,
16344 "--cpu-used=0",
16345 "--threads=1",
16346 "--row-mt=0",
16347 "--sb-size=64",
16348 "--enable-rect-partitions=1",
16349 "--enable-ab-partitions=0",
16350 "--enable-1to4-partitions=0",
16351 "--min-partition-size=16",
16352 "--max-partition-size=32",
16353 "--enable-restoration=0",
16354 "--enable-palette=0",
16355 "--deltaq-mode=0",
16356 // The point of this gate.
16357 "--enable-filter-intra=1",
16358 // NOTE (lane-rectsplit r2, verifier finding): every intra
16359 // mode stays ON here. The square filter-intra gate reaches
16360 // for filter intra by switching the directional/smooth/paeth
16361 // competitors off, and this gate CANNOT: with them off
16362 // aomenc stops picking rect partitions at all (rect
16363 // strips 0/20 seeds, r1's table). What fires filter intra on
16364 // a strip here is the quantiser (`--cq-level=25`), not the
16365 // mode set -- `EC_RECTSPLIT_OFF` below is the diagnosis knob
16366 // that re-runs the subset search.
16367 "--enable-cfl-intra=0",
16368 "--enable-intrabc=0",
16369 "--obu",
16370 "-o",
16371 "-",
16372 "-",
16373 ];
16374 // Diagnosis knob (default: every intra mode on): turning the
16375 // directional/smooth/paeth competitors off is how the square
16376 // filter-intra gate makes RD reach for filter intra, but with all
16377 // four off aomenc stops picking rect partitions here entirely
16378 // (rect strips=0, filter-intra blocks=28, measured this round),
16379 // so the firing recipe is a search over subsets.
16380 let mut args = args;
16381 let off = std::env::var("EC_RECTSPLIT_OFF").unwrap_or_default();
16382 for tool in off.split(',').filter(|t| !t.is_empty()) {
16383 args.push(match tool {
16384 "smooth" => "--enable-smooth-intra=0",
16385 "paeth" => "--enable-paeth-intra=0",
16386 "dir" => "--enable-directional-intra=0",
16387 "angle" => "--enable-angle-delta=0",
16388 other => panic!("unknown EC_RECTSPLIT_OFF entry {other}"),
16389 });
16390 }
16391 let mut child = Command::new(aomenc_path())
16392 .args(&args)
16393 .stdin(Stdio::piped())
16394 .stdout(Stdio::piped())
16395 .stderr(Stdio::piped())
16396 .spawn()
16397 .expect("aomenc failed to start");
16398 child
16399 .stdin
16400 .take()
16401 .expect("aomenc stdin")
16402 .write_all(&y4m.stdout)
16403 .expect("writing y4m to aomenc");
16404 let out = child.wait_with_output().expect("aomenc failed to run");
16405 assert!(
16406 out.status.success(),
16407 "aomenc refused the fixture: {}",
16408 String::from_utf8_lossy(&out.stderr)
16409 );
16410 let stream = out.stdout;
16411 assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})");
16412 let attempt_before = crate::decode::filter_intra_rect_hits();
16413 let frames = match decode_stream(&stream) {
16414 Err(e) => {
16415 let msg = e.to_string();
16416 assert!(
16417 msg.contains("unsupported"),
16418 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
16419 );
16420 named_refusals += 1;
16421 continue;
16422 }
16423 Ok(frames) => frames,
16424 };
16425 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
16426 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
16427 if let Some(i) = frames[0]
16428 .y
16429 .iter()
16430 .zip(&ffmpeg_frames[0].y)
16431 .position(|(a, b)| a != b)
16432 {
16433 let diffs: Vec<usize> = frames[0]
16434 .y
16435 .iter()
16436 .zip(&ffmpeg_frames[0].y)
16437 .enumerate()
16438 .filter(|(_, (a, b))| a != b)
16439 .map(|(j, _)| j)
16440 .collect();
16441 let (x0, x1) = (
16442 diffs.iter().map(|j| j % width).min().unwrap(),
16443 diffs.iter().map(|j| j % width).max().unwrap(),
16444 );
16445 let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width);
16446 eprintln!(
16447 "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \
16448 -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}",
16449 i % width,
16450 i / width,
16451 frames[0].y[i],
16452 ffmpeg_frames[0].y[i],
16453 diffs.len(),
16454 );
16455 }
16456 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
16457 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
16458 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
16459 compared_hits += crate::decode::filter_intra_rect_hits() - attempt_before;
16460 matched += 1;
16461 }
16462 let fi_hits = compared_hits;
16463 eprintln!(
16464 "{NAME}: rect strips this run={}, filter-intra blocks (any shape)={}",
16465 crate::decode::rect_partition_hits() - rect_before,
16466 crate::decode::filter_intra_hits() - fi_square_before
16467 );
16468 assert!(
16469 matched > 0,
16470 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
16471 );
16472 assert!(
16473 fi_hits > 0,
16474 "{NAME}: no HORZ/VERT strip used filter intra ({matched} pixel-exact matches, \
16475 {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run"
16476 );
16477 eprintln!(
16478 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
16479 filter_intra_rect_hits delta={fi_hits} out of {n_attempts} attempts"
16480 );
16481 }
16482
16483 /// lane-fistrip r1, the 10-bit arm of the strip gate (his films are
16484 /// yuv420p10le). Same ceiling as its 8-bit twin -- kept `#[ignore]`d
16485 /// with the measurement rather than weakened: MEASURED over seeds
16486 /// 42..61 the 8x16/16x8 strips aomenc writes filter intra on are
16487 /// `skip=0`, which `decode_leaf_rect` refuses, so
16488 /// `filter_intra_rect_sub16_hits` never reaches a pixel compare.
16489 /// lane-fistrip r2 adds seeds 49 and 213 to the window: those are the two
16490 /// seeds measured to fire the feature on the 8-BIT twin's recipe (this
16491 /// arm's 10-bit encode is a different stream, so they are a widening, not
16492 /// a measured firing set for this recipe -- the round that un-ignores
16493 /// this gate must re-measure which 10-bit seeds fire it).
16494 #[ignore = "2026-09-02, re-measured on the merged tree: the coded-strip refusal is lifted, but every firing 10-bit seed now stops at the sub16 SPLIT-TRANSFORM refusal (49, 55) or palette-in-screen-content (45, 46); 16 attempts decode pixel-exact with 0 hits, so the gate would prove nothing"]
16495 #[test]
16496 fn a_real_aomenc_10bit_filter_intra_on_a_sub16_strip_decodes_pixel_exact() {
16497 const NAME: &str = "a_real_aomenc_10bit_filter_intra_on_a_sub16_strip_decodes_pixel_exact";
16498 let _gate_lock = lock_gate_counters();
16499 if !have_ffmpeg() {
16500 eprintln!("SKIP {NAME}: no ffmpeg");
16501 return;
16502 }
16503 if !have_aomenc() {
16504 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16505 return;
16506 }
16507 let mut seeds: Vec<u32> = (42..62).collect();
16508 seeds.push(213);
16509 ten_bit_tool_gate(
16510 NAME,
16511 192,
16512 128,
16513 1,
16514 &[
16515 "--limit=1",
16516 "--cq-level=25",
16517 "--cpu-used=0",
16518 "--threads=1",
16519 "--row-mt=0",
16520 "--sb-size=64",
16521 "--enable-rect-partitions=1",
16522 "--enable-ab-partitions=0",
16523 "--enable-1to4-partitions=0",
16524 "--min-partition-size=8",
16525 "--max-partition-size=32",
16526 "--enable-restoration=0",
16527 "--enable-palette=0",
16528 "--deltaq-mode=0",
16529 "--enable-filter-intra=1",
16530 "--enable-cfl-intra=0",
16531 "--enable-intrabc=0",
16532 ],
16533 &seeds,
16534 &[(
16535 "filter_intra_rect_sub16_hits",
16536 crate::decode::filter_intra_rect_sub16_hits as fn() -> usize,
16537 )],
16538 );
16539 }
16540
16541 /// lane-fistrip r1, the pinned half of this lane's proof: one real
16542 /// `aomenc` stream (recipe below, byte-reproducible -- md5
16543 /// ac3a64773e5454ee9b5d8650507063cd, hashed twice) whose key frame
16544 /// carries four `BLOCK_16X8` DC_PRED leaves, one of which sets
16545 /// `use_filter_intra`. `av1_filter_intra_allowed_bsize` allows 16x8, so
16546 /// aomenc writes that flag; before this round `filter_intra_size_class_rect`
16547 /// had no row for the shape, the symbol was never read, and the tile
16548 /// desynced ON THAT BLOCK -- observable as a DIFFERENT named refusal
16549 /// ("a HORZ/VERT intra strip below 16x16 with a split transform", a
16550 /// `tx_depth` read out of a desynced stream) instead of this one.
16551 ///
16552 /// The stream cannot be pixel-compared yet: the 16x8 strip that carries
16553 /// the flag is `skip=0`, and a coded rect strip below 16x16 has no
16554 /// residual path here (its own refusal, another lane's ceiling). What
16555 /// this test pins is the SYMBOL: the flag is read, the counter fires
16556 /// once, and the decode stops at the coded-strip ceiling rather than
16557 /// wandering off a desynced stream.
16558 ///
16559 /// Fixture recipe (`crates/ec-av1/fixtures/filter_intra_8x16_strip_seed49.obu`):
16560 /// `ffmpeg -f lavfi -i gradients=size=192x128:c0=0x986ae1:c1=0xd3e49a:
16561 /// c2=0x0b1e53:c3=0x42980c:seed=49:duration=0.04:rate=25 -pix_fmt yuv420p`
16562 /// into `aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=25
16563 /// --cpu-used=0 --threads=1 --row-mt=0 --sb-size=64
16564 /// --enable-rect-partitions=1 --enable-ab-partitions=0
16565 /// --enable-1to4-partitions=0 --min-partition-size=8
16566 /// --max-partition-size=32 --enable-restoration=0 --enable-palette=0
16567 /// --deltaq-mode=0 --enable-filter-intra=1 --enable-cfl-intra=0
16568 /// --enable-intrabc=0 --obu`.
16569 #[test]
16570 fn a_pinned_aomenc_16x8_strip_reads_its_use_filter_intra_flag() {
16571 const NAME: &str = "a_pinned_aomenc_16x8_strip_reads_its_use_filter_intra_flag";
16572 let _gate_lock = lock_gate_counters();
16573 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16574 .join("fixtures/filter_intra_8x16_strip_seed49.obu");
16575 let stream = std::fs::read(&path)
16576 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
16577 let before = crate::decode::filter_intra_rect_sub16_hits();
16578 let err = decode_stream(&stream).expect_err(
16579 "{NAME}: this stream's 16x8 filter-intra strip is skip=0, which this decoder \
16580 still refuses -- a clean decode means the coded-strip ceiling moved and this \
16581 test should become a pixel compare",
16582 );
16583 let hits = crate::decode::filter_intra_rect_sub16_hits() - before;
16584 assert_eq!(
16585 hits, 1,
16586 "{NAME}: expected exactly one 16x8 strip to read use_filter_intra=1 (aomdec's own \
16587 EC_TRACE_MODE shows four BLOCK_16X8 DC_PRED leaves here); got {hits}"
16588 );
16589 let msg = err.to_string();
16590 assert!(
16591 // 2026-09-02, merging lane-fistrip onto a main that already carries
16592 // lane-rectx: the coded-strip ceiling this fixture used to hit is
16593 // gone, and the very next one on the SAME block is the split
16594 // transform under a sub-16 strip (per-unit rect prediction is not
16595 // ported). Still a refusal ON that block, still not a desync.
16596 msg.contains("a HORZ/VERT intra strip below 16x16 with a split transform"),
16597 "{NAME}: decode must reach the sub16 split-transform ceiling ON that block, not \
16598 wander off a desynced stream; got: {msg}"
16599 );
16600 }
16601
16602 /// lane-fistrip r1: the filter-intra strip gate above, one partition
16603 /// level DOWN (`--min-partition-size=8`, so a 16x16 HORZ/VERT splits
16604 /// into 8x16/16x8 leaves). `av1_filter_intra_allowed_bsize` is
16605 /// `wide <= 32 && high <= 32`, which both of those satisfy, so aomenc
16606 /// writes a `use_filter_intra` flag on every DC_PRED one of them --
16607 /// `filter_intra_size_class_rect` had no row for either shape and
16608 /// [`crate::decode::read_intra_mode_rect`] therefore never READ that
16609 /// symbol (class `symbol-consumption-gap`, a silent desync rather than
16610 /// a refusal). Hard-asserts
16611 /// [`crate::decode::filter_intra_rect_sub16_hits`], not the wider
16612 /// `filter_intra_rect_hits`: a 32x16 strip firing filter intra would
16613 /// satisfy that one and prove nothing about the new shapes.
16614 /// MEASURED (lane-fistrip r1, seeds 42..=241; r2 re-ran 50..=241), which
16615 /// is why it is `#[ignore]`d rather than green: over those 200 seeds at
16616 /// cq 25 aomenc put filter intra on an 8x16/16x8 strip exactly TWICE --
16617 /// **seed 49 and seed 213** -- and both times that strip was `skip=0`, so
16618 /// the attempt refused at the coded-rect-strip-below-16x16 ceiling before
16619 /// any pixel compare (r1: 177 pixel-exact matches, 23 refusals, compared
16620 /// sub16 delta 0, all-attempt delta 2; r2 seeds 50..=241: 172 matches, 20
16621 /// refusals, the one all-attempt hit at seed 213). BOTH firing seeds are
16622 /// appended to this gate's seed window below, so the un-ignore compares
16623 /// two real hits. Un-ignore this the round that ceiling lifts; the symbol
16624 /// itself is pinned by
16625 /// [`a_pinned_aomenc_16x8_strip_reads_its_use_filter_intra_flag`], whose
16626 /// `expect_err` must become a pixel compare in that same round.
16627 #[ignore = "2026-09-02, re-measured on the merged tree: 35 of 41 attempts decode pixel-exact with ZERO mismatches, but both firing seeds (49, 213) stop at the sub16 split-transform / HORZ_A-B refusals, so no filter-intra 8x16/16x8 strip is compared yet"]
16628 #[test]
16629 fn a_real_aomenc_stream_with_filter_intra_on_a_sub16_horz_vert_strip_decodes_pixel_exact() {
16630 const NAME: &str =
16631 "a_real_aomenc_stream_with_filter_intra_on_a_sub16_horz_vert_strip_decodes_pixel_exact";
16632 let _gate_lock = lock_gate_counters();
16633 if !have_ffmpeg() {
16634 eprintln!("SKIP {NAME}: no ffmpeg");
16635 return;
16636 }
16637 if !have_aomenc() {
16638 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16639 return;
16640 }
16641 let (width, height) = (192usize, 128usize);
16642 let mut named_refusals = 0u32;
16643 let mut matched = 0u32;
16644 let mut compared_hits = 0usize;
16645 let n_attempts: u32 = std::env::var("EC_FISTRIP_GATE_ATTEMPTS")
16646 .ok()
16647 .and_then(|s| s.parse().ok())
16648 .unwrap_or(40);
16649 // lane-fistrip r2: the two seeds that MEASURABLY fire filter intra on
16650 // an 8x16/16x8 strip are 49 and 213 -- the only two in seeds 42..=241
16651 // (r1 measured 42..=241 and reported "all-attempt delta 2" with seed
16652 // 49; r2 re-ran seeds 50..=241 and found the second, log
16653 // `$HOME/.cache/fistrip-seedscan-r2.log`: "seed 213 refused with sub16
16654 // filter-intra delta 1"). Both are appended to whatever window
16655 // `EC_FISTRIP_GATE_ATTEMPTS` asks for, so the un-ignore after the
16656 // coded-rect-strip ceiling lifts compares TWO real hits instead of
16657 // depending on the default window happening to contain one.
16658 const FIRING_SEEDS: [u32; 2] = [49, 213];
16659 let mut seeds: Vec<u32> = (0..n_attempts).map(|a| 42 + a).collect();
16660 for s in FIRING_SEEDS {
16661 if !seeds.contains(&s) {
16662 seeds.push(s);
16663 }
16664 }
16665 let cq = format!(
16666 "--cq-level={}",
16667 std::env::var("EC_FISTRIP_CQ").unwrap_or_else(|_| "25".into())
16668 );
16669 // Diagnosis: the counter over EVERY attempt, refused ones included --
16670 // a filter-intra 8x16 strip inside an attempt that later refused
16671 // (non-skip, split transform) fires this but never reaches
16672 // `compared_hits`, and the two numbers differing is what says the
16673 // recipe reaches the feature but this decoder's other ceilings hide
16674 // it.
16675 let all_before = crate::decode::filter_intra_rect_sub16_hits();
16676 for &seed in &seeds {
16677 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
16678 let y4m = Command::new("ffmpeg")
16679 .args([
16680 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
16681 "yuv4mpegpipe", "-",
16682 ])
16683 .stdin(Stdio::null())
16684 .stdout(Stdio::piped())
16685 .stderr(Stdio::piped())
16686 .output()
16687 .expect("ffmpeg failed to run");
16688 assert!(
16689 y4m.status.success(),
16690 "ffmpeg fixture: {}",
16691 String::from_utf8_lossy(&y4m.stderr)
16692 );
16693 let args: Vec<&str> = vec![
16694 "--codec=av1",
16695 "--passes=1",
16696 "--end-usage=q",
16697 &cq,
16698 "--cpu-used=0",
16699 "--threads=1",
16700 "--row-mt=0",
16701 "--sb-size=64",
16702 "--enable-rect-partitions=1",
16703 "--enable-ab-partitions=0",
16704 "--enable-1to4-partitions=0",
16705 // The point of this gate: one level below the 32x16/16x32
16706 // strips the sibling gate covers.
16707 "--min-partition-size=8",
16708 "--max-partition-size=32",
16709 "--enable-restoration=0",
16710 "--enable-palette=0",
16711 "--deltaq-mode=0",
16712 "--enable-filter-intra=1",
16713 "--enable-cfl-intra=0",
16714 "--enable-intrabc=0",
16715 "--obu",
16716 "-o",
16717 "-",
16718 "-",
16719 ];
16720 // Diagnosis knob only (default: every intra mode on) -- the same
16721 // subset search the 32x16/16x32 sibling gate carries.
16722 let mut args = args;
16723 let off = std::env::var("EC_FISTRIP_OFF").unwrap_or_default();
16724 for tool in off.split(',').filter(|t| !t.is_empty()) {
16725 args.push(match tool {
16726 "smooth" => "--enable-smooth-intra=0",
16727 "paeth" => "--enable-paeth-intra=0",
16728 "dir" => "--enable-directional-intra=0",
16729 "angle" => "--enable-angle-delta=0",
16730 other => panic!("unknown EC_FISTRIP_OFF entry {other}"),
16731 });
16732 }
16733 let mut child = Command::new(aomenc_path())
16734 .args(&args)
16735 .stdin(Stdio::piped())
16736 .stdout(Stdio::piped())
16737 .stderr(Stdio::piped())
16738 .spawn()
16739 .expect("aomenc failed to start");
16740 child
16741 .stdin
16742 .take()
16743 .expect("aomenc stdin")
16744 .write_all(&y4m.stdout)
16745 .expect("writing y4m to aomenc");
16746 let out = child.wait_with_output().expect("aomenc failed to run");
16747 assert!(
16748 out.status.success(),
16749 "aomenc refused the fixture: {}",
16750 String::from_utf8_lossy(&out.stderr)
16751 );
16752 let stream = out.stdout;
16753 assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})");
16754 let attempt_before = crate::decode::filter_intra_rect_sub16_hits();
16755 let frames = match decode_stream(&stream) {
16756 Err(e) => {
16757 let msg = e.to_string();
16758 assert!(
16759 msg.contains("unsupported"),
16760 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
16761 );
16762 // Diagnosis: a refused attempt that DID fire the feature
16763 // says which other ceiling of this decoder hides it.
16764 eprintln!(
16765 "{NAME}: seed {seed} refused with sub16 filter-intra delta {}: {msg}",
16766 crate::decode::filter_intra_rect_sub16_hits() - attempt_before
16767 );
16768 named_refusals += 1;
16769 continue;
16770 }
16771 Ok(frames) => frames,
16772 };
16773 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
16774 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
16775 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
16776 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
16777 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
16778 compared_hits += crate::decode::filter_intra_rect_sub16_hits() - attempt_before;
16779 matched += 1;
16780 }
16781 eprintln!(
16782 "{NAME}: filter_intra_rect_sub16_hits over ALL attempts (refused included) = {}",
16783 crate::decode::filter_intra_rect_sub16_hits() - all_before
16784 );
16785 assert!(
16786 matched > 0,
16787 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
16788 );
16789 assert!(
16790 compared_hits > 0,
16791 "{NAME}: no 8x16/16x8 strip used filter intra ({matched} pixel-exact matches, \
16792 {named_refusals} refusals out of {} attempts) -- gate proved nothing this run",
16793 seeds.len()
16794 );
16795 eprintln!(
16796 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
16797 filter_intra_rect_sub16_hits delta={compared_hits} (all attempts including \
16798 refused: {}) out of {} attempts",
16799 crate::decode::filter_intra_rect_sub16_hits() - all_before,
16800 seeds.len()
16801 );
16802 }
16803
16804 /// lane-rectsplit r1 gate (b): [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]'s
16805 /// own recipe (`--sb-size=64`, `--min/max-partition-size=32/64`, so every
16806 /// SB-level decision is genuinely NONE/SPLIT/HORZ/VERT) with its
16807 /// `--enable-tx-size-search=0` DROPPED: the 64x32/32x64 strips may then
16808 /// carry a split transform, which [`crate::decode::decode_block_rect64`]
16809 /// refused by name ("a superblock-level HORZ/VERT strip with a split
16810 /// transform") until lane-rectsplit r2 lifted it.
16811 ///
16812 /// The hard assert is on [`crate::decode::rect_split_sb_interior_tu_hits`],
16813 /// NOT the shared `rect_split_tx_hits()` gate (a) uses: that counter also
16814 /// counts 32x32-level and depth-1 strips, whose units are all in the
16815 /// first transform-unit row/column. Only a superblock-level strip split
16816 /// past depth 1 has an INTERIOR unit (`row_off > 0 && col_off > 0`),
16817 /// which is the per-unit availability rule this port exists for, and no
16818 /// gate fired one before this round.
16819 ///
16820 /// This gate was `#[ignore]`d RED through r3 (seed 50 luma (171,56)).
16821 /// Root cause, r4, TWO defects, neither of them availability -- the
16822 /// strip's own per-unit prediction was exact all along:
16823 /// 1. `av1_nz_map_ctx_offset` is indexed by libaom's COLUMN-major
16824 /// `coeff_idx = col * 32 + row`, so [`crate::decode::base_ctx`] read
16825 /// the `TX_32X64`/`TX_64X32` offset tables transposed (r2 saw this and
16826 /// r3 reverted it, because "fixing" it turned the merged SB HORZ/VERT
16827 /// gate RED at seed 43);
16828 /// 2. that seed-43 RED was a SECOND defect the first one had been hiding
16829 /// behind a refusal: `EOB_PT_512_CHROMA` was transcribed from
16830 /// `av1_default_eob_multi512_cdfs`'s `eob_multi_ctx = 1` row (the flat
16831 /// `V_DCT`/`H_DCT` distribution), so the first real 32x16 chroma
16832 /// transform read `eob_pt` 7 where aomdec read 2. With both fixed,
16833 /// seeds 43 and 50 are pixel-exact.
16834 #[test]
16835 fn a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact() {
16836 const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact";
16837 let _gate_lock = lock_gate_counters();
16838 if !have_ffmpeg() {
16839 eprintln!("SKIP {NAME}: no ffmpeg");
16840 return;
16841 }
16842 if !have_aomenc() {
16843 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16844 return;
16845 }
16846 let (width, height) = (192usize, 128usize);
16847 let before = crate::decode::rect_split_tx_hits();
16848 let mut named_refusals = 0u32;
16849 let mut matched = 0u32;
16850 // lane-rectsplit r2 (verifier finding): the feature counter is
16851 // sampled PER ATTEMPT and folded in only after that attempt was
16852 // decoded AND pixel-compared. One delta across the whole sweep
16853 // counted strips decoded by attempts that went on to hit a named
16854 // refusal, so the gate could pass with every COMPARED stream
16855 // containing none of the feature at all.
16856 let mut compared_hits = 0usize;
16857 let mut split_so_far = 0usize;
16858 // Bounded sweep: see this gate's own doc for the seed-77 residue and
16859 // why extending it is a diagnosis knob, not a pass/fail one.
16860 let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
16861 .ok()
16862 .and_then(|s| s.parse().ok())
16863 .unwrap_or(20);
16864 for attempt in 0..n_attempts {
16865 let seed = 42 + attempt;
16866 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
16867 let y4m = Command::new("ffmpeg")
16868 .args([
16869 "-v", "error", "-f", "lavfi", "-i", &source,
16870 // REAL chroma (lane-sqchroma r1 dropped the `hue=s=0`
16871 // guard this recipe carried): the "PRE-EXISTING square-path
16872 // chroma defect" that guard named does not reproduce at
16873 // HEAD -- seeds 42..61, cq 12/20/32/45, plus testsrc2 and
16874 // mandelbrot, all decode pixel-exact with
16875 // `--enable-rect-partitions=0`, and this gate is green with
16876 // the filter gone. Its own gate is
16877 // `a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact`.
16878 "-pix_fmt", "yuv420p", "-f",
16879 "yuv4mpegpipe", "-",
16880 ])
16881 .stdin(Stdio::null())
16882 .stdout(Stdio::piped())
16883 .stderr(Stdio::piped())
16884 .output()
16885 .expect("ffmpeg failed to run");
16886 assert!(
16887 y4m.status.success(),
16888 "ffmpeg fixture: {}",
16889 String::from_utf8_lossy(&y4m.stderr)
16890 );
16891 // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's
16892 // own default (search ON) is the entire point of this gate.
16893 let args: Vec<&str> = vec![
16894 "--codec=av1",
16895 "--passes=1",
16896 "--end-usage=q",
16897 "--cq-level=45",
16898 "--cpu-used=0",
16899 "--threads=1",
16900 "--row-mt=0",
16901 "--sb-size=64",
16902 "--enable-rect-partitions=1",
16903 "--enable-ab-partitions=0",
16904 "--enable-1to4-partitions=0",
16905 "--min-partition-size=32",
16906 "--max-partition-size=64",
16907 "--enable-restoration=0",
16908 "--enable-palette=0",
16909 "--deltaq-mode=0",
16910 "--enable-filter-intra=0",
16911 "--enable-cfl-intra=0",
16912 "--enable-intrabc=0",
16913 "--obu",
16914 "-o",
16915 "-",
16916 "-",
16917 ];
16918 let mut child = Command::new(aomenc_path())
16919 .args(&args)
16920 .stdin(Stdio::piped())
16921 .stdout(Stdio::piped())
16922 .stderr(Stdio::piped())
16923 .spawn()
16924 .expect("aomenc failed to start");
16925 child
16926 .stdin
16927 .take()
16928 .expect("aomenc stdin")
16929 .write_all(&y4m.stdout)
16930 .expect("writing y4m to aomenc");
16931 let out = child.wait_with_output().expect("aomenc failed to run");
16932 assert!(
16933 out.status.success(),
16934 "aomenc refused the fixture: {}",
16935 String::from_utf8_lossy(&out.stderr)
16936 );
16937 let stream = out.stdout;
16938 assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})");
16939 let attempt_before = crate::decode::rect_split_sb_interior_tu_hits();
16940 let frames = match decode_stream(&stream) {
16941 Err(e) => {
16942 let msg = e.to_string();
16943 assert!(
16944 msg.contains("unsupported"),
16945 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
16946 );
16947 named_refusals += 1;
16948 continue;
16949 }
16950 Ok(frames) => frames,
16951 };
16952 let after = crate::decode::rect_split_tx_hits();
16953 eprintln!(
16954 "{NAME}: seed {seed} decoded, split-tx strips this stream: {}",
16955 after - before - split_so_far
16956 );
16957 split_so_far = after - before;
16958 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
16959 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
16960 if let Some(i) = frames[0]
16961 .y
16962 .iter()
16963 .zip(&ffmpeg_frames[0].y)
16964 .position(|(a, b)| a != b)
16965 {
16966 let diffs: Vec<usize> = frames[0]
16967 .y
16968 .iter()
16969 .zip(&ffmpeg_frames[0].y)
16970 .enumerate()
16971 .filter(|(_, (a, b))| a != b)
16972 .map(|(j, _)| j)
16973 .collect();
16974 let (x0, x1) = (
16975 diffs.iter().map(|j| j % width).min().unwrap(),
16976 diffs.iter().map(|j| j % width).max().unwrap(),
16977 );
16978 let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width);
16979 eprintln!(
16980 "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \
16981 -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}",
16982 i % width,
16983 i / width,
16984 frames[0].y[i],
16985 ffmpeg_frames[0].y[i],
16986 diffs.len(),
16987 );
16988 }
16989 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
16990 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
16991 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
16992 compared_hits += crate::decode::rect_split_sb_interior_tu_hits() - attempt_before;
16993 matched += 1;
16994 }
16995 let split_hits = compared_hits;
16996 assert!(
16997 matched > 0,
16998 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
16999 );
17000 assert!(
17001 split_hits > 0,
17002 "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \
17003 matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \
17004 this run"
17005 );
17006 eprintln!(
17007 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
17008 rect_split_sb_interior_tu_hits delta={split_hits} (over COMPARED streams only) \
17009 out of {n_attempts} attempts"
17010 );
17011 }
17012
17013 /// lane-part32 r4: a real `aomenc` stream whose superblock-level
17014 /// partition decision is one of the four AB arms (`PARTITION_HORZ_A`/
17015 /// `_B`/`VERT_A`/`_B` at 64x64: two 32x32 squares plus one 64x32/32x64
17016 /// strip) must decode pixel-exact. Same recipe as the HORZ/VERT sibling
17017 /// above with `--enable-ab-partitions=1`; `sb_ab_hits() > 0` is a HARD
17018 /// assert, so a run where aomenc's RD never picked an AB arm fails
17019 /// rather than passing vacuously.
17020 #[test]
17021 fn a_real_aomenc_stream_with_a_superblock_level_ab_partition_decodes_pixel_exact() {
17022 const NAME: &str =
17023 "a_real_aomenc_stream_with_a_superblock_level_ab_partition_decodes_pixel_exact";
17024 let _gate_lock = lock_gate_counters();
17025 if !have_ffmpeg() {
17026 eprintln!("SKIP {NAME}: no ffmpeg");
17027 return;
17028 }
17029 if !have_aomenc() {
17030 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17031 return;
17032 }
17033 let (width, height, frame_count) = (192usize, 128usize, 1usize);
17034 let mut named_refusals = 0u32;
17035 let mut matched = 0u32;
17036 let n_attempts: u32 = std::env::var("EC_SBAB_GATE_ATTEMPTS")
17037 .ok()
17038 .and_then(|s| s.parse().ok())
17039 .unwrap_or(40);
17040 for attempt in 0..n_attempts {
17041 let seed = 42 + attempt;
17042 let duration = frame_count as f64 / 25.0;
17043 let source =
17044 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
17045 let y4m = Command::new("ffmpeg")
17046 .args([
17047 "-v",
17048 "error",
17049 "-f",
17050 "lavfi",
17051 "-i",
17052 &source,
17053 "-pix_fmt",
17054 "yuv420p",
17055 "-f",
17056 "yuv4mpegpipe",
17057 "-",
17058 ])
17059 .stdin(Stdio::null())
17060 .stdout(Stdio::piped())
17061 .stderr(Stdio::piped())
17062 .output()
17063 .expect("ffmpeg failed to run");
17064 assert!(
17065 y4m.status.success(),
17066 "ffmpeg fixture: {}",
17067 String::from_utf8_lossy(&y4m.stderr)
17068 );
17069 let args: Vec<&str> = vec![
17070 "--codec=av1",
17071 "--passes=1",
17072 "--end-usage=q",
17073 "--cq-level=45",
17074 "--cpu-used=0",
17075 "--threads=1",
17076 "--row-mt=0",
17077 "--sb-size=64",
17078 "--enable-rect-partitions=1",
17079 "--enable-ab-partitions=1",
17080 "--enable-1to4-partitions=0",
17081 "--min-partition-size=32",
17082 "--max-partition-size=64",
17083 "--enable-restoration=0",
17084 "--enable-palette=0",
17085 "--deltaq-mode=0",
17086 "--enable-filter-intra=0",
17087 "--enable-cfl-intra=0",
17088 "--enable-intrabc=0",
17089 "--enable-tx-size-search=0",
17090 "--obu",
17091 "-o",
17092 "-",
17093 "-",
17094 ];
17095 let mut child = Command::new(aomenc_path())
17096 .args(&args)
17097 .stdin(Stdio::piped())
17098 .stdout(Stdio::piped())
17099 .stderr(Stdio::piped())
17100 .spawn()
17101 .expect("aomenc failed to start");
17102 child
17103 .stdin
17104 .take()
17105 .expect("aomenc stdin")
17106 .write_all(&y4m.stdout)
17107 .expect("writing y4m to aomenc");
17108 let out = child.wait_with_output().expect("aomenc failed to run");
17109 assert!(
17110 out.status.success(),
17111 "aomenc refused the fixture: {}",
17112 String::from_utf8_lossy(&out.stderr)
17113 );
17114 let stream = out.stdout;
17115 let frames = match decode_stream(&stream) {
17116 Err(e) => {
17117 let msg = e.to_string();
17118 assert!(
17119 msg.contains("unsupported"),
17120 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
17121 );
17122 // r5: the four SB-level AB arms (`partition_w64` 4-7)
17123 // decode since this round, so the only partition refusal
17124 // left at 64x64 is the 1:4 pair (values 8/9, four
17125 // 64x16/16x64 strips, whose luma TX_64X16 this decoder
17126 // has no transform for); the refusals this loop actually
17127 // counts on these fixtures are the pre-existing
17128 // screen-content-palette strip one. Every refusal is
17129 // named, so a genuine decode failure still fails the
17130 // assert above rather than skipping.
17131 named_refusals += 1;
17132 eprintln!("seed {seed} refusal: {msg}");
17133 continue;
17134 }
17135 Ok(frames) => frames,
17136 };
17137 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17138 assert_eq!(frames.len(), frame_count);
17139 let mismatched = frames
17140 .iter()
17141 .zip(&ffmpeg_frames)
17142 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17143 if mismatched {
17144 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
17145 std::fs::write(&path, &stream).expect("writing pinned stream");
17146 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
17147 }
17148 }
17149 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17150 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
17151 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
17152 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
17153 }
17154 matched += 1;
17155 }
17156 assert!(
17157 matched > 0,
17158 "{NAME}: every attempt refused; the gate never decoded a stream"
17159 );
17160 let arms = crate::decode::sb_ab_hits_by_arm();
17161 for (i, name) in ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"].iter().enumerate() {
17162 assert!(
17163 arms[i] > 0,
17164 "{NAME}: zero superblock-level PARTITION_{name} blocks fired (arms={arms:?}, \
17165 {matched} matches, {named_refusals} refusals out of {n_attempts}) -- that arm \
17166 proved nothing this run"
17167 );
17168 }
17169 eprintln!(
17170 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
17171 {n_attempts}, sb_ab_hits={} arms(HORZ_A,HORZ_B,VERT_A,VERT_B)={arms:?}",
17172 crate::decode::sb_ab_hits()
17173 );
17174 }
17175
17176 /// lane-part32 r2: prints the exact mismatch geometry (block coords,
17177 /// got/want pixels) of the pinned seed-42 stream captured off
17178 /// `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
17179 /// via `EC_AV1_GATE_DUMP`. Debug-only, `#[ignore]`d.
17180 #[test]
17181 #[ignore = "debug harness, run manually with EC_AV1_GATE_DUMP_PIN"]
17182 fn debug_part32_r2_sbpart_pin_mismatch_geometry() {
17183 let path = std::env::var("EC_AV1_GATE_DUMP_PIN").expect("set EC_AV1_GATE_DUMP_PIN");
17184 let stream = std::fs::read(&path).expect("read pinned stream");
17185 let frames = decode_stream(&stream).expect("pinned stream must decode");
17186 if let Ok(dump) = std::env::var("EC_DEBUG_DUMP_Y") {
17187 let bytes: Vec<u8> = frames[0].y.iter().map(|&v| v as u8).collect();
17188 std::fs::write(&dump, bytes).expect("write y dump");
17189 }
17190 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 192, 128, 1);
17191 let got = &frames[0];
17192 let want = &ffmpeg_frames[0];
17193 let width = 192usize;
17194 let mut n = 0;
17195 let (mut min_x, mut max_x, mut min_y, mut max_y) = (width, 0, 128, 0);
17196 for y in 0..128usize {
17197 for x in 0..width {
17198 let idx = y * width + x;
17199 if got.y[idx] != want.y[idx] {
17200 n += 1;
17201 min_x = min_x.min(x);
17202 max_x = max_x.max(x);
17203 min_y = min_y.min(y);
17204 max_y = max_y.max(y);
17205 }
17206 }
17207 }
17208 eprintln!(
17209 "total luma mismatches: {n} bbox x=[{min_x},{max_x}] y=[{min_y},{max_y}] frame=192x128"
17210 );
17211 for y in 0..128usize {
17212 let mut row_first = None;
17213 let mut row_count = 0;
17214 for x in 0..width {
17215 let idx = y * width + x;
17216 if got.y[idx] != want.y[idx] {
17217 if row_first.is_none() {
17218 row_first = Some(x);
17219 }
17220 row_count += 1;
17221 }
17222 }
17223 if let Some(fx) = row_first {
17224 eprintln!("row {y}: first mismatch x={fx} count={row_count}");
17225 }
17226 }
17227 }
17228
17229 /// lane-rect64q r1: same recipe as
17230 /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]
17231 /// minus `--deltaq-mode=0` -- real aomenc's non-realtime default is
17232 /// `DELTA_Q_OBJECTIVE` (`av1_cx_iface.c:271`), so dropping that one flag
17233 /// is enough to make `delta_q_present=1` the norm and drive
17234 /// [`crate::decode::decode_block_rect64`]'s running `CURRENT_Q_IDX` away
17235 /// from the frame-constant `base_q_idx` inside a real rect64 SB --
17236 /// exactly the bug this round's dequant fix targets. Hard-asserts
17237 /// `rect64_qidx_drift_hits() > 0`: without that, this gate could pass
17238 /// vacuously the same way the `--deltaq-mode=0` sibling always did.
17239 ///
17240 /// lane-rect64q r1: measured, does NOT fire -- 15/40 attempts matched
17241 /// but `rect64_qidx_drift_hits()` stayed 0 every time. Real aomenc's RD
17242 /// never chose a nonzero delta-q on this tiny synthetic gradients frame
17243 /// even with `deltaq-mode` left at its default; `#[ignore]`d rather than
17244 /// deleted so the recipe and the negative result both survive for the
17245 /// next attempt (see `lanes/rect64q-r1.report.md`).
17246 #[test]
17247 #[ignore = "drift never observed this round -- see lanes/rect64q-r1.report.md"]
17248 fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact()
17249 {
17250 const NAME: &str =
17251 "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact";
17252 let _gate_lock = lock_gate_counters();
17253 if !have_ffmpeg() {
17254 eprintln!("SKIP {NAME}: no ffmpeg");
17255 return;
17256 }
17257 if !have_aomenc() {
17258 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17259 return;
17260 }
17261 let (width, height, frame_count) = (192usize, 128usize, 1usize);
17262 let mut named_refusals = 0u32;
17263 let mut matched = 0u32;
17264 let n_attempts: u32 = std::env::var("EC_SBPART_DQ_GATE_ATTEMPTS")
17265 .ok()
17266 .and_then(|s| s.parse().ok())
17267 .unwrap_or(40);
17268 for attempt in 0..n_attempts {
17269 let seed = 42 + attempt;
17270 let duration = frame_count as f64 / 25.0;
17271 let source =
17272 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
17273 let y4m = Command::new("ffmpeg")
17274 .args([
17275 "-v",
17276 "error",
17277 "-f",
17278 "lavfi",
17279 "-i",
17280 &source,
17281 "-pix_fmt",
17282 "yuv420p",
17283 "-f",
17284 "yuv4mpegpipe",
17285 "-",
17286 ])
17287 .stdin(Stdio::null())
17288 .stdout(Stdio::piped())
17289 .stderr(Stdio::piped())
17290 .output()
17291 .expect("ffmpeg failed to run");
17292 assert!(
17293 y4m.status.success(),
17294 "ffmpeg fixture: {}",
17295 String::from_utf8_lossy(&y4m.stderr)
17296 );
17297 let args: Vec<&str> = vec![
17298 "--codec=av1",
17299 "--passes=1",
17300 "--end-usage=q",
17301 "--cq-level=45",
17302 "--cpu-used=0",
17303 "--threads=1",
17304 "--row-mt=0",
17305 "--sb-size=64",
17306 "--enable-rect-partitions=1",
17307 "--enable-ab-partitions=0",
17308 "--enable-1to4-partitions=0",
17309 "--min-partition-size=32",
17310 "--max-partition-size=64",
17311 "--enable-restoration=0",
17312 "--enable-palette=0",
17313 "--enable-filter-intra=0",
17314 "--enable-cfl-intra=0",
17315 "--enable-intrabc=0",
17316 "--enable-tx-size-search=0",
17317 "--obu",
17318 "-o",
17319 "-",
17320 "-",
17321 ];
17322 let mut child = Command::new(aomenc_path())
17323 .args(&args)
17324 .stdin(Stdio::piped())
17325 .stdout(Stdio::piped())
17326 .stderr(Stdio::piped())
17327 .spawn()
17328 .expect("aomenc failed to start");
17329 child
17330 .stdin
17331 .take()
17332 .expect("aomenc stdin")
17333 .write_all(&y4m.stdout)
17334 .expect("writing y4m to aomenc");
17335 let out = child.wait_with_output().expect("aomenc failed to run");
17336 assert!(
17337 out.status.success(),
17338 "aomenc refused the fixture: {}",
17339 String::from_utf8_lossy(&out.stderr)
17340 );
17341 let stream = out.stdout;
17342 let frames = match decode_stream(&stream) {
17343 Err(e) => {
17344 let msg = e.to_string();
17345 assert!(
17346 msg.contains("unsupported"),
17347 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
17348 );
17349 named_refusals += 1;
17350 eprintln!("seed {seed} refusal: {msg}");
17351 continue;
17352 }
17353 Ok(frames) => frames,
17354 };
17355 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17356 assert_eq!(frames.len(), frame_count);
17357 let mismatched = frames
17358 .iter()
17359 .zip(&ffmpeg_frames)
17360 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17361 if mismatched {
17362 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
17363 std::fs::write(&path, &stream).expect("writing pinned stream");
17364 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
17365 }
17366 }
17367 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17368 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
17369 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
17370 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
17371 }
17372 matched += 1;
17373 }
17374 assert!(
17375 matched > 0,
17376 "{NAME}: every attempt refused; the gate never decoded a stream"
17377 );
17378 assert!(
17379 crate::decode::rect64_qidx_drift_hits() > 0,
17380 "{NAME}: zero rect64 dequant calls ever observed CURRENT_Q_IDX != base_q_idx \
17381 ({matched} matches, {named_refusals} refusals out of {n_attempts}) -- delta_q \
17382 was never actually exercised through decode_block_rect64 this run"
17383 );
17384 eprintln!(
17385 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
17386 {n_attempts}, sb_rect_hits={}, rect64_qidx_drift_hits={}",
17387 crate::decode::sb_rect_hits(),
17388 crate::decode::rect64_qidx_drift_hits()
17389 );
17390 }
17391
17392 /// lane-sbpart r4: replays a pinned mismatch byte-for-byte off disk (no
17393 /// aomenc/ffmpeg re-encode), same pattern as `pinned_golden3/4_stream_
17394 /// decodes_pixel_exact` -- fast red/green loop for the bisect, and lets
17395 /// `EC_AV1_TRACE=1` be set for one run without re-driving the encoder.
17396 #[test]
17397 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
17398 fn pinned_sbpart_stream_decodes_pixel_exact() {
17399 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
17400 .map(std::path::PathBuf::from)
17401 .unwrap_or_else(|_| pin_dir().join("sbpart-pin.obu"));
17402 let Ok(stream) = std::fs::read(&path) else {
17403 eprintln!(
17404 "SKIP pinned_sbpart_stream_decodes_pixel_exact: no pinned bytes at {} \
17405 -- re-capture with EC_AV1_GATE_DUMP off the sbpart gate",
17406 path.display()
17407 );
17408 return;
17409 };
17410 if !have_ffmpeg() {
17411 eprintln!("SKIP pinned_sbpart_stream_decodes_pixel_exact: no ffmpeg");
17412 return;
17413 }
17414 let frames = decode_stream(&stream).expect("pinned stream must decode");
17415 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 192, 128, 1);
17416 let (width, height) = (192usize, 128usize);
17417 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17418 if std::env::var_os("EC_SBPART_DIAG").is_some() {
17419 let (mut min_r, mut max_r, mut min_c, mut max_c, mut n) =
17420 (usize::MAX, 0usize, usize::MAX, 0usize, 0usize);
17421 for r in 0..height {
17422 for c in 0..width {
17423 let idx = r * width + c;
17424 if got.y[idx] != want.y[idx] {
17425 min_r = min_r.min(r);
17426 max_r = max_r.max(r);
17427 min_c = min_c.min(c);
17428 max_c = max_c.max(c);
17429 n += 1;
17430 }
17431 }
17432 }
17433 eprintln!(
17434 "DIAG frame {i}: {n} luma mismatches, bbox rows [{min_r}..{max_r}] cols \
17435 [{min_c}..{max_c}] of {width}x{height}"
17436 );
17437 // Per-64px-superblock-column mismatch counts, to see whether
17438 // corruption starts exactly at the rect64 SB or bleeds into
17439 // SBs decoded earlier (raster order).
17440 for sb_col in 0..(width + 63) / 64 {
17441 let c0 = sb_col * 64;
17442 let c1 = (c0 + 64).min(width);
17443 let mut cnt = 0usize;
17444 let mut first = None;
17445 for r in 0..height {
17446 for c in c0..c1 {
17447 let idx = r * width + c;
17448 if got.y[idx] != want.y[idx] {
17449 cnt += 1;
17450 if first.is_none() {
17451 first = Some((r, c));
17452 }
17453 }
17454 }
17455 }
17456 eprintln!(
17457 "DIAG frame {i} sb_col {sb_col} (cols {c0}..{c1}): {cnt} mismatches, \
17458 first={first:?}"
17459 );
17460 }
17461 }
17462 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned sbpart)");
17463 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned sbpart)");
17464 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned sbpart)");
17465 }
17466 }
17467
17468 /// lane-tx64x16 r1: a real `aomenc` stream whose superblock-level
17469 /// partition decision is `PARTITION_HORZ_4`/`PARTITION_VERT_4` (four
17470 /// 64x16 / 16x64 strips) must decode pixel-exact. Both arms are HARD
17471 /// asserted, and only hits earned inside an attempt that then compared
17472 /// pixel-exact against ffmpeg are counted -- a strip decoded by an
17473 /// attempt that later refused proves nothing (class
17474 /// gate-skips-on-its-own-failure). `--enable-1to4-partitions=1` is the
17475 /// tool switch; `--min-partition-size=16` keeps the RD search from
17476 /// recursing below 16x16, where several other unlanded partition shapes
17477 /// live.
17478 #[test]
17479 fn a_real_aomenc_stream_with_a_superblock_level_1to4_partition_decodes_pixel_exact() {
17480 const NAME: &str =
17481 "a_real_aomenc_stream_with_a_superblock_level_1to4_partition_decodes_pixel_exact";
17482 let _gate_lock = lock_gate_counters();
17483 if !have_ffmpeg() {
17484 eprintln!("SKIP {NAME}: no ffmpeg");
17485 return;
17486 }
17487 if !have_aomenc() {
17488 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17489 return;
17490 }
17491 let (width, height, frame_count) = (192usize, 128usize, 1usize);
17492 let mut named_refusals = 0u32;
17493 let mut matched = 0u32;
17494 let (mut horz_proved, mut vert_proved) = (0usize, 0usize);
17495 let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32);
17496 let n_attempts: u32 = std::env::var("EC_TX64X16_GATE_ATTEMPTS")
17497 .ok()
17498 .and_then(|s| s.parse().ok())
17499 .unwrap_or(40);
17500 for attempt in 0..n_attempts {
17501 let seed = 42 + attempt;
17502 let duration = frame_count as f64 / 25.0;
17503 // Odd attempts render the SAME generator rotated 90 degrees
17504 // (generated at height x width, then `transpose`), because
17505 // aomenc's RD picks `PARTITION_VERT_4` on this content and
17506 // essentially never `HORZ_4`: the two arms are a transposed
17507 // pair, and a gate that only ever sees one of them cannot catch
17508 // a transposed scan/context table (class scan-weights-cross-axis).
17509 let source = if attempt % 2 == 0 {
17510 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
17511 } else {
17512 format!(
17513 "{},transpose=1",
17514 gradients_source(seed, height, width, &format!("duration={duration}:rate=25"))
17515 )
17516 };
17517 let y4m = Command::new("ffmpeg")
17518 .args([
17519 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
17520 "yuv4mpegpipe", "-",
17521 ])
17522 .stdin(Stdio::null())
17523 .stdout(Stdio::piped())
17524 .stderr(Stdio::piped())
17525 .output()
17526 .expect("ffmpeg failed to run");
17527 assert!(
17528 y4m.status.success(),
17529 "ffmpeg fixture: {}",
17530 String::from_utf8_lossy(&y4m.stderr)
17531 );
17532 let args: Vec<&str> = vec![
17533 "--codec=av1",
17534 "--passes=1",
17535 "--end-usage=q",
17536 "--cq-level=45",
17537 "--cpu-used=0",
17538 "--threads=1",
17539 "--row-mt=0",
17540 "--sb-size=64",
17541 "--enable-rect-partitions=1",
17542 "--enable-ab-partitions=0",
17543 "--enable-1to4-partitions=1",
17544 "--min-partition-size=16",
17545 "--max-partition-size=64",
17546 "--enable-restoration=0",
17547 "--enable-palette=0",
17548 "--deltaq-mode=0",
17549 "--enable-filter-intra=0",
17550 "--enable-cfl-intra=0",
17551 "--enable-intrabc=0",
17552 "--enable-tx-size-search=0",
17553 "--obu",
17554 "-o",
17555 "-",
17556 "-",
17557 ];
17558 let mut child = Command::new(aomenc_path())
17559 .args(&args)
17560 .stdin(Stdio::piped())
17561 .stdout(Stdio::piped())
17562 .stderr(Stdio::piped())
17563 .spawn()
17564 .expect("aomenc failed to start");
17565 child
17566 .stdin
17567 .take()
17568 .expect("aomenc stdin")
17569 .write_all(&y4m.stdout)
17570 .expect("writing y4m to aomenc");
17571 let out = child.wait_with_output().expect("aomenc failed to run");
17572 assert!(
17573 out.status.success(),
17574 "aomenc refused the fixture: {}",
17575 String::from_utf8_lossy(&out.stderr)
17576 );
17577 let stream = out.stdout;
17578 let before = (
17579 crate::decode::sb_rect4_horz_hits(),
17580 crate::decode::sb_rect4_vert_hits(),
17581 );
17582 let frames = match decode_stream(&stream) {
17583 Err(e) => {
17584 let msg = e.to_string();
17585 assert!(
17586 msg.contains("unsupported"),
17587 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
17588 );
17589 named_refusals += 1;
17590 eprintln!("seed {seed} refusal: {msg}");
17591 continue;
17592 }
17593 Ok(frames) => frames,
17594 };
17595 let (horz, vert) = (
17596 crate::decode::sb_rect4_horz_hits() - before.0,
17597 crate::decode::sb_rect4_vert_hits() - before.1,
17598 );
17599 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17600 assert_eq!(frames.len(), frame_count);
17601 let mismatched = frames
17602 .iter()
17603 .zip(&ffmpeg_frames)
17604 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17605 if horz + vert == 0 {
17606 // Out of this gate's territory: aomenc's RD picked no 1:4
17607 // partition at all for this seed, so the attempt can neither
17608 // prove nor disprove the arms under test. NOT silently
17609 // dropped -- counted and printed, and a mismatch here is
17610 // reported as a defect of another lane's shape (r1 found
17611 // one: seed 55 of this very recipe decodes 3944 wrong luma
17612 // samples with zero 1:4 blocks in the stream, first at
17613 // (154, 59), inside the 64x32 `PARTITION_HORZ` superblock at
17614 // (128, 64) -- see lanes/tx64x16-r1.report.md). Selecting on
17615 // "the stream contains the feature", never on "the stream
17616 // decoded correctly", is what keeps this from being survivor
17617 // bias.
17618 out_of_scope += 1;
17619 if mismatched {
17620 out_of_scope_mismatch += 1;
17621 eprintln!(
17622 "{NAME}: seed {seed} MISMATCHES with zero 1:4 blocks -- a pre-existing \
17623 defect of another shape, not this gate's arms"
17624 );
17625 }
17626 continue;
17627 }
17628 if mismatched {
17629 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
17630 std::fs::write(&path, &stream).expect("writing pinned stream");
17631 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
17632 }
17633 }
17634 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17635 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
17636 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
17637 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
17638 }
17639 horz_proved += horz;
17640 vert_proved += vert;
17641 matched += 1;
17642 }
17643 assert!(
17644 matched > 0,
17645 "{NAME}: every attempt refused; the gate never decoded a stream"
17646 );
17647 assert!(
17648 horz_proved > 0 && vert_proved > 0,
17649 "{NAME}: a 1:4 arm never fired inside a pixel-exact attempt \
17650 (horz={horz_proved}, vert={vert_proved}, {matched} matches, {named_refusals} \
17651 refusals out of {n_attempts}) -- gate proved nothing this run"
17652 );
17653 eprintln!(
17654 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
17655 {n_attempts}, horz_4 strips={horz_proved}, vert_4 strips={vert_proved}, \
17656 {out_of_scope} attempts carried no 1:4 block ({out_of_scope_mismatch} of them \
17657 mismatched -- other lanes' shapes)"
17658 );
17659 // Class gate-skips-on-its-own-failure: an attempt that decoded but
17660 // does not carry this gate's shape is still a decode this crate got
17661 // wrong. Counted separately so the message names the other shape,
17662 // never tolerated.
17663 assert_eq!(
17664 out_of_scope_mismatch, 0,
17665 "{NAME}: {out_of_scope_mismatch} attempt(s) with no 1:4 block decoded but \
17666 mismatched ffmpeg -- a defect of another shape, not a pass"
17667 );
17668 }
17669
17670 /// lane-tx64x16 r3: the 32x32-LEVEL 1:4 pair -- `PARTITION_HORZ_4` /
17671 /// `PARTITION_VERT_4` at 32x32, i.e. four 32x8 / 8x32 strips, the arm the
17672 /// ReelB mid-film extract stops at ("a 32x32 partition type this
17673 /// decoder does not code (value=8)"). `--min-partition-size=8` is what
17674 /// lets aomenc's RD reach the 32-level 1:4 shapes; `--max-partition-size=32`
17675 /// keeps the superblock-level pair (already gated by its own test above)
17676 /// out of the counters. Both orientations HARD-asserted per bit depth --
17677 /// the luma scans and the two new chroma scans (`SCAN_16X4`/`SCAN_4X16`)
17678 /// are transposed pairs, so a one-sided gate cannot catch a transposition
17679 /// (class scan-weights-cross-axis). `rect4_coeff_hits` is asserted too:
17680 /// an all-skip stream would exercise none of the new coefficient tables
17681 /// (class gate-blind-to-feature). Only hits earned inside an attempt that
17682 /// then compared pixel-exact are counted (class
17683 /// gate-skips-on-its-own-failure); the 10-bit arm is what retires
17684 /// `enable-1to4-partitions` from `NEVER_EXERCISED_10BIT`.
17685 #[test]
17686 // lane-tx64x16 r4: the fixture r3 could not find. `gradients` never wins
17687 // a 32-level 1:4 shape; 8-pixel BANDS do -- each 32x8 strip is flat, so
17688 // HORZ_4 beats both HORZ (two bands per 32x16) and SPLIT, while the noise
17689 // layer keeps aomenc out of screen-content mode. Measured 16 HORZ_4 / 24
17690 // VERT_4 strips per frame, both bit depths (lanes/tx64x16-r4.report.md).
17691 fn a_real_aomenc_stream_with_a_32x32_level_1to4_partition_decodes_pixel_exact() {
17692 const NAME: &str =
17693 "a_real_aomenc_stream_with_a_32x32_level_1to4_partition_decodes_pixel_exact";
17694 let _gate_lock = lock_gate_counters();
17695 if !have_ffmpeg() {
17696 eprintln!("SKIP {NAME}: no ffmpeg");
17697 return;
17698 }
17699 if !have_aomenc() {
17700 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17701 return;
17702 }
17703 let (width, height, frame_count) = (192usize, 128usize, 1usize);
17704 let n_attempts: u32 = std::env::var("EC_TX64X16_GATE32_ATTEMPTS")
17705 .ok()
17706 .and_then(|s| s.parse().ok())
17707 .unwrap_or(8);
17708 for bit_depth in [8u32, 10u32] {
17709 let mut named_refusals = 0u32;
17710 let mut matched = 0u32;
17711 let (mut horz_proved, mut vert_proved, mut coeff_proved) = (0usize, 0usize, 0usize);
17712 let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32);
17713 for attempt in 0..n_attempts {
17714 let seed = 42 + attempt;
17715 let duration = frame_count as f64 / 25.0;
17716 // 8-pixel bands: a 32x8 strip is flat, a 32x16 one is not, so
17717 // aomenc's RD picks HORZ_4 (bands across Y) / VERT_4 (bands
17718 // across X). Odd attempts are the transposed source -- the
17719 // transposed-pair discipline the superblock-level 1:4 gate
17720 // above documents, and the only way a transposed scan table is
17721 // caught (class scan-weights-cross-axis). The noise layer is
17722 // what keeps the flat bands out of screen-content mode; its
17723 // seed is explicit, never lavfi's ignored default.
17724 let axis = if attempt % 2 == 0 { "Y" } else { "X" };
17725 let step = 67 + (attempt / 2) * 12;
17726 let noise = 6 + (attempt % 4) * 3;
17727 let source = format!(
17728 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
17729 geq=lum='mod(floor({axis}/8)*{step},256)',\
17730 noise=alls={noise}:all_seed={seed},format=yuv420p"
17731 );
17732 let cq_level = format!("--cq-level={}", if attempt % 4 < 2 { 32 } else { 45 });
17733 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
17734 let y4m = Command::new("ffmpeg")
17735 .args([
17736 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
17737 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
17738 ])
17739 .stdin(Stdio::null())
17740 .stdout(Stdio::piped())
17741 .stderr(Stdio::piped())
17742 .output()
17743 .expect("ffmpeg failed to run");
17744 assert!(
17745 y4m.status.success(),
17746 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
17747 String::from_utf8_lossy(&y4m.stderr)
17748 );
17749 let depth_arg = format!("--bit-depth={bit_depth}");
17750 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
17751 let args: Vec<&str> = vec![
17752 "--codec=av1",
17753 "--passes=1",
17754 "--end-usage=q",
17755 &cq_level,
17756 "--cpu-used=0",
17757 "--threads=1",
17758 "--row-mt=0",
17759 "--sb-size=64",
17760 &depth_arg,
17761 &input_depth_arg,
17762 "--enable-rect-partitions=1",
17763 "--enable-ab-partitions=0",
17764 "--enable-1to4-partitions=1",
17765 "--min-partition-size=8",
17766 "--max-partition-size=32",
17767 "--enable-restoration=0",
17768 "--enable-palette=0",
17769 "--deltaq-mode=0",
17770 "--enable-filter-intra=0",
17771 "--enable-cfl-intra=0",
17772 "--enable-intrabc=0",
17773 "--enable-tx-size-search=0",
17774 "--obu",
17775 "-o",
17776 "-",
17777 "-",
17778 ];
17779 let mut child = Command::new(aomenc_path())
17780 .args(&args)
17781 .stdin(Stdio::piped())
17782 .stdout(Stdio::piped())
17783 .stderr(Stdio::piped())
17784 .spawn()
17785 .expect("aomenc failed to start");
17786 child
17787 .stdin
17788 .take()
17789 .expect("aomenc stdin")
17790 .write_all(&y4m.stdout)
17791 .expect("writing y4m to aomenc");
17792 let out = child.wait_with_output().expect("aomenc failed to run");
17793 assert!(
17794 out.status.success(),
17795 "aomenc refused the fixture: {}",
17796 String::from_utf8_lossy(&out.stderr)
17797 );
17798 let stream = out.stdout;
17799 let before = (
17800 crate::decode::rect4_32_horz_hits(),
17801 crate::decode::rect4_32_vert_hits(),
17802 crate::decode::rect4_coeff_hits(),
17803 );
17804 let frames = match decode_stream(&stream) {
17805 Err(e) => {
17806 let msg = e.to_string();
17807 assert!(
17808 msg.contains("unsupported"),
17809 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, seed \
17810 {seed}): {msg}"
17811 );
17812 named_refusals += 1;
17813 eprintln!("{bit_depth}-bit seed {seed} refusal: {msg}");
17814 continue;
17815 }
17816 Ok(frames) => frames,
17817 };
17818 let (horz, vert, coeff) = (
17819 crate::decode::rect4_32_horz_hits() - before.0,
17820 crate::decode::rect4_32_vert_hits() - before.1,
17821 crate::decode::rect4_coeff_hits() - before.2,
17822 );
17823 let ffmpeg_frames = if bit_depth == 10 {
17824 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
17825 } else {
17826 ffmpeg_decode_sequence(&stream, width, height, frame_count)
17827 };
17828 assert_eq!(frames.len(), frame_count);
17829 let mismatched = frames
17830 .iter()
17831 .zip(&ffmpeg_frames)
17832 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17833 if horz + vert == 0 {
17834 // Out of this gate's territory (no 32-level 1:4 block in
17835 // the stream): counted and printed, never silently
17836 // dropped, and a mismatch here is another shape's defect.
17837 out_of_scope += 1;
17838 if mismatched {
17839 out_of_scope_mismatch += 1;
17840 eprintln!(
17841 "{NAME}: {bit_depth}-bit seed {seed} MISMATCHES with zero 32-level \
17842 1:4 blocks -- a pre-existing defect of another shape"
17843 );
17844 }
17845 continue;
17846 }
17847 if mismatched {
17848 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
17849 std::fs::write(&path, &stream).expect("writing pinned stream");
17850 eprintln!(
17851 "EC_AV1_GATE_DUMP: wrote mismatching stream ({bit_depth}-bit, seed \
17852 {seed}) to {path}"
17853 );
17854 }
17855 }
17856 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17857 assert_eq!(
17858 got.y, want.y,
17859 "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit, seed {seed})"
17860 );
17861 assert_eq!(
17862 got.u, want.u,
17863 "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit, seed {seed})"
17864 );
17865 assert_eq!(
17866 got.v, want.v,
17867 "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit, seed {seed})"
17868 );
17869 }
17870 horz_proved += horz;
17871 vert_proved += vert;
17872 coeff_proved += coeff;
17873 matched += 1;
17874 }
17875 assert!(
17876 matched > 0,
17877 "{NAME}: every {bit_depth}-bit attempt refused; the gate never decoded a stream"
17878 );
17879 assert!(
17880 horz_proved > 0 && vert_proved > 0,
17881 "{NAME}: a 32-level 1:4 arm never fired inside a pixel-exact {bit_depth}-bit \
17882 attempt (horz={horz_proved}, vert={vert_proved}, {matched} matches, \
17883 {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run"
17884 );
17885 assert!(
17886 coeff_proved > 0,
17887 "{NAME}: every {bit_depth}-bit 32-level 1:4 strip was skip -- the 32x8/16x4 \
17888 coefficient tables were never read"
17889 );
17890 eprintln!(
17891 "{NAME}: {bit_depth}-bit: {named_refusals} named refusals, {matched} pixel-exact \
17892 matches out of {n_attempts}, horz_4 strips={horz_proved}, vert_4 \
17893 strips={vert_proved}, coded strips={coeff_proved}, {out_of_scope} attempts \
17894 carried no 32-level 1:4 block ({out_of_scope_mismatch} mismatched)"
17895 );
17896 assert_eq!(
17897 out_of_scope_mismatch, 0,
17898 "{NAME}: {bit_depth}-bit: {out_of_scope_mismatch} attempt(s) with zero 32-level \
17899 1:4 blocks decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
17900 );
17901 }
17902 }
17903
17904 /// lane-fi32x8 r1 (class symbol-consumption-gap): the 32x32-level 1:4
17905 /// strips (32x8/8x32) are inside `av1_filter_intra_allowed_bsize`'s
17906 /// "both sides <= 32" bound, so libaom reads a `use_filter_intra` flag on
17907 /// every DC_PRED one of them -- and `--enable-filter-intra` is ON by
17908 /// aomenc default, so the sibling gate above (which spells it `=0`) could
17909 /// never see it. `filter_intra_size_class_rect` had no row for either
17910 /// shape, so the symbol was never read and the tile desynced silently
17911 /// from that strip on. Same band fixture as the sibling (8-px bands +
17912 /// seeded noise, both orientations), the ONLY recipe change being
17913 /// `--enable-filter-intra=1` appended AFTER the base recipe (aomenc keeps
17914 /// the LAST occurrence of a repeated `--enable-*` flag). The counter is
17915 /// this shape's OWN (`filter_intra_rect4_hits`), not the shared rect one,
17916 /// so a filter-intra 16x8 strip elsewhere in the frame cannot stand in
17917 /// for it; only hits earned inside an attempt that then compared
17918 /// pixel-exact are counted (class gate-skips-on-its-own-failure), and
17919 /// both bit depths are asserted independently.
17920 ///
17921 /// `--enable-tx-size-search=0` is kept from the sibling recipe: a 1:4
17922 /// strip with `tx_depth != 0` is still refused by name ("a 32x32-level
17923 /// 1:4 strip with a split transform"), so a search-on arm would only
17924 /// harvest refusals, not coverage -- filter intra is proven at depth 0
17925 /// here and the per-TU case belongs to the round that lifts that refusal.
17926 #[test]
17927 fn a_real_aomenc_stream_with_filter_intra_on_a_32_level_1to4_strip_decodes_pixel_exact() {
17928 const NAME: &str =
17929 "a_real_aomenc_stream_with_filter_intra_on_a_32_level_1to4_strip_decodes_pixel_exact";
17930 let _gate_lock = lock_gate_counters();
17931 if !have_ffmpeg() {
17932 eprintln!("SKIP {NAME}: no ffmpeg");
17933 return;
17934 }
17935 if !have_aomenc() {
17936 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17937 return;
17938 }
17939 let (width, height, frame_count) = (192usize, 128usize, 1usize);
17940 let n_attempts: u32 = std::env::var("EC_FI32X8_GATE_ATTEMPTS")
17941 .ok()
17942 .and_then(|s| s.parse().ok())
17943 // 16, not 12 (measured, r1): the first attempt whose VERT_4
17944 // (8x32) strips pick filter intra at 8 bit is attempt 13.
17945 .unwrap_or(16);
17946 for bit_depth in [8u32, 10u32] {
17947 let mut named_refusals = 0u32;
17948 let mut matched = 0u32;
17949 let (mut fi_horz_proved, mut fi_vert_proved, mut strips_proved) = (0usize, 0usize, 0usize);
17950 let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32);
17951 for attempt in 0..n_attempts {
17952 let seed = 42 + attempt;
17953 let duration = frame_count as f64 / 25.0;
17954 let axis = if attempt % 2 == 0 { "Y" } else { "X" };
17955 let step = 67 + (attempt / 2) * 12;
17956 // A HEAVIER noise layer than the sibling gate's 6..15 (lane-fi32x8 r1,
17957 // measured): filter intra is what aomenc reaches for when a flat
17958 // band is noisy, so at 6..15 the flag fired on a 1:4 strip in 3 of
17959 // 40 8-bit attempts and in NONE of 40 10-bit ones, while at 18..27
17960 // it fires in most attempts at BOTH depths.
17961 let noise = 18 + (attempt % 4) * 3;
17962 let source = format!(
17963 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
17964 geq=lum='mod(floor({axis}/8)*{step},256)',\
17965 noise=alls={noise}:all_seed={seed},format=yuv420p"
17966 );
17967 let cq_level = format!("--cq-level={}", [32, 45, 55][(attempt / 2 % 3) as usize]);
17968 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
17969 let y4m = Command::new("ffmpeg")
17970 .args([
17971 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
17972 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
17973 ])
17974 .stdin(Stdio::null())
17975 .stdout(Stdio::piped())
17976 .stderr(Stdio::piped())
17977 .output()
17978 .expect("ffmpeg failed to run");
17979 assert!(
17980 y4m.status.success(),
17981 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
17982 String::from_utf8_lossy(&y4m.stderr)
17983 );
17984 let depth_arg = format!("--bit-depth={bit_depth}");
17985 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
17986 let args: Vec<&str> = vec![
17987 "--codec=av1",
17988 "--passes=1",
17989 "--end-usage=q",
17990 &cq_level,
17991 "--cpu-used=0",
17992 "--threads=1",
17993 "--row-mt=0",
17994 "--sb-size=64",
17995 &depth_arg,
17996 &input_depth_arg,
17997 "--enable-rect-partitions=1",
17998 "--enable-ab-partitions=0",
17999 "--enable-1to4-partitions=1",
18000 "--min-partition-size=8",
18001 "--max-partition-size=32",
18002 "--enable-restoration=0",
18003 "--enable-palette=0",
18004 "--deltaq-mode=0",
18005 "--enable-cfl-intra=0",
18006 "--enable-intrabc=0",
18007 "--enable-tx-size-search=0",
18008 // The competing intra modes off (lane-fi32x8 r1): with
18009 // directional/paeth/smooth intra available, aomenc's RD
18010 // picks filter intra on a 32x8 strip in only ~3 of 40
18011 // attempts at 8 bit and NEVER at 10 bit (measured, see the
18012 // r1 report), so this shape's own symbol would go
18013 // unexercised at 10 bit. Leaving DC and filter intra as
18014 // the block's luma intra choices makes the flag fire
18015 // without weakening the gate: every decoded frame is
18016 // still compared to ffmpeg in full.
18017 "--enable-directional-intra=0",
18018 "--enable-paeth-intra=0",
18019 "--enable-smooth-intra=0",
18020 // THE override, last (aomenc keeps the last occurrence).
18021 "--enable-filter-intra=1",
18022 "--obu",
18023 "-o",
18024 "-",
18025 "-",
18026 ];
18027 let mut child = Command::new(aomenc_path())
18028 .args(&args)
18029 .stdin(Stdio::piped())
18030 .stdout(Stdio::piped())
18031 .stderr(Stdio::piped())
18032 .spawn()
18033 .expect("aomenc failed to start");
18034 child
18035 .stdin
18036 .take()
18037 .expect("aomenc stdin")
18038 .write_all(&y4m.stdout)
18039 .expect("writing y4m to aomenc");
18040 let out = child.wait_with_output().expect("aomenc failed to run");
18041 assert!(
18042 out.status.success(),
18043 "aomenc refused the fixture: {}",
18044 String::from_utf8_lossy(&out.stderr)
18045 );
18046 let stream = out.stdout;
18047 let before = (
18048 crate::decode::filter_intra_rect4_horz_hits(),
18049 crate::decode::filter_intra_rect4_vert_hits(),
18050 crate::decode::rect4_32_horz_hits() + crate::decode::rect4_32_vert_hits(),
18051 );
18052 let frames = match decode_stream(&stream) {
18053 Err(e) => {
18054 let msg = e.to_string();
18055 assert!(
18056 msg.contains("unsupported"),
18057 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, seed \
18058 {seed}): {msg}"
18059 );
18060 named_refusals += 1;
18061 eprintln!("{bit_depth}-bit seed {seed} refusal: {msg}");
18062 continue;
18063 }
18064 Ok(frames) => frames,
18065 };
18066 let (fi_horz, fi_vert, strips) = (
18067 crate::decode::filter_intra_rect4_horz_hits() - before.0,
18068 crate::decode::filter_intra_rect4_vert_hits() - before.1,
18069 crate::decode::rect4_32_horz_hits() + crate::decode::rect4_32_vert_hits()
18070 - before.2,
18071 );
18072 let fi = fi_horz + fi_vert;
18073 let ffmpeg_frames = if bit_depth == 10 {
18074 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
18075 } else {
18076 ffmpeg_decode_sequence(&stream, width, height, frame_count)
18077 };
18078 assert_eq!(frames.len(), frame_count);
18079 let mismatched = frames
18080 .iter()
18081 .zip(&ffmpeg_frames)
18082 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
18083 // Per-attempt line (opt-in): which (seed, cq, axis, noise)
18084 // actually made aomenc pick filter intra ON a 1:4 strip is
18085 // exactly what a re-tune of this fixture needs, and it is not
18086 // recoverable from the summary.
18087 if std::env::var_os("EC_FI32X8_VERBOSE").is_some() {
18088 eprintln!(
18089 "{NAME}: {bit_depth}-bit seed {seed} {cq_level} axis={axis} noise={noise} \
18090 fi={fi_horz}+{fi_vert} strips={strips} mismatched={mismatched}"
18091 );
18092 }
18093 if fi == 0 {
18094 out_of_scope += 1;
18095 if mismatched {
18096 out_of_scope_mismatch += 1;
18097 eprintln!(
18098 "{NAME}: {bit_depth}-bit seed {seed} MISMATCHES with zero \
18099 filter-intra 1:4 strips ({strips} plain 1:4 strips) -- a defect of \
18100 another shape"
18101 );
18102 }
18103 continue;
18104 }
18105 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18106 assert_eq!(
18107 got.y, want.y,
18108 "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit, seed {seed})"
18109 );
18110 assert_eq!(
18111 got.u, want.u,
18112 "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit, seed {seed})"
18113 );
18114 assert_eq!(
18115 got.v, want.v,
18116 "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit, seed {seed})"
18117 );
18118 }
18119 fi_horz_proved += fi_horz;
18120 fi_vert_proved += fi_vert;
18121 strips_proved += strips;
18122 matched += 1;
18123 }
18124 // BOTH orientations, per bit depth: rows 8/9 of `cdf::FILTER_INTRA`
18125 // are asymmetric (18101 for 32x8, 20229 for 8x32), so a one-sided
18126 // assert would pass on a transposed pair.
18127 assert!(
18128 fi_horz_proved > 0 && fi_vert_proved > 0 && matched > 0,
18129 "{NAME}: a 32x8/8x32 strip orientation never read use_filter_intra=1 inside a \
18130 pixel-exact {bit_depth}-bit attempt (32x8={fi_horz_proved}, \
18131 8x32={fi_vert_proved}, {matched} matches, {named_refusals} refusals, \
18132 {out_of_scope} attempts with no filter-intra 1:4 strip, out of {n_attempts}) \
18133 -- gate proved nothing this run"
18134 );
18135 eprintln!(
18136 "{NAME}: {bit_depth}-bit: {named_refusals} named refusals, {matched} pixel-exact \
18137 matches out of {n_attempts}, filter-intra 1:4 strips={fi_horz_proved}x(32x8)+{fi_vert_proved}x(8x32) of \
18138 {strips_proved} 1:4 strips, {out_of_scope} attempts carried none \
18139 ({out_of_scope_mismatch} mismatched)"
18140 );
18141 assert_eq!(
18142 out_of_scope_mismatch, 0,
18143 "{NAME}: {bit_depth}-bit: {out_of_scope_mismatch} attempt(s) with zero \
18144 filter-intra 1:4 strips decoded but mismatched ffmpeg -- a defect of another \
18145 shape, not a pass"
18146 );
18147 }
18148 }
18149
18150 /// lane-tiles r11: every tile gate before this one turns the coding tools
18151 /// OFF (rect/ab partitions, tx-size search, cdef, restoration all `=0`)
18152 /// to isolate the per-tile loop, which is exactly the
18153 /// [[tool-disabled-in-every-gate]] shape -- a tile-edge defect in any of
18154 /// those tools is invisible to all of them. This one runs the BROAD tool
18155 /// set (rect + ab partitions, default tx search, cdef and loop
18156 /// restoration both on, deblocking left at its default so it filters
18157 /// across tile boundaries as the spec requires) over a real 2D tile grid,
18158 /// through `decode_stream` rather than the tile entry point, so it is the
18159 /// same path a caller decoding a file takes.
18160 ///
18161 /// 256x128 is four 64x64 superblocks wide and two tall, so
18162 /// `--tile-columns=1 --tile-rows=1` really yields a 2x2 grid and
18163 /// `--tile-columns=2` really yields 4 columns; both are asserted from the
18164 /// parsed `tile_info` rather than assumed, and the decoded-tile counter
18165 /// (`tile_hits`) is asserted at >= 4 per decoded frame so a stream whose
18166 /// header claims 4 tiles but whose decode only walked one cannot pass.
18167 // `#[track_caller]` so a failing assert names the calling arm's line, and
18168 // so `gate_coverage`'s body split (on `\n #[`) treats this helper's
18169 // recipe as its own gate rather than gluing it onto the preceding one.
18170 #[track_caller]
18171 fn run_multi_tile_gate(
18172 name: &str,
18173 tile_cols_log2: u32,
18174 tile_rows_log2: u32,
18175 bit_depth: usize,
18176 frame_count: usize,
18177 extra: &[&str],
18178 // lane-tiles r12: the palette arm's own override proof. `true` asserts,
18179 // per attempt, that the arm's `--tune-content=screen --enable-palette=1`
18180 // really reached the encoder (frame header `allow_screen_content_tools`)
18181 // AND that a palette block fired at a TILE's left column -- the exact
18182 // block whose colour cache must not see the previous tile's colours.
18183 require_tile_left_palette: bool,
18184 // `None` = the shared `gradients_source`. The palette arm overrides it
18185 // with `smptebars`, the flat few-colour source the existing palette
18186 // gates use -- gradients never make aomenc pick a palette block.
18187 source_override: Option<&str>,
18188 ) {
18189 let _gate_lock = lock_gate_counters();
18190 if !have_ffmpeg() {
18191 eprintln!("SKIP {name}: no ffmpeg");
18192 return;
18193 }
18194 if !have_aomenc() {
18195 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
18196 return;
18197 }
18198 let (width, height) = (256usize, 128usize);
18199 let expected_tiles = (1usize << tile_cols_log2) * (1usize << tile_rows_log2);
18200 let mut matched = 0u32;
18201 let mut named_refusals = 0u32;
18202 let mut uv_edge_suppressed = 0usize;
18203 let n_attempts: u32 = std::env::var("EC_TILES_GATE_ATTEMPTS")
18204 .ok()
18205 .and_then(|s| s.parse().ok())
18206 .unwrap_or(6);
18207 for attempt in 0..n_attempts {
18208 let seed = 42 + attempt;
18209 let duration = frame_count as f64 / 25.0;
18210 let source = match source_override {
18211 Some(src) => format!("{src}=size={width}x{height}:duration={duration}:rate=25"),
18212 None => gradients_source(seed, width, height, &format!("duration={duration}:rate=25")),
18213 };
18214 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
18215 let y4m = Command::new("ffmpeg")
18216 .args([
18217 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt, "-strict",
18218 "-1", "-f", "yuv4mpegpipe", "-",
18219 ])
18220 .stdin(Stdio::null())
18221 .stdout(Stdio::piped())
18222 .stderr(Stdio::piped())
18223 .output()
18224 .expect("ffmpeg failed to run");
18225 assert!(
18226 y4m.status.success(),
18227 "ffmpeg fixture: {}",
18228 String::from_utf8_lossy(&y4m.stderr)
18229 );
18230 let cols = format!("--tile-columns={tile_cols_log2}");
18231 let rows = format!("--tile-rows={tile_rows_log2}");
18232 let limit = format!("--limit={frame_count}");
18233 let depth_args: Vec<String> = if bit_depth == 10 {
18234 vec!["--input-bit-depth=10".to_owned(), "--bit-depth=10".to_owned()]
18235 } else {
18236 Vec::new()
18237 };
18238 let mut args: Vec<&str> = vec![
18239 "--codec=av1",
18240 "--passes=1",
18241 "--end-usage=q",
18242 "--cq-level=40",
18243 "--cpu-used=4",
18244 &limit,
18245 "--kf-max-dist=1000",
18246 "--threads=1",
18247 "--row-mt=0",
18248 // This decoder is 64x64-superblock only, and `--tile-columns`
18249 // splits on superblock boundaries, so 128x128 superblocks
18250 // would leave 256px only two tiles' worth of columns.
18251 "--sb-size=64",
18252 &cols,
18253 &rows,
18254 // The point of this gate: tools ON across tile edges.
18255 "--enable-rect-partitions=1",
18256 "--enable-ab-partitions=1",
18257 "--enable-cdef=1",
18258 "--enable-restoration=1",
18259 // Still off: capabilities this decoder refuses outright, which
18260 // would turn every attempt into a refusal and make the gate
18261 // vacuous rather than proving anything about tiles.
18262 "--enable-1to4-partitions=0",
18263 "--min-partition-size=16",
18264 // Overridable by `extra` (aomenc takes the last occurrence of
18265 // a repeated flag), which the palette arm below relies on.
18266 "--enable-palette=0",
18267 "--enable-intrabc=0",
18268 "--enable-ref-frame-mvs=0",
18269 "--enable-global-motion=0",
18270 ];
18271 args.extend(extra.iter().copied());
18272 args.extend(depth_args.iter().map(String::as_str));
18273 args.extend(["--obu", "-o", "-", "-"]);
18274 let mut child = Command::new(aomenc_path())
18275 .args(&args)
18276 .stdin(Stdio::piped())
18277 .stdout(Stdio::piped())
18278 .stderr(Stdio::piped())
18279 .spawn()
18280 .expect("aomenc failed to start");
18281 child
18282 .stdin
18283 .take()
18284 .expect("aomenc stdin")
18285 .write_all(&y4m.stdout)
18286 .expect("writing y4m to aomenc");
18287 let out = child.wait_with_output().expect("aomenc failed to run");
18288 assert!(
18289 out.status.success(),
18290 "aomenc refused the fixture: {}",
18291 String::from_utf8_lossy(&out.stderr)
18292 );
18293 let stream = out.stdout;
18294
18295 // The stream must really carry the tile grid asked for, or the
18296 // gate proves nothing (aomenc silently clamps tile counts that do
18297 // not fit the frame's superblock grid).
18298 {
18299 let mut probe = Av1Parser::new();
18300 let mut pos = 0usize;
18301 let mut checked = false;
18302 while pos < stream.len() {
18303 let obu = probe.parse_obu(&stream[pos..]).expect("parsing the gate stream");
18304 pos += obu.total_size;
18305 let header = match &obu.kind {
18306 ObuKind::Frame(h, _) => h,
18307 ObuKind::FrameHeader(h) => h,
18308 // lane-tiles r12: prove the base recipe's tools-on
18309 // flags arrived (a repeated aomenc `--enable-*` keeps
18310 // the LAST occurrence -- measured, see the report --
18311 // so a per-arm override must not silently vanish).
18312 ObuKind::SequenceHeader(seq) => {
18313 assert!(
18314 seq.enable_cdef && seq.enable_restoration,
18315 "{name}: --enable-cdef=1 --enable-restoration=1 did not reach \
18316 aomenc (seq enable_cdef={} enable_restoration={}, seed {seed})",
18317 seq.enable_cdef,
18318 seq.enable_restoration
18319 );
18320 continue;
18321 }
18322 _ => continue,
18323 };
18324 // A `show_existing_frame` header codes no tile info at all
18325 // (spec 5.9.2 returns before `tile_info()`), so its
18326 // `TileInfo` is the parser's 1x1 default -- checking it
18327 // here would fail every inter stream for a header that
18328 // carries no tiling.
18329 if header.show_existing_frame {
18330 continue;
18331 }
18332 if require_tile_left_palette {
18333 assert!(
18334 header.allow_screen_content_tools,
18335 "{name}: --tune-content=screen/--enable-palette=1 did not reach \
18336 aomenc -- allow_screen_content_tools is 0 (seed {seed})"
18337 );
18338 }
18339 assert_eq!(
18340 (header.tile_info.cols * header.tile_info.rows) as usize,
18341 expected_tiles,
18342 "{name}: aomenc wrote {}x{} tiles, not the {expected_tiles} asked for \
18343 (seed {seed})",
18344 header.tile_info.cols,
18345 header.tile_info.rows
18346 );
18347 checked = true;
18348 }
18349 assert!(checked, "{name}: no frame header in the stream (seed {seed})");
18350 }
18351
18352 let before = crate::decode::tile_hits();
18353 let pal_before = crate::decode::palette_tile_left_hits();
18354 let uv_edge_before = crate::decode::uv_tile_edge_suppressed_hits();
18355 let frames = match decode_stream(&stream) {
18356 Err(e) => {
18357 let msg = e.to_string();
18358 assert!(
18359 msg.contains("unsupported"),
18360 "{name} failed outright, not a named refusal (seed {seed}): {msg}"
18361 );
18362 named_refusals += 1;
18363 eprintln!("seed {seed} refusal: {msg}");
18364 continue;
18365 }
18366 Ok(frames) => frames,
18367 };
18368 let hits = crate::decode::tile_hits() - before;
18369 assert!(
18370 hits >= expected_tiles * frames.len(),
18371 "{name}: tile_hits delta was {hits}, expected >= {} -- every tile of every \
18372 frame must actually decode (seed {seed})",
18373 expected_tiles * frames.len()
18374 );
18375 let ffmpeg_frames = if bit_depth == 10 {
18376 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
18377 } else {
18378 ffmpeg_decode_sequence(&stream, width, height, frames.len())
18379 };
18380 let mismatched = frames
18381 .iter()
18382 .zip(&ffmpeg_frames)
18383 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
18384 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
18385 std::fs::write(&path, &stream).expect("writing pinned stream");
18386 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
18387 }
18388 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18389 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (seed {seed})");
18390 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (seed {seed})");
18391 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (seed {seed})");
18392 }
18393 if require_tile_left_palette {
18394 let pal = crate::decode::palette_tile_left_hits() - pal_before;
18395 assert!(
18396 pal >= 1,
18397 "{name}: this attempt decoded and matched but fired {pal} palette blocks at \
18398 a tile's left column -- the tile-relative palette cache guard is untested \
18399 (seed {seed})"
18400 );
18401 }
18402 // lane-mtfix r1: the chroma edge-filter neighbour of a block on a
18403 // tile's first mi row/column lives in the tile above/left, where
18404 // libaom has no neighbour at all. This counts the reads suppressed
18405 // there whose frame-wide coarse slot held a non-DC mode -- the
18406 // reads that would otherwise pick the wrong chroma edge filter
18407 // strength (they did, before this fix: seed 46 of this gate).
18408 uv_edge_suppressed += crate::decode::uv_tile_edge_suppressed_hits() - uv_edge_before;
18409 matched += 1;
18410 }
18411 assert!(
18412 matched > 0,
18413 "{name}: every attempt refused ({named_refusals}); the gate never decoded a \
18414 multi-tile stream with the coding tools on"
18415 );
18416 eprintln!(
18417 "{name}: {matched} pixel-exact matches, {named_refusals} named refusals, \
18418 {uv_edge_suppressed} chroma edge reads suppressed at a tile edge"
18419 );
18420 }
18421
18422 #[test]
18423 fn a_real_aomenc_multi_tile_intra_stream_decodes_pixel_exact() {
18424 const NAME: &str = "a_real_aomenc_multi_tile_intra_stream_decodes_pixel_exact";
18425 let before = crate::decode::uv_tile_edge_suppressed_hits();
18426 run_multi_tile_gate(NAME, 1, 1, 8, 1, &[], false, None);
18427 // lane-mtfix r1: this is the only arm with a tile ROW boundary, so it
18428 // is the one that exercises the tile-relative guard on the chroma
18429 // edge-filter neighbour. Without the guard, seed 46's first block of
18430 // the bottom-right tile read the tile ABOVE it and mis-filtered its
18431 // chroma edge (U/V off by 1..2 over chroma x[120..127] y[32..37]).
18432 if have_ffmpeg() && have_aomenc() {
18433 assert!(
18434 crate::decode::uv_tile_edge_suppressed_hits() > before,
18435 "{NAME}: no chroma edge-filter neighbour read was suppressed at a tile edge -- \
18436 the tile-relative guard is untested by this gate"
18437 );
18438 }
18439 }
18440
18441 #[test]
18442 fn a_real_aomenc_multi_tile_intra_10bit_stream_decodes_pixel_exact() {
18443 run_multi_tile_gate(
18444 "a_real_aomenc_multi_tile_intra_10bit_stream_decodes_pixel_exact",
18445 2,
18446 0,
18447 10,
18448 1,
18449 &[],
18450 false,
18451 None,
18452 );
18453 }
18454
18455 /// OPEN DEFECT (lane-tiles r11), which is why this arm is `#[ignore]`d
18456 /// rather than deleted or quietly reseeded: at seed 42 this recipe
18457 /// mismatches ffmpeg from frame 4 on, in one 32x32 block at
18458 /// x[224..255] y[32..63] (measured with `--loopfilter-control=0`, which
18459 /// removes the deblock spreading; with deblocking on the region grows to
18460 /// x[221..255] y[30..69] and crosses the tile row boundary at y=64), and
18461 /// the error then propagates through inter prediction to 12 of 16 frames.
18462 /// Ablations that did NOT remove it: `--enable-restoration=0`,
18463 /// `--enable-cdef=0`, `--loopfilter-control=0`. It is seed-specific
18464 /// (seeds 47 and 48 decode 16/16 exact with two tile rows) and its
18465 /// tile attribution is UNPROVEN: the single-tile control at seed 42
18466 /// re-encodes to different partitions and refuses on
18467 /// "an inter SB-level partition type other than SPLIT", so no
18468 /// same-content one-tile comparison exists. Reproducer:
18469 /// `EC_AV1_GATE_DUMP=<path> cargo test -p ec-av1 --lib
18470 /// a_real_aomenc_multi_tile_inter_stream -- --ignored`.
18471 #[test]
18472 #[ignore = "open defect: seed-42 32x32 block at x[224..255] y[32..63] mismatches; tile attribution unproven"]
18473 fn a_real_aomenc_multi_tile_inter_stream_decodes_pixel_exact() {
18474 run_multi_tile_gate(
18475 "a_real_aomenc_multi_tile_inter_stream_decodes_pixel_exact",
18476 1,
18477 1,
18478 8,
18479 16,
18480 // Pre-existing, non-tile decoder limits this lane does not own:
18481 // the inter path only recurses a superblock as SPLIT (so the SB
18482 // level must be forced to split) and never reads a `tx_depth`
18483 // symbol under `TxMode::Select`. Both are named refusals in
18484 // `refusal_inventory.rs`; without these two flags every inter
18485 // attempt refuses before a single tile edge is compared.
18486 &["--max-partition-size=32", "--enable-tx-size-search=0"],
18487 false,
18488 None,
18489 );
18490 }
18491
18492 /// lane-tiles r11, the defect this arm exists for: `palette_ctx_and_cache`
18493 /// / `palette_uv_cache` (`decode.rs`) read the LEFT palette neighbour with
18494 /// no availability guard at all, where libaom's `av1_get_palette_cache`
18495 /// takes `xd->left_mbmi`, which is NULL at the block's own TILE left
18496 /// column. A second tile column therefore inherited the previous tile's
18497 /// palette colours and `palette_y_mode` ctx. Screen content is what makes
18498 /// aomenc pick palette at all, so this arm drives `--tune-content=screen
18499 /// --enable-palette=1` over a 2-column grid and asserts a real palette
18500 /// block actually fired.
18501 /// `#[ignore]`d at r11 and NOT yet proof of the fix: with the broad tool
18502 /// set every seed refuses before a palette block reconstructs
18503 /// ("a HORZ_A/HORZ_B/VERT_A partition below 16x16"), and the per-arm
18504 /// `extra` overrides do not switch the base recipe's tools off -- aomenc
18505 /// keeps the FIRST occurrence of a repeated `--enable-*` flag (measured:
18506 /// appending `--enable-rect-partitions=0` after the base `=1` changed the
18507 /// refusal not at all). Next round: put `extra` BEFORE the base list in
18508 /// `run_multi_tile_gate`'s args, then this arm should reach a palette
18509 /// block on smptebars with rect/ab off.
18510 #[test]
18511 fn a_real_aomenc_multi_tile_palette_stream_decodes_pixel_exact() {
18512 const NAME: &str = "a_real_aomenc_multi_tile_palette_stream_decodes_pixel_exact";
18513 let before = crate::decode::palette_hits();
18514 run_multi_tile_gate(
18515 NAME,
18516 1,
18517 0,
18518 8,
18519 1,
18520 &["--enable-palette=1", "--tune-content=screen", "--cq-level=30", "--enable-tx-size-search=0", "--max-partition-size=32",
18521 // Screen content + rect strips is a separate, pre-existing
18522 // refusal ("palette syntax is consumed for square blocks
18523 // only"); this arm owns the palette CACHE at a tile edge, so
18524 // it takes the square-only path the other palette gates take.
18525 "--enable-rect-partitions=0", "--enable-ab-partitions=0"],
18526 true,
18527 Some("smptebars"),
18528 );
18529 if have_ffmpeg() && have_aomenc() {
18530 assert!(
18531 crate::decode::palette_hits() > before,
18532 "{NAME}: no palette block fired -- the gate proves nothing about the palette \
18533 cache at a tile edge"
18534 );
18535 }
18536 }
18537
18538 #[test]
18539 fn a_real_aomenc_multi_tile_inter_10bit_stream_decodes_pixel_exact() {
18540 run_multi_tile_gate(
18541 "a_real_aomenc_multi_tile_inter_10bit_stream_decodes_pixel_exact",
18542 2,
18543 0,
18544 10,
18545 16,
18546 // Pre-existing, non-tile decoder limits this lane does not own:
18547 // the inter path only recurses a superblock as SPLIT (so the SB
18548 // level must be forced to split) and never reads a `tx_depth`
18549 // symbol under `TxMode::Select`. Both are named refusals in
18550 // `refusal_inventory.rs`; without these two flags every inter
18551 // attempt refuses before a single tile edge is compared.
18552 &["--max-partition-size=32", "--enable-tx-size-search=0"],
18553 false,
18554 None,
18555 );
18556 }
18557
18558 /// lane-rectchroma r1: a real `aomenc` stream in which a HORZ/VERT strip
18559 /// splits its transform (`--enable-tx-size-search` left ON) and whose
18560 /// chroma half is one of the four rect shapes that had NO coefficient
18561 /// tables in [`crate::decode`] before this round -- 32x8 / 8x32 (the 1:4
18562 /// superblock strips 64x16 / 16x64) and 8x4 / 4x8 (the 8x16 / 16x8 rect
18563 /// of a 16x16-level AB partition). Every such strip refused by name
18564 /// ("a coded HORZ/VERT strip whose chroma transform has no rect
18565 /// coefficient tables here"), which is where both ReelC extracts stopped.
18566 ///
18567 /// Per-shape counters, deltas taken only over attempts that then compared
18568 /// pixel-exact (class counter-from-refused-stream), on 8 AND 10 bit (his
18569 /// films are `yuv420p10le`). Odd seeds render the source transposed so
18570 /// the 32x8/8x32 and 8x4/4x8 pairs both fire -- a single-orientation
18571 /// sweep cannot catch a transposed scan table (class
18572 /// scan-weights-cross-axis).
18573 #[test]
18574 fn a_real_aomenc_stream_with_a_coded_strip_whose_chroma_is_a_4to1_or_sub8_rect_decodes_pixel_exact()
18575 {
18576 const NAME: &str = "a_real_aomenc_stream_with_a_coded_strip_whose_chroma_is_a_4to1_or_sub8_rect_decodes_pixel_exact";
18577 // No seed is excluded any more: seed 46's cq-32 mismatch was the
18578 // per-transform-unit reach (lane-band46 / palette2 r12), and the pin
18579 // below decodes it pixel-exact at both depths.
18580 const EXCLUDED_SEEDS: &[u32] = &[];
18581 let _gate_lock = lock_gate_counters();
18582 if !have_ffmpeg() {
18583 eprintln!("SKIP {NAME}: no ffmpeg");
18584 return;
18585 }
18586 if !have_aomenc() {
18587 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18588 return;
18589 }
18590 let (width, height) = (192usize, 128usize);
18591 let n_attempts: u32 = std::env::var("EC_RECTCHROMA_GATE_ATTEMPTS")
18592 .ok()
18593 .and_then(|s| s.parse().ok())
18594 .unwrap_or(20);
18595 // 32x8, 8x32, 8x4, 4x8, summed over both bit depths.
18596 let mut proved = [0usize; 4];
18597 let mut matched = 0u32;
18598 let mut refusals = 0u32;
18599 // Diagnostics: how much of the territory the COMPARED streams carried
18600 // at all, so a zero above reads as "recipe picked nothing" rather
18601 // than "the shape never split" without another run.
18602 let (mut split_strips, mut rect4_strips) = (0usize, 0usize);
18603 let mut all_rect4 = 0usize;
18604 // Asserted separately: this is the gate that takes `enable-1to4-
18605 // partitions` off `gate_coverage::NEVER_EXERCISED_10BIT`, so the
18606 // 10-bit half has to carry the shape on its own.
18607 let mut rect4_strips_10bit = 0usize;
18608 let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32);
18609 // Attempts that stopped at the new named refusal for a 1:4 strip
18610 // whose transform splits once (see the assert at the end).
18611 let mut depth1_refusals = 0u32;
18612 for (bit_depth, cq) in [(8u32, 45u32), (8, 32), (8, 60), (10, 45), (10, 32), (10, 60)] {
18613 for attempt in 0..n_attempts {
18614 let seed = 42 + attempt;
18615 if EXCLUDED_SEEDS.contains(&seed) {
18616 continue;
18617 }
18618 let stream = rectchroma_stream(bit_depth, cq, attempt, width, height);
18619 let before = crate::decode::rect_split_chroma_shape_hits();
18620 let split_before = crate::decode::rect_split_tx_hits();
18621 let rect4_before = (
18622 crate::decode::sb_rect4_horz_hits(),
18623 crate::decode::sb_rect4_vert_hits(),
18624 );
18625 let frames = match decode_stream(&stream) {
18626 Err(e) => {
18627 let msg = e.to_string();
18628 assert!(
18629 msg.contains("unsupported"),
18630 "{NAME} failed outright, not a named refusal ({bit_depth}-bit seed \
18631 {seed}): {msg}"
18632 );
18633 refusals += 1;
18634 if msg.contains("splits only once") {
18635 depth1_refusals += 1;
18636 }
18637 all_rect4 += (crate::decode::sb_rect4_horz_hits() - rect4_before.0)
18638 + (crate::decode::sb_rect4_vert_hits() - rect4_before.1);
18639 let r4 = (crate::decode::sb_rect4_horz_hits() - rect4_before.0)
18640 + (crate::decode::sb_rect4_vert_hits() - rect4_before.1);
18641 eprintln!(
18642 "{NAME}: {bit_depth}-bit cq {cq} seed {seed} refusal (1:4 strips so \
18643 far {r4}): {msg}"
18644 );
18645 continue;
18646 }
18647 Ok(frames) => frames,
18648 };
18649 let after = crate::decode::rect_split_chroma_shape_hits();
18650 if (0..4).any(|k| after[k] > before[k]) {
18651 eprintln!(
18652 "{NAME}: {bit_depth}-bit cq {cq} seed {seed} carries chroma shapes \
18653 32x8={} 8x32={} 8x4={} 4x8={}",
18654 after[0] - before[0],
18655 after[1] - before[1],
18656 after[2] - before[2],
18657 after[3] - before[3]
18658 );
18659 }
18660 let rect4_now = (crate::decode::sb_rect4_horz_hits() - rect4_before.0)
18661 + (crate::decode::sb_rect4_vert_hits() - rect4_before.1);
18662 let reference = if bit_depth == 10 {
18663 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
18664 } else {
18665 ffmpeg_decode_sequence(&stream, width, height, frames.len())
18666 };
18667 assert_eq!(frames.len(), reference.len(), "{NAME}: frame count");
18668 if rect4_now == 0 {
18669 // Out of this gate's territory (same rule the sibling
18670 // superblock-1:4 gate applies): aomenc picked no 1:4
18671 // strip at all, so the attempt can neither prove nor
18672 // disprove this round's shape. Counted and PRINTED, never
18673 // silently dropped -- selection is on "the stream carries
18674 // the feature", never on "the stream decoded correctly".
18675 out_of_scope += 1;
18676 if frames.iter().zip(&reference).any(|(g, w)| {
18677 g.y != w.y || g.u != w.u || g.v != w.v
18678 }) {
18679 out_of_scope_mismatch += 1;
18680 eprintln!(
18681 "{NAME}: {bit_depth}-bit cq {cq} seed {seed} MISMATCHES with zero \
18682 1:4 strips -- a pre-existing defect of another shape, not this \
18683 gate's arms"
18684 );
18685 }
18686 continue;
18687 }
18688 for (i, (got, want)) in frames.iter().zip(&reference).enumerate() {
18689 assert_eq!(
18690 got.y, want.y,
18691 "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit cq {cq} seed {seed})"
18692 );
18693 assert_eq!(
18694 got.u, want.u,
18695 "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit cq {cq} seed {seed})"
18696 );
18697 assert_eq!(
18698 got.v, want.v,
18699 "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit cq {cq} seed {seed})"
18700 );
18701 }
18702 for k in 0..4 {
18703 proved[k] += after[k] - before[k];
18704 }
18705 split_strips += crate::decode::rect_split_tx_hits() - split_before;
18706 let rect4 = (crate::decode::sb_rect4_horz_hits() - rect4_before.0)
18707 + (crate::decode::sb_rect4_vert_hits() - rect4_before.1);
18708 rect4_strips += rect4;
18709 if bit_depth == 10 {
18710 rect4_strips_10bit += rect4;
18711 }
18712 matched += 1;
18713 }
18714 }
18715 eprintln!(
18716 "{NAME}: {matched} pixel-exact matches, {refusals} named refusals out of \
18717 {} attempts; chroma shapes proved 32x8={} 8x32={} 8x4={} 4x8={}; compared \
18718 streams carried {split_strips} split-transform strips and {rect4_strips} \
18719 superblock 1:4 strips ({all_rect4} more in refused streams); {out_of_scope} \
18720 attempts carried no 1:4 strip ({out_of_scope_mismatch} of them mismatched -- \
18721 other shapes' defects)",
18722 6 * n_attempts,
18723 proved[0],
18724 proved[1],
18725 proved[2],
18726 proved[3]
18727 );
18728 assert_eq!(
18729 out_of_scope_mismatch, 0,
18730 "{NAME}: {out_of_scope_mismatch} attempts carrying no 1:4 strip mismatched \
18731 ffmpeg -- a defect of another shape, not out of scope for the suite (the one \
18732 known case, seed 46, was the per-TU reach and is fixed)"
18733 );
18734 assert!(
18735 matched > 0,
18736 "{NAME}: every attempt refused; the gate never decoded a stream"
18737 );
18738 assert!(
18739 rect4_strips_10bit > 0,
18740 "{NAME}: no superblock 1:4 strip in any pixel-exact 10-BIT stream -- this gate is \
18741 what claims 10-bit coverage for enable-1to4-partitions"
18742 );
18743 assert!(
18744 rect4_strips > 0,
18745 "{NAME}: no superblock 1:4 strip in any pixel-exact stream -- recipe lost its \
18746 territory, gate proved nothing this run"
18747 );
18748 // r1's actual capability delta. Before this round a 1:4 strip whose
18749 // transform depth is 1 was decoded as if its units were SQUARE
18750 // (`bw.min(bh) >> (depth - 1)`), because `sub_tx_size_map[TX_64X16]`
18751 // is TX_32X16, a 2:1 RECT, not TX_16X16 -- 8-bit cq 45 seed 42 of
18752 // this very recipe decoded 2 such strips and MISMATCHED ffmpeg on
18753 // frame 0 luma. It is now refused by name (rect luma transform units
18754 // inside a split strip are unported; the chroma half's 32x8/8x32
18755 // tables this round wired are in place for it). This assert is what
18756 // keeps that from silently regressing to a wrong-pixel decode.
18757 assert!(
18758 depth1_refusals > 0,
18759 "{NAME}: no attempt reached a depth-1 1:4 split strip -- the recipe no longer \
18760 covers the shape this round fixed"
18761 );
18762 eprintln!("{NAME}: {depth1_refusals} attempts refused the depth-1 1:4 split strip by name");
18763 }
18764
18765 /// The chroma-rect gate's fixture + aomenc recipe for one attempt, shared
18766 /// with the seed-46 pin test below so the pin cannot drift from the gate.
18767 fn rectchroma_stream(
18768 bit_depth: u32,
18769 cq: u32,
18770 attempt: u32,
18771 width: usize,
18772 height: usize,
18773 ) -> Vec<u8> {
18774 const NAME: &str = "rectchroma_stream";
18775 let seed = 42 + attempt;
18776 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
18777 // `gradients_source`, the content the sibling split-transform
18778 // superblock gate uses. A band/noise `geq` fixture was tried
18779 // first (r1) and gave 12/12 pixel-exact streams carrying ZERO
18780 // 1:4 strips -- vacuous. Odd attempts render it transposed so
18781 // HORZ_4 and VERT_4 both appear (class scan-weights-cross-axis).
18782 let bands = format!(
18783 "geq=lum='mod(floor(Y/16),2)*160+48':cb=128:cr=128,noise=alls=10:all_seed={seed}"
18784 );
18785 let source = if attempt % 2 == 0 {
18786 format!("color=c=black:size={width}x{height}:duration=0.04:rate=25,{bands}")
18787 } else {
18788 format!(
18789 "color=c=black:size={height}x{width}:duration=0.04:rate=25,{bands},transpose=1"
18790 )
18791 };
18792 let y4m = Command::new("ffmpeg")
18793 .args([
18794 "-v", "error", "-f", "lavfi", "-i", &source, "-t", "0.04", "-pix_fmt",
18795 pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
18796 ])
18797 .stdin(Stdio::null())
18798 .stdout(Stdio::piped())
18799 .stderr(Stdio::piped())
18800 .output()
18801 .expect("ffmpeg failed to run");
18802 assert!(
18803 y4m.status.success(),
18804 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
18805 String::from_utf8_lossy(&y4m.stderr)
18806 );
18807 let cq_arg = format!("--cq-level={cq}");
18808 let depth_arg = format!("--bit-depth={bit_depth}");
18809 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
18810 let mut child = Command::new(aomenc_path())
18811 .args([
18812 "--codec=av1",
18813 "--passes=1",
18814 "--end-usage=q",
18815 &cq_arg,
18816 "--cpu-used=0",
18817 "--threads=1",
18818 "--row-mt=0",
18819 "--sb-size=64",
18820 &depth_arg,
18821 &input_depth_arg,
18822 "--enable-rect-partitions=1",
18823 // AB off: it competes with 1:4 in the RD search (with
18824 // AB on, 0 superblock 1:4 strips appeared in 16
18825 // compared streams), and AB below 16x16 is another
18826 // lane's refusal.
18827 "--enable-ab-partitions=0",
18828 "--enable-1to4-partitions=1",
18829 // 16, not 8: with 8 every seed of this recipe stops
18830 // at a 32x32-level PARTITION_HORZ_4/VERT_4 (partition
18831 // values 8/9, 32x8/8x32 luma strips), a shape this
18832 // decoder does not code at all yet -- 12/12 attempts
18833 // refused before a pixel was compared (measured r1).
18834 // At 16 the 1:4 split happens at the superblock, the
18835 // 64x16/16x64 strips whose chroma half is 32x8/8x32.
18836 "--min-partition-size=16",
18837 "--max-partition-size=64",
18838 "--enable-restoration=0",
18839 "--enable-palette=0",
18840 "--deltaq-mode=0",
18841 "--enable-filter-intra=0",
18842 "--enable-cfl-intra=0",
18843 "--enable-intrabc=0",
18844 "--obu",
18845 "-o",
18846 "-",
18847 "-",
18848 ])
18849 .stdin(Stdio::piped())
18850 .stdout(Stdio::piped())
18851 .stderr(Stdio::piped())
18852 .spawn()
18853 .expect("aomenc failed to start");
18854 child
18855 .stdin
18856 .take()
18857 .expect("aomenc stdin")
18858 .write_all(&y4m.stdout)
18859 .expect("writing y4m to aomenc");
18860 let out = child.wait_with_output().expect("aomenc failed to run");
18861 assert!(
18862 out.status.success(),
18863 "{NAME}: aomenc refused the fixture: {}",
18864 String::from_utf8_lossy(&out.stderr)
18865 );
18866 out.stdout
18867 }
18868
18869 /// PIN for the stream the chroma-rect gate used to exclude: cq 32 seed 46
18870 /// mismatched ffmpeg at BOTH bit depths while carrying zero 1:4 strips.
18871 /// The defect was the per-transform-unit intra reach (lane-band46 /
18872 /// palette2 r12); un-ignored 2026-09-02 once it decoded pixel-exact.
18873 #[test]
18874 fn the_chroma_rect_gates_excluded_seed_46_decodes_pixel_exact() {
18875 const NAME: &str = "the_chroma_rect_gates_excluded_seed_46_decodes_pixel_exact";
18876 let _gate_lock = lock_gate_counters();
18877 if !have_ffmpeg() {
18878 eprintln!("SKIP {NAME}: no ffmpeg");
18879 return;
18880 }
18881 if !have_aomenc() {
18882 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18883 return;
18884 }
18885 let (width, height) = (192usize, 128usize);
18886 // seed 46 == attempt 4 of the gate's sweep, cq 32.
18887 for bit_depth in [8u32, 10] {
18888 let stream = rectchroma_stream(bit_depth, 32, 4, width, height);
18889 let frames = decode_stream(&stream)
18890 .unwrap_or_else(|e| panic!("{NAME}: {bit_depth}-bit seed 46 refused: {e}"));
18891 let reference = if bit_depth == 10 {
18892 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
18893 } else {
18894 ffmpeg_decode_sequence(&stream, width, height, frames.len())
18895 };
18896 assert_eq!(frames.len(), reference.len(), "{NAME}: frame count");
18897 for (i, (got, want)) in frames.iter().zip(&reference).enumerate() {
18898 assert_eq!(got.y, want.y, "{NAME} frame {i} luma ({bit_depth}-bit seed 46)");
18899 assert_eq!(got.u, want.u, "{NAME} frame {i} U ({bit_depth}-bit seed 46)");
18900 assert_eq!(got.v, want.v, "{NAME} frame {i} V ({bit_depth}-bit seed 46)");
18901 }
18902 }
18903 }
18904
18905
18906 /// lane-band46 r1: a real `aomenc` band stream whose 16x16 (and 8x8)
18907 /// intra blocks SPLIT their transform, so every unit but the first
18908 /// answers `has_top_right`/`has_bottom_left` from its `row_off`/`col_off`
18909 /// inside the parent block rather than from the standalone-block tables
18910 /// (libaom `reconintra.c`; class reach-is-per-transform-unit).
18911 ///
18912 /// Seed 46 of the sibling 1:4-strip recipe is the stream that found it:
18913 /// it carries ZERO 1:4 strips, so that gate skipped it as out of scope
18914 /// while frame 0 luma mismatched ffmpeg over 916 samples -- the first at
18915 /// (x 14, y 18), the second 8x8 transform unit of the D203_PRED block at
18916 /// mi (4, 0), whose bottom-left samples sit in a unit that is not
18917 /// reconstructed yet (`col_off > 0` => `has_bottom_left` is 0). The full
18918 /// mode-info range ladder matched aomdec element for element, so the
18919 /// defect was reconstruction, never entropy.
18920 ///
18921 /// The gate asserts the fix FIRED (`split_tu_reach_fix_hits`, transform
18922 /// units whose reach differs from the old standalone answer) on 8 AND 10
18923 /// bit, and that seed 46 itself decodes pixel-exact.
18924 #[test]
18925 fn a_real_aomenc_band_stream_seed46_decodes_pixel_exact() {
18926 const NAME: &str = "a_real_aomenc_band_stream_seed46_decodes_pixel_exact";
18927 let _gate_lock = lock_gate_counters();
18928 if !have_ffmpeg() {
18929 eprintln!("SKIP {NAME}: no ffmpeg");
18930 return;
18931 }
18932 if !have_aomenc() {
18933 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18934 return;
18935 }
18936 let (width, height) = (192usize, 128usize);
18937 let mut matched = 0u32;
18938 let mut refusals = 0u32;
18939 let mut fixed_tus = 0usize;
18940 let mut fixed_tus_10bit = 0usize;
18941 let mut seed46_compared = [false; 2];
18942 for (di, bit_depth) in [8u32, 10].into_iter().enumerate() {
18943 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
18944 for seed in 42u32..=51 {
18945 // Byte-identical recipe to the 1:4-strip sibling gate, whose
18946 // seed-46 attempt is what exposed this defect (that gate
18947 // classes a no-1:4 stream as out of scope; this one compares
18948 // it).
18949 let bands = format!(
18950 "geq=lum='mod(floor(Y/16),2)*160+48':cb=128:cr=128,noise=alls=10:all_seed={seed}"
18951 );
18952 let source = if seed % 2 == 0 {
18953 format!("color=c=black:size={width}x{height}:duration=0.04:rate=25,{bands}")
18954 } else {
18955 format!(
18956 "color=c=black:size={height}x{width}:duration=0.04:rate=25,{bands},transpose=1"
18957 )
18958 };
18959 let y4m = Command::new("ffmpeg")
18960 .args([
18961 "-v", "error", "-f", "lavfi", "-i", &source, "-t", "0.04", "-pix_fmt",
18962 pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
18963 ])
18964 .stdin(Stdio::null())
18965 .stdout(Stdio::piped())
18966 .stderr(Stdio::piped())
18967 .output()
18968 .expect("ffmpeg failed to run");
18969 assert!(
18970 y4m.status.success(),
18971 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
18972 String::from_utf8_lossy(&y4m.stderr)
18973 );
18974 let depth_arg = format!("--bit-depth={bit_depth}");
18975 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
18976 let mut child = Command::new(aomenc_path())
18977 .args([
18978 "--codec=av1",
18979 "--passes=1",
18980 "--end-usage=q",
18981 "--cq-level=32",
18982 "--cpu-used=0",
18983 "--threads=1",
18984 "--row-mt=0",
18985 "--sb-size=64",
18986 &depth_arg,
18987 &input_depth_arg,
18988 "--enable-rect-partitions=1",
18989 "--enable-ab-partitions=0",
18990 "--enable-1to4-partitions=1",
18991 "--min-partition-size=16",
18992 "--max-partition-size=64",
18993 // Left ON: this is what makes a 16x16 block code four
18994 // 8x8 transform units, the shape the fix is about.
18995 "--enable-tx-size-search=1",
18996 "--enable-restoration=0",
18997 "--enable-palette=0",
18998 "--deltaq-mode=0",
18999 "--enable-filter-intra=0",
19000 "--enable-cfl-intra=0",
19001 "--enable-intrabc=0",
19002 "--obu",
19003 "-o",
19004 "-",
19005 "-",
19006 ])
19007 .stdin(Stdio::piped())
19008 .stdout(Stdio::piped())
19009 .stderr(Stdio::piped())
19010 .spawn()
19011 .expect("aomenc failed to start");
19012 child
19013 .stdin
19014 .take()
19015 .expect("aomenc stdin")
19016 .write_all(&y4m.stdout)
19017 .expect("writing y4m to aomenc");
19018 let out = child.wait_with_output().expect("aomenc failed to run");
19019 assert!(
19020 out.status.success(),
19021 "{NAME}: aomenc refused the fixture: {}",
19022 String::from_utf8_lossy(&out.stderr)
19023 );
19024 let stream = out.stdout;
19025 let before = crate::decode::split_tu_reach_fix_hits();
19026 let frames = match decode_stream(&stream) {
19027 Err(e) => {
19028 let msg = e.to_string();
19029 assert!(
19030 msg.contains("unsupported"),
19031 "{NAME} failed outright, not a named refusal ({bit_depth}-bit seed \
19032 {seed}): {msg}"
19033 );
19034 assert!(
19035 seed != 46,
19036 "{NAME}: seed 46 ({bit_depth}-bit) must decode -- it is this gate's \
19037 pinned stream, and it refused: {msg}"
19038 );
19039 refusals += 1;
19040 eprintln!("{NAME}: {bit_depth}-bit seed {seed} refusal: {msg}");
19041 continue;
19042 }
19043 Ok(frames) => frames,
19044 };
19045 let reference = if bit_depth == 10 {
19046 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
19047 } else {
19048 ffmpeg_decode_sequence(&stream, width, height, frames.len())
19049 };
19050 assert_eq!(frames.len(), reference.len(), "{NAME}: frame count");
19051 for (i, (got, want)) in frames.iter().zip(&reference).enumerate() {
19052 assert_eq!(
19053 got.y, want.y,
19054 "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit seed {seed})"
19055 );
19056 assert_eq!(
19057 got.u, want.u,
19058 "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit seed {seed})"
19059 );
19060 assert_eq!(
19061 got.v, want.v,
19062 "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit seed {seed})"
19063 );
19064 }
19065 let fixed = crate::decode::split_tu_reach_fix_hits() - before;
19066 fixed_tus += fixed;
19067 if bit_depth == 10 {
19068 fixed_tus_10bit += fixed;
19069 }
19070 if seed == 46 {
19071 seed46_compared[di] = true;
19072 }
19073 matched += 1;
19074 }
19075 }
19076 eprintln!(
19077 "{NAME}: {matched} pixel-exact streams, {refusals} named refusals out of 20; \
19078 {fixed_tus} split transform units took the per-TU reach ({fixed_tus_10bit} of them \
19079 10-bit)"
19080 );
19081 assert!(
19082 seed46_compared[0] && seed46_compared[1],
19083 "{NAME}: seed 46 was not compared on both depths (8-bit {}, 10-bit {})",
19084 seed46_compared[0], seed46_compared[1]
19085 );
19086 assert!(
19087 fixed_tus > 0,
19088 "{NAME}: no split transform unit answered its reach from its offset inside the \
19089 parent block -- the recipe lost the shape this gate pins"
19090 );
19091 assert!(
19092 fixed_tus_10bit > 0,
19093 "{NAME}: the shape never appeared in a 10-BIT pixel-exact stream (his films are \
19094 yuv420p10le)"
19095 );
19096 }
19097}