forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiB50503afTahinli3 months ago1344 commits

stream.rs13662 lines, 609.8 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 WarpModel,
22};
23use ec_core::{Error, Result};
24
25use crate::cdf_state::Cdfs;
26use crate::decode;
27use crate::decode::{
28 decode_inter_frame_tile_with_cdfs, decode_key_frame_tile, decode_key_frame_tile_with_cdfs,
29 q_ctx_of,
30};
31use crate::encode::Picture;
32
33/// lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the
34/// current thread, overriding the environment variable. Every ffmpeg/aomdec
35/// pixel gate in this repo compares SHOWN frames only (class
36/// gate-blind-to-hidden-frames), so the hidden alt-ref frames a real aomenc
37/// stream carries were never compared at all; the gate that does compare
38/// them needs a dump path that cannot race a sibling test's decode on
39/// another thread, which a process-global env var cannot give.
40thread_local! {
41 static FINAL_DUMP_PREFIX: std::cell::RefCell<Option<String>> =
42 const { std::cell::RefCell::new(None) };
43}
44
45/// Sets (or with `None` clears) this thread's `EC_AV1_FINAL_DUMP` prefix.
46#[allow(dead_code)]
47pub(crate) fn set_final_dump_prefix(prefix: Option<String>) {
48 FINAL_DUMP_PREFIX.with(|c| *c.borrow_mut() = prefix);
49}
50
51fn final_dump_prefix() -> Option<String> {
52 FINAL_DUMP_PREFIX
53 .with(|c| c.borrow().clone())
54 .or_else(|| std::env::var("EC_AV1_FINAL_DUMP").ok())
55}
56
57/// Decode every frame in a raw AV1 OBU stream, in coding order.
58///
59/// A key frame becomes the reference for the inter frames that follow it,
60/// until the next key frame resets the DPB — the same single-slot chain
61/// [`crate::encode::encode_sequence`] threads on the write side. Only a
62/// `Frame` OBU (an uncompressed header and its tile group in one OBU, which
63/// is all this crate's encoder ever writes) carries a tile payload; sequence
64/// headers and temporal delimiters are consumed for the state they carry (or
65/// skipped) and produce no picture.
66///
67/// # Errors
68/// Returns an error when the stream is truncated or malformed (as
69/// [`Av1Parser`] reports it), when a frame header names anything this
70/// crate's tile decoders do not reconstruct (see their own docs), or when an
71/// inter frame appears before any key frame has supplied a reference.
72pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
73 let final_dump = final_dump_prefix();
74 let mut parser = Av1Parser::new();
75 let mut pictures = Vec::new();
76 let mut pictures_decoded: usize = 0;
77 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
78 // previous frame's `refresh_frame_flags` stored into it, exactly like the
79 // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,
80 // not simply "the previous frame decoded"; a frame whose own predecessor
81 // didn't refresh that slot (an altref/hidden frame, or any GOP with more
82 // than one live reference) must keep predicting from whatever picture is
83 // still sitting there. Round 7's cdffwd hunt: a global `reference`
84 // overwritten every frame silently always used "the most recent decode"
85 // instead, producing a bit-exact motion vector into the WRONG picture --
86 // luma-only (chroma coincidentally shares this fixture's flat regions)
87 // and small-magnitude (the two pictures mostly agree), which is exactly
88 // what made it look like a rounding bug rather than a wrong reference.
89 let mut ref_slots: [Option<Picture>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
90 // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion
91 // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom
92 // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was
93 // decoded with -- `Picture` itself carries neither, so both ride
94 // alongside `ref_slots` on the exact same `refresh_frame_flags` update.
95 let mut motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES] =
96 std::array::from_fn(|_| None);
97 let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES];
98 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
99 // previous frame's `refresh_frame_flags` stored into it -- the frame's
100 // own end-of-tile adapted table, or (when the frame set
101 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
102 let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
103 // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also
104 // remembers the segment map the frame stored there decoded, which is what
105 // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds`
106 // (spec `load_previous_segment_ids`) for temporal segment-id prediction
107 // and for a `segmentation_update_map == 0` frame's inherited map.
108 let mut seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
109
110 let mut pos = 0usize;
111 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec
112 // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone
113 // `OBU_FRAME_HEADER` first, with `show_existing_frame == false` and no
114 // tile payload of its own -- `OBU_FRAME` (the `ObuKind::Frame` arm below)
115 // only ever folds ONE tile group into the header's own OBU. Stash the
116 // header here and accumulate tiles from each `OBU_TILE_GROUP` that
117 // follows until every tile of the frame has arrived.
118 let mut pending_header: Option<Box<FrameHeader>> = None;
119 let mut pending_tiles: Vec<Tile> = Vec::new();
120 while pos < data.len() {
121 let obu = parser.parse_obu(&data[pos..])?;
122 let obu_offset = pos;
123 pos += obu.total_size;
124
125 if let ObuKind::FrameHeader(header) = &obu.kind {
126 if !header.show_existing_frame {
127 // Before this fix, this branch fired unconditionally for
128 // EVERY `FrameHeader` OBU (including this one), so a
129 // standalone header always fell into the `show_existing_frame`
130 // slot lookup below and misreported "a show_existing_frame
131 // header naming an empty reference slot" for a frame that was
132 // never a show_existing_frame header at all.
133 pending_header = Some(header.clone());
134 pending_tiles = Vec::new();
135 continue;
136 }
137 // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this
138 // OBU only names a DPB slot to output again -- the coded-frame
139 // count and the shown-picture count are different things (a
140 // hidden altref's own `Frame` OBU below is never pushed to
141 // `pictures` on its own; it is only pushed here, later, when a
142 // `show_existing_frame` header names its slot). Before r15 this
143 // arm didn't exist at all: every `ObuKind::Frame` was pushed
144 // unconditionally regardless of `show_frame`, so a hidden altref
145 // was emitted (wrongly, in decode order) and its real
146 // `show_existing_frame` output was silently dropped.
147 let slot = header.frame_to_show_map_idx as usize;
148 let picture = ref_slots[slot].clone().ok_or_else(|| {
149 Error::unsupported(
150 "AV1 decode_stream",
151 "a show_existing_frame header naming an empty reference slot",
152 )
153 })?;
154 for i in 0..NUM_REF_FRAMES {
155 if header.refresh_frame_flags & (1 << i) != 0 {
156 cdf_slots[i] = cdf_slots[slot].clone();
157 ref_slots[i] = Some(picture.clone());
158 motion_field_slots[i] = motion_field_slots[slot].clone();
159 seg_map_slots[i] = seg_map_slots[slot].clone();
160 order_hint_slots[i] = order_hint_slots[slot];
161 }
162 }
163 let output = if header.film_grain.apply_grain {
164 // lane-hbd10 r1: grain synthesis is bit-depth generic
165 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
166 let bit_depth = parser
167 .sequence_header()
168 .map_or(8, |seq| seq.color_config.bit_depth);
169 let mc_identity = parser
170 .sequence_header()
171 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
172 crate::film_grain::apply_grain(
173 &picture,
174 &header.film_grain,
175 mc_identity,
176 bit_depth as u32,
177 )
178 } else {
179 picture
180 };
181 pictures.push(output);
182 continue;
183 }
184 // `tiles_base_offset` is added to every `Tile::offset` below to reach
185 // an absolute position in `data`. `OBU_FRAME`'s tiles are relative to
186 // this OBU's own `obu_offset`; an accumulated run of `OBU_TILE_GROUP`s
187 // may span several different OBUs (each at a different offset in
188 // `data`), so those tiles are normalised to an absolute offset the
189 // moment they are appended to `pending_tiles`, and `tiles_base_offset`
190 // is 0 for that case.
191 let (header, tiles, tiles_base_offset): (Box<FrameHeader>, Vec<Tile>, usize) =
192 match obu.kind {
193 ObuKind::Frame(header, tiles) => (header, tiles, obu_offset),
194 ObuKind::TileGroup(new_tiles) => {
195 let header = pending_header.clone().ok_or_else(|| {
196 Error::corrupt(
197 "AV1 decode_stream: a tile group OBU with no preceding frame header",
198 )
199 })?;
200 let expected = header.tile_info.cols * header.tile_info.rows;
201 pending_tiles.extend(new_tiles.into_iter().map(|mut t| {
202 t.offset += obu_offset;
203 t
204 }));
205 if (pending_tiles.len() as u32) < expected {
206 continue;
207 }
208 pending_header = None;
209 (header, std::mem::take(&mut pending_tiles), 0)
210 }
211 _ => continue,
212 };
213 // Every tile is decoded below through `tile_bufs`; this only rejects a
214 // frame OBU that carries no tile group at all.
215 if tiles.is_empty() {
216 return Err(Error::unsupported(
217 "AV1 decode_stream",
218 "a frame OBU with no tile group",
219 ));
220 }
221 // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
222 // block of each 64x64) only reads a literal `cdef_idx` when
223 // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a
224 // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is
225 // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into
226 // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so
227 // a `cdef_bits > 0` stream no longer needs this refusal.
228 // Both frame types now read their transform size under
229 // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads
230 // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's
231 // `decode_inter_block`/`decode_inter_block8` read the recursive
232 // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the
233 // blanket inter-frame refusal that used to stand here is gone. What
234 // remains refused is named at its own site in `read_block_tx_size`.
235 // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`,
236 // libaom decodemv.c): three more per-block/per-SB symbols this crate
237 // never reads at all, each gated by a header field this decoder
238 // otherwise accepts uncomplaining -- the same silent-desync shape
239 // `use_filter_intra` was. `allow_screen_content_tools` gates both
240 // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/
241 // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel`
242 // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse
243 // before desyncing rather than silently miscode, the same pattern as
244 // the CDEF/TxMode::Select refusals above.
245 // lane-screen r2: key frames consume (not reconstruct) palette/
246 // intrabc syntax via read_intra_mode, and decode_inter_block/
247 // decode_inter_block8's own intra-sub-block branches now consume
248 // palette the same way (libaom's read_intra_block_mode_info has no
249 // intrabc call at all -- that symbol is intra-frame-only). A
250 // genuine palette/intrabc use still refuses by name deeper in the
251 // block readers, so no whole-frame refusal is needed here anymore.
252 // lane-realworld r5: both delta_q (maybe_read_delta_q, CURRENT_Q_IDX)
253 // and delta_lf (maybe_read_delta_lf, CURRENT_DELTA_LF ->
254 // Neighbours::delta_lf_grid -> lf_level) are now read and applied;
255 // no whole-frame refusal needed here anymore.
256 //
257 // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an
258 // earlier round), `BIT_DEPTH` is wired from this frame's own sequence
259 // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10`
260 // stream decodes pixel-exact against ffmpeg's own decode of the same
261 // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The
262 // blanket refusal that used to be here is gone; `film_grain.rs` and
263 // `superres.rs` still refuse narrowly by name (their own hardcoded
264 // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes
265 // will show up as a real pixel mismatch, not a silent truncation --
266 // the whole reason the widen (and this wiring) happened.
267 // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9,
268 // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the
269 // per-segment quantizer (spec 7.12.2) and loop-filter level
270 // (spec 7.14.4). The three features that instead REWRITE a block's
271 // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the
272 // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress
273 // symbols `decode_inter_block` unconditionally reads) -- have no
274 // reader on the inter path, so they still refuse by name rather than
275 // desyncing. aomenc's `--aq-mode` segmentation only ever sets
276 // `SEG_LVL_ALT_Q`.
277 if header.segmentation.enabled {
278 for segment in 0..MAX_SEGMENTS {
279 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
280 if header.segmentation.feature_enabled[segment][feature] {
281 return Err(Error::unsupported(
282 "AV1 decode_stream",
283 "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)",
284 ));
285 }
286 }
287 }
288 }
289 // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the
290 // primary reference frame's slot, and is all-zero without one.
291 let prev_seg_map = if header.primary_ref_frame == PRIMARY_REF_NONE {
292 None
293 } else {
294 seg_map_slots[header.ref_frame_idx[header.primary_ref_frame as usize] as usize].clone()
295 };
296 decode::set_segmentation(
297 header.segmentation,
298 header.mi_rows as usize,
299 header.mi_cols as usize,
300 prev_seg_map.as_deref(),
301 );
302 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
303 // symbol (spec 7.16's upscaling is a pixel-domain post-process
304 // libaom's `decodeframe.c` runs between CDEF and loop restoration,
305 // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile
306 // reads stay bit-exact in sync and `crate::superres::upscale_picture`
307 // (below, after decode) makes its `Picture` the spec-correct
308 // `upscaled_width` instead of silently staying at `frame_width`.
309 // lane-superres r10: an INTER frame under `use_superres` no longer
310 // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3)
311 // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/
312 // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes
313 // at the downscaled `frame_width` and upscales its own output the
314 // same way the key-frame branch above does (see the inter branch
315 // below). The combinations `predict_scaled` does not cover
316 // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8
317 // leaf) still refuse by name, deep in `decode.rs`, rather than
318 // silently mispredicting -- see `refusal_inventory.rs`.
319 // Loop restoration carries per-restoration-unit symbols in the tile
320 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
321 // superblock walk) -- lane-lr r2 ported the reader
322 // (`crate::restoration`), r3 moved this refusal check to AFTER the
323 // tile decode call below (was here, before it, in r2 -- meaning
324 // `read_lr` was NEVER actually reached through `decode_stream`, the
325 // gap the r3 gate caught live: 40/40 attempts hit this refusal with
326 // zero `read_lr_unit` hits). Checking post-decode instead proves the
327 // superblock walk actually survived `read_lr` (no desync) before
328 // refusing on the true remaining gap: decoded Wiener/SGR filters are
329 // stored per unit but never applied to pixels.
330 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
331 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
332 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
333 // zero vector only under `GmType == IDENTITY` -- any other warp
334 // model needs the full affine/translation MV derivation this
335 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
336 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
337 // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
338 // to every one of the 7 single-reference slots `decode_inter_block`
339 // can now select.
340 //
341 // lane-gm r2 STEP-8 ATTEMPT (reverted): removing this refusal
342 // exposed a real pixel mismatch --
343 // a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact
344 // seed 43, frame 1 luma, with EC_WEDGE_GATE_ATTEMPTS=20
345 // EC_AV1_REQUIRE_AOMENC=1 -- so the single-ref/compound MV wiring
346 // is not yet provably correct end to end; keeping the refusal
347 // until that seed is captured (EC_AV1_GATE_DUMP), self-pinned, and
348 // root-caused rather than shipping a wrong decode.
349 //
350 // lane-gm r3 ROOT CAUSE (pinned, range-ladder-confirmed, still not
351 // fixed): the mismatch is NOT an mv/mvstack/entropy bug -- msac
352 // RANGE at the first divergent block (mi=(8,0), frame 1) matches
353 // aomdec's own `EC_PART` trace bit-for-bit (rng=38664 both sides),
354 // and this decoder's own `gm_get_motion_vector` for that block
355 // (ROTZOOM, seed 43's own header) computes the spec-correct
356 // mv=(-8,8) (hand-verified against mv.h's `block_center_x`/`_y`,
357 // which found and fixed a real `- 1` omission in `warp.rs` --
358 // harmless for THIS block's rounding but a genuine spec bug fixed
359 // regardless). The actual gap: `reconinter.c`'s `allow_warp` has a
360 // `global_warp_allowed` branch (`warp_types.global_warp_allowed =
361 // is_global_mv_block(...)`, `reconinter_enc.c:281`) that predicts
362 // an `is_global_mv_block` block (ROTZOOM/AFFINE GLOBALMV, >=8x8)
363 // with the FULL per-pixel affine global-motion warp, independent
364 // of `motion_mode` -- this decoder only ever builds a warp
365 // prediction for local `WARPED_CAUSAL` motion mode and falls back
366 // to plain translational MC with the block-centre mv for every
367 // other GLOBALMV block, which is only a centre-point approximation
368 // of the true per-pixel warp. That is the entire remaining gap.
369 // lane-gm r4: `decode.rs` now feeds `global_motion[ref]` into
370 // `crate::warp::global_warp_params` for every single-ref
371 // `is_global_mv_block` (ROTZOOM/AFFINE), matching `allow_warp`'s
372 // `global_warp_allowed` branch -- ROTZOOM is pin-verified
373 // (`gm-seed43.obu`, frame 1 luma MATCH) and TRANSLATION already
374 // worked (`gm_get_motion_vector`'s translation-only mv, no warp
375 // needed). AFFINE is untested this round (no aomenc fixture in the
376 // wedge gate reached a 6-parameter model) -- keep refusing it by
377 // name rather than shipping an unverified decode.
378 if header.frame_type != FrameType::Key
379 && header.global_motion[..7]
380 .iter()
381 .any(|gm| gm.model == WarpModel::Affine)
382 {
383 return Err(Error::unsupported(
384 "AV1 decode_stream",
385 "an inter frame whose global motion for a single-reference frame is AFFINE (unverified this round; ROTZOOM/TRANSLATION/IDENTITY are proven)",
386 ));
387 }
388 // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two
389 // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and
390 // refused the shape by name rather than guess-fix it. r5 localized
391 // the mismatch to an ordinary NEWMV/GOLDEN block, not the new
392 // global-warp branch at all -- proving "two active slots" was a
393 // correlated symptom, not the cause. r6 range-laddered that block
394 // against aomdec's `EC_TRACE_MODE` (identical `rng` before/after
395 // mode info -- symbol consumption bit-exact) and found the real
396 // defect in `mvstack.rs`'s single-reference predictor fallback:
397 // libaom's `setup_ref_mv_list` fills any `mv_ref_list` slot the real
398 // neighbour scan left short with this block's OWN global motion
399 // vector for its ref (`gm_get_motion_vector`), not zero -- invisible
400 // whenever the live ref's global motion is itself
401 // identity/translation, wrong the moment it's a real ROTZOOM/AFFINE
402 // and the querying block's own stack comes up short (frame 14's
403 // mi=(0,0), the very first block decoded, has no neighbours at
404 // all). Fixed at the predictor fallback; the refusal above (single
405 // untested shape: AFFINE on a single-ref frame) stays, but the
406 // *multi-slot* refusal this comment used to guard is lifted -- the
407 // r5/r6 pin (seed-43 wedge-gate mismatch) now decodes all 24 frames
408 // byte-exact with it gone.
409 // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
410 // `comp_mode` per block whenever this frame's own `reference_select`
411 // header bit is set (spec 5.11.25), and refuse by name the blocks
412 // that pick `COMPOUND_REFERENCE` -- two-reference motion
413 // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
414 // is wired at the block level too (forced NEAREST_NEARESTMV compound
415 // of `skip_mode_frame`, plain average blend), so the old blanket
416 // `skip_mode_present` refusal is gone.
417 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
418 // which tile's end-of-tile adapted CDFs become the frame's own.
419 // lane-tiles r8: this comment used to claim a `!= 0` refusal existed
420 // "further down" -- it did not (`decode.rs` reads
421 // `tile_info.context_update_tile_id` generically at both the
422 // key-frame and inter-frame tile loops' `result_cdfs = cdfs` sites,
423 // never hardcoded to tile 0); stale documentation, not a real gap.
424 // `a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact`
425 // hard-asserts a live aomenc stream naming tile 1/2/3 decodes
426 // pixel-exact, so the capability is now proven as well as described
427 // correctly.
428 //
429 // lane-tiles r4/r6/r7/r8: the multi-tile refusal itself is scoped,
430 // not blanket. `decode_key_frame_tile_with_cdfs` and (r6)
431 // `decode_inter_frame_tile_with_cdfs` both genuinely loop every
432 // tile, `mvstack.rs`'s `MiGrid` is bounded per tile
433 // (`MiGrid::set_tile_bounds`), and `PlaneBuf`'s `tile_x0/y0/x1/y1`
434 // origin receives real values at every call site (r6's
435 // `set_tile_origin` sweep). r7 proved the two remaining
436 // tile-*column* gaps closed (inter frames, >2 columns with loop
437 // filtering on). r8 proved tile *rows* the same way: the per-tile
438 // loop's row math (`tile_num / tile_info.cols`,
439 // `mi_row_starts`/`set_tile_origin`'s `y0`/`y1`) is exactly
440 // symmetric with the column path already proven, and
441 // `a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact`
442 // (bypass gate, loop filter ON) confirmed it: 20/20 pixel-exact.
443 // `a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_
444 // stream` below re-proves it through this entry point. Tile columns
445 // and tile rows (any count, loop filter on) are no longer capped.
446 // `Tile::offset` is relative to the buffer `parse_obu` was handed
447 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
448 // to `obu_offset`, not to `data` as a whole.
449 let tile_bufs: Vec<&[u8]> = tiles
450 .iter()
451 .map(|t| {
452 data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size)
453 .ok_or(Error::NeedMore)
454 })
455 .collect::<Result<_>>()?;
456 let enable_filter_intra = parser
457 .sequence_header()
458 .is_some_and(|seq| seq.enable_filter_intra);
459 let enable_dual_filter = parser
460 .sequence_header()
461 .is_some_and(|seq| seq.enable_dual_filter);
462 let enable_edge_filter = parser
463 .sequence_header()
464 .is_some_and(|seq| seq.enable_intra_edge_filter);
465 // Inter frames' intra blocks read this through a thread-local that only
466 // the key-frame tile path used to set; without this call a stream whose
467 // inter frames are decoded on a thread that previously decoded a
468 // different sequence would inherit that sequence's bit.
469 crate::decode::set_enable_edge_filter(enable_edge_filter);
470 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
471 // which every dequant/inverse-transform clamp reads -- set per frame,
472 // not once per process, for the same cross-sequence-on-one-thread
473 // reason as `set_enable_edge_filter` above. Defaults to 8 when no
474 // sequence header has been seen yet, matching every existing fixture.
475 let bit_depth = parser
476 .sequence_header()
477 .map_or(8, |seq| seq.color_config.bit_depth);
478 // lane-bd12: the sequence-header parser accepts `twelve_bit`, but every
479 // rounding shift below is written for 8/10-bit only -- `warp.rs`'s
480 // `REDUCE_BITS_HORIZ` is a hard 3 where libaom uses
481 // `round_0 + max(bd + FILTER_BITS - round_0 - 14, 0)` (5 at bd 12), the
482 // MC `round_0`/`round_1` change at 12-bit (libaom convolve.h:83), the
483 // Wiener rounding bits change, and neither CDEF nor film grain has a
484 // 12-bit path. Refuse by name rather than decode silently wrong pixels.
485 if bit_depth == 12 {
486 return Err(Error::unsupported(
487 "AV1 decode_stream",
488 "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)",
489 ));
490 }
491 crate::decode::set_bit_depth(bit_depth);
492 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
493 let enable_masked_compound = parser
494 .sequence_header()
495 .is_some_and(|seq| seq.enable_masked_compound);
496 let enable_jnt_comp = parser
497 .sequence_header()
498 .is_some_and(|seq| seq.enable_jnt_comp);
499 // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's
500 // read site doc.
501 let enable_interintra_compound = parser
502 .sequence_header()
503 .is_some_and(|seq| seq.enable_interintra_compound);
504 let interp_fixed = match header.interpolation_filter {
505 ec_av1_syntax::InterpolationFilter::Switchable => None,
506 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
507 };
508 // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
509 // from that reference slot's saved CDF state instead of the spec 8.4
510 // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
511 // builds.
512 let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
513 None
514 } else {
515 let slot = header.ref_frame_idx[header.primary_ref_frame as usize] as usize;
516 Some(cdf_slots[slot].clone().ok_or_else(|| {
517 Error::unsupported(
518 "AV1 decode_stream",
519 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
520 )
521 })?)
522 };
523 let started_from = initial_cdfs.clone();
524
525 let order_hint_bits = parser
526 .sequence_header()
527 .map_or(0, |seq| seq.order_hint_bits);
528 // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
529 // of the picture sitting in each of its 7 single references' DPB
530 // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
531 // (a later frame projects from it) whether or not this frame itself
532 // reads temporal candidates.
533 let ref_order_hints: [u32; 7] =
534 std::array::from_fn(|i| order_hint_slots[header.ref_frame_idx[i] as usize]);
535
536 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
537 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
538 &tile_bufs,
539 &header.tile_info,
540 header.mi_cols,
541 header.mi_rows,
542 header.quantization.base_q_idx,
543 crate::quant::QuantDeltas {
544 y_dc: i32::from(header.quantization.delta_q_y_dc),
545 u_dc: i32::from(header.quantization.delta_q_u_dc),
546 u_ac: i32::from(header.quantization.delta_q_u_ac),
547 v_dc: i32::from(header.quantization.delta_q_v_dc),
548 v_ac: i32::from(header.quantization.delta_q_v_ac),
549 },
550 header.frame_width,
551 header.frame_height,
552 enable_filter_intra,
553 enable_edge_filter,
554 &header.cdef,
555 &header.loop_filter,
556 &header.loop_restoration,
557 initial_cdfs,
558 header.tx_mode == TxMode::Select,
559 header.reduced_tx_set,
560 header.allow_screen_content_tools,
561 header.allow_intrabc,
562 header.delta,
563 )?;
564 // lane-superres stage 3, spec 7.16: upscale AFTER deblock+CDEF
565 // (both already applied inside `decode_key_frame_tile_with_cdfs`)
566 // and BEFORE this picture is stored as a reference or handed to
567 // the caller -- loop restoration is not yet ported, so there is
568 // no LR step here for the upscale to precede.
569 // r3: the real decoded margin beyond `frame_width` (set by the
570 // call above, right before anything else can overwrite it) --
571 // see `decode::take_last_frame_wide_margin`'s doc.
572 let wide_margin = crate::decode::take_last_frame_wide_margin();
573 let picture = if header.use_superres {
574 crate::superres::upscale_picture(
575 &picture,
576 header.upscaled_width as usize,
577 wide_margin.as_ref(),
578 bit_depth as u32,
579 )
580 } else {
581 picture
582 };
583 // A key frame codes no inter blocks -- its own saved motion
584 // field has no cells set, matching libaom's own "intra frame
585 // contributes nothing to a later projection" behaviour, but
586 // still carries `order_hint`/`ref_order_hints` for the distance
587 // arithmetic a later frame's projection needs.
588 let motion_field = crate::motion_field::MotionField::new(
589 header.mi_cols as usize,
590 header.mi_rows as usize,
591 header.order_hint,
592 ref_order_hints,
593 );
594 (picture, end_cdfs, motion_field)
595 } else {
596 let last_slot = header.ref_frame_idx[0] as usize;
597 let reference = ref_slots[last_slot].as_ref().ok_or_else(|| {
598 Error::unsupported(
599 "AV1 decode_stream",
600 "an inter frame with no key frame before it",
601 )
602 })?;
603 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
604 // (spec 7.8/7.20). Any of them having no picture yet is not a
605 // stream error on its own: `decode_inter_block` only needs a
606 // given slot when a block actually selects that reference, and
607 // refuses by name there if the slot is still empty -- widened
608 // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
609 // one of the 7 single-reference slots.
610 // lane-fimv r1: record the header state the fimv gate asserts on
611 // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause).
612 if header.force_integer_mv {
613 decode::note_force_integer_mv_frame();
614 }
615 let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| {
616 if ref_frame == 0 {
617 None
618 } else {
619 ref_slots
620 .get(header.ref_frame_idx[ref_frame - 1] as usize)
621 .and_then(Option::as_ref)
622 }
623 });
624 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
625 // this frame's header actually asks for temporal candidates --
626 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
627 // behaviour bit for bit when this is `None` (see its own doc).
628 let tpl_field = header.use_ref_frame_mvs.then(|| {
629 crate::motion_field::setup_motion_field(
630 &motion_field_slots,
631 header.ref_frame_idx,
632 header.order_hint,
633 order_hint_bits,
634 header.mi_rows as usize,
635 header.mi_cols as usize,
636 )
637 });
638 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
639 &tile_bufs,
640 &header.tile_info,
641 header.mi_cols,
642 header.mi_rows,
643 header.quantization.base_q_idx,
644 crate::quant::QuantDeltas {
645 y_dc: i32::from(header.quantization.delta_q_y_dc),
646 u_dc: i32::from(header.quantization.delta_q_u_dc),
647 u_ac: i32::from(header.quantization.delta_q_u_ac),
648 v_dc: i32::from(header.quantization.delta_q_v_dc),
649 v_ac: i32::from(header.quantization.delta_q_v_ac),
650 },
651 header.frame_width,
652 header.frame_height,
653 reference,
654 other_refs,
655 &header.cdef,
656 &header.loop_filter,
657 &header.loop_restoration,
658 initial_cdfs,
659 header.allow_high_precision_mv,
660 header.force_integer_mv,
661 header.ref_frame_sign_bias,
662 header.global_motion,
663 interp_fixed,
664 enable_dual_filter,
665 order_hint_bits,
666 header.order_hint,
667 ref_order_hints,
668 tpl_field.as_ref(),
669 header.reference_select,
670 enable_masked_compound,
671 enable_jnt_comp,
672 enable_interintra_compound,
673 header.skip_mode_present,
674 header.skip_mode_frame,
675 header.reduced_tx_set,
676 header.tx_mode == TxMode::Select,
677 header.is_motion_mode_switchable,
678 header.allow_warped_motion,
679 header.allow_screen_content_tools,
680 header.delta,
681 )?;
682 // lane-superres r10: mirrors the key-frame branch above --
683 // `decode_inter_frame_tile_with_cdfs` decodes at the downscaled
684 // `frame_width`/`frame_height` and crops to it; upscale AFTER
685 // (deblock/CDEF/LR already applied inside that call) BEFORE this
686 // picture is stored as a reference or shown, same margin
687 // mechanism (`take_last_frame_wide_margin`, read immediately
688 // after the call, before any other frame decode can overwrite
689 // it).
690 let wide_margin = crate::decode::take_last_frame_wide_margin();
691 let picture = if header.use_superres {
692 crate::superres::upscale_picture(
693 &picture,
694 header.upscaled_width as usize,
695 wide_margin.as_ref(),
696 bit_depth as u32,
697 )
698 } else {
699 picture
700 };
701 (picture, end_cdfs, motion_field)
702 };
703 // lane-lr r4: the Wiener/self-guided pixel filters are wired
704 // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
705 // `uses_lr` frames now decode all the way to pixels.
706 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
707 // *initial* table into the slots it refreshes, not the adapted
708 // end-of-tile one.
709 let stored_cdfs = if header.disable_frame_end_update_cdf {
710 started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
711 } else {
712 // Spec 7.20 `save_cdfs` (libaom `av1_reset_cdf_symbol_counters`):
713 // the adapted table is saved with every symbol counter zeroed,
714 // not with the counts the tile's own decode left behind.
715 let mut end_cdfs = end_cdfs;
716 end_cdfs.reset_counts();
717 end_cdfs
718 };
719 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
720 use std::io::Write;
721 if let Ok(mut f) = std::fs::OpenOptions::new()
722 .create(true)
723 .append(true)
724 .open(&path)
725 {
726 let _ = writeln!(f, "=== frame idx={} ===", pictures.len());
727 let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
728 let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
729 let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
730 let _ = writeln!(f, "skip {:?}", stored_cdfs.skip);
731 let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv);
732 let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv);
733 let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv);
734 let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint);
735 }
736 }
737 // lane-comppin r3: decode-order (not display-order) dump of every
738 // frame's own post-deblock buffer -- the pre-existing pixel diff
739 // (`scratch_isolate_pinned_mismatch`) only ever compares *shown*
740 // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a
741 // later shown frame is otherwise invisible; diff this byte-for-byte
742 // against `EC_AV1_POSTFILT_DUMP.fN` from the instrumented aomdec
743 // build to isolate whether the defect is in a hidden frame's own
744 // reconstruction or downstream of it.
745 if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") {
746 use std::io::Write;
747 let idx = pictures_decoded;
748 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
749 // lane-hbd r4: debug dump narrows to u8 -- this diagnostic
750 // predates 10-bit support and is an 8-bit-oracle comparison
751 // only (aomdec's own dump is 8-bit here too).
752 let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
753 let _ = f.write_all(&narrow(&picture.y));
754 let _ = f.write_all(&narrow(&picture.u));
755 let _ = f.write_all(&narrow(&picture.v));
756 }
757 }
758 // lane-hidden r1: the frame exactly as it is about to be stored into
759 // the reference slots -- after deblock/CDEF/LR/superres, in DECODE
760 // order, hidden (`show_frame == 0`) alt-ref frames included, and
761 // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the
762 // u8-narrowing diagnostic dumps above. Matches the instrumented
763 // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte
764 // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a
765 // hidden frame's pixels comparable at all.
766 if let Some(prefix) = &final_dump {
767 use std::io::Write;
768 if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{pictures_decoded}")) {
769 let mut buf = Vec::new();
770 for plane in [&picture.y, &picture.u, &picture.v] {
771 if bit_depth == 8 {
772 buf.extend(plane.iter().map(|&s| s as u8));
773 } else {
774 for &s in plane {
775 buf.extend_from_slice(&s.to_le_bytes());
776 }
777 }
778 }
779 let _ = f.write_all(&buf);
780 }
781 }
782 pictures_decoded += 1;
783 let decoded_seg_map = decode::take_segment_ids();
784 for i in 0..NUM_REF_FRAMES {
785 if header.refresh_frame_flags & (1 << i) != 0 {
786 cdf_slots[i] = Some(stored_cdfs.clone());
787 // Spec 7.18.3.1: synthesized grain is never stored for later
788 // prediction -- the reference bank always keeps the clean,
789 // pre-grain decode, even though the frame pushed onto the
790 // caller's output below carries the grained picture.
791 ref_slots[i] = Some(picture.clone());
792 motion_field_slots[i] = Some(motion_field.clone());
793 seg_map_slots[i] = Some(decoded_seg_map.clone());
794 order_hint_slots[i] = header.order_hint;
795 }
796 }
797 if header.show_frame {
798 let output = if header.film_grain.apply_grain {
799 let mc_identity = parser
800 .sequence_header()
801 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
802 crate::film_grain::apply_grain(
803 &picture,
804 &header.film_grain,
805 mc_identity,
806 bit_depth as u32,
807 )
808 } else {
809 picture
810 };
811 pictures.push(output);
812 }
813 }
814 Ok(pictures)
815}
816
817#[cfg(test)]
818mod tests {
819 use super::*;
820 use crate::encode::{Picture as Pic, encode_key_frame, encode_sequence};
821
822 fn test_card(width: usize, height: usize) -> Pic {
823 let mut picture = Pic::grey(width, height);
824 for row in 0..height {
825 for col in 0..width {
826 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
827 }
828 }
829 for row in 0..height / 2 {
830 for col in 0..width / 2 {
831 let i = row * width / 2 + col;
832 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
833 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
834 }
835 }
836 picture
837 }
838
839 fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic {
840 let mut picture = Pic::grey(width, height);
841 for y in 0..height {
842 for x in 0..width {
843 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
844 let gradient = sx * 200.0 / width as f64;
845 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
846 }
847 }
848 for y in 0..height / 2 {
849 for x in 0..width / 2 {
850 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
851 let i = y * width / 2 + x;
852 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
853 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
854 }
855 }
856 picture
857 }
858
859 /// A stream whose sequence header says `twelve_bit` is refused by name
860 /// rather than decoded with the 8/10-bit rounding shifts (`warp.rs`'s
861 /// hard `REDUCE_BITS_HORIZ = 3`, MC/Wiener round bits, ungated CDEF and
862 /// film grain). Reachability, not a pixel claim: the header is written at
863 /// `seq_profile = 2` so `twelve_bit` is actually coded, and the frame's
864 /// tile payload is never reached.
865 #[test]
866 fn a_twelve_bit_sequence_header_is_refused_by_name() {
867 let picture = test_card(64, 64);
868 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
869 let mut color = ec_av1_syntax::ColorConfig {
870 bit_depth: 12,
871 ..Default::default()
872 };
873 color.num_planes = 3;
874 // Only seq_profile 2 codes the `twelve_bit` bit (spec 5.5.2).
875 let (mut seq, header) =
876 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
877 seq.seq_profile = 2;
878 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
879 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap());
880
881 let err = decode_stream(&stream).unwrap_err().to_string();
882 assert!(
883 err.contains(
884 "a bit depth of 12 (this decoder is gated at 8 and 10 only: \
885 warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)"
886 ),
887 "expected the 12-bit refusal, got: {err}"
888 );
889 }
890
891 /// `decode_stream` on a lone key frame's stream matches both the tile
892 /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and
893 /// the encoder's own reconstruction, at an even and an odd size.
894 #[test]
895 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
896 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
897 let picture = test_card(width, height);
898 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
899 let via_tile = decode_key_frame_tile(
900 &encoded.tile,
901 encoded.mi_cols,
902 encoded.mi_rows,
903 encoded.base_q_idx,
904 width as u32,
905 height as u32,
906 false,
907 &ec_av1_syntax::CdefParams::default(),
908 &ec_av1_syntax::LoopFilterParams::default(),
909 false,
910 // Our own encoder always writes `reduced_tx_set: true`.
911 true,
912 false,
913 false,
914 )
915 .unwrap();
916 let via_stream = decode_stream(&encoded.stream).unwrap();
917 assert_eq!(via_stream.len(), 1, "{width}x{height}: one picture");
918 assert_eq!(via_stream[0].y, via_tile.y, "{width}x{height}: luma");
919 assert_eq!(via_stream[0].u, via_tile.u, "{width}x{height}: U");
920 assert_eq!(via_stream[0].v, via_tile.v, "{width}x{height}: V");
921 assert_eq!(
922 via_stream[0].y, encoded.reconstruction.y,
923 "{width}x{height}: luma vs encoder reconstruction"
924 );
925 }
926 }
927
928 /// A GOP (key frame plus panned inter frames, so blocks actually take
929 /// motion) decodes bit-exact through `decode_stream` alone, threading its
930 /// own DPB rather than a test-supplied reference.
931 fn gop_round_trips(width: usize, height: usize) {
932 let pictures: Vec<_> = (0..4)
933 .map(|i| panned_test_card(width, height, i * 3))
934 .collect();
935 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
936 let decoded = decode_stream(&encoded.stream).unwrap();
937 assert_eq!(decoded.len(), encoded.frames.len());
938 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
939 assert_eq!(
940 got.y, frame.reconstruction.y,
941 "{width}x{height} frame {i} luma"
942 );
943 assert_eq!(
944 got.u, frame.reconstruction.u,
945 "{width}x{height} frame {i} U"
946 );
947 assert_eq!(
948 got.v, frame.reconstruction.v,
949 "{width}x{height} frame {i} V"
950 );
951 }
952 }
953
954 #[test]
955 fn decode_stream_round_trips_a_gop() {
956 gop_round_trips(128, 64);
957 }
958
959 /// Same claim at a size that is not a whole number of 32x32 blocks, so
960 /// the inter frame's 16x16-leaf split path is exercised too.
961 #[test]
962 fn decode_stream_round_trips_an_odd_size_gop() {
963 gop_round_trips(216, 96);
964 }
965
966 use std::io::Write;
967 use std::process::{Command, Stdio};
968
969 /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`,
970 /// `skip_mode`/compound) all read a process-global atomic counter delta
971 /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to
972 /// prove a real block picked the feature under test, not just that a
973 /// header bit was set. Under `cargo test`'s default parallel run, a
974 /// SIBLING test's own decode bumps the same global counter mid-gate --
975 /// a false "fired" reading pixel-compares an attempt the gate would
976 /// otherwise `continue` past, on top of genuine defects that path may
977 /// still have. Serialising every counter-delta gate behind this one
978 /// mutex makes firing detection honest again (matches the existing
979 /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`).
980 static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
981 /// Three-bucket gate summary (class [[gate-skips-on-its-own-failure]]):
982 /// every attempt lands in exactly one bucket -- decoded pixel-exact WITH
983 /// the feature counter moving, decoded pixel-exact WITHOUT it, or a named
984 /// refusal -- and the three sum to the attempts made.
985 fn gate_buckets(name: &str, counted_exact: u32, uncounted_exact: u32, named_refusals: usize) {
986 eprintln!(
987 "{name}: buckets counted-exact={counted_exact} uncounted-exact={uncounted_exact} \
988 named-refusals={named_refusals} (attempts {})",
989 counted_exact as usize + uncounted_exact as usize + named_refusals
990 );
991 }
992
993 fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
994 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
995 }
996
997 /// lane-cdfflake: a cheap, dependency-free (FNV-1a, not cryptographic --
998 /// this is a load-bearing-identity fingerprint for flake triage, not a
999 /// security digest, so no `sha2` dep is pulled in) fixture fingerprint
1000 /// for the cdf-forwarding gate's instrumentation below.
1001 fn fnv1a64(bytes: &[u8]) -> u64 {
1002 let mut hash = 0xcbf29ce484222325u64;
1003 for &b in bytes {
1004 hash ^= b as u64;
1005 hash = hash.wrapping_mul(0x100000001b3);
1006 }
1007 hash
1008 }
1009
1010 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
1011 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
1012 /// aomenc gate decodes its stream through ffmpeg and is meaningless
1013 /// without it -- turns it into a hard failure. Without this the require
1014 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
1015 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
1016 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
1017 fn have_ffmpeg() -> bool {
1018 let present = Command::new("ffmpeg")
1019 .arg("-version")
1020 .stdout(Stdio::null())
1021 .stderr(Stdio::null())
1022 .status()
1023 .is_ok_and(|s| s.success());
1024 assert!(
1025 present
1026 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
1027 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
1028 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
1029 );
1030 present
1031 }
1032
1033 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
1034 fn ffmpeg_decode_sequence(
1035 stream: &[u8],
1036 width: usize,
1037 height: usize,
1038 frames: usize,
1039 ) -> Vec<Pic> {
1040 let mut child = Command::new("ffmpeg")
1041 .args([
1042 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
1043 ])
1044 .stdin(Stdio::piped())
1045 .stdout(Stdio::piped())
1046 .stderr(Stdio::piped())
1047 .spawn()
1048 .expect("ffmpeg failed to start");
1049 child
1050 .stdin
1051 .take()
1052 .expect("ffmpeg stdin")
1053 .write_all(stream)
1054 .expect("writing the stream to ffmpeg");
1055 let out = child.wait_with_output().expect("ffmpeg failed to run");
1056 assert!(
1057 out.status.success(),
1058 "ffmpeg refused the stream: {}",
1059 String::from_utf8_lossy(&out.stderr)
1060 );
1061 let (luma, chroma) = (width * height, width * height / 4);
1062 let frame_bytes = luma + 2 * chroma;
1063 assert_eq!(
1064 out.stdout.len(),
1065 frame_bytes * frames,
1066 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
1067 String::from_utf8_lossy(&out.stderr)
1068 );
1069 (0..frames)
1070 .map(|i| {
1071 let base = i * frame_bytes;
1072 Pic {
1073 width,
1074 height,
1075 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
1076 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
1077 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
1078 }
1079 })
1080 .collect()
1081 }
1082
1083 /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples
1084 /// are 2-byte little-endian, one full 16-bit range regardless of the
1085 /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the
1086 /// bit depth). The 8-bit helper above stays untouched -- every existing
1087 /// gate depends on it.
1088 fn ffmpeg_decode_sequence_10bit(
1089 stream: &[u8],
1090 width: usize,
1091 height: usize,
1092 frames: usize,
1093 ) -> Vec<Pic> {
1094 let mut child = Command::new("ffmpeg")
1095 .args([
1096 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt",
1097 "yuv420p10le", "-",
1098 ])
1099 .stdin(Stdio::piped())
1100 .stdout(Stdio::piped())
1101 .stderr(Stdio::piped())
1102 .spawn()
1103 .expect("ffmpeg failed to start");
1104 child
1105 .stdin
1106 .take()
1107 .expect("ffmpeg stdin")
1108 .write_all(stream)
1109 .expect("writing the stream to ffmpeg");
1110 let out = child.wait_with_output().expect("ffmpeg failed to run");
1111 assert!(
1112 out.status.success(),
1113 "ffmpeg refused the stream: {}",
1114 String::from_utf8_lossy(&out.stderr)
1115 );
1116 let (luma, chroma) = (width * height, width * height / 4);
1117 let frame_samples = luma + 2 * chroma;
1118 let frame_bytes = frame_samples * 2;
1119 assert_eq!(
1120 out.stdout.len(),
1121 frame_bytes * frames,
1122 "expected {frames} 4:2:0 10-bit frames, ffmpeg said: {}",
1123 String::from_utf8_lossy(&out.stderr)
1124 );
1125 fn le16(bytes: &[u8]) -> Vec<u16> {
1126 bytes
1127 .chunks_exact(2)
1128 .map(|c| u16::from_le_bytes([c[0], c[1]]))
1129 .collect()
1130 }
1131 (0..frames)
1132 .map(|i| {
1133 let base = i * frame_bytes;
1134 Pic {
1135 width,
1136 height,
1137 y: le16(&out.stdout[base..base + luma * 2]),
1138 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
1139 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
1140 }
1141 })
1142 .collect()
1143 }
1144
1145 /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an
1146 /// independent decoder, not just this crate checking its own tile path.
1147 #[test]
1148 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
1149 if !have_ffmpeg() {
1150 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
1151 return;
1152 }
1153 let (width, height) = (128usize, 64usize);
1154 let pictures: Vec<_> = (0..3)
1155 .map(|i| panned_test_card(width, height, i * 3))
1156 .collect();
1157 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
1158 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
1159 let decoded = decode_stream(&encoded.stream).unwrap();
1160 assert_eq!(decoded.len(), 3);
1161 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
1162 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");
1163 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");
1164 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");
1165 }
1166 }
1167
1168 /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME`
1169 /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s
1170 /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc
1171 /// attempts never could: frame 0 is a real key frame (this crate's own
1172 /// encoder, real texture), refreshing all 8 DPB slots as spec requires --
1173 /// slot 3 keeps that exact picture from here on. Frame 1 is a hand-coded
1174 /// inter frame whose lone 32x32 block is *intra* (`DC_PRED`, `skip`),
1175 /// refreshing only slot 0 with a flat 128 block -- distinguishable from
1176 /// frame 0's real texture, so slot 0 (`LAST_FRAME`) and slot 3
1177 /// (`GOLDEN_FRAME`) hold visibly different pictures once frame 2 runs.
1178 /// Frame 2 is a hand-coded inter frame naming `ref_frame_idx[3] = 3`
1179 /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose
1180 /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME`
1181 /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy
1182 /// of GOLDEN's picture, so its output must equal frame 0's own
1183 /// reconstruction exactly, and must differ from frame 1's -- proof the
1184 /// decoder actually read the golden plane, not silently substituted
1185 /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a
1186 /// deblock/MC residue that turned out to be film-grain synthesis
1187 /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN);
1188 /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing
1189 /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so
1190 /// this fixture flips back to its round-4 pixel-exact form. ffmpeg
1191 /// decodes the identical wire bytes as the foreign oracle
1192 /// (shared-oracle-blindness class): this crate's own decoder agreeing
1193 /// with itself would prove nothing.
1194 #[test]
1195 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
1196 if !have_ffmpeg() {
1197 eprintln!(
1198 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
1199 );
1200 return;
1201 }
1202 use crate::cdf_state::Cdfs;
1203 use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of};
1204 use crate::encode::{inter_frame_headers, key_frame_headers};
1205 use crate::frame::frame_obu;
1206 use crate::msac::SymbolEncoder;
1207 use crate::mvstack::{
1208 GOLDEN_FRAME, MiGrid, find_mv_stack, single_ref_p1_ctx, single_ref_p3_ctx,
1209 single_ref_p5_ctx,
1210 };
1211 use crate::obu::temporal_delimiter;
1212
1213 let (width, height) = (32usize, 32usize);
1214 let base_q_idx = 100u8;
1215 // The whole picture is one 32x32 block: `partition_ctx`/`skip_ctx`/
1216 // `intra_inter_ctx`'s neighbour inputs are all "no neighbour yet" --
1217 // a fresh `Neighbours`' `above_side_mi`/`left_side_mi` start at `SB`
1218 // (64), so `partition_ctx_mi`'s `side_mi * 2 <= side` (32) is false
1219 // on both axes (ctx 0), and `above_skip`/`left_skip`/`above_inter`/
1220 // `left_inter`/`above_ref`/`left_ref` all start `false`/`-1`
1221 // (decode.rs `Neighbours::new`) -- computed here without
1222 // constructing the (module-private) `Neighbours` itself.
1223 const PARTITION_NONE: usize = 0;
1224 let ii_ctx = intra_inter_ctx(false, false, false, false);
1225 let sr_p1_ctx = single_ref_p1_ctx(None, None, None, None);
1226 let sr_p3_ctx = single_ref_p3_ctx(None, None, None, None);
1227 let sr_p5_ctx = single_ref_p5_ctx(None, None, None, None);
1228
1229 for run in 0..4 {
1230 let picture = test_card(width, height);
1231 let key = encode_key_frame(&picture, base_q_idx, 0.5).unwrap();
1232 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
1233
1234 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
1235 // 128 block (no neighbours to predict `DC_PRED` from).
1236 let (_, header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
1237 let tile1 = {
1238 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1239 let mut enc = SymbolEncoder::new();
1240 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
1241 enc.symbol(1, &mut cdfs.skip[0]); // skip
1242 enc.symbol(0, &mut cdfs.intra_inter[ii_ctx]); // is_inter = false
1243 enc.symbol(0, &mut cdfs.y_mode[3]); // DC_PRED, size group 3 (32x32)
1244 enc.symbol(0, &mut cdfs.uv_mode_cfl[0]); // DC_PRED
1245 enc.finish()
1246 };
1247 let mut stream = key.stream.clone();
1248 stream.extend(temporal_delimiter());
1249 stream.extend(frame_obu(&seq, &header1, &tile1).unwrap());
1250
1251 // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME,
1252 // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0).
1253 let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap();
1254 header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1
1255 let tile2 = {
1256 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1257 let mut enc = SymbolEncoder::new();
1258 let grid = MiGrid::new(8, 8);
1259 let stack = find_mv_stack(&grid, 0, 0, 8, 8, GOLDEN_FRAME, 8, 8);
1260 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
1261 enc.symbol(1, &mut cdfs.skip[0]); // skip
1262 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter = true
1263 enc.symbol(0, &mut cdfs.single_ref[sr_p1_ctx][0]); // p1: LAST/LAST2/LAST3/GOLDEN group
1264 enc.symbol(1, &mut cdfs.single_ref[sr_p3_ctx][2]); // p3: GOLDEN/LAST3 sub-group
1265 enc.symbol(1, &mut cdfs.single_ref[sr_p5_ctx][4]); // p5: GOLDEN_FRAME
1266 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new -> not NEWMV
1267 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero -> not GLOBALMV
1268 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // nearest -> NEARESTMV, (0, 0)
1269 enc.finish()
1270 };
1271 stream.extend(temporal_delimiter());
1272 stream.extend(frame_obu(&seq, &header2, &tile2).unwrap());
1273
1274 let before = non_last_ref_hits();
1275 let decoded = decode_stream(&stream).unwrap();
1276 assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures");
1277 assert!(
1278 non_last_ref_hits() > before,
1279 "run {run}: GOLDEN_FRAME never fired"
1280 );
1281
1282 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3);
1283 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
1284 assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg");
1285 assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg");
1286 assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg");
1287 }
1288 assert_eq!(
1289 decoded[0].y, key.reconstruction.y,
1290 "run {run}: frame 0 vs the encoder's own reconstruction"
1291 );
1292 assert_eq!(
1293 decoded[2].y, key.reconstruction.y,
1294 "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names"
1295 );
1296 assert_ne!(
1297 decoded[2].y, decoded[1].y,
1298 "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \
1299 distinguishable -- the gate proves nothing"
1300 );
1301 }
1302 }
1303
1304 /// Builds a `gradients` lavfi source string with colours derived from
1305 /// `seed`, not left to the filter's own default.
1306 ///
1307 /// Measured (lane-fixdet r1): ffmpeg's `gradients` source IGNORES its
1308 /// `seed=` parameter for colour selection -- five encodes of an
1309 /// identical command line (same `seed=`, same everything) produced five
1310 /// different fixtures, because the unset `c0..c9` stops are randomized
1311 /// from something other than that seed. Every one of this file's ~20
1312 /// gate fixtures built a `gradients` source this way, so none of them
1313 /// had a reproducible input: a pin captured from one run could not be
1314 /// regenerated, and "attempt N failed" was as likely to be a different
1315 /// fixture as a different decode outcome.
1316 ///
1317 /// Freezing the colours outright (as the earliest four gates below do,
1318 /// hand-picking `c0=red:c1=blue:c2=green`) fixes reproducibility but
1319 /// throws away the per-attempt content variety the sweep gates need to
1320 /// make features (OBMC, warp, wedge, ...) fire at all -- this repo's own
1321 /// `sampler-decorrelated-gate` class. So: derive `c0..c3` deterministically
1322 /// FROM the seed with a plain integer hash, and keep passing `seed=`
1323 /// itself too, so a future ffmpeg that actually honours it only adds
1324 /// more variety, never removes the determinism this buys.
1325 fn gradients_source(seed: u32, width: usize, height: usize, tail: &str) -> String {
1326 fn hash_color(seed: u32, salt: u32) -> String {
1327 let h = seed
1328 .wrapping_mul(2_654_435_761)
1329 .wrapping_add(salt.wrapping_mul(0x9E37_79B9))
1330 ^ (seed.rotate_left(13));
1331 format!("0x{:06x}", h & 0x00ff_ffff)
1332 }
1333 let (c0, c1, c2, c3) = (
1334 hash_color(seed, 0),
1335 hash_color(seed, 1),
1336 hash_color(seed, 2),
1337 hash_color(seed, 3),
1338 );
1339 format!("gradients=size={width}x{height}:c0={c0}:c1={c1}:c2={c2}:c3={c3}:seed={seed}:{tail}")
1340 }
1341
1342 /// The determinism guard: same seed twice must byte-match ffmpeg's own
1343 /// output; different seeds must not. Regresses this fix if it ever
1344 /// breaks.
1345 #[test]
1346 fn gradients_source_is_reproducible_per_seed() {
1347 if !have_ffmpeg() {
1348 eprintln!("SKIP gradients_source_is_reproducible_per_seed: no ffmpeg");
1349 return;
1350 }
1351 fn render_hash(lavfi: &str) -> Vec<u8> {
1352 let out = Command::new("ffmpeg")
1353 .args([
1354 "-v", "error", "-f", "lavfi", "-i", lavfi, "-frames:v", "1", "-f", "rawvideo",
1355 "-",
1356 ])
1357 .stdin(Stdio::null())
1358 .stdout(Stdio::piped())
1359 .stderr(Stdio::piped())
1360 .output()
1361 .expect("ffmpeg failed to run");
1362 assert!(out.status.success(), "ffmpeg refused {lavfi}");
1363 out.stdout
1364 }
1365 let a1 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
1366 let a2 = render_hash(&gradients_source(43, 64, 64, "duration=0.04:rate=25"));
1367 let a3 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
1368 assert_eq!(a1, a3, "same seed must reproduce byte-identical output");
1369 assert_ne!(a1, a2, "different seeds must not collide");
1370 }
1371
1372 /// Encodes a real libaom-av1 stream (via ffmpeg's own encoder, not this
1373 /// crate's) with the same reduced-partition flags lane-av1adst's r6
1374 /// probe found still select `ADST_ADST`/`ADST_DCT`/`DCT_ADST` on
1375 /// gradient content (TX_SET_INTRA_2), and decodes it with
1376 /// [`decode_stream`] -- lifting the round-2 refusal is only real if it
1377 /// gets past an encoder this crate never wrote a byte of.
1378 fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {
1379 libaom_encode_with(lavfi, width, height, crf, &[])
1380 }
1381
1382 /// As [`libaom_encode`], with extra encoder args appended -- used to pin
1383 /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8`
1384 /// RD search is not otherwise stable run-to-run on this box, and lavfi
1385 /// `gradients` needs its own `seed=` for the same reason) and to gate
1386 /// individual feature flags (`-enable-cdef 0`) a given fixture needs off.
1387 fn libaom_encode_with(
1388 lavfi: &str,
1389 width: usize,
1390 height: usize,
1391 crf: u32,
1392 extra: &[&str],
1393 ) -> Option<Vec<u8>> {
1394 let mut args = vec![
1395 "-v",
1396 "error",
1397 "-f",
1398 "lavfi",
1399 "-i",
1400 lavfi,
1401 "-frames:v",
1402 "1",
1403 "-pix_fmt",
1404 "yuv420p",
1405 "-c:v",
1406 "libaom-av1",
1407 ];
1408 let crf_str = crf.to_string();
1409 args.extend(["-crf", &crf_str]);
1410 args.extend([
1411 "-cpu-used",
1412 "8",
1413 "-enable-rect-partitions",
1414 "0",
1415 "-enable-ab-partitions",
1416 "0",
1417 "-enable-1to4-partitions",
1418 "0",
1419 "-enable-angle-delta",
1420 "0",
1421 "-enable-cfl-intra",
1422 "0",
1423 ]);
1424 args.extend(extra.iter().copied());
1425 args.extend(["-f", "obu", "-"]);
1426 let out = Command::new("ffmpeg")
1427 .args(&args)
1428 .stdin(Stdio::null())
1429 .stdout(Stdio::piped())
1430 .stderr(Stdio::piped())
1431 .output()
1432 .expect("ffmpeg failed to run");
1433 if !out.status.success() {
1434 eprintln!(
1435 "ffmpeg refused to encode {lavfi} at {width}x{height}: {}",
1436 String::from_utf8_lossy(&out.stderr)
1437 );
1438 return None;
1439 }
1440 Some(out.stdout)
1441 }
1442
1443 /// The end-to-end gate: two real libaom-av1 configs, decoded with
1444 /// [`decode_stream`] and checked against ffmpeg's own decode of the same
1445 /// bytes. Not every config this encoder writes decodes yet (partitions
1446 /// below 16x16, AB partitions, CfL and others remain round-2 gaps per the
1447 /// r6 catalogue) -- both configs here pick `cpu-used 8` plus the
1448 /// partition/angle-delta/CfL flags r6 found narrow the encoder onto this
1449 /// decoder's supported syntax, while still landing on non-`DCT_DCT` tx
1450 /// types on gradient content.
1451 #[test]
1452 fn a_real_libaom_stream_with_adst_decodes_end_to_end() {
1453 if !have_ffmpeg() {
1454 eprintln!("SKIP a_real_libaom_stream_with_adst_decodes_end_to_end: no ffmpeg");
1455 return;
1456 }
1457 let configs: [(String, usize, usize, u32); 2] = [
1458 ("testsrc2=size=64x64:rate=1".to_string(), 64, 64, 15),
1459 (gradients_source(42, 64, 64, "rate=1"), 64, 64, 15),
1460 ];
1461 let mut verdicts = Vec::new();
1462 for (lavfi, width, height, crf) in configs {
1463 let lavfi = lavfi.as_str();
1464 let Some(stream) = libaom_encode(lavfi, width, height, crf) else {
1465 verdicts.push(format!("{lavfi}: ffmpeg itself refused to encode"));
1466 continue;
1467 };
1468 match decode_stream(&stream) {
1469 Ok(frames) => {
1470 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1471 let matches = frames[0].y == ffmpeg_frames[0].y
1472 && frames[0].u == ffmpeg_frames[0].u
1473 && frames[0].v == ffmpeg_frames[0].v;
1474 verdicts.push(format!(
1475 "{lavfi}: decoded, {} ffmpeg's own decode",
1476 if matches { "MATCHES" } else { "MISMATCHES" }
1477 ));
1478 // Not a hard `assert!`: libaom's own mode decisions at
1479 // `cpu-used 8` are not observed stable run-to-run on this
1480 // box (multi-threaded RD search), so a run that happens
1481 // to land on a still-unsupported syntax element (e.g. a
1482 // partition below 16x16, a separate round-2 gap) can
1483 // decode without erroring yet disagree -- that failure
1484 // mode belongs to those other gaps, not to this round's
1485 // ADST wiring, and the eprintln below reports it either
1486 // way rather than hiding it.
1487 }
1488 Err(e) => {
1489 verdicts.push(format!("{lavfi}: still refuses ({e})"));
1490 }
1491 }
1492 }
1493 eprintln!("libaom ADST end-to-end verdicts:");
1494 for v in &verdicts {
1495 eprintln!(" {v}");
1496 }
1497 }
1498
1499 /// Hardened past the report-only test above: a real libaom-av1 gradients
1500 /// stream, pinned deterministic (`gradients`' own `seed=`, plus
1501 /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search
1502 /// cannot pick a different mode set run to run) and with CDEF turned off
1503 /// (this decoder's tile path never applies that in-loop filter -- see
1504 /// `cdef_is_active` in `decode_stream` -- so a stream that leaves it on
1505 /// decodes-but-wrong instead of refusing at cdef_bits==0; ffmpeg's
1506 /// `-enable-cdef 0` keeps this fixture out of that gap rather than this
1507 /// test working around it). Asserts pixel-exact against ffmpeg's own
1508 /// decode of the identical bytes, not just "decoded without error".
1509 #[test]
1510 fn a_real_libaom_gradients_stream_decodes_pixel_exact() {
1511 if !have_ffmpeg() {
1512 eprintln!("SKIP a_real_libaom_gradients_stream_decodes_pixel_exact: no ffmpeg");
1513 return;
1514 }
1515 let (width, height) = (64, 64);
1516 let stream = libaom_encode_with(
1517 &gradients_source(42, width, height, "rate=1"),
1518 width,
1519 height,
1520 15,
1521 &[
1522 "-threads",
1523 "1",
1524 "-row-mt",
1525 "0",
1526 "-tile-columns",
1527 "0",
1528 "-tile-rows",
1529 "0",
1530 "-enable-cdef",
1531 "0",
1532 ],
1533 )
1534 .expect("ffmpeg encode");
1535 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
1536 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1537 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
1538 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
1539 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
1540 }
1541
1542 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but at
1543 /// 32x32 (below `is_cfl_allowed`'s 32x32 luma bound as a *single*
1544 /// undivided block, spec 5.11.5) rather than 64x64 -- a whole 64x64 SB
1545 /// is never CFL-eligible itself, only its <=32x32 partitions, and
1546 /// `testsrc2`/`gradients` at 64x64 with rect/ab/1to4/angle-delta search
1547 /// disabled reliably pick a whole-SB `PARTITION_NONE` (probed
1548 /// lane-av1real r2), so no fixture at that size exercises CfL at all.
1549 /// A 32x32 frame is exactly the whole-block, CFL-allowed case, and
1550 /// lane-av1real r2 found `gradients` there reliably selects
1551 /// `UV_CFL_PRED` (`uv_mode=13`) across a crf sweep -- `testsrc2` there
1552 /// stays DC. Proves the CfL port this round added, not just DC-chroma
1553 /// decode: pixel-exact against ffmpeg's own decode, not just "decoded".
1554 ///
1555 #[test]
1556 fn a_real_libaom_cfl_stream_decodes_pixel_exact() {
1557 if !have_ffmpeg() {
1558 eprintln!("SKIP a_real_libaom_cfl_stream_decodes_pixel_exact: no ffmpeg");
1559 return;
1560 }
1561 let (width, height) = (32, 32);
1562 let stream = libaom_encode_with(
1563 &gradients_source(42, width, height, "rate=1"),
1564 width,
1565 height,
1566 15,
1567 &[
1568 "-threads",
1569 "1",
1570 "-row-mt",
1571 "0",
1572 "-tile-columns",
1573 "0",
1574 "-tile-rows",
1575 "0",
1576 "-enable-cdef",
1577 "0",
1578 ],
1579 )
1580 .expect("ffmpeg encode");
1581 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
1582 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1583 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
1584 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
1585 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
1586 }
1587
1588 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves
1589 /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
1590 /// proves `apply_cdef` itself, not just that this decoder still works
1591 /// when the filter never fires. Gradient content at a low crf reliably
1592 /// gives libaom something to dering. If a run happens to land on
1593 /// `cdef_bits > 0` (per-64x64 `cdef_idx`, still unimplemented -- see the
1594 /// refusal in `decode_stream`) the stream is skipped rather than failed:
1595 /// that gap is named by the refusal's own error text, not silently
1596 /// swallowed here.
1597 #[test]
1598 fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
1599 if !have_ffmpeg() {
1600 eprintln!(
1601 "SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: no ffmpeg"
1602 );
1603 return;
1604 }
1605 let (width, height) = (64, 64);
1606 let stream = libaom_encode_with(
1607 &gradients_source(42, width, height, "rate=1"),
1608 width,
1609 height,
1610 30,
1611 &[
1612 "-threads",
1613 "1",
1614 "-row-mt",
1615 "0",
1616 "-tile-columns",
1617 "0",
1618 "-tile-rows",
1619 "0",
1620 ],
1621 )
1622 .expect("ffmpeg encode");
1623 match decode_stream(&stream) {
1624 Ok(frames) => {
1625 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1626 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (CDEF on)");
1627 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (CDEF on)");
1628 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (CDEF on)");
1629 }
1630 Err(e) => {
1631 eprintln!("SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: {e}");
1632 }
1633 }
1634 }
1635
1636 /// Path to a real `aomenc` build carrying the reference options this
1637 /// fixture needs (`--max-partition-size`, `--enable-tx-size-search`,
1638 /// `--loopfilter-control`) -- this box's `ffmpeg` links a libaom too old
1639 /// to expose `enable-tx-size-search`/`loopfilter-control` through its
1640 /// own `-aom-params` passthrough (probed live: "Cannot find aom
1641 /// option"), so [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]
1642 /// shells out to the standalone binary instead of ffmpeg's libaom-av1
1643 /// wrapper every other test here uses. `EC_AV1_AOMENC` overrides the
1644 /// default dev-build path; the test skips (not fails) when neither this
1645 /// nor `ffmpeg` is present.
1646 fn aomenc_path() -> std::path::PathBuf {
1647 if let Some(p) = std::env::var_os("EC_AV1_AOMENC") {
1648 return std::path::PathBuf::from(p);
1649 }
1650 // The oracle used to live only under `/tmp`, which this box's tmpfs
1651 // guard reclaims -- when it did, all 20 aomenc gates below went
1652 // silently vacuous (SKIP, suite still green). The durable location
1653 // is provisioned by `scripts/build-aom-oracle.sh`; the `/tmp` path
1654 // stays last as a legacy fallback.
1655 let mut candidates = Vec::new();
1656 if let Some(home) = std::env::var_os("HOME") {
1657 candidates.push(std::path::PathBuf::from(&home).join(".cache/aom-oracle/build/aomenc"));
1658 }
1659 candidates.push("/tmp/libaom-src/build/encoder/aomenc".into());
1660 candidates
1661 .iter()
1662 .find(|p| p.is_file())
1663 .cloned()
1664 .unwrap_or_else(|| candidates.remove(0))
1665 }
1666
1667 /// Whether the aomenc oracle is present. Absence normally SKIPs (a
1668 /// checkout without the oracle should still run the rest of the suite),
1669 /// but `EC_AV1_REQUIRE_AOMENC=1` turns it into a hard failure so a batch
1670 /// run cannot report green off 20 skipped gates.
1671 /// Where a pinned stream lives. `fixtures/` is a symlink to a durable
1672 /// directory outside the repo, so a pin captured in one session is still
1673 /// there in the next; a session scratchpad is not (tmpfs reaps it, and
1674 /// four pins were silently dead because of that).
1675 fn pin_dir() -> std::path::PathBuf {
1676 if let Some(p) = std::env::var_os("EC_AV1_PIN_DIR") {
1677 return std::path::PathBuf::from(p);
1678 }
1679 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1680 .join("../../fixtures")
1681 .canonicalize()
1682 .unwrap_or_else(|_| std::path::PathBuf::from("fixtures"))
1683 }
1684
1685 fn have_aomenc() -> bool {
1686 let present = aomenc_path().is_file();
1687 assert!(
1688 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
1689 "EC_AV1_REQUIRE_AOMENC is set but no aomenc at {} -- run scripts/build-aom-oracle.sh",
1690 aomenc_path().display()
1691 );
1692 present
1693 }
1694
1695 /// The instrumented `aomdec` beside the `aomenc` oracle
1696 /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`).
1697 fn aomdec_path() -> std::path::PathBuf {
1698 if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") {
1699 return std::path::PathBuf::from(p);
1700 }
1701 aomenc_path().with_file_name("aomdec")
1702 }
1703
1704 /// Decodes `stream` with both this decoder and the instrumented oracle
1705 /// `aomdec`, and compares EVERY decoded frame in DECODE order --
1706 /// including the hidden (`show_frame == 0`) alt-ref frames no other gate
1707 /// in this repo can see, because `decode_stream` only pushes shown
1708 /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames
1709 /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces
1710 /// only as drift on some later shown frame, if at all).
1711 ///
1712 /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it
1713 /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in
1714 /// `decode_stream`, the oracle's in rung 12 of
1715 /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as
1716 /// u16 LE. Returns `(frames_decoded, hidden_frames)`.
1717 fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) {
1718 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
1719 let _ = std::fs::remove_dir_all(&dir);
1720 std::fs::create_dir_all(&dir).expect("scratch dir");
1721 let obu = dir.join("in.obu");
1722 std::fs::write(&obu, stream).expect("writing the stream");
1723 let aom_prefix = dir.join("aom");
1724 let out = Command::new(aomdec_path())
1725 .args(["--codec=av1", "-o"])
1726 .arg(dir.join("out.y4m"))
1727 .arg(&obu)
1728 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
1729 .stdin(Stdio::null())
1730 .stdout(Stdio::piped())
1731 .stderr(Stdio::piped())
1732 .output()
1733 .expect("aomdec failed to run");
1734 assert!(
1735 out.status.success(),
1736 "{name}: the oracle aomdec refused the stream: {}",
1737 String::from_utf8_lossy(&out.stderr)
1738 );
1739 let count_dumps = |prefix: &std::path::Path| -> usize {
1740 let mut n = 0usize;
1741 while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() {
1742 n += 1;
1743 }
1744 n
1745 };
1746 let oracle_frames = count_dumps(&aom_prefix);
1747 assert!(
1748 oracle_frames > 0,
1749 "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \
1750 scripts/instrument-aom-oracle.sh is missing from {}",
1751 aomdec_path().display()
1752 );
1753 let ours_prefix = dir.join("ours");
1754 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
1755 let decoded = decode_stream(stream);
1756 set_final_dump_prefix(None);
1757 let shown = decoded
1758 .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}"))
1759 .len();
1760 let our_frames = count_dumps(&ours_prefix);
1761 assert_eq!(
1762 our_frames, oracle_frames,
1763 "{name}: decoded {our_frames} frames in decode order, the oracle decoded \
1764 {oracle_frames}"
1765 );
1766 for i in 0..oracle_frames {
1767 let want =
1768 std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
1769 let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
1770 assert_eq!(
1771 got.len(),
1772 want.len(),
1773 "{name}: decode-order frame {i} is {} bytes, the oracle's is {}",
1774 got.len(),
1775 want.len()
1776 );
1777 if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) {
1778 let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count();
1779 panic!(
1780 "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \
1781 hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \
1782 bytes differ -- stream pinned at {}",
1783 oracle_frames - shown,
1784 got[at],
1785 want[at],
1786 obu.display()
1787 );
1788 }
1789 }
1790 let hidden = oracle_frames - shown;
1791 let _ = std::fs::remove_dir_all(&dir);
1792 (oracle_frames, hidden)
1793 }
1794
1795 /// lane-hidden r2: the `--arnr-maxframes=0` SECOND ARM of an existing
1796 /// gate -- the gate's own recipe is never changed, this re-encodes the
1797 /// same fixture with libaom's temporal alt-ref filter switched off and
1798 /// runs [`decode_all_frames_vs_oracle`] on the result. Measured: with
1799 /// the filter at its default EVERY alt-ref recipe in this file emits
1800 /// ZERO hidden frames (the candidates are filtered away), so the
1801 /// hidden-frame compare on the gate's own stream is vacuous; this arm
1802 /// is what actually puts `show_frame == 0` frames on the wire.
1803 ///
1804 /// Runs at most once per gate name per process (the loop gates sweep
1805 /// dozens of attempts and each arm costs a full encode + two decodes).
1806 /// A stream this decoder refuses BY NAME skips the arm -- the arm is
1807 /// about hidden frames, not about that capability gap -- while a pixel
1808 /// mismatch is a hard failure raised inside the compare.
1809 fn hidden_arnr_arm(name: &str, y4m: &[u8], args: &[&str]) -> Option<(usize, usize)> {
1810 static ARMED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
1811 std::sync::OnceLock::new();
1812 if !ARMED
1813 .get_or_init(Default::default)
1814 .lock()
1815 .unwrap()
1816 .insert(name.to_string())
1817 {
1818 return None;
1819 }
1820 let mut arm: Vec<&str> = vec!["--arnr-maxframes=0"];
1821 arm.extend_from_slice(args);
1822 let mut child = Command::new(aomenc_path())
1823 .args(&arm)
1824 .stdin(Stdio::piped())
1825 .stdout(Stdio::piped())
1826 .stderr(Stdio::piped())
1827 .spawn()
1828 .expect("aomenc failed to start");
1829 child
1830 .stdin
1831 .take()
1832 .expect("aomenc stdin")
1833 .write_all(y4m)
1834 .expect("writing y4m to aomenc");
1835 let out = child.wait_with_output().expect("aomenc failed to run");
1836 assert!(
1837 out.status.success(),
1838 "{name} HIDDEN-ARM: aomenc refused its own recipe plus --arnr-maxframes=0: {}",
1839 String::from_utf8_lossy(&out.stderr)
1840 );
1841 let stream = out.stdout;
1842 match decode_stream(&stream) {
1843 Err(e) => {
1844 let msg = e.to_string();
1845 assert!(
1846 msg.contains("unsupported"),
1847 "{name} HIDDEN-ARM failed outright: {msg}"
1848 );
1849 eprintln!("{name} HIDDEN-ARM: skipped on a named refusal: {msg}");
1850 None
1851 }
1852 Ok(_) => Some(decode_all_frames_vs_oracle(&stream, &format!("{name}-arnr0"))),
1853 }
1854 }
1855
1856
1857 /// The repo's first hidden-frame pixel gate. Every other aomenc gate
1858 /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and
1859 /// both sides emit SHOWN frames only -- so an alt-ref frame that is
1860 /// decoded, stored into a reference slot and never displayed was, until
1861 /// this gate, never compared to anything (class
1862 /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the
1863 /// default `--lag-in-frames`, so they are full of exactly these frames.
1864 ///
1865 /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc
1866 /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's
1867 /// temporal filter on, this fixture's alt-ref candidates get filtered
1868 /// away and the encoder emits ZERO hidden frames (measured: 0 hidden
1869 /// with the filter on, 3 with it off), which would have made the gate
1870 /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so
1871 /// a recipe that stops producing hidden frames fails rather than skips.
1872 #[test]
1873 fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() {
1874 const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact";
1875 let _gate_lock = lock_gate_counters();
1876 if !have_ffmpeg() {
1877 eprintln!("SKIP {NAME}: no ffmpeg");
1878 return;
1879 }
1880 if !have_aomenc() {
1881 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1882 return;
1883 }
1884 for bit_depth in [8u32, 10u32] {
1885 let (width, height, frames) = (64usize, 64usize, 40usize);
1886 let duration = frames as f64 / 25.0;
1887 let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25");
1888 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
1889 let y4m = Command::new("ffmpeg")
1890 .args([
1891 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
1892 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
1893 ])
1894 .stdin(Stdio::null())
1895 .stdout(Stdio::piped())
1896 .stderr(Stdio::piped())
1897 .output()
1898 .expect("ffmpeg failed to run");
1899 assert!(
1900 y4m.status.success(),
1901 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
1902 String::from_utf8_lossy(&y4m.stderr)
1903 );
1904 let depth_arg = format!("--bit-depth={bit_depth}");
1905 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
1906 let mut child = Command::new(aomenc_path())
1907 .args([
1908 "--codec=av1",
1909 "--passes=1",
1910 "--end-usage=q",
1911 "--cq-level=45",
1912 "--cpu-used=0",
1913 "--threads=1",
1914 "--row-mt=0",
1915 "--kf-max-dist=1000",
1916 "--enable-order-hint=1",
1917 "--auto-alt-ref=1",
1918 "--lag-in-frames=25",
1919 "--arnr-maxframes=0",
1920 &depth_arg,
1921 &input_depth_arg,
1922 // The same tool set every sibling inter gate pins -- the
1923 // open capability gaps (rect/AB partitions, warped/OBMC,
1924 // masked compound, palette, ...) are other lanes' work;
1925 // this gate is about hidden frames, not about them.
1926 "--enable-warped-motion=0",
1927 "--enable-obmc=0",
1928 "--enable-masked-comp=0",
1929 "--enable-interintra-comp=0",
1930 "--enable-onesided-comp=0",
1931 "--enable-interintra-wedge=0",
1932 "--enable-smooth-interintra=0",
1933 "--enable-rect-partitions=0",
1934 "--enable-ab-partitions=0",
1935 "--enable-1to4-partitions=0",
1936 "--enable-filter-intra=0",
1937 "--enable-smooth-intra=0",
1938 "--enable-paeth-intra=0",
1939 "--enable-directional-intra=0",
1940 "--enable-angle-delta=0",
1941 "--enable-tx-size-search=0",
1942 "--enable-cdef=0",
1943 "--enable-restoration=0",
1944 "--max-partition-size=32",
1945 "--min-partition-size=32",
1946 "--enable-palette=0",
1947 "--enable-intrabc=0",
1948 "--enable-cfl-intra=0",
1949 "--enable-ref-frame-mvs=0",
1950 "--obu",
1951 "-o",
1952 "-",
1953 "-",
1954 ])
1955 .stdin(Stdio::piped())
1956 .stdout(Stdio::piped())
1957 .stderr(Stdio::piped())
1958 .spawn()
1959 .expect("aomenc failed to start");
1960 child
1961 .stdin
1962 .take()
1963 .expect("aomenc stdin")
1964 .write_all(&y4m.stdout)
1965 .expect("writing y4m to aomenc");
1966 let out = child.wait_with_output().expect("aomenc failed to run");
1967 assert!(
1968 out.status.success(),
1969 "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}",
1970 String::from_utf8_lossy(&out.stderr)
1971 );
1972 let stream = out.stdout;
1973 let (total, hidden) =
1974 decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit"));
1975 assert!(
1976 hidden >= 2,
1977 "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \
1978 {total} decoded -- the gate would be vacuous (class \
1979 gate-blind-to-hidden-frames)"
1980 );
1981 eprintln!(
1982 "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, all \
1983 pixel-exact vs the oracle in decode order"
1984 );
1985 }
1986 }
1987
1988 /// A real `aomenc` filter-intra fixture: every other intra mode disabled
1989 /// (smooth/paeth/directional/angle-delta) and
1990 /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s
1991 /// <=32x32 bound means `use_filter_intra` never reads at all, spec
1992 /// 5.11.14), so the only way this frame codes is `DC_PRED` with filter
1993 /// intra on top -- `--loopfilter-control=0` is required too: this
1994 /// decoder has no in-loop deblocking filter at all, and libaom's default
1995 /// (on) smooths every block-boundary column, which first looked like a
1996 /// filter-intra math bug (mismatches straddling the 32-pixel block
1997 /// seam) until the recipe without it round-tripped byte-exact. Checks
1998 /// [`decode::filter_intra_hits`] actually moved (a process-global
1999 /// counter, so before/after rather than an absolute value) to prove the
2000 /// symbol fired, then pixel-exactness against ffmpeg's own decode of the
2001 /// identical bytes on every plane.
2002 #[test]
2003 fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {
2004 if !have_ffmpeg() {
2005 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no ffmpeg");
2006 return;
2007 }
2008 if !have_aomenc() {
2009 eprintln!(
2010 "SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no aomenc at {}",
2011 aomenc_path().display()
2012 );
2013 return;
2014 }
2015 let (width, height) = (64usize, 64usize);
2016 // Recipe-search hooks: with the encoder pinned to one thread the
2017 // stream is a deterministic function of (seed, cq), so a firing recipe
2018 // can be searched for without a rebuild.
2019 let fi_seed: u32 = std::env::var("EC_FI_SEED")
2020 .ok()
2021 .and_then(|v| v.parse().ok())
2022 .unwrap_or(42);
2023 let fi_source = gradients_source(fi_seed, 64, 64, "duration=0.04:rate=25");
2024 let fi_cq = std::env::var("EC_FI_CQ").unwrap_or_else(|_| "40".to_string());
2025 let fi_cq_arg = format!("--cq-level={fi_cq}");
2026 let y4m = Command::new("ffmpeg")
2027 .args([
2028 "-v",
2029 "error",
2030 "-f",
2031 "lavfi",
2032 "-i",
2033 &fi_source,
2034 "-pix_fmt",
2035 "yuv420p",
2036 "-f",
2037 "yuv4mpegpipe",
2038 "-",
2039 ])
2040 .stdin(Stdio::null())
2041 .stdout(Stdio::piped())
2042 .stderr(Stdio::piped())
2043 .output()
2044 .expect("ffmpeg failed to run");
2045 assert!(
2046 y4m.status.success(),
2047 "ffmpeg refused to generate the y4m fixture: {}",
2048 String::from_utf8_lossy(&y4m.stderr)
2049 );
2050 let mut child = Command::new(aomenc_path())
2051 .args([
2052 "--codec=av1",
2053 "--passes=1",
2054 "--end-usage=q",
2055 &fi_cq_arg,
2056 "--cpu-used=0",
2057 // Every sibling gate pins these; this one did not, and a
2058 // multi-threaded aomenc is not deterministic, so each run
2059 // encoded a slightly different stream and the gate flaked
2060 // against whichever features that run happened to pick.
2061 // Pinning them makes seed 42 mean one stream (class
2062 // `parallel-flake-is-attempt-selection`).
2063 "--threads=1",
2064 "--row-mt=0",
2065 "--enable-filter-intra=1",
2066 "--enable-smooth-intra=0",
2067 "--enable-paeth-intra=0",
2068 "--enable-directional-intra=0",
2069 "--enable-angle-delta=0",
2070 "--enable-tx-size-search=0",
2071 "--enable-cdef=0",
2072 "--max-partition-size=32",
2073 "--loopfilter-control=0",
2074 "--enable-palette=0",
2075 "--enable-intrabc=0",
2076 "--obu",
2077 "-o",
2078 "-",
2079 "-",
2080 ])
2081 .stdin(Stdio::piped())
2082 .stdout(Stdio::piped())
2083 .stderr(Stdio::piped())
2084 .spawn()
2085 .expect("aomenc failed to start");
2086 child
2087 .stdin
2088 .take()
2089 .expect("aomenc stdin")
2090 .write_all(&y4m.stdout)
2091 .expect("writing the y4m fixture to aomenc");
2092 let out = child.wait_with_output().expect("aomenc failed to run");
2093 assert!(
2094 out.status.success(),
2095 "aomenc refused the fixture: {}",
2096 String::from_utf8_lossy(&out.stderr)
2097 );
2098 let stream = out.stdout;
2099 let before = decode::filter_intra_hits();
2100 // `screen_content_tools_determination` (libaom encoder_utils.c) is a
2101 // real internal trial-encode/PSNR comparison, not a flag this CLI
2102 // exposes a knob for -- on this flat gradient fixture it lands on
2103 // `allow_screen_content_tools=0` most runs but occasionally trips
2104 // over its 0.9 dB threshold the other way even with palette/intrabc
2105 // both disabled. That is a genuine separate gap (`decode_stream`
2106 // never reads `intrabc`/`palette_mode_info`), not a filter-intra
2107 // regression, so it is skipped here exactly as
2108 // `a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact`
2109 // above skips its own still-unsupported-gap runs.
2110 let frames = match decode_stream(&stream) {
2111 Ok(frames) => frames,
2112 Err(e) => {
2113 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: {e}");
2114 return;
2115 }
2116 };
2117 assert!(
2118 decode::filter_intra_hits() > before,
2119 "use_filter_intra never fired decoding this stream"
2120 );
2121 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
2122 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
2123 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
2124 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
2125 }
2126
2127 /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`
2128 /// (SMPTE colour bars -- a handful of large flat luma regions, exactly
2129 /// the "flat, few-colour, repetitive" content `av1_choose_palette_map`'s
2130 /// RD trial rewards) with `hue=s=0` to flatten chroma to one constant
2131 /// value, so `DC_PRED` already nails every chroma block with zero
2132 /// residual and the encoder's own RD never has a reason to spend bits on
2133 /// a *UV* palette too (a real symbol this decoder still refuses --
2134 /// lane-palette r3's own scope is Y only). `smptebars` has no seed to
2135 /// vary, so the fixture is deterministic by construction; hashed twice
2136 /// below to prove it rather than assert it. `--enable-rect-partitions=0`
2137 /// / `-ab-` / `-1to4-` keep every intra block square, sidestepping the
2138 /// rect-strip screen-content refusal at `read_intra_mode_rect`
2139 /// (decode.rs ~2226) -- that refusal is this lane's own next milestone,
2140 /// not this gate's. `--sb-size=64` and `--threads=1 --row-mt=0` are the
2141 /// sibling-lane facts this charter paid for: a single 64x64 frame is one
2142 /// superblock either way, but pinning them keeps the recipe identical to
2143 /// every other gate in this file. HARD-asserts
2144 /// [`decode::palette_hits`] moved -- a stream that never reads a real
2145 /// palette block would refuse (or not) by construction without proving
2146 /// this milestone at all.
2147 ///
2148 /// lane-palette r4/r6/r7: r3/r4 found that this fixture's reconstructed
2149 /// pixels did not match ffmpeg's decode of the same bytes even though
2150 /// every symbol read by `decode_color_index_map` checked line-for-line
2151 /// against the oracle and matched. r6's range trace (`compare-range-not-tell`)
2152 /// pinned the real cause: `decode_color_index_map` was called from the
2153 /// wrong syntax position -- inline right after the Y colours, instead of
2154 /// after the whole mode-info read (UV palette mode_info + `filter_intra`,
2155 /// `av1_visit_palette`'s real call order). r7 ported the UV palette
2156 /// mode_info read and moved the colour-index-map decode after
2157 /// `filter_intra`; this gate now asserts a real pixel match instead of
2158 /// the old named refusal.
2159 #[test]
2160 fn a_real_aomenc_stream_with_palette_y_decodes_pixel_exact() {
2161 const NAME: &str = "a_real_aomenc_stream_with_palette_y_decodes_pixel_exact";
2162 if !have_ffmpeg() {
2163 eprintln!("SKIP {NAME}: no ffmpeg");
2164 return;
2165 }
2166 if !have_aomenc() {
2167 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2168 return;
2169 }
2170 let source = "smptebars=size=64x64:rate=25";
2171 fn render(source: &str) -> Vec<u8> {
2172 Command::new("ffmpeg")
2173 .args([
2174 "-v",
2175 "error",
2176 "-f",
2177 "lavfi",
2178 "-i",
2179 source,
2180 "-vf",
2181 "hue=s=0",
2182 "-pix_fmt",
2183 "yuv420p",
2184 "-t",
2185 "0.04",
2186 "-f",
2187 "yuv4mpegpipe",
2188 "-",
2189 ])
2190 .stdin(Stdio::null())
2191 .stdout(Stdio::piped())
2192 .stderr(Stdio::piped())
2193 .output()
2194 .expect("ffmpeg failed to run")
2195 .stdout
2196 }
2197 let y4m_a = render(source);
2198 let y4m_b = render(source);
2199 assert_eq!(
2200 y4m_a, y4m_b,
2201 "smptebars must render byte-identical across two runs"
2202 );
2203 let y4m = y4m_a;
2204 let mut child = Command::new(aomenc_path())
2205 .args([
2206 "--codec=av1",
2207 "--passes=1",
2208 "--end-usage=q",
2209 "--cq-level=30",
2210 "--cpu-used=0",
2211 "--threads=1",
2212 "--row-mt=0",
2213 "--sb-size=64",
2214 "--tune-content=screen",
2215 "--enable-palette=1",
2216 "--enable-intrabc=0",
2217 "--enable-rect-partitions=0",
2218 "--enable-ab-partitions=0",
2219 "--enable-1to4-partitions=0",
2220 "--min-partition-size=32",
2221 "--max-partition-size=32",
2222 "--enable-filter-intra=0",
2223 "--enable-smooth-intra=0",
2224 "--enable-paeth-intra=0",
2225 "--enable-directional-intra=0",
2226 "--enable-angle-delta=0",
2227 "--enable-cfl-intra=0",
2228 "--enable-cdef=0",
2229 "--enable-restoration=0",
2230 "--enable-tx-size-search=0",
2231 "--loopfilter-control=0",
2232 "--obu",
2233 "-o",
2234 "-",
2235 "-",
2236 ])
2237 .stdin(Stdio::piped())
2238 .stdout(Stdio::piped())
2239 .stderr(Stdio::piped())
2240 .spawn()
2241 .expect("aomenc failed to start");
2242 child
2243 .stdin
2244 .take()
2245 .expect("aomenc stdin")
2246 .write_all(&y4m)
2247 .expect("writing y4m to aomenc");
2248 let out = child.wait_with_output().expect("aomenc failed to run");
2249 assert!(
2250 out.status.success(),
2251 "aomenc refused the fixture: {}",
2252 String::from_utf8_lossy(&out.stderr)
2253 );
2254 let stream = out.stdout;
2255 let before = decode::palette_hits();
2256 let frames = match decode_stream(&stream) {
2257 Ok(frames) => frames,
2258 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2259 };
2260 assert!(
2261 decode::palette_hits() > before,
2262 "palette_y_mode never fired decoding this stream -- gate is vacuous"
2263 );
2264 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1);
2265 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
2266 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
2267 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
2268 }
2269
2270 /// lane-hbd r5: a real `aomenc --bit-depth=10` stream, decoded through
2271 /// this crate's own 10-bit planes (`Picture` widened to `u16` in an
2272 /// earlier round) and checked pixel-exact against ffmpeg's own decode of
2273 /// the identical bytes via [`ffmpeg_decode_sequence_10bit`]. Confirms
2274 /// (hard-asserts, not just trusts) the sequence header this stream
2275 /// actually parses to says `bit_depth == 10` before trusting any pixel
2276 /// match -- a stream that silently fell back to 8-bit would still
2277 /// "match" trivially.
2278 #[test]
2279 fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {
2280 const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact";
2281 if !have_ffmpeg() {
2282 eprintln!("SKIP {NAME}: no ffmpeg");
2283 return;
2284 }
2285 if !have_aomenc() {
2286 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2287 return;
2288 }
2289 let (width, height) = (64usize, 64usize);
2290 let y4m = Command::new("ffmpeg")
2291 .args([
2292 "-v",
2293 "error",
2294 "-f",
2295 "lavfi",
2296 "-i",
2297 &gradients_source(42, width, height, "duration=0.04:rate=25"),
2298 "-pix_fmt",
2299 "yuv420p10le",
2300 "-strict",
2301 "-1",
2302 "-t",
2303 "0.04",
2304 "-f",
2305 "yuv4mpegpipe",
2306 "-",
2307 ])
2308 .stdin(Stdio::null())
2309 .stdout(Stdio::piped())
2310 .stderr(Stdio::piped())
2311 .output()
2312 .expect("ffmpeg failed to run");
2313 assert!(
2314 y4m.status.success(),
2315 "ffmpeg failed to render the 10-bit fixture: {}",
2316 String::from_utf8_lossy(&y4m.stderr)
2317 );
2318 let mut child = Command::new(aomenc_path())
2319 .args([
2320 "--codec=av1",
2321 "--passes=1",
2322 "--end-usage=q",
2323 "--cq-level=30",
2324 "--cpu-used=0",
2325 "--threads=1",
2326 "--row-mt=0",
2327 "--sb-size=64",
2328 "--input-bit-depth=10",
2329 "--bit-depth=10",
2330 "--limit=1",
2331 "--obu",
2332 "-o",
2333 "-",
2334 "-",
2335 ])
2336 .stdin(Stdio::piped())
2337 .stdout(Stdio::piped())
2338 .stderr(Stdio::piped())
2339 .spawn()
2340 .expect("aomenc failed to start");
2341 child
2342 .stdin
2343 .take()
2344 .expect("aomenc stdin")
2345 .write_all(&y4m.stdout)
2346 .expect("writing y4m to aomenc");
2347 let out = child.wait_with_output().expect("aomenc failed to run");
2348 assert!(
2349 out.status.success(),
2350 "aomenc refused the 10-bit fixture: {}",
2351 String::from_utf8_lossy(&out.stderr)
2352 );
2353 let stream = out.stdout;
2354 // Confirm the sequence header this stream actually parses to before
2355 // trusting any pixel comparison below.
2356 let mut probe = Av1Parser::new();
2357 let mut pos = 0usize;
2358 while pos < stream.len() && probe.sequence_header().is_none() {
2359 let obu = probe.parse_obu(&stream[pos..]).unwrap();
2360 pos += obu.total_size;
2361 }
2362 let seq = probe
2363 .sequence_header()
2364 .expect("stream has a sequence header OBU");
2365 assert_eq!(
2366 seq.color_config.bit_depth, 10,
2367 "{NAME}: aomenc did not actually write a 10-bit sequence header"
2368 );
2369 let frames = match decode_stream(&stream) {
2370 Ok(frames) => frames,
2371 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit stream: {e}"),
2372 };
2373 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
2374 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (10-bit)");
2375 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (10-bit)");
2376 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
2377 }
2378
2379 /// The 10-bit *inter* counterpart of the gate above: a real `aomenc`
2380 /// `yuv420p10le` sequence whose non-key frames are plain forward
2381 /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0
2382 /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate),
2383 /// decoded pixel-exact on every frame. 10-bit intra was proven exact by
2384 /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated.
2385 #[test]
2386 fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() {
2387 const NAME: &str = "a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact";
2388 let _gate_lock = lock_gate_counters();
2389 if !have_ffmpeg() {
2390 eprintln!("SKIP {NAME}: no ffmpeg");
2391 return;
2392 }
2393 if !have_aomenc() {
2394 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2395 return;
2396 }
2397 let (width, height, frame_count) = (128usize, 64usize, 16usize);
2398 let y4m = Command::new("ffmpeg")
2399 .args([
2400 "-v",
2401 "error",
2402 "-f",
2403 "lavfi",
2404 "-i",
2405 &gradients_source(42, width, height, "duration=0.64:rate=25"),
2406 "-pix_fmt",
2407 "yuv420p10le",
2408 "-strict",
2409 "-1",
2410 "-t",
2411 "0.64",
2412 "-f",
2413 "yuv4mpegpipe",
2414 "-",
2415 ])
2416 .stdin(Stdio::null())
2417 .stdout(Stdio::piped())
2418 .stderr(Stdio::piped())
2419 .output()
2420 .expect("ffmpeg failed to run");
2421 assert!(
2422 y4m.status.success(),
2423 "ffmpeg failed to render the 10-bit fixture: {}",
2424 String::from_utf8_lossy(&y4m.stderr)
2425 );
2426 let mut child = Command::new(aomenc_path())
2427 .args([
2428 "--codec=av1",
2429 "--passes=1",
2430 "--end-usage=q",
2431 "--cq-level=15",
2432 "--cpu-used=0",
2433 "--threads=1",
2434 "--row-mt=0",
2435 "--sb-size=64",
2436 "--input-bit-depth=10",
2437 "--bit-depth=10",
2438 "--lag-in-frames=0",
2439 "--auto-alt-ref=0",
2440 "--kf-max-dist=1000",
2441 "--error-resilient=1",
2442 "--aq-mode=0",
2443 "--deltaq-mode=0",
2444 "--enable-rect-partitions=0",
2445 "--enable-ab-partitions=0",
2446 "--enable-1to4-partitions=0",
2447 "--enable-filter-intra=0",
2448 "--enable-smooth-intra=0",
2449 "--enable-paeth-intra=0",
2450 "--enable-directional-intra=0",
2451 "--enable-angle-delta=0",
2452 "--enable-tx-size-search=0",
2453 "--enable-cdef=1",
2454 "--enable-restoration=1",
2455 "--min-partition-size=16",
2456 "--max-partition-size=32",
2457 "--enable-palette=0",
2458 "--enable-intrabc=0",
2459 "--enable-cfl-intra=0",
2460 "--enable-ref-frame-mvs=0",
2461 "--obu",
2462 "-o",
2463 "-",
2464 "-",
2465 ])
2466 .stdin(Stdio::piped())
2467 .stdout(Stdio::piped())
2468 .stderr(Stdio::piped())
2469 .spawn()
2470 .expect("aomenc failed to start");
2471 child
2472 .stdin
2473 .take()
2474 .expect("aomenc stdin")
2475 .write_all(&y4m.stdout)
2476 .expect("writing y4m to aomenc");
2477 let out = child.wait_with_output().expect("aomenc failed to run");
2478 assert!(
2479 out.status.success(),
2480 "aomenc refused the 10-bit fixture: {}",
2481 String::from_utf8_lossy(&out.stderr)
2482 );
2483 let stream = out.stdout;
2484 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
2485 std::fs::write(dump, &stream).expect("dump stream");
2486 }
2487 let mut probe = Av1Parser::new();
2488 let mut pos = 0usize;
2489 while pos < stream.len() && probe.sequence_header().is_none() {
2490 let obu = probe.parse_obu(&stream[pos..]).unwrap();
2491 pos += obu.total_size;
2492 }
2493 assert_eq!(
2494 probe
2495 .sequence_header()
2496 .expect("stream has a sequence header OBU")
2497 .color_config
2498 .bit_depth,
2499 10,
2500 "{NAME}: aomenc did not actually write a 10-bit sequence header"
2501 );
2502 let before_deblock = decode::deblock_hits();
2503 let before_inter = decode::inter_pred_hits();
2504 let before_lr = crate::restoration::wiener_hits()
2505 + crate::restoration::sgrproj_hits()
2506 + crate::restoration::switchable_hits();
2507 let frames = match decode_stream(&stream) {
2508 Ok(frames) => frames,
2509 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"),
2510 };
2511 assert!(
2512 decode::inter_pred_hits() > before_inter,
2513 "{NAME}: no inter-predicted block decoded -- the gate proves nothing"
2514 );
2515 assert!(
2516 decode::deblock_hits() > before_deblock,
2517 "{NAME}: no deblocking edge fired -- raise cq-level"
2518 );
2519 // Loop restoration is where the 10-bit inter/intra defect lived
2520 // (lane-hbdinter r1: the self-guided box sums were never brought back
2521 // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened
2522 // to pick RESTORE_NONE would pass while proving nothing.
2523 assert!(
2524 crate::restoration::wiener_hits()
2525 + crate::restoration::sgrproj_hits()
2526 + crate::restoration::switchable_hits()
2527 > before_lr,
2528 "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level"
2529 );
2530 eprintln!(
2531 "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}",
2532 decode::inter_pred_hits() - before_inter,
2533 decode::deblock_hits() - before_deblock,
2534 decode::cdef_idx_hits(),
2535 crate::restoration::wiener_hits(),
2536 crate::restoration::sgrproj_hits(),
2537 );
2538 assert_eq!(frames.len(), frame_count);
2539 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count);
2540 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2541 if got.y != want.y || got.u != want.u || got.v != want.v {
2542 let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu");
2543 let _ = std::fs::write(&pin, &stream);
2544 let first = |a: &Vec<u16>, b: &Vec<u16>| {
2545 a.iter()
2546 .zip(b)
2547 .enumerate()
2548 .find(|(_, (x, y))| x != y)
2549 .map(|(k, (x, y))| (k, *x, *y))
2550 };
2551 panic!(
2552 "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}",
2553 first(&got.y, &want.y),
2554 first(&got.u, &want.u),
2555 first(&got.v, &want.v),
2556 pin.display()
2557 );
2558 }
2559 }
2560 }
2561
2562 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1`
2563 /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the
2564 /// identical bytes (ffmpeg synthesizes grain by default -- no
2565 /// grain-disable flag is passed anywhere in this file). Proves the
2566 /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`,
2567 /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather
2568 /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed
2569 /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a
2570 /// silent 8-bit fallback nor a stream aomenc emitted without
2571 /// `apply_grain` can make it pass vacuously.
2572 #[test]
2573 fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() {
2574 const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact";
2575 if !have_ffmpeg() {
2576 eprintln!("SKIP {NAME}: no ffmpeg");
2577 return;
2578 }
2579 if !have_aomenc() {
2580 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2581 return;
2582 }
2583 let (width, height) = (64usize, 64usize);
2584 let stream = encode_10bit_gradients(
2585 NAME,
2586 width,
2587 height,
2588 1,
2589 &["--film-grain-test=1", "--limit=1"],
2590 );
2591 assert_eq!(
2592 parsed_bit_depth(&stream),
2593 10,
2594 "{NAME}: aomenc did not actually write a 10-bit sequence header"
2595 );
2596 let mut probe = Av1Parser::new();
2597 let mut pos = 0usize;
2598 let mut saw_grain = false;
2599 while pos < stream.len() {
2600 let obu = probe.parse_obu(&stream[pos..]).unwrap();
2601 pos += obu.total_size;
2602 if let ObuKind::Frame(header, _) = obu.kind
2603 && header.film_grain.apply_grain
2604 {
2605 // A grain block whose scaling LUT is empty would blend a
2606 // zero delta into every pixel and let this gate pass without
2607 // the bit-depth math mattering at all.
2608 assert!(
2609 header.film_grain.num_y_points > 0,
2610 "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op"
2611 );
2612 saw_grain = true;
2613 }
2614 }
2615 assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain");
2616 let before = crate::film_grain::grain_hits();
2617 let frames = match decode_stream(&stream) {
2618 Ok(frames) => frames,
2619 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2620 };
2621 assert!(
2622 crate::film_grain::grain_hits() > before,
2623 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
2624 );
2625 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
2626 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
2627 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
2628 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
2629 eprintln!("{NAME}: pixel-exact, grain_hits={}", crate::film_grain::grain_hits());
2630 }
2631
2632 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1
2633 /// --superres-denominator=12` key frame, decoded pixel-exact against
2634 /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s
2635 /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit
2636 /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts
2637 /// `bit_depth == 10` and `superres_hits > 0`.
2638 #[test]
2639 fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() {
2640 const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact";
2641 if !have_ffmpeg() {
2642 eprintln!("SKIP {NAME}: no ffmpeg");
2643 return;
2644 }
2645 if !have_aomenc() {
2646 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2647 return;
2648 }
2649 let (width, height) = (64usize, 64usize);
2650 let stream = encode_10bit_gradients(
2651 NAME,
2652 width,
2653 height,
2654 1,
2655 &[
2656 "--limit=1",
2657 "--kf-max-dist=0",
2658 "--superres-mode=1",
2659 "--superres-denominator=12",
2660 "--superres-kf-denominator=12",
2661 "--enable-rect-partitions=0",
2662 "--enable-ab-partitions=0",
2663 "--enable-1to4-partitions=0",
2664 "--enable-filter-intra=0",
2665 "--enable-smooth-intra=0",
2666 "--enable-paeth-intra=0",
2667 "--enable-directional-intra=0",
2668 "--enable-angle-delta=0",
2669 "--enable-tx-size-search=0",
2670 "--enable-cdef=0",
2671 "--enable-restoration=0",
2672 "--max-partition-size=32",
2673 "--min-partition-size=32",
2674 "--enable-palette=0",
2675 "--enable-intrabc=0",
2676 "--enable-cfl-intra=0",
2677 ],
2678 );
2679 assert_eq!(
2680 parsed_bit_depth(&stream),
2681 10,
2682 "{NAME}: aomenc did not actually write a 10-bit sequence header"
2683 );
2684 let before = crate::superres::superres_hits();
2685 let frames = match decode_stream(&stream) {
2686 Ok(frames) => frames,
2687 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
2688 };
2689 assert!(
2690 crate::superres::superres_hits() > before,
2691 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
2692 );
2693 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
2694 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
2695 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
2696 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
2697 eprintln!(
2698 "{NAME}: pixel-exact, superres_hits={}",
2699 crate::superres::superres_hits()
2700 );
2701 }
2702
2703 /// lane-hbdgates r1: drive one 10-bit aomenc recipe over `seeds`, decode
2704 /// every attempt and pixel-compare every SHOWN frame against ffmpeg's own
2705 /// 10-bit decode of the identical bytes. Per-tool firing counters are
2706 /// sampled PER ATTEMPT and summed only over attempts that decoded *and*
2707 /// compared -- a stream that hit a named refusal contributes nothing
2708 /// (class `counter-from-refused-stream`). Named refusals are tolerated
2709 /// and reported; a pixel mismatch is a hard failure, never a SKIP.
2710 fn ten_bit_tool_gate(
2711 name: &str,
2712 width: usize,
2713 height: usize,
2714 frames: usize,
2715 extra: &[&str],
2716 seeds: &[u32],
2717 counters: &[(&str, fn() -> usize)],
2718 ) {
2719 fn first_diff(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
2720 ours.iter()
2721 .zip(theirs.iter())
2722 .position(|(a, b)| a != b)
2723 .map(|i| {
2724 format!(
2725 "first diff at index {i} (row {}, col {}): ours {} vs ffmpeg {}",
2726 i / width,
2727 i % width,
2728 ours[i],
2729 theirs[i]
2730 )
2731 })
2732 }
2733 let mut totals = vec![0usize; counters.len()];
2734 let mut refusals: Vec<String> = Vec::new();
2735 let mut compared = 0usize;
2736 for &seed in seeds {
2737 let stream = encode_10bit_gradients_seed(name, seed, width, height, frames, extra);
2738 assert_eq!(
2739 parsed_bit_depth(&stream),
2740 10,
2741 "{name}: aomenc did not write a 10-bit sequence header (seed {seed})"
2742 );
2743 let before: Vec<usize> = counters.iter().map(|(_, f)| f()).collect();
2744 let decoded = match decode_stream(&stream) {
2745 Ok(frames) => frames,
2746 Err(e) => {
2747 refusals.push(format!("seed {seed}: {e}"));
2748 continue;
2749 }
2750 };
2751 // Deltas are read BEFORE the pixel compare so a mismatch report
2752 // says whether the tool under test actually fired on the failing
2753 // stream (a mismatch with a zero delta is some other defect).
2754 let deltas: Vec<usize> = counters
2755 .iter()
2756 .zip(before.iter())
2757 .map(|((_, f), b)| f() - b)
2758 .collect();
2759 let fired: Vec<String> = counters
2760 .iter()
2761 .zip(deltas.iter())
2762 .map(|((label, _), d)| format!("{label}={d}"))
2763 .collect();
2764 let fired = fired.join(" ");
2765 let reference = ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len());
2766 assert_eq!(
2767 decoded.len(),
2768 reference.len(),
2769 "{name}: seed {seed}: shown-frame count vs ffmpeg"
2770 );
2771 for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() {
2772 for (plane, (a, b), w) in [
2773 ("Y", (&ours.y, &theirs.y), width),
2774 ("U", (&ours.u, &theirs.u), width / 2),
2775 ("V", (&ours.v, &theirs.v), width / 2),
2776 ] {
2777 if let Some(d) = first_diff(a, b, w) {
2778 panic!("{name}: seed {seed} frame {i} plane {plane}: {d} [{fired}]");
2779 }
2780 }
2781 }
2782 compared += 1;
2783 for (i, d) in deltas.iter().enumerate() {
2784 totals[i] += d;
2785 }
2786 }
2787 assert!(
2788 compared > 0,
2789 "{name}: every attempt hit a named refusal:\n{}",
2790 refusals.join("\n")
2791 );
2792 for (i, (label, _)) in counters.iter().enumerate() {
2793 assert!(
2794 totals[i] > 0,
2795 "{name}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
2796 the gate would prove nothing about that tool. refusals:\n{}",
2797 refusals.join("\n")
2798 );
2799 }
2800 let summary: Vec<String> = counters
2801 .iter()
2802 .zip(totals.iter())
2803 .map(|((label, _), t)| format!("{label}={t}"))
2804 .collect();
2805 eprintln!(
2806 "{name}: {compared}/{} attempts pixel-exact, {}",
2807 seeds.len(),
2808 summary.join(" ")
2809 );
2810 }
2811
2812 /// lane-hbdgates r1: the four intra tools that had an 8-bit gate and no
2813 /// 10-bit one (`filter-intra`, `smooth-intra`, `paeth-intra`,
2814 /// `intra-edge-filter`) on ONE real 10-bit `aomenc` key frame, each with
2815 /// its own hard-asserted counter. His two films are yuv420p10le, so an
2816 /// 8-bit-only gate for these tools proves nothing about the streams that
2817 /// matter (lane-covbd r1).
2818 #[test]
2819 fn a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact() {
2820 const NAME: &str = "a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact";
2821 if !have_ffmpeg() {
2822 eprintln!("SKIP {NAME}: no ffmpeg");
2823 return;
2824 }
2825 if !have_aomenc() {
2826 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2827 return;
2828 }
2829 ten_bit_tool_gate(
2830 NAME,
2831 64,
2832 64,
2833 1,
2834 &[
2835 "--limit=1",
2836 "--kf-max-dist=0",
2837 "--enable-filter-intra=1",
2838 "--enable-smooth-intra=1",
2839 "--enable-paeth-intra=1",
2840 "--enable-intra-edge-filter=1",
2841 "--enable-directional-intra=1",
2842 "--enable-angle-delta=0",
2843 "--enable-rect-partitions=0",
2844 "--enable-ab-partitions=0",
2845 "--enable-1to4-partitions=0",
2846 "--enable-tx-size-search=0",
2847 "--enable-cdef=0",
2848 "--enable-restoration=0",
2849 "--max-partition-size=32",
2850 "--min-partition-size=16",
2851 "--enable-palette=0",
2852 "--enable-intrabc=0",
2853 "--enable-cfl-intra=0",
2854 "--enable-ref-frame-mvs=0",
2855 ],
2856 &[42, 7, 11, 23, 31, 57],
2857 &[
2858 ("filter_intra_hits", decode::filter_intra_hits),
2859 ("smooth_pred_hits", crate::intra::smooth_pred_hits),
2860 ("paeth_pred_hits", crate::intra::paeth_pred_hits),
2861 ("intra_edge_filter_hits", crate::intra::intra_edge_filter_hits),
2862 ],
2863 );
2864 }
2865
2866 /// lane-hbdgates r1: `--enable-restoration=1` at 10 bits. Every earlier
2867 /// bit-depth gate ran `--enable-restoration=0`, which is exactly why two
2868 /// high-bit-depth loop-restoration defects survived to 2026-09-01
2869 /// (SGR box sums unscaled, Wiener clamp at the 8-bit bound). Same recipe
2870 /// as the 8-bit LR gate, at 10 bits.
2871 // Written `#[ignore]`d on lane-hbdgates (the branch lacked lane-hbdinter's
2872 // 10-bit LR fix and failed at seed 42, frame 0, Y index 122: ours 351 vs
2873 // ffmpeg 350). Un-ignored on the merge into main 2026-09-01, where the
2874 // SGR box-sum scaling and the Wiener clamp are fixed: 16/16 attempts
2875 // pixel-exact, lr_hits=28.
2876 #[test]
2877 fn a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact() {
2878 const NAME: &str = "a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact";
2879 if !have_ffmpeg() {
2880 eprintln!("SKIP {NAME}: no ffmpeg");
2881 return;
2882 }
2883 if !have_aomenc() {
2884 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2885 return;
2886 }
2887 // 192x128 = 3x2 superblocks, so `read_lr` is re-entered per SB
2888 // (the 8-bit LR gate's own trap warning); cq-level=15 because
2889 // aomenc's RD only picks a non-RESTORE_NONE frame type at low cq.
2890 ten_bit_tool_gate(
2891 NAME,
2892 192,
2893 128,
2894 1,
2895 &[
2896 "--limit=1",
2897 "--kf-max-dist=0",
2898 "--cq-level=15",
2899 "--enable-restoration=1",
2900 "--enable-cdef=0",
2901 "--enable-rect-partitions=0",
2902 "--enable-ab-partitions=0",
2903 "--enable-1to4-partitions=0",
2904 "--enable-filter-intra=0",
2905 "--enable-smooth-intra=0",
2906 "--enable-paeth-intra=0",
2907 "--enable-tx-size-search=0",
2908 "--max-partition-size=32",
2909 "--min-partition-size=16",
2910 "--enable-palette=0",
2911 "--enable-intrabc=0",
2912 "--enable-cfl-intra=0",
2913 "--enable-ref-frame-mvs=0",
2914 ],
2915 &LR_SEEDS,
2916 &[("lr_hits", ten_bit_lr_hits)],
2917 );
2918 }
2919
2920 /// Seeds swept by the 10-bit LR gate (the 8-bit gate needs ~40 attempts
2921 /// to land a non-RESTORE_NONE frame; every attempt here still has to
2922 /// decode pixel-exact).
2923 const LR_SEEDS: [u32; 16] = [42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
2924
2925 /// Wiener + SGR + switchable loop-restoration firings, summed.
2926 fn ten_bit_lr_hits() -> usize {
2927 crate::restoration::wiener_hits()
2928 + crate::restoration::sgrproj_hits()
2929 + crate::restoration::switchable_hits()
2930 }
2931
2932 /// lane-hbdgates r1: `--enable-rect-partitions=1 --enable-ab-partitions=1`
2933 /// at 10 bits, one intra stream, one counter per tool
2934 /// (`rect_partition_hits`, `partab_hits`) so a stream that only fired the
2935 /// rect arms cannot stand in for AB.
2936 #[test]
2937 fn a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact() {
2938 const NAME: &str = "a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact";
2939 if !have_ffmpeg() {
2940 eprintln!("SKIP {NAME}: no ffmpeg");
2941 return;
2942 }
2943 if !have_aomenc() {
2944 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2945 return;
2946 }
2947 // The 8-bit free-partition/AB recipe, verbatim, at 10 bits: AB
2948 // splits are an INTER dispatch here (intra-frame AB is still a named
2949 // refusal), so the stream needs alt-refs and 24 frames, not one key
2950 // frame.
2951 ten_bit_tool_gate(
2952 NAME,
2953 64,
2954 64,
2955 24,
2956 &[
2957 "--cq-level=45",
2958 "--kf-max-dist=1000",
2959 "--auto-alt-ref=1",
2960 "--lag-in-frames=16",
2961 "--enable-fwd-kf=0",
2962 "--enable-order-hint=1",
2963 "--enable-warped-motion=1",
2964 "--enable-obmc=1",
2965 "--tune-content=default",
2966 "--enable-masked-comp=0",
2967 "--enable-interintra-comp=0",
2968 "--enable-onesided-comp=0",
2969 "--enable-interintra-wedge=0",
2970 "--enable-smooth-interintra=0",
2971 "--enable-rect-partitions=1",
2972 "--enable-ab-partitions=1",
2973 "--enable-1to4-partitions=0",
2974 "--enable-filter-intra=0",
2975 "--enable-smooth-intra=0",
2976 "--enable-paeth-intra=0",
2977 "--enable-directional-intra=0",
2978 "--enable-angle-delta=0",
2979 "--enable-tx-size-search=0",
2980 "--enable-cdef=0",
2981 "--enable-restoration=0",
2982 "--max-partition-size=32",
2983 "--min-partition-size=16",
2984 "--enable-palette=0",
2985 "--enable-intrabc=0",
2986 "--enable-cfl-intra=0",
2987 "--enable-ref-frame-mvs=0",
2988 ],
2989 &LR_SEEDS,
2990 &[
2991 ("rect_partition_hits", decode::rect_partition_hits),
2992 ("partab_hits", decode::partab_hits),
2993 ],
2994 );
2995 }
2996
2997 /// `bit_depth` of the first sequence header in `stream`.
2998 fn parsed_bit_depth(stream: &[u8]) -> u8 {
2999 let mut probe = Av1Parser::new();
3000 let mut pos = 0usize;
3001 while pos < stream.len() && probe.sequence_header().is_none() {
3002 let obu = probe.parse_obu(&stream[pos..]).unwrap();
3003 pos += obu.total_size;
3004 }
3005 probe
3006 .sequence_header()
3007 .expect("stream has a sequence header OBU")
3008 .color_config
3009 .bit_depth
3010 }
3011
3012 /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and
3013 /// encode it with a real 10-bit `aomenc`, returning the OBU stream.
3014 /// `extra` carries the tool flags under test.
3015 fn encode_10bit_gradients(
3016 name: &str,
3017 width: usize,
3018 height: usize,
3019 frames: usize,
3020 extra: &[&str],
3021 ) -> Vec<u8> {
3022 encode_10bit_gradients_seed(name, 42, width, height, frames, extra)
3023 }
3024
3025 /// As [`encode_10bit_gradients`], but with the fixture seed exposed --
3026 /// lane-hbdgates r1 sweeps seeds so a tool that aomenc's RD declines on
3027 /// one fixture still gets a firing stream.
3028 fn encode_10bit_gradients_seed(
3029 name: &str,
3030 seed: u32,
3031 width: usize,
3032 height: usize,
3033 frames: usize,
3034 extra: &[&str],
3035 ) -> Vec<u8> {
3036 let duration = frames as f64 / 25.0;
3037 let y4m = Command::new("ffmpeg")
3038 .args([
3039 "-v",
3040 "error",
3041 "-f",
3042 "lavfi",
3043 "-i",
3044 &gradients_source(seed, width, height, &format!("duration={duration}:rate=25")),
3045 "-pix_fmt",
3046 "yuv420p10le",
3047 "-strict",
3048 "-1",
3049 "-t",
3050 &format!("{duration}"),
3051 "-f",
3052 "yuv4mpegpipe",
3053 "-",
3054 ])
3055 .stdin(Stdio::null())
3056 .stdout(Stdio::piped())
3057 .stderr(Stdio::piped())
3058 .output()
3059 .expect("ffmpeg failed to run");
3060 assert!(
3061 y4m.status.success(),
3062 "{name}: ffmpeg failed to render the 10-bit fixture: {}",
3063 String::from_utf8_lossy(&y4m.stderr)
3064 );
3065 let mut args: Vec<&str> = vec!["--codec=av1", "--passes=1", "--end-usage=q"];
3066 // lane-hbdgates r1: a caller-supplied `--cq-level` REPLACES the
3067 // default rather than being appended after it -- two `--cq-level`
3068 // flags on one aomenc line is a coin flip on which one lands.
3069 if !extra.iter().any(|a| a.starts_with("--cq-level=")) {
3070 args.push("--cq-level=30");
3071 }
3072 args.extend_from_slice(&[
3073 "--cpu-used=0",
3074 "--threads=1",
3075 "--row-mt=0",
3076 "--sb-size=64",
3077 "--input-bit-depth=10",
3078 "--bit-depth=10",
3079 ]);
3080 args.extend_from_slice(extra);
3081 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
3082 let mut child = Command::new(aomenc_path())
3083 .args(&args)
3084 .stdin(Stdio::piped())
3085 .stdout(Stdio::piped())
3086 .stderr(Stdio::piped())
3087 .spawn()
3088 .expect("aomenc failed to start");
3089 child
3090 .stdin
3091 .take()
3092 .expect("aomenc stdin")
3093 .write_all(&y4m.stdout)
3094 .expect("writing y4m to aomenc");
3095 let out = child.wait_with_output().expect("aomenc failed to run");
3096 assert!(
3097 out.status.success(),
3098 "{name}: aomenc refused the 10-bit fixture: {}",
3099 String::from_utf8_lossy(&out.stderr)
3100 );
3101 out.stdout
3102 }
3103
3104 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
3105 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
3106 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
3107 /// which flattened chroma to a single value specifically to avoid
3108 /// exercising this path). Same square-only recipe as the palette-Y gate
3109 /// (`--enable-rect-partitions=0`/`-ab-`/`-1to4-`, fixed 32x32 partition)
3110 /// so a UV palette block never lands inside the still-refused HORZ/VERT
3111 /// screen-content strip. HARD-asserts [`decode::palette_uv_hits`] moved
3112 /// -- a stream that never reads a real UV palette block would decode (or
3113 /// not) by construction without proving this milestone at all
3114 /// ([[gate-blind-to-feature]]).
3115 #[test]
3116 fn a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact() {
3117 const NAME: &str = "a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact";
3118 if !have_ffmpeg() {
3119 eprintln!("SKIP {NAME}: no ffmpeg");
3120 return;
3121 }
3122 if !have_aomenc() {
3123 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3124 return;
3125 }
3126 let source = "testsrc2=size=64x64:rate=25";
3127 fn render(source: &str) -> Vec<u8> {
3128 Command::new("ffmpeg")
3129 .args([
3130 "-v",
3131 "error",
3132 "-f",
3133 "lavfi",
3134 "-i",
3135 source,
3136 "-pix_fmt",
3137 "yuv420p",
3138 "-t",
3139 "0.16",
3140 "-f",
3141 "yuv4mpegpipe",
3142 "-",
3143 ])
3144 .stdin(Stdio::null())
3145 .stdout(Stdio::piped())
3146 .stderr(Stdio::piped())
3147 .output()
3148 .expect("ffmpeg failed to run")
3149 .stdout
3150 }
3151 let y4m_a = render(source);
3152 let y4m_b = render(source);
3153 assert_eq!(
3154 y4m_a, y4m_b,
3155 "testsrc2 must render byte-identical across two runs"
3156 );
3157 let y4m = y4m_a;
3158 let mut child = Command::new(aomenc_path())
3159 .args([
3160 "--codec=av1",
3161 "--passes=1",
3162 "--end-usage=q",
3163 "--cq-level=30",
3164 "--cpu-used=0",
3165 "--threads=1",
3166 "--row-mt=0",
3167 "--sb-size=64",
3168 "--tune-content=screen",
3169 "--enable-palette=1",
3170 "--enable-intrabc=0",
3171 "--enable-rect-partitions=0",
3172 "--enable-ab-partitions=0",
3173 "--enable-1to4-partitions=0",
3174 "--min-partition-size=32",
3175 "--max-partition-size=32",
3176 "--enable-filter-intra=0",
3177 "--enable-cdef=0",
3178 "--enable-restoration=0",
3179 "--enable-tx-size-search=0",
3180 "--loopfilter-control=0",
3181 "--obu",
3182 "-o",
3183 "-",
3184 "-",
3185 ])
3186 .stdin(Stdio::piped())
3187 .stdout(Stdio::piped())
3188 .stderr(Stdio::piped())
3189 .spawn()
3190 .expect("aomenc failed to start");
3191 child
3192 .stdin
3193 .take()
3194 .expect("aomenc stdin")
3195 .write_all(&y4m)
3196 .expect("writing y4m to aomenc");
3197 let out = child.wait_with_output().expect("aomenc failed to run");
3198 assert!(
3199 out.status.success(),
3200 "aomenc refused the fixture: {}",
3201 String::from_utf8_lossy(&out.stderr)
3202 );
3203 let stream = out.stdout;
3204 let before = decode::palette_uv_hits();
3205 let frames = match decode_stream(&stream) {
3206 Ok(frames) => frames,
3207 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
3208 };
3209 assert!(
3210 decode::palette_uv_hits() > before,
3211 "palette_uv_mode never fired decoding this stream -- gate is vacuous"
3212 );
3213 let frame_count = frames.len();
3214 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, frame_count);
3215 for i in 0..frame_count {
3216 assert_eq!(frames[i].y, ffmpeg_frames[i].y, "luma vs ffmpeg, frame {i}");
3217 assert_eq!(frames[i].u, ffmpeg_frames[i].u, "U vs ffmpeg, frame {i}");
3218 assert_eq!(frames[i].v, ffmpeg_frames[i].v, "V vs ffmpeg, frame {i}");
3219 }
3220 }
3221
3222 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s
3223 /// harness, but with the deblocking filter left *on* (no
3224 /// `--loopfilter-control=0`) at a crf high enough that libaom actually
3225 /// picks a nonzero level -- proves `apply_deblock` itself, not just that
3226 /// this decoder still works when every edge lands on level 0. CDEF
3227 /// stays off so a pixel mismatch can only come from the loop filter.
3228 #[test]
3229 fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() {
3230 if !have_ffmpeg() {
3231 eprintln!(
3232 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no ffmpeg"
3233 );
3234 return;
3235 }
3236 if !have_aomenc() {
3237 eprintln!(
3238 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no aomenc at {}",
3239 aomenc_path().display()
3240 );
3241 return;
3242 }
3243 let (width, height) = (64usize, 64usize);
3244 let source = gradients_source(42, width, height, "duration=0.04:rate=25");
3245 let y4m = Command::new("ffmpeg")
3246 .args(["-v", "error", "-f", "lavfi", "-i"])
3247 .arg(&source)
3248 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
3249 .stdin(Stdio::null())
3250 .stdout(Stdio::piped())
3251 .stderr(Stdio::piped())
3252 .output()
3253 .expect("ffmpeg failed to run");
3254 assert!(
3255 y4m.status.success(),
3256 "ffmpeg fixture: {}",
3257 String::from_utf8_lossy(&y4m.stderr)
3258 );
3259 let mut child = Command::new(aomenc_path())
3260 .args([
3261 "--codec=av1",
3262 "--passes=1",
3263 "--end-usage=q",
3264 "--cq-level=55",
3265 "--cpu-used=0",
3266 "--enable-filter-intra=0",
3267 "--enable-smooth-intra=0",
3268 "--enable-paeth-intra=0",
3269 "--enable-directional-intra=0",
3270 "--enable-angle-delta=0",
3271 "--enable-tx-size-search=0",
3272 "--enable-cdef=0",
3273 // Loop restoration is a named refusal (aomenc's RD picks
3274 // Sgrproj on this kind of content) -- off in every recipe
3275 // whose test targets a different surface.
3276 "--enable-restoration=0",
3277 "--max-partition-size=32",
3278 "--enable-palette=0",
3279 "--enable-intrabc=0",
3280 "--enable-cfl-intra=0",
3281 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
3282 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
3283 "--enable-ref-frame-mvs=0",
3284 "--obu",
3285 "-o",
3286 "-",
3287 "-",
3288 ])
3289 .stdin(Stdio::piped())
3290 .stdout(Stdio::piped())
3291 .stderr(Stdio::piped())
3292 .spawn()
3293 .expect("aomenc failed to start");
3294 child
3295 .stdin
3296 .take()
3297 .expect("aomenc stdin")
3298 .write_all(&y4m.stdout)
3299 .expect("writing y4m to aomenc");
3300 let out = child.wait_with_output().expect("aomenc failed to run");
3301 assert!(
3302 out.status.success(),
3303 "aomenc refused the fixture: {}",
3304 String::from_utf8_lossy(&out.stderr)
3305 );
3306 let stream = out.stdout;
3307 let before = decode::deblock_hits();
3308 let frames = match decode_stream(&stream) {
3309 Ok(frames) => frames,
3310 Err(e) => {
3311 eprintln!(
3312 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: {e}"
3313 );
3314 return;
3315 }
3316 };
3317 assert!(
3318 decode::deblock_hits() > before,
3319 "no deblocking edge fired decoding this stream -- raise cq-level"
3320 );
3321 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3322 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
3323 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
3324 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
3325 }
3326
3327 /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`],
3328 /// but WITHOUT `--enable-tx-size-search=0` -- the one flag every other
3329 /// recipe in this file pins off specifically to keep the stream on
3330 /// `TxMode::Largest`. Dropped, aomenc's RD is free to pick
3331 /// `TxMode::Select` and split some blocks' luma transform below their own
3332 /// side (spec 5.11.16), which is what this test's `tx_depth_hits()`
3333 /// counter proves actually happened -- a stream that resolves every
3334 /// `tx_depth` to 0 would pixel-match by construction (identical to
3335 /// `TxMode::Largest`) without exercising the new split-TU decode path at
3336 /// all. Same multi-seed retry shape as
3337 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]:
3338 /// aomenc's own RD is free (with tx-size search on) to also occasionally
3339 /// pick `allow_screen_content_tools` on this content, a separate,
3340 /// already-named refusal -- try several seeds, and the first stream that
3341 /// both decodes AND actually split a transform must be pixel-exact.
3342 #[test]
3343 fn a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact() {
3344 if !have_ffmpeg() {
3345 eprintln!(
3346 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no ffmpeg"
3347 );
3348 return;
3349 }
3350 if !have_aomenc() {
3351 eprintln!(
3352 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no aomenc at {}",
3353 aomenc_path().display()
3354 );
3355 return;
3356 }
3357 let (width, height) = (64usize, 64usize);
3358 let mut refusals = Vec::new();
3359 let mut uncounted_exact = 0u32;
3360 for attempt in 0..40u32 {
3361 let seed = 42 + attempt;
3362 // A flat gradient never has enough local detail for the RD
3363 // search to prefer a split transform over the block's own full
3364 // size -- `mandelbrot`'s fractal boundary gives every attempt
3365 // (a different `start_scale`) sharp, varied-frequency edges.
3366 // start_scale 5.0 is the proven first try (decodes pixel-exact
3367 // AND reads the seven-symbol set-1 tx_type rows on TX8 TUs);
3368 // later attempts walk down for variety when aomenc's RD flips
3369 // elsewhere.
3370 let source = format!(
3371 "mandelbrot=size=64x64:start_scale={}:rate=25",
3372 5.0 - f64::from(attempt) * 0.06
3373 );
3374 let y4m = Command::new("ffmpeg")
3375 .args([
3376 "-v",
3377 "error",
3378 "-f",
3379 "lavfi",
3380 "-i",
3381 &source,
3382 // Desaturated: chroma stays flat (constant 128) so
3383 // `uv_mode` always resolves to `DC_PRED` and this
3384 // decoder's still-unsupported directional-chroma round-2
3385 // gap never fires, leaving the luma detail alone to
3386 // drive whether `TxMode::Select`'s RD splits a block.
3387 "-vf",
3388 "hue=s=0",
3389 "-pix_fmt",
3390 "yuv420p",
3391 "-t",
3392 "0.04",
3393 "-f",
3394 "yuv4mpegpipe",
3395 "-",
3396 ])
3397 .stdin(Stdio::null())
3398 .stdout(Stdio::piped())
3399 .stderr(Stdio::piped())
3400 .output()
3401 .expect("ffmpeg failed to run");
3402 assert!(
3403 y4m.status.success(),
3404 "ffmpeg fixture: {}",
3405 String::from_utf8_lossy(&y4m.stderr)
3406 );
3407 let mut child = Command::new(aomenc_path())
3408 .args([
3409 "--codec=av1",
3410 "--passes=1",
3411 "--end-usage=q",
3412 "--cq-level=45",
3413 "--cpu-used=0",
3414 "--enable-rect-partitions=0",
3415 "--enable-ab-partitions=0",
3416 "--enable-1to4-partitions=0",
3417 "--enable-filter-intra=0",
3418 // Every non-DC intra tool off: directional chroma and
3419 // angle deltas are separate round-2 gaps, and DC-only
3420 // residual is exactly what gives the RD search a reason
3421 // to split a transform.
3422 "--enable-smooth-intra=0",
3423 "--enable-paeth-intra=0",
3424 "--enable-directional-intra=0",
3425 "--enable-angle-delta=0",
3426 "--enable-cdef=0",
3427 // Loop restoration is a named refusal (aomenc's RD picks
3428 // Sgrproj on this kind of content) -- off in every recipe
3429 // whose test targets a different surface.
3430 "--enable-restoration=0",
3431 "--max-partition-size=32",
3432 // 16x16 blocks are what split into the TX8 TUs whose
3433 // set-1 tx_type rows this gate exists to prove; some
3434 // scales resolve depth 2 (TX4, a named refusal) and the
3435 // attempt loop just moves on.
3436 "--min-partition-size=16",
3437 "--enable-palette=0",
3438 "--enable-intrabc=0",
3439 "--enable-cfl-intra=0",
3440 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
3441 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
3442 "--enable-ref-frame-mvs=0",
3443 "--obu",
3444 "-o",
3445 "-",
3446 "-",
3447 ])
3448 .stdin(Stdio::piped())
3449 .stdout(Stdio::piped())
3450 .stderr(Stdio::piped())
3451 .spawn()
3452 .expect("aomenc failed to start");
3453 child
3454 .stdin
3455 .take()
3456 .expect("aomenc stdin")
3457 .write_all(&y4m.stdout)
3458 .expect("writing y4m to aomenc");
3459 let out = child.wait_with_output().expect("aomenc failed to run");
3460 assert!(
3461 out.status.success(),
3462 "aomenc refused the fixture: {}",
3463 String::from_utf8_lossy(&out.stderr)
3464 );
3465 let stream = out.stdout;
3466 let before = decode::tx_depth_hits();
3467 let frames = match decode_stream(&stream) {
3468 Ok(frames) => frames,
3469 Err(e) => {
3470 refusals.push(format!("seed {seed}: {e}"));
3471 continue;
3472 }
3473 };
3474 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
3475 // is ALWAYS pixel-compared below; the hit counter only decides whether
3476 // the attempt counts toward the firing total.
3477 let counted = decode::tx_depth_hits() != before;
3478 if !counted {
3479 uncounted_exact += 1;
3480 refusals.push(format!(
3481 "seed {seed}: decoded and pixel-compared, but no block resolved a split \
3482 tx_depth"
3483 ));
3484 }
3485 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3486 assert_eq!(
3487 frames[0].y, ffmpeg_frames[0].y,
3488 "luma vs ffmpeg (seed {seed})"
3489 );
3490 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
3491 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
3492 if counted {
3493 gate_buckets(
3494 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
3495 1,
3496 uncounted_exact,
3497 refusals.len() - uncounted_exact as usize,
3498 );
3499 return;
3500 }
3501 }
3502 gate_buckets(
3503 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
3504 0,
3505 uncounted_exact,
3506 refusals.len() - uncounted_exact as usize,
3507 );
3508 eprintln!(
3509 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: every attempt \
3510 hit a named refusal or never split a transform:\n{}",
3511 refusals.join("\n")
3512 );
3513 }
3514
3515 /// lane-txselect's decisive gate: a real aomenc INTER sequence WITHOUT
3516 /// `--enable-tx-size-search=0`, the flag every other inter recipe in this
3517 /// file pins off precisely to keep the stream on `TxMode::Largest`.
3518 /// Dropped, aomenc takes its own default (`TX_MODE_SELECT` -- which is
3519 /// what both of the user's real films use), and an inter block's
3520 /// transform size is then the recursive `txfm_split` tree of spec
3521 /// 5.11.17 rather than one whole-block transform. A stream that decoded
3522 /// pixel-exact while every `txfm_split` symbol resolved to "no split"
3523 /// would prove nothing (it is `TxMode::Largest` by another name), so this
3524 /// gate hard-asserts BOTH counters: at least one `txfm_split` symbol read
3525 /// AND at least one split actually taken. Exhausting every attempt is a
3526 /// FAILURE, not a SKIP -- an unfired gate is a vacuous gate.
3527 #[test]
3528 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact() {
3529 tx_select_inter_gate(8);
3530 }
3531
3532 /// The 10-bit arm of the gate above (lane-txselect r2): both of the
3533 /// user's films are `yuv420p10le` and var-tx is exactly the tool they
3534 /// use, so an 8-bit-only proof would not reach them. Same recipe plus
3535 /// `-b 10 --input-bit-depth=10`.
3536 #[test]
3537 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact_10bit() {
3538 tx_select_inter_gate(10);
3539 }
3540
3541 fn tx_select_inter_gate(bit_depth: u32) {
3542 if !have_ffmpeg() {
3543 eprintln!(
3544 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no ffmpeg"
3545 );
3546 return;
3547 }
3548 if !have_aomenc() {
3549 eprintln!(
3550 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no aomenc at {}",
3551 aomenc_path().display()
3552 );
3553 return;
3554 }
3555 let (width, height, frame_count) = (64usize, 64usize, 4usize);
3556 let mut refusals = Vec::new();
3557 let mut uncounted_exact = 0u32;
3558 for attempt in 0..40u32 {
3559 let seed = 42 + attempt;
3560 // Detail is what makes aomenc's RD prefer a split transform; a
3561 // flat gradient resolves every `txfm_split` to 0. `mandelbrot`'s
3562 // fractal boundary is the same source the sibling intra tx-select
3563 // gate uses, at a different `start_scale` per attempt.
3564 let source = format!(
3565 "mandelbrot=size=64x64:start_scale={}:rate=25",
3566 5.0 - f64::from(attempt) * 0.06
3567 );
3568 let y4m = Command::new("ffmpeg")
3569 .args([
3570 "-v",
3571 "error",
3572 "-f",
3573 "lavfi",
3574 "-i",
3575 &source,
3576 // Desaturated chroma: `uv_mode` stays DC_PRED, so the
3577 // still-refused directional-chroma gap never fires and
3578 // luma detail alone drives the transform split.
3579 "-vf",
3580 "hue=s=0",
3581 "-pix_fmt",
3582 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
3583 // y4m carries no official 10-bit tag; ffmpeg writes one
3584 // only under `-strict -1` (a no-op at 8 bit).
3585 "-strict",
3586 "-1",
3587 "-t",
3588 "0.16",
3589 "-f",
3590 "yuv4mpegpipe",
3591 "-strict",
3592 "-1",
3593 "-",
3594 ])
3595 .stdin(Stdio::null())
3596 .stdout(Stdio::piped())
3597 .stderr(Stdio::piped())
3598 .output()
3599 .expect("ffmpeg failed to run");
3600 assert!(
3601 y4m.status.success(),
3602 "ffmpeg fixture: {}",
3603 String::from_utf8_lossy(&y4m.stderr)
3604 );
3605 let depth_args: &[&str] = if bit_depth == 10 {
3606 &["-b", "10", "--input-bit-depth=10"]
3607 } else {
3608 &[]
3609 };
3610 let mut child = Command::new(aomenc_path())
3611 .args(depth_args)
3612 .args([
3613 "--codec=av1",
3614 "--passes=1",
3615 "--end-usage=q",
3616 "--cq-level=55",
3617 "--cpu-used=0",
3618 "--lag-in-frames=0",
3619 "--auto-alt-ref=0",
3620 "--kf-max-dist=1000",
3621 "--threads=1",
3622 "--row-mt=0",
3623 "--enable-order-hint=0",
3624 "--enable-warped-motion=0",
3625 "--enable-obmc=0",
3626 "--enable-masked-comp=0",
3627 "--enable-interintra-comp=0",
3628 "--enable-dist-wtd-comp=0",
3629 "--enable-diff-wtd-comp=0",
3630 "--enable-onesided-comp=0",
3631 "--enable-interintra-wedge=0",
3632 "--enable-smooth-interintra=0",
3633 "--enable-rect-partitions=0",
3634 "--enable-ab-partitions=0",
3635 "--enable-1to4-partitions=0",
3636 "--enable-filter-intra=0",
3637 "--enable-smooth-intra=0",
3638 "--enable-paeth-intra=0",
3639 "--enable-directional-intra=0",
3640 "--enable-angle-delta=0",
3641 // DELIBERATELY ABSENT: --enable-tx-size-search=0.
3642 "--enable-cdef=0",
3643 "--enable-restoration=0",
3644 "--max-partition-size=32",
3645 // Sub-16 inter partitions are a separate named refusal
3646 // (this decoder codes no inter block below 16x16 through
3647 // the square path this gate drives), and detailed content
3648 // makes aomenc's RD reach for them on nearly every seed.
3649 "--min-partition-size=16",
3650 "--enable-palette=0",
3651 "--enable-intrabc=0",
3652 "--enable-cfl-intra=0",
3653 "--enable-ref-frame-mvs=0",
3654 "--obu",
3655 "-o",
3656 "-",
3657 "-",
3658 ])
3659 .stdin(Stdio::piped())
3660 .stdout(Stdio::piped())
3661 .stderr(Stdio::piped())
3662 .spawn()
3663 .expect("aomenc failed to start");
3664 child
3665 .stdin
3666 .take()
3667 .expect("aomenc stdin")
3668 .write_all(&y4m.stdout)
3669 .expect("writing y4m to aomenc");
3670 let out = child.wait_with_output().expect("aomenc failed to run");
3671 assert!(
3672 out.status.success(),
3673 "aomenc refused the fixture: {}",
3674 String::from_utf8_lossy(&out.stderr)
3675 );
3676 let stream = out.stdout;
3677 let (reads_before, hits_before) =
3678 (decode::txfm_split_reads(), decode::txfm_split_hits());
3679 let frames = match decode_stream(&stream) {
3680 Ok(frames) => frames,
3681 Err(e) => {
3682 let msg = e.to_string();
3683 assert!(
3684 msg.contains("unsupported"),
3685 "tx-select inter decode failed outright (seed {seed}): {msg}"
3686 );
3687 refusals.push(format!("seed {seed}: {msg}"));
3688 continue;
3689 }
3690 };
3691 let (reads, hits) = (
3692 decode::txfm_split_reads() - reads_before,
3693 decode::txfm_split_hits() - hits_before,
3694 );
3695 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
3696 // is ALWAYS pixel-compared below; the hit counter only decides whether
3697 // the attempt counts toward the firing total.
3698 let counted = hits != 0;
3699 if !counted {
3700 uncounted_exact += 1;
3701 refusals.push(format!(
3702 "seed {seed}: decoded and pixel-compared, but no block took a txfm_split \
3703 ({reads} symbols read)"
3704 ));
3705 }
3706 let ffmpeg_frames = if bit_depth == 10 {
3707 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
3708 } else {
3709 ffmpeg_decode_sequence(&stream, width, height, frame_count)
3710 };
3711 assert_eq!(frames.len(), frame_count);
3712 eprintln!(
3713 "txselect gate {bit_depth}-bit seed={seed}: txfm_split reads={reads} splits taken={hits}"
3714 );
3715 // Name the first differing sample before the assert fires: a
3716 // 64x64 plane's `assert_eq!` output is 4096 numbers, useless for
3717 // locating a desync.
3718 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3719 for (plane, (g, w)) in [
3720 ("Y", (&got.y, &want.y)),
3721 ("U", (&got.u, &want.u)),
3722 ("V", (&got.v, &want.v)),
3723 ] {
3724 let stride = if plane == "Y" { width } else { width / 2 };
3725 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
3726 eprintln!(
3727 "txselect gate seed={seed}: frame {i} {plane} first diff at \
3728 ({}, {}) got {} want {} ({} samples differ)",
3729 at % stride,
3730 at / stride,
3731 g[at],
3732 w[at],
3733 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
3734 );
3735 let coords: Vec<String> = g
3736 .iter()
3737 .zip(w.iter())
3738 .enumerate()
3739 .filter(|(_, (a, b))| a != b)
3740 .take(12)
3741 .map(|(k, (a, b))| format!("({},{})={a}/{b}", k % stride, k / stride))
3742 .collect();
3743 eprintln!("txselect gate seed={seed}: frame {i} {plane} diffs {coords:?}");
3744 }
3745 }
3746 }
3747 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3748 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
3749 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
3750 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
3751 }
3752 if counted {
3753 gate_buckets(
3754 &format!("tx_select_inter_gate({bit_depth})"),
3755 1,
3756 uncounted_exact,
3757 refusals.len() - uncounted_exact as usize,
3758 );
3759 return;
3760 }
3761 }
3762 gate_buckets(
3763 &format!("tx_select_inter_gate({bit_depth})"),
3764 0,
3765 uncounted_exact,
3766 refusals.len() - uncounted_exact as usize,
3767 );
3768 panic!(
3769 "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}",
3770 refusals.join("\n")
3771 );
3772 }
3773
3774 /// lane-chroma r2 stage 1: a real aomenc key frame with
3775 /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`)
3776 /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still-
3777 /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never
3778 /// fires; smooth *luma* neighbours are exactly what this gate wants to
3779 /// exercise, proving [`decode::smooth_luma_hits`] actually landed a
3780 /// directional block next to a smooth-predicted one and decoded
3781 /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix).
3782 #[test]
3783 fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() {
3784 if !have_ffmpeg() {
3785 eprintln!(
3786 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg"
3787 );
3788 return;
3789 }
3790 if !have_aomenc() {
3791 eprintln!(
3792 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}",
3793 aomenc_path().display()
3794 );
3795 return;
3796 }
3797 let (width, height) = (64usize, 64usize);
3798 let mut refusals = Vec::new();
3799 let mut fired_runs = 0u32;
3800 let mut uncounted_exact = 0u32;
3801 for attempt in 0..40u32 {
3802 let seed = 42 + attempt;
3803 let source = format!(
3804 "mandelbrot=size=64x64:start_scale={}:rate=25",
3805 5.0 - f64::from(attempt) * 0.06
3806 );
3807 let y4m = Command::new("ffmpeg")
3808 .args([
3809 "-v",
3810 "error",
3811 "-f",
3812 "lavfi",
3813 "-i",
3814 &source,
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 "--enable-smooth-intra=1",
3845 // Smooth/paeth chroma is a still-refused, separate
3846 // round-2 gap -- off so no attempt trips it while this
3847 // gate is purely about luma's edge-filter fix.
3848 "--enable-paeth-intra=0",
3849 "--enable-tx-size-search=0",
3850 "--enable-cdef=0",
3851 "--enable-restoration=0",
3852 "--enable-intra-edge-filter=1",
3853 "--max-partition-size=32",
3854 "--min-partition-size=16",
3855 "--enable-palette=0",
3856 "--enable-intrabc=0",
3857 "--enable-cfl-intra=0",
3858 "--enable-ref-frame-mvs=0",
3859 "--obu",
3860 "-o",
3861 "-",
3862 "-",
3863 ])
3864 .stdin(Stdio::piped())
3865 .stdout(Stdio::piped())
3866 .stderr(Stdio::piped())
3867 .spawn()
3868 .expect("aomenc failed to start");
3869 child
3870 .stdin
3871 .take()
3872 .expect("aomenc stdin")
3873 .write_all(&y4m.stdout)
3874 .expect("writing y4m to aomenc");
3875 let out = child.wait_with_output().expect("aomenc failed to run");
3876 assert!(
3877 out.status.success(),
3878 "aomenc refused the fixture: {}",
3879 String::from_utf8_lossy(&out.stderr)
3880 );
3881 let stream = out.stdout;
3882 let smooth_before = decode::smooth_luma_hits();
3883 let frames = match decode_stream(&stream) {
3884 Ok(frames) => frames,
3885 Err(e) => {
3886 refusals.push(format!("seed {seed}: {e}"));
3887 continue;
3888 }
3889 };
3890 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
3891 // is ALWAYS pixel-compared below; the hit counter only decides whether
3892 // the attempt counts toward the firing total.
3893 let counted = decode::smooth_luma_hits() != smooth_before;
3894 if counted {
3895 fired_runs += 1;
3896 } else {
3897 uncounted_exact += 1;
3898 refusals.push(format!(
3899 "seed {seed}: decoded and pixel-compared, but no smooth-luma-neighbour block \
3900 fired"
3901 ));
3902 }
3903 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3904 assert_eq!(
3905 frames[0].y, ffmpeg_frames[0].y,
3906 "luma vs ffmpeg (seed {seed})"
3907 );
3908 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
3909 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
3910 if fired_runs >= 4 {
3911 gate_buckets(
3912 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
3913 fired_runs,
3914 uncounted_exact,
3915 refusals.len() - uncounted_exact as usize,
3916 );
3917 return;
3918 }
3919 }
3920 gate_buckets(
3921 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
3922 fired_runs,
3923 uncounted_exact,
3924 refusals.len() - uncounted_exact as usize,
3925 );
3926 assert!(
3927 fired_runs > 0,
3928 "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}",
3929 refusals.join("\n")
3930 );
3931 }
3932
3933 /// The smooth/paeth-chroma gate (lane-chroma r1/r3): a real aomenc key
3934 /// frame with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the
3935 /// opposite of the directional-chroma gate below, which turns these OFF
3936 /// to keep this gap from firing while directional chroma is under test).
3937 /// Some seeds won't pick smooth/paeth for chroma at all -- retry like
3938 /// every other real-encoder gate here, but the first attempt that
3939 /// actually fires [`decode::smooth_uv_hits`] must decode pixel-exact.
3940 #[test]
3941 fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() {
3942 if !have_ffmpeg() {
3943 eprintln!(
3944 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg"
3945 );
3946 return;
3947 }
3948 if !have_aomenc() {
3949 eprintln!(
3950 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}",
3951 aomenc_path().display()
3952 );
3953 return;
3954 }
3955 let (width, height) = (64usize, 64usize);
3956 let mut refusals = Vec::new();
3957 let mut fired_runs = 0u32;
3958 let mut uncounted_exact = 0u32;
3959 for attempt in 0..40u32 {
3960 let seed = 42 + attempt;
3961 let source = format!(
3962 "mandelbrot=size=64x64:start_scale={}:rate=25",
3963 5.0 - f64::from(attempt) * 0.06
3964 );
3965 let y4m = Command::new("ffmpeg")
3966 .args([
3967 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-t",
3968 "0.04", "-f", "yuv4mpegpipe", "-",
3969 ])
3970 .stdin(Stdio::null())
3971 .stdout(Stdio::piped())
3972 .stderr(Stdio::piped())
3973 .output()
3974 .expect("ffmpeg failed to run");
3975 assert!(
3976 y4m.status.success(),
3977 "ffmpeg fixture: {}",
3978 String::from_utf8_lossy(&y4m.stderr)
3979 );
3980 let mut child = Command::new(aomenc_path())
3981 .args([
3982 "--codec=av1",
3983 "--passes=1",
3984 "--end-usage=q",
3985 "--cq-level=45",
3986 "--cpu-used=0",
3987 "--enable-rect-partitions=0",
3988 "--enable-ab-partitions=0",
3989 "--enable-1to4-partitions=0",
3990 "--enable-filter-intra=0",
3991 "--enable-smooth-intra=1",
3992 "--enable-paeth-intra=1",
3993 "--enable-tx-size-search=0",
3994 "--enable-cdef=0",
3995 "--enable-restoration=0",
3996 "--enable-intra-edge-filter=1",
3997 "--max-partition-size=32",
3998 // 8x8/leaf8 splits are a separate, already-named refusal.
3999 "--min-partition-size=16",
4000 "--enable-palette=0",
4001 "--enable-intrabc=0",
4002 "--enable-cfl-intra=0",
4003 "--enable-ref-frame-mvs=0",
4004 "--obu",
4005 "-o",
4006 "-",
4007 "-",
4008 ])
4009 .stdin(Stdio::piped())
4010 .stdout(Stdio::piped())
4011 .stderr(Stdio::piped())
4012 .spawn()
4013 .expect("aomenc failed to start");
4014 child
4015 .stdin
4016 .take()
4017 .expect("aomenc stdin")
4018 .write_all(&y4m.stdout)
4019 .expect("writing y4m to aomenc");
4020 let out = child.wait_with_output().expect("aomenc failed to run");
4021 assert!(
4022 out.status.success(),
4023 "aomenc refused the fixture: {}",
4024 String::from_utf8_lossy(&out.stderr)
4025 );
4026 let stream = out.stdout;
4027 let smooth_before = decode::smooth_uv_hits();
4028 let frames = match decode_stream(&stream) {
4029 Ok(frames) => frames,
4030 Err(e) => {
4031 refusals.push(format!("seed {seed}: {e}"));
4032 continue;
4033 }
4034 };
4035 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
4036 // is ALWAYS pixel-compared below; the hit counter only decides whether
4037 // the attempt counts toward the firing total.
4038 let counted = decode::smooth_uv_hits() != smooth_before;
4039 if counted {
4040 fired_runs += 1;
4041 } else {
4042 uncounted_exact += 1;
4043 refusals.push(format!(
4044 "seed {seed}: decoded and pixel-compared, but no smooth/paeth uv_mode fired"
4045 ));
4046 }
4047 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4048 assert_eq!(
4049 frames[0].y, ffmpeg_frames[0].y,
4050 "luma vs ffmpeg (seed {seed})"
4051 );
4052 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
4053 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
4054 if fired_runs >= 4 {
4055 gate_buckets(
4056 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
4057 fired_runs,
4058 uncounted_exact,
4059 refusals.len() - uncounted_exact as usize,
4060 );
4061 return;
4062 }
4063 }
4064 gate_buckets(
4065 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
4066 fired_runs,
4067 uncounted_exact,
4068 refusals.len() - uncounted_exact as usize,
4069 );
4070 assert!(
4071 fired_runs > 0,
4072 "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}",
4073 refusals.join("\n")
4074 );
4075 }
4076
4077 /// The directional-chroma/angle-delta gate: a real aomenc key frame with
4078 /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the
4079 /// opposite of every sibling recipe's `=0`, which existed specifically to
4080 /// keep this round-2 gap from firing while a different surface was under
4081 /// test). A colourful, sharp-edged source gives the RD search a reason to
4082 /// pick a directional `uv_mode` and/or a nonzero angle delta -- some
4083 /// seeds still won't, so retry like every other real-encoder gate here,
4084 /// but the first attempt that actually fires either counter must decode
4085 /// pixel-exact.
4086 #[test]
4087 fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() {
4088 if !have_ffmpeg() {
4089 eprintln!(
4090 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg"
4091 );
4092 return;
4093 }
4094 if !have_aomenc() {
4095 eprintln!(
4096 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}",
4097 aomenc_path().display()
4098 );
4099 return;
4100 }
4101 let (width, height) = (64usize, 64usize);
4102 let mut refusals = Vec::new();
4103 let mut fired_runs = 0u32;
4104 let mut uncounted_exact = 0u32;
4105 for attempt in 0..40u32 {
4106 let seed = 42 + attempt;
4107 let source = format!(
4108 "mandelbrot=size=64x64:start_scale={}:rate=25",
4109 5.0 - f64::from(attempt) * 0.06
4110 );
4111 let y4m = Command::new("ffmpeg")
4112 .args([
4113 "-v",
4114 "error",
4115 "-f",
4116 "lavfi",
4117 "-i",
4118 &source,
4119 "-pix_fmt",
4120 "yuv420p",
4121 "-t",
4122 "0.04",
4123 "-f",
4124 "yuv4mpegpipe",
4125 "-",
4126 ])
4127 .stdin(Stdio::null())
4128 .stdout(Stdio::piped())
4129 .stderr(Stdio::piped())
4130 .output()
4131 .expect("ffmpeg failed to run");
4132 assert!(
4133 y4m.status.success(),
4134 "ffmpeg fixture: {}",
4135 String::from_utf8_lossy(&y4m.stderr)
4136 );
4137 let mut child = Command::new(aomenc_path())
4138 .args([
4139 "--codec=av1",
4140 "--passes=1",
4141 "--end-usage=q",
4142 "--cq-level=45",
4143 "--cpu-used=0",
4144 "--enable-rect-partitions=0",
4145 "--enable-ab-partitions=0",
4146 "--enable-1to4-partitions=0",
4147 "--enable-filter-intra=0",
4148 // Smooth/Paeth chroma is a separate, still-refused round-2
4149 // gap (an unrelated `Edges::build` no-neighbour bug this
4150 // lane does not cover) -- off so the RD search's only
4151 // non-DC/CFL chroma choice left is directional.
4152 "--enable-smooth-intra=0",
4153 "--enable-paeth-intra=0",
4154 "--enable-tx-size-search=0",
4155 "--enable-cdef=0",
4156 "--enable-restoration=0",
4157 // The intra edge filter/upsample (spec 7.11.2.7-2.9) is
4158 // now implemented (`directional()`) -- left ON (aomenc's
4159 // own default) so this gate actually exercises it instead
4160 // of the un-filtered fast path a disabled flag would keep
4161 // testing.
4162 "--enable-intra-edge-filter=1",
4163 "--max-partition-size=32",
4164 // Same reason as the tx-select gate above: 8x8 and other
4165 // sub-16x16 splits are a separate, already-named refusal.
4166 "--min-partition-size=16",
4167 "--enable-palette=0",
4168 "--enable-intrabc=0",
4169 "--enable-cfl-intra=0",
4170 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
4171 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
4172 "--enable-ref-frame-mvs=0",
4173 "--obu",
4174 "-o",
4175 "-",
4176 "-",
4177 ])
4178 .stdin(Stdio::piped())
4179 .stdout(Stdio::piped())
4180 .stderr(Stdio::piped())
4181 .spawn()
4182 .expect("aomenc failed to start");
4183 child
4184 .stdin
4185 .take()
4186 .expect("aomenc stdin")
4187 .write_all(&y4m.stdout)
4188 .expect("writing y4m to aomenc");
4189 let out = child.wait_with_output().expect("aomenc failed to run");
4190 assert!(
4191 out.status.success(),
4192 "aomenc refused the fixture: {}",
4193 String::from_utf8_lossy(&out.stderr)
4194 );
4195 let stream = out.stdout;
4196 let (uv_before, angle_before) =
4197 (decode::directional_uv_hits(), decode::angle_delta_hits());
4198 let frames = match decode_stream(&stream) {
4199 Ok(frames) => frames,
4200 Err(e) => {
4201 refusals.push(format!("seed {seed}: {e}"));
4202 continue;
4203 }
4204 };
4205 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
4206 // is ALWAYS pixel-compared below; the hit counter only decides whether
4207 // the attempt counts toward the firing total.
4208 let counted = decode::directional_uv_hits() != uv_before
4209 || decode::angle_delta_hits() != angle_before;
4210 if counted {
4211 fired_runs += 1;
4212 } else {
4213 uncounted_exact += 1;
4214 refusals.push(format!(
4215 "seed {seed}: decoded and pixel-compared, but neither a directional uv_mode \
4216 nor a nonzero angle delta fired"
4217 ));
4218 }
4219 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4220 assert_eq!(
4221 frames[0].y, ffmpeg_frames[0].y,
4222 "luma vs ffmpeg (seed {seed})"
4223 );
4224 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
4225 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
4226 if fired_runs >= 4 {
4227 gate_buckets(
4228 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
4229 fired_runs,
4230 uncounted_exact,
4231 refusals.len() - uncounted_exact as usize,
4232 );
4233 return;
4234 }
4235 }
4236 gate_buckets(
4237 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
4238 fired_runs,
4239 uncounted_exact,
4240 refusals.len() - uncounted_exact as usize,
4241 );
4242 assert!(
4243 fired_runs > 0,
4244 "every attempt hit a named refusal or never exercised directional chroma:\n{}",
4245 refusals.join("\n")
4246 );
4247 }
4248
4249 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
4250 /// --auto-alt-ref=0` keep every non-key frame a simple forward
4251 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this
4252 /// decoder's inter path does not model), `--kf-max-dist` past the clip's
4253 /// own length keeps frame 0 the only key frame.
4254 /// lane-inter8 r1: the inter tile path's SB-level `PARTITION_NONE` -- a
4255 /// whole 64x64 superblock coded as ONE inter block, which is what aomenc
4256 /// picks for static content and which this decoder refused by name
4257 /// ("an inter SB-level partition type other than SPLIT") until this
4258 /// round. HARD-asserts [`decode::inter_sb_none_hits`] moved (the arm
4259 /// really fired, class refusal-lifted-without-a-gate) and every frame is
4260 /// pixel-exact vs ffmpeg; a decode error is a FAILURE here, never a SKIP
4261 /// (class gate-skips-on-its-own-failure).
4262 /// lane-inter8 r1: generalised so the same recipe can target a deeper
4263 /// level of the inter partition tree -- `min_part` is aomenc's
4264 /// `--min-partition-size`, and `hits`/`what` name the counter that proves
4265 /// the arm under test really fired.
4266 fn inter_sb_none_gate(
4267 name: &str,
4268 ten_bit: bool,
4269 min_part: &str,
4270 max_part: &str,
4271 hits: fn() -> usize,
4272 what: &str,
4273 // lane-inter8 r3: extra aomenc flags + the frame width they need.
4274 // `--tile-columns=1` needs a frame at least two superblocks wide or
4275 // aomenc silently codes one tile column and the arm is vacuous.
4276 extra: &[&str],
4277 width: usize,
4278 ) {
4279 if !have_ffmpeg() {
4280 eprintln!("SKIP {name}: no ffmpeg");
4281 return;
4282 }
4283 if !have_aomenc() {
4284 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
4285 return;
4286 }
4287 let (height, frame_count) = (64usize, 4usize);
4288 // A deterministic synthetic source with real motion (a static source
4289 // codes every inter frame as skip and never exercises the residual
4290 // path); bounded with `-t` (class gate-loader-slurps-whole-file).
4291 let y4m = Command::new("ffmpeg")
4292 .args([
4293 "-v",
4294 "error",
4295 "-f",
4296 "lavfi",
4297 "-i",
4298 &format!("mandelbrot=size={width}x{height}:rate=25"),
4299 "-t",
4300 "0.16",
4301 "-pix_fmt",
4302 if ten_bit { "yuv420p10le" } else { "yuv420p" },
4303 // y4m calls 10-bit unofficial (same as the 10-bit key-frame
4304 // gate's own fixture).
4305 "-strict",
4306 "-1",
4307 "-f",
4308 "yuv4mpegpipe",
4309 "-",
4310 ])
4311 .stdin(Stdio::null())
4312 .stdout(Stdio::piped())
4313 .stderr(Stdio::piped())
4314 .output()
4315 .expect("ffmpeg failed to run");
4316 assert!(
4317 y4m.status.success(),
4318 "{name}: ffmpeg fixture: {}",
4319 String::from_utf8_lossy(&y4m.stderr)
4320 );
4321 let mut args: Vec<String> = [
4322 "--codec=av1",
4323 "--passes=1",
4324 "--end-usage=q",
4325 "--cq-level=40",
4326 "--cpu-used=0",
4327 "--lag-in-frames=0",
4328 "--auto-alt-ref=0",
4329 "--kf-max-dist=1000",
4330 // No cross-frame CDF forwarding in this fixture (see the
4331 // deblocking gate's own note).
4332 "--error-resilient=1",
4333 // This gate targets the SB-level NONE arm only: rect/AB/1-to-4
4334 // partitions and sub-16x16 splits stay off so a failure here
4335 // cannot be another lane's missing arm.
4336 "--enable-rect-partitions=0",
4337 "--enable-ab-partitions=0",
4338 "--enable-1to4-partitions=0",
4339 "--enable-filter-intra=0",
4340 "--enable-smooth-intra=0",
4341 "--enable-paeth-intra=0",
4342 "--enable-directional-intra=0",
4343 "--enable-angle-delta=0",
4344 "--enable-tx-size-search=0",
4345 "--enable-cdef=0",
4346 "--enable-restoration=0",
4347 "--enable-palette=0",
4348 "--enable-intrabc=0",
4349 "--enable-cfl-intra=0",
4350 "--enable-ref-frame-mvs=0",
4351 "--obu",
4352 "-o",
4353 "-",
4354 "-",
4355 ]
4356 .iter()
4357 .map(|s| (*s).to_string())
4358 .collect();
4359 for e in extra {
4360 args.insert(1, (*e).to_string());
4361 }
4362 args.insert(1, format!("--min-partition-size={min_part}"));
4363 args.insert(1, format!("--max-partition-size={max_part}"));
4364 if ten_bit {
4365 args.insert(1, "--input-bit-depth=10".to_string());
4366 args.insert(1, "--bit-depth=10".to_string());
4367 }
4368 let mut child = Command::new(aomenc_path())
4369 .args(&args)
4370 .stdin(Stdio::piped())
4371 .stdout(Stdio::piped())
4372 .stderr(Stdio::piped())
4373 .spawn()
4374 .expect("aomenc failed to start");
4375 child
4376 .stdin
4377 .take()
4378 .expect("aomenc stdin")
4379 .write_all(&y4m.stdout)
4380 .expect("writing y4m to aomenc");
4381 let out = child.wait_with_output().expect("aomenc failed to run");
4382 assert!(
4383 out.status.success(),
4384 "{name}: aomenc refused the fixture: {}",
4385 String::from_utf8_lossy(&out.stderr)
4386 );
4387 let stream = out.stdout;
4388 let before = hits();
4389 let frames = match decode_stream(&stream) {
4390 Ok(frames) => frames,
4391 Err(e) => {
4392 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
4393 let _ = std::fs::write(&pin, &stream);
4394 panic!("{name}: decode_stream refused a real aomenc stream: {e} (pinned at {})", pin.display());
4395 }
4396 };
4397 assert!(
4398 hits() > before,
4399 "{name}: no {what} fired -- this gate proves nothing"
4400 );
4401 let ffmpeg_frames = if ten_bit {
4402 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
4403 } else {
4404 ffmpeg_decode_sequence(&stream, width, height, frame_count)
4405 };
4406 assert_eq!(frames.len(), frame_count, "{name}: frame count");
4407 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4408 if got.y != want.y || got.u != want.u || got.v != want.v {
4409 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
4410 let _ = std::fs::write(&pin, &stream);
4411 panic!("{name}: frame {i} mismatch vs ffmpeg -- stream pinned at {}", pin.display());
4412 }
4413 }
4414 }
4415
4416 #[test]
4417 fn a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
4418 inter_sb_none_gate(
4419 "a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
4420 false,
4421 "32",
4422 "64",
4423 decode::inter_sb_none_hits,
4424 "whole-superblock inter PARTITION_NONE",
4425 &[],
4426 64,
4427 );
4428 }
4429
4430 #[test]
4431 fn a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
4432 inter_sb_none_gate(
4433 "a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
4434 true,
4435 "32",
4436 "64",
4437 decode::inter_sb_none_hits,
4438 "whole-superblock inter PARTITION_NONE",
4439 &[],
4440 64,
4441 );
4442 }
4443
4444 /// lane-inter8 r1: the same recipe with `--min-partition-size=8`, so
4445 /// aomenc's RD may split a 16x16 inter block into four 8x8 leaves. The
4446 /// interior (non-edge-straddling) `PARTITION_SPLIT` at the 16x16 level
4447 /// was refused by name until this round; the straddle path always ran the
4448 /// same loop, so only [`decode::inter_sub16_split_hits`] -- which counts
4449 /// interior splits only -- proves the newly-lifted alphabet value fired.
4450 // lane-inter8 r2: GREEN. The neighbour side bands are mi-granular, every
4451 // leaf stamps its own 2x2-mi span (including the compound-return path
4452 // that used to skip `record_mi` entirely) and the compound
4453 // group/index contexts read the LEAF's mi cell, not its 16x16's corner.
4454 /// lane-inter8 r3, from lane-sub8's verifier finding: the mi-granular
4455 /// inter neighbour bands added in r2 must reset per TILE (above) and per
4456 /// SB row (left) and guard availability tile-relative, so the same recipe
4457 /// runs again at 128x64 with two tile columns -- a leaf on the second
4458 /// tile's first column has no left neighbour and must not read the first
4459 /// tile's band.
4460 // lane-inter8 r3: RED for a reason OUTSIDE this lane -- at 128x64 (the
4461 // narrowest frame two tile columns can exist in) aomenc codes an
4462 // SB-level rect partition on the KEY frame despite
4463 // --enable-rect-partitions=0, so the stream stops at "a superblock-level
4464 // partition type other than NONE or SPLIT" (lane-sbpart's arm) before a
4465 // single 8x8 leaf is reached. The tile-relative audit it was written for
4466 // was done by inspection instead: every reader of the mi bands guards on
4467 // `tile_row0_mi`/`tile_col0_mi` (no `> 0` guard exists in decode.rs),
4468 // `start_tile` resets the above mi bands over the tile's own mi column
4469 // span and `start_row` resets every left mi band.
4470 #[ignore = "lane-inter8 r3: blocked by the SB-level rect-partition refusal at 128x64 (lane-sbpart's arm), not by tile context"]
4471 #[test]
4472 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact()
4473 {
4474 inter_sb_none_gate(
4475 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact",
4476 false,
4477 "8",
4478 "16",
4479 decode::inter_sub16_split_hits,
4480 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
4481 &["--tile-columns=1"],
4482 128,
4483 );
4484 }
4485
4486 #[test]
4487 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
4488 inter_sb_none_gate(
4489 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
4490 false,
4491 "8",
4492 "16",
4493 decode::inter_sub16_split_hits,
4494 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
4495 &[],
4496 64,
4497 );
4498 }
4499
4500 #[test]
4501 // lane-inter8 r2: still RED, and ignored rather than deleted -- the 8-bit
4502 // twin above is green, this 10-bit recipe stops at "an INTER 32x32
4503 // partition type this decoder does not code (value=9)". That is OUR
4504 // desync, proven: `EC_TRACE=1 aomdec` on the pinned stream reads
4505 // 16 `bsize=9 value=3` (SPLIT) partitions and never a single value=9
4506 // anywhere (class refusal-from-own-desync; the r1 ledger line claiming
4507 // aomenc emits PARTITION_VERT_4 despite --enable-1to4-partitions=0 is
4508 // hereby disproven). The divergence itself is not yet bisected.
4509 #[ignore = "lane-inter8 r2: 10-bit twin still desyncs (surfaces as a bogus 32x32 value=9 refusal); 8-bit gate is green"]
4510 fn a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
4511 inter_sb_none_gate(
4512 "a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
4513 true,
4514 "8",
4515 "16",
4516 decode::inter_sub16_split_hits,
4517 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
4518 &[],
4519 64,
4520 );
4521 }
4522
4523 #[test]
4524 fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() {
4525 if !have_ffmpeg() {
4526 eprintln!(
4527 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no ffmpeg"
4528 );
4529 return;
4530 }
4531 if !have_aomenc() {
4532 eprintln!(
4533 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no aomenc at {}",
4534 aomenc_path().display()
4535 );
4536 return;
4537 }
4538 let (width, height, frame_count) = (64usize, 64usize, 4usize);
4539 let source = gradients_source(42, width, height, "duration=0.16:rate=25");
4540 let y4m = Command::new("ffmpeg")
4541 .args(["-v", "error", "-f", "lavfi", "-i"])
4542 .arg(&source)
4543 .args([
4544 "-pix_fmt",
4545 "yuv420p",
4546 "-f",
4547 "yuv4mpegpipe",
4548 "-",
4549 ])
4550 .stdin(Stdio::null())
4551 .stdout(Stdio::piped())
4552 .stderr(Stdio::piped())
4553 .output()
4554 .expect("ffmpeg failed to run");
4555 assert!(
4556 y4m.status.success(),
4557 "ffmpeg fixture: {}",
4558 String::from_utf8_lossy(&y4m.stderr)
4559 );
4560 let mut child = Command::new(aomenc_path())
4561 .args([
4562 "--codec=av1",
4563 "--passes=1",
4564 "--end-usage=q",
4565 "--cq-level=55",
4566 "--cpu-used=0",
4567 "--lag-in-frames=0",
4568 "--auto-alt-ref=0",
4569 "--kf-max-dist=1000",
4570 // Forces `primary_ref_frame = PRIMARY_REF_NONE` on every
4571 // frame (spec 5.9.2): without it a real encoder's inter
4572 // frame loads its initial CDF state from the previous
4573 // frame's *adapted* tables (spec 7.20's `load_cdfs`), which
4574 // this decoder never does -- it always starts each frame's
4575 // `Cdfs` from the spec defaults (`decode.rs`'s
4576 // `Cdfs::new(q_ctx)`, called fresh per frame in
4577 // `decode_stream`). Without this flag the inter frame's
4578 // very first symbol desyncs immediately (traced 2026-08-27:
4579 // no coefficient trace at all before the tile's first
4580 // partition read comes back an out-of-alphabet value). A
4581 // real decoder needs cross-frame CDF forwarding to handle
4582 // that stream; this fixture sidesteps it the same way a
4583 // real broadcast/low-latency encode legitimately can.
4584 "--error-resilient=1",
4585 "--enable-rect-partitions=0",
4586 "--enable-ab-partitions=0",
4587 "--enable-1to4-partitions=0",
4588 "--enable-filter-intra=0",
4589 "--enable-smooth-intra=0",
4590 "--enable-paeth-intra=0",
4591 "--enable-directional-intra=0",
4592 "--enable-angle-delta=0",
4593 "--enable-tx-size-search=0",
4594 "--enable-cdef=0",
4595 // Loop restoration is a named refusal (aomenc's RD picks
4596 // Sgrproj on this kind of content) -- off in every recipe
4597 // whose test targets a different surface.
4598 "--enable-restoration=0",
4599 "--max-partition-size=32",
4600 "--enable-palette=0",
4601 "--enable-intrabc=0",
4602 "--enable-cfl-intra=0",
4603 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
4604 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
4605 "--enable-ref-frame-mvs=0",
4606 "--obu",
4607 "-o",
4608 "-",
4609 "-",
4610 ])
4611 .stdin(Stdio::piped())
4612 .stdout(Stdio::piped())
4613 .stderr(Stdio::piped())
4614 .spawn()
4615 .expect("aomenc failed to start");
4616 child
4617 .stdin
4618 .take()
4619 .expect("aomenc stdin")
4620 .write_all(&y4m.stdout)
4621 .expect("writing y4m to aomenc");
4622 let out = child.wait_with_output().expect("aomenc failed to run");
4623 assert!(
4624 out.status.success(),
4625 "aomenc refused the fixture: {}",
4626 String::from_utf8_lossy(&out.stderr)
4627 );
4628 let stream = out.stdout;
4629 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
4630 std::fs::write(dump, &stream).expect("dump stream");
4631 }
4632 let before = decode::deblock_hits();
4633 let frames = match decode_stream(&stream) {
4634 Ok(frames) => frames,
4635 Err(e) => {
4636 eprintln!(
4637 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: {e}"
4638 );
4639 return;
4640 }
4641 };
4642 assert!(
4643 decode::deblock_hits() > before,
4644 "no deblocking edge fired decoding this sequence -- raise cq-level"
4645 );
4646 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
4647 assert_eq!(frames.len(), frame_count);
4648 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4649 // gradients' colors ignore its seed, so this gate encodes fresh
4650 // content every run -- a mismatch here may never reproduce.
4651 // Self-pin the stream before panicking so the failure is
4652 // bisectable (replay: EC_AV1_PIN on scratch_isolate_pinned_mismatch).
4653 let ok = got.y == want.y && got.u == want.u && got.v == want.v;
4654 if !ok {
4655 let pin = std::env::temp_dir().join("ec-av1-deblocking-gate-fail.obu");
4656 let _ = std::fs::write(&pin, &stream);
4657 panic!("frame {i} mismatch vs ffmpeg -- stream pinned at {}", pin.display());
4658 }
4659 }
4660 }
4661
4662 /// The decisive cross-frame CDF forwarding test: identical to
4663 /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`]
4664 /// except it drops `--error-resilient=1`, so aomenc codes every inter
4665 /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`)
4666 /// and expects the decoder to resume from the previous frame's *adapted*
4667 /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding,
4668 /// frame 1's very first tile symbol desyncs (an out-of-alphabet
4669 /// partition read); with it, every frame decodes pixel-exact.
4670 #[test]
4671 fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() {
4672 if !have_ffmpeg() {
4673 eprintln!(
4674 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg"
4675 );
4676 return;
4677 }
4678 if !have_aomenc() {
4679 eprintln!(
4680 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}",
4681 aomenc_path().display()
4682 );
4683 return;
4684 }
4685 let (width, height, frame_count) = (64usize, 64usize, 4usize);
4686 // The fixture's content varies run to run (lavfi gradients ignores its
4687 // seed option for the c0..c7 colors -- they default to "random"), so:
4688 // most encodes of this recipe trip one of the decoder's NAMED round-2
4689 // refusals (a reference other than LAST_FRAME, a sub-16 partition --
4690 // genuine coverage gaps, separately documented), and only some produce
4691 // a stream fully inside this decoder's declared support. So: attempt
4692 // several seeds, and the first stream that DECODES must be pixel-exact
4693 // -- that assertion is what guards the forwarded-CDF state (a wrong
4694 // table decodes plausible-but-wrong pixels; the counter-reset bug this
4695 // gate caught did exactly that). Exhausting every attempt on named
4696 // refusals skips loudly, listing them.
4697 let mut refusals = Vec::new();
4698 for attempt in 0..8u32 {
4699 let seed = 42 + attempt;
4700 let source = gradients_source(seed, 64, 64, "duration=0.16:rate=25");
4701 let y4m = Command::new("ffmpeg")
4702 .args([
4703 "-v",
4704 "error",
4705 "-f",
4706 "lavfi",
4707 "-i",
4708 &source,
4709 "-pix_fmt",
4710 "yuv420p",
4711 "-f",
4712 "yuv4mpegpipe",
4713 "-",
4714 ])
4715 .stdin(Stdio::null())
4716 .stdout(Stdio::piped())
4717 .stderr(Stdio::piped())
4718 .output()
4719 .expect("ffmpeg failed to run");
4720 assert!(
4721 y4m.status.success(),
4722 "ffmpeg fixture: {}",
4723 String::from_utf8_lossy(&y4m.stderr)
4724 );
4725 // lane-cdfflake: hard length check on the y4m fixture itself --
4726 // a truncated/racing ffmpeg write would otherwise surface as a
4727 // downstream pixel mismatch indistinguishable from a real decode
4728 // defect. y4m frames are `FRAME\n` (6 bytes) + raw 4:2:0 payload;
4729 // find the header/frame-data boundary at the first `FRAME` marker
4730 // rather than parsing the header fields (duration/rate can move
4731 // the header text length without moving the frame math).
4732 let marker_at = y4m
4733 .stdout
4734 .windows(5)
4735 .position(|w| w == b"FRAME")
4736 .expect("y4m stream missing FRAME marker");
4737 let frame_420_bytes = width * height * 3 / 2;
4738 assert_eq!(
4739 y4m.stdout.len(),
4740 marker_at + frame_count * (6 + frame_420_bytes),
4741 "y4m fixture length mismatch (seed {seed})"
4742 );
4743 let y4m_hash = fnv1a64(&y4m.stdout);
4744 let mut child = Command::new(aomenc_path())
4745 .args([
4746 "--codec=av1",
4747 "--passes=1",
4748 "--end-usage=q",
4749 "--cq-level=55",
4750 "--cpu-used=0",
4751 "--lag-in-frames=0",
4752 "--auto-alt-ref=0",
4753 "--kf-max-dist=1000",
4754 // `--threads=1` (not the default): a multithreaded RD search
4755 // makes aomenc's screen-content-tools heuristic race (seen
4756 // flaky under `cargo test`'s own parallelism -- the same
4757 // fixture, same seed, occasionally sets
4758 // `allow_screen_content_tools`, a round-2 gap unrelated to
4759 // CDF forwarding), so pin it to one thread for a
4760 // deterministic header.
4761 "--threads=1",
4762 "--row-mt=0",
4763 // `--enable-order-hint=0` kills BWDREF/ALTREF entirely (no
4764 // order hints -> no bidirectional distance weighting) and,
4765 // combined with `--auto-alt-ref=0`/`--lag-in-frames=0`
4766 // above, leaves aomenc's RD search only LAST_FRAME/
4767 // LAST2_FRAME/LAST3_FRAME/GOLDEN_FRAME to pick from --
4768 // GOLDEN itself needs no order hint (it is the keyframe's
4769 // fixed slot, not a distance-weighted reference), so this
4770 // does not suppress GOLDEN selection the way the sibling
4771 // CDF-forwarding gate's own comment worried about; it just
4772 // narrows the pool this gate needs GOLDEN to win out of.
4773 "--enable-order-hint=0",
4774 "--enable-warped-motion=0",
4775 "--enable-obmc=0",
4776 "--enable-masked-comp=0",
4777 "--enable-interintra-comp=0",
4778 "--enable-dist-wtd-comp=0",
4779 "--enable-diff-wtd-comp=0",
4780 "--enable-onesided-comp=0",
4781 "--enable-interintra-wedge=0",
4782 "--enable-smooth-interintra=0",
4783 "--enable-rect-partitions=0",
4784 "--enable-ab-partitions=0",
4785 "--enable-1to4-partitions=0",
4786 "--enable-filter-intra=0",
4787 "--enable-smooth-intra=0",
4788 "--enable-paeth-intra=0",
4789 "--enable-directional-intra=0",
4790 "--enable-angle-delta=0",
4791 "--enable-tx-size-search=0",
4792 "--enable-cdef=0",
4793 // Loop restoration is a named refusal (aomenc's RD picks
4794 // Sgrproj on this kind of content) -- off in every recipe
4795 // whose test targets a different surface.
4796 "--enable-restoration=0",
4797 "--max-partition-size=32",
4798 "--enable-palette=0",
4799 "--enable-intrabc=0",
4800 "--enable-cfl-intra=0",
4801 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
4802 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
4803 "--enable-ref-frame-mvs=0",
4804 "--obu",
4805 "-o",
4806 "-",
4807 "-",
4808 ])
4809 .stdin(Stdio::piped())
4810 .stdout(Stdio::piped())
4811 .stderr(Stdio::piped())
4812 .spawn()
4813 .expect("aomenc failed to start");
4814 child
4815 .stdin
4816 .take()
4817 .expect("aomenc stdin")
4818 .write_all(&y4m.stdout)
4819 .expect("writing y4m to aomenc");
4820 let out = child.wait_with_output().expect("aomenc failed to run");
4821 assert!(
4822 out.status.success(),
4823 "aomenc refused the fixture: {}",
4824 String::from_utf8_lossy(&out.stderr)
4825 );
4826 let stream = out.stdout;
4827 let stream_hash = fnv1a64(&stream);
4828 // A named `unsupported` refusal is a documented coverage gap (each
4829 // one carries its own test debt elsewhere), not a forwarding verdict
4830 // -- try the next seed. Any stream that DECODES must be pixel-exact,
4831 // and any non-refusal error is a hard failure.
4832 let frames = match decode_stream(&stream) {
4833 Err(e) => {
4834 let msg = e.to_string();
4835 assert!(
4836 msg.contains("unsupported"),
4837 "cross-frame CDF forwarding failed outright (seed {seed}): {msg}"
4838 );
4839 refusals.push(format!("seed {seed}: {msg}"));
4840 continue;
4841 }
4842 Ok(frames) => frames,
4843 };
4844 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
4845 assert_eq!(frames.len(), frame_count);
4846 // lane-cdfflake: reconstruct ffmpeg's raw reference bytes (the
4847 // three per-frame slices are contiguous chunks of the raw
4848 // `-f rawvideo` output ffmpeg_decode_sequence sliced, so
4849 // concatenating them back is bit-for-bit the same bytes ffmpeg
4850 // actually produced -- no second ffmpeg invocation needed).
4851 let ffmpeg_raw: Vec<u8> = ffmpeg_frames
4852 .iter()
4853 .flat_map(|p| p.y.iter().chain(&p.u).chain(&p.v).map(|&v| v as u8))
4854 .collect();
4855 let ffmpeg_raw_hash = fnv1a64(&ffmpeg_raw);
4856 eprintln!(
4857 "cdfflake attempt seed={seed}: y4m_hash={y4m_hash:016x} \
4858 stream_hash={stream_hash:016x} ffmpeg_raw_hash={ffmpeg_raw_hash:016x}"
4859 );
4860 // lane-av1golden3: pin the exact raw stream on the first mismatch
4861 // so a flaky-looking gate failure becomes a deterministic, static
4862 // fixture to bisect against -- env-gated, no cost on a normal run.
4863 let mismatched = frames
4864 .iter()
4865 .zip(&ffmpeg_frames)
4866 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
4867 if mismatched {
4868 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
4869 std::fs::write(&path, &stream).expect("writing pinned stream");
4870 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
4871 }
4872 // lane-cdfflake: unconditional pin on mismatch -- the aomenc
4873 // stream AND ffmpeg's raw reference bytes, so a flake caught
4874 // under load names the liar (stream bytes differ from a
4875 // clean rerun -> subprocess instability; reference bytes
4876 // differ -> ffmpeg instability; both stable -> real decode
4877 // defect) without relying on the env var being set.
4878 // The pin goes to `fixtures/`, which outlives the session: an
4879 // earlier version wrote to a session scratchpad, so once tmpfs
4880 // reaped it a real mismatch aborted on the write instead of
4881 // reporting itself. A failed write must not mask the assert
4882 // below either, so it warns rather than panicking.
4883 let sp = pin_dir();
4884 let stream_pin = sp.join(format!("cdfflake-stream-seed{seed}.bin"));
4885 let ref_pin = sp.join(format!("cdfflake-ffmpeg-raw-seed{seed}.bin"));
4886 for (path, bytes) in [(&stream_pin, &stream), (&ref_pin, &ffmpeg_raw)] {
4887 if let Err(e) = std::fs::write(path, bytes) {
4888 eprintln!("cdfflake: could not pin to {}: {e}", path.display());
4889 }
4890 }
4891 eprintln!(
4892 "cdfflake MISMATCH seed={seed}: pinned stream + ffmpeg reference to {}",
4893 sp.display()
4894 );
4895 }
4896 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4897 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
4898 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
4899 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
4900 }
4901 return;
4902 }
4903 eprintln!(
4904 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: every \
4905 attempt hit a named refusal:\n{}",
4906 refusals.join("\n")
4907 );
4908 }
4909
4910 /// lane-av1golden3: reproduces the pinned mismatch bytes captured by
4911 /// `EC_AV1_GATE_DUMP=$SP/golden3-pin.obu` off
4912 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
4913 /// (seed 47, frame 1 U). Deterministic and static -- no aomenc/ffmpeg
4914 /// re-encode involved, only re-decodes the fixed bytes on disk, so it is
4915 /// `#[ignore]`d (the file only exists on this machine's scratchpad) but
4916 /// gives a fast red/green loop for the actual fix.
4917 #[test]
4918 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
4919 fn pinned_golden3_stream_decodes_pixel_exact() {
4920 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
4921 .map(std::path::PathBuf::from)
4922 .unwrap_or_else(|_| pin_dir().join("golden3-pin.obu"));
4923 let Ok(stream) = std::fs::read(&path) else {
4924 eprintln!(
4925 "SKIP pinned_golden3_stream_decodes_pixel_exact: no pinned bytes at {} \
4926 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
4927 path.display()
4928 );
4929 return;
4930 };
4931 if !have_ffmpeg() {
4932 eprintln!("SKIP pinned_golden3_stream_decodes_pixel_exact: no ffmpeg");
4933 return;
4934 }
4935 let frames = decode_stream(&stream).expect("pinned stream must decode");
4936 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
4937 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4938 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
4939 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
4940 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
4941 }
4942 }
4943
4944 /// lane-av1golden4: reproduces the pinned mismatch bytes captured by
4945 /// `EC_AV1_GATE_DUMP=$SP/golden4-pin.obu` off
4946 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
4947 /// (seed 43, frame 3 luma) the round the GOLDEN mask lifted. Deterministic
4948 /// and static -- `#[ignore]`d, run manually.
4949 #[test]
4950 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
4951 fn pinned_golden4_stream_decodes_pixel_exact() {
4952 use crate::decode::non_last_ref_hits;
4953 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
4954 .map(std::path::PathBuf::from)
4955 .unwrap_or_else(|_| pin_dir().join("golden4-pin.obu"));
4956 let Ok(stream) = std::fs::read(&path) else {
4957 eprintln!(
4958 "SKIP pinned_golden4_stream_decodes_pixel_exact: no pinned bytes at {} \
4959 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
4960 path.display()
4961 );
4962 return;
4963 };
4964 if !have_ffmpeg() {
4965 eprintln!("SKIP pinned_golden4_stream_decodes_pixel_exact: no ffmpeg");
4966 return;
4967 }
4968 let before = non_last_ref_hits();
4969 let frames = decode_stream(&stream).expect("pinned stream must decode");
4970 eprintln!(
4971 "non_last_ref_hits before={before} after={}",
4972 non_last_ref_hits()
4973 );
4974 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
4975 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
4976 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
4977 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
4978 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
4979 }
4980 }
4981
4982 /// lane-av1golden7 round 9: pins the residual GOLDEN_FRAME MC bug found
4983 /// by the forwarding gate once film grain is out of the way (1/20 real
4984 /// aomenc streams, frame 3 luma, apply_grain=false, `non_last_ref_hits`
4985 /// delta=2). `GOLDEN_FRAME` refuses by name until this decodes exact.
4986 #[test]
4987 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
4988 fn pinned_golden7_stream_decodes_pixel_exact() {
4989 use crate::decode::non_last_ref_hits;
4990 let path = concat!(
4991 env!("CARGO_MANIFEST_DIR"),
4992 "/../../fixtures/golden7-forwarding-mismatch.obu"
4993 );
4994 let stream = std::fs::read(path).expect("reading pinned stream");
4995 if !have_ffmpeg() {
4996 eprintln!("SKIP pinned_golden7_stream_decodes_pixel_exact: no ffmpeg");
4997 return;
4998 }
4999 let before = non_last_ref_hits();
5000 let frames = decode_stream(&stream).expect("pinned stream must decode");
5001 eprintln!(
5002 "non_last_ref_hits before={before} after={}",
5003 non_last_ref_hits()
5004 );
5005 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
5006 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5007 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
5008 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
5009 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
5010 }
5011 }
5012
5013 /// lane-av1refs's decisive single-non-LAST-reference gate: identical
5014 /// recipe to
5015 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
5016 /// except `--enable-order-hint=0` is DROPPED (that flag's own comment on
5017 /// the sibling test names it as exactly what suppresses aomenc's RD from
5018 /// ever picking `GOLDEN_FRAME`) and the sequence runs 8 frames, not 4 --
5019 /// more chances for the RD search to reach past the first GOP's initial
5020 /// key frame. `--auto-alt-ref=0` stays: this decoder only supports
5021 /// `LAST_FRAME`/`GOLDEN_FRAME` so far, and alt-ref/backward references
5022 /// are still a named refusal, not this gate's target. A stream that
5023 /// decodes without firing [`decode::non_last_ref_hits`] is not a
5024 /// coverage win for this round -- SKIP it as a genuine, named miss
5025 /// rather than pass silently on untested ground.
5026 #[test]
5027 fn a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact() {
5028 if !have_ffmpeg() {
5029 eprintln!(
5030 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no ffmpeg"
5031 );
5032 return;
5033 }
5034 if !have_aomenc() {
5035 eprintln!(
5036 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no aomenc at {}",
5037 aomenc_path().display()
5038 );
5039 return;
5040 }
5041 let (width, height, frame_count) = (64usize, 64usize, 8usize);
5042 let mut refusals = Vec::new();
5043 let mut never_fired = 0u32;
5044 // aomenc's own RD search is nondeterministic run-to-run even at
5045 // `--threads=1` (confirmed live: identical CLI args, identical
5046 // input, two different output byte streams) -- so beyond varying
5047 // the fixture's seed, each attempt is its own independent coin
5048 // flip against every named refusal below. 120 attempts (not 40)
5049 // to give that coin flip enough tries to land on a stream this
5050 // decoder both accepts and that fires GOLDEN_FRAME. `duration=0.32`
5051 // at `rate=25` (not `0.24`) matches every sibling gate's own
5052 // frame-count fixture exactly -- a shorter duration here once
5053 // produced a frame-0 (keyframe, no reference at all) luma mismatch
5054 // against ffmpeg, i.e. a source-frame-count rounding artifact of
5055 // this recipe's own choosing, not a decoder bug.
5056 for attempt in 0..120u32 {
5057 let seed = 42 + attempt % 40;
5058 let source = gradients_source(seed, 64, 64, "duration=0.32:rate=25");
5059 let y4m = Command::new("ffmpeg")
5060 .args([
5061 "-v",
5062 "error",
5063 "-f",
5064 "lavfi",
5065 "-i",
5066 &source,
5067 "-pix_fmt",
5068 "yuv420p",
5069 "-f",
5070 "yuv4mpegpipe",
5071 "-",
5072 ])
5073 .stdin(Stdio::null())
5074 .stdout(Stdio::piped())
5075 .stderr(Stdio::piped())
5076 .output()
5077 .expect("ffmpeg failed to run");
5078 assert!(
5079 y4m.status.success(),
5080 "ffmpeg fixture: {}",
5081 String::from_utf8_lossy(&y4m.stderr)
5082 );
5083 let mut child = Command::new(aomenc_path())
5084 .args([
5085 "--codec=av1",
5086 "--passes=1",
5087 "--end-usage=q",
5088 "--cq-level=55",
5089 "--cpu-used=0",
5090 "--lag-in-frames=0",
5091 "--auto-alt-ref=0",
5092 "--kf-max-dist=1000",
5093 "--threads=1",
5094 "--row-mt=0",
5095 // Narrows the RD search's reference alphabet toward
5096 // LAST_FRAME/GOLDEN_FRAME -- without this, aomenc's RD is
5097 // just as likely to pick LAST2/LAST3/BWDREF/ALTREF2/
5098 // ALTREF (this decoder's already-documented, still-open
5099 // refusals), starving this gate of the one reference it
5100 // targets.
5101 "--max-reference-frames=3",
5102 "--reduced-reference-set=1",
5103 "--enable-warped-motion=0",
5104 "--enable-obmc=0",
5105 "--enable-masked-comp=0",
5106 "--enable-interintra-comp=0",
5107 "--enable-dist-wtd-comp=0",
5108 "--enable-diff-wtd-comp=0",
5109 "--enable-onesided-comp=0",
5110 "--enable-interintra-wedge=0",
5111 "--enable-smooth-interintra=0",
5112 "--enable-rect-partitions=0",
5113 "--enable-ab-partitions=0",
5114 "--enable-1to4-partitions=0",
5115 "--enable-filter-intra=0",
5116 "--enable-smooth-intra=0",
5117 "--enable-paeth-intra=0",
5118 "--enable-directional-intra=0",
5119 "--enable-angle-delta=0",
5120 "--enable-tx-size-search=0",
5121 "--enable-cdef=0",
5122 "--enable-restoration=0",
5123 // `min == max == 32` forces PARTITION_NONE for every
5124 // 32x32 block, not just biases toward it -- with
5125 // `--min-partition-size=16` alone aomenc's exhaustive
5126 // `cpu-used=0` RD search still occasionally read HORZ/
5127 // VERT/SPLIT partitions below 32x32 despite
5128 // `--enable-rect-partitions=0`/`--enable-ab-partitions=0`/
5129 // `--enable-1to4-partitions=0` all being off (two
5130 // separate, already-documented round-2 gaps: "a
5131 // partition below 16x16", "a partition type this encoder
5132 // never writes"), starving this gate's already-narrow
5133 // seed pool. Locking both bounds to 32 removes any
5134 // partition-depth choice from the search entirely, so
5135 // this gate can isolate GOLDEN_FRAME selection alone.
5136 "--max-partition-size=32",
5137 "--min-partition-size=32",
5138 "--enable-palette=0",
5139 "--enable-intrabc=0",
5140 "--enable-cfl-intra=0",
5141 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
5142 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
5143 "--enable-ref-frame-mvs=0",
5144 // `--tune-content=film` was dropped: on this box it
5145 // makes aomenc emit `apply_grain` almost every attempt
5146 // (lane-av1golden8 round 10 measurement, live: 120/120
5147 // real attempts hit a named refusal, 0 ever fired
5148 // GOLDEN_FRAME -- mostly `apply_grain`, dominated by its
5149 // own recipe flag) -- film grain synthesis has its own
5150 // dedicated refusal test and must not starve this gate
5151 // of the GOLDEN_FRAME draws it exists to prove. Default
5152 // content tuning still occasionally flips
5153 // `allow_screen_content_tools` on for this synthetic
5154 // gradient content (a separate, already-documented open
5155 // refusal), which the 120-attempt coin flip below
5156 // tolerates the same way.
5157 "--obu",
5158 "-o",
5159 "-",
5160 "-",
5161 ])
5162 .stdin(Stdio::piped())
5163 .stdout(Stdio::piped())
5164 .stderr(Stdio::piped())
5165 .spawn()
5166 .expect("aomenc failed to start");
5167 child
5168 .stdin
5169 .take()
5170 .expect("aomenc stdin")
5171 .write_all(&y4m.stdout)
5172 .expect("writing y4m to aomenc");
5173 let out = child.wait_with_output().expect("aomenc failed to run");
5174 assert!(
5175 out.status.success(),
5176 "aomenc refused the fixture: {}",
5177 String::from_utf8_lossy(&out.stderr)
5178 );
5179 let stream = out.stdout;
5180 let before = decode::non_last_ref_hits();
5181 let frames = match decode_stream(&stream) {
5182 Err(e) => {
5183 let msg = e.to_string();
5184 assert!(
5185 msg.contains("unsupported"),
5186 "a golden-reference stream failed outright (seed {seed}): {msg}"
5187 );
5188 refusals.push(format!("seed {seed}: {msg}"));
5189 continue;
5190 }
5191 Ok(frames) => frames,
5192 };
5193 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
5194 // is ALWAYS pixel-compared below; the hit counter only decides whether
5195 // the attempt counts toward the firing total.
5196 // This seed's RD search may never have picked GOLDEN_FRAME -- a
5197 // genuine miss, not a refusal, and not a reason to skip the pixels.
5198 let counted = decode::non_last_ref_hits() != before;
5199 if !counted {
5200 never_fired += 1;
5201 }
5202 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
5203 assert_eq!(frames.len(), frame_count);
5204 // Same pin-on-mismatch pattern as the CDF forwarding gate above:
5205 // env-gated, no cost on a normal run.
5206 let mismatched = frames
5207 .iter()
5208 .zip(&ffmpeg_frames)
5209 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
5210 if mismatched {
5211 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
5212 std::fs::write(&path, &stream).expect("writing pinned stream");
5213 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
5214 }
5215 }
5216 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5217 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
5218 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
5219 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
5220 }
5221 if counted {
5222 eprintln!(
5223 "FIRING seed {seed}: non_last_ref_hits advanced by {}",
5224 decode::non_last_ref_hits() - before
5225 );
5226 gate_buckets(
5227 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
5228 1,
5229 never_fired,
5230 refusals.len(),
5231 );
5232 return;
5233 }
5234 }
5235 gate_buckets(
5236 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
5237 0,
5238 never_fired,
5239 refusals.len(),
5240 );
5241 eprintln!(
5242 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: \
5243 {never_fired} attempts decoded but never fired GOLDEN_FRAME, and every other \
5244 attempt hit a named refusal:\n{}",
5245 refusals.join("\n")
5246 );
5247 }
5248
5249 /// lane-av1refs's decisive gate for the 5 references widened past
5250 /// `LAST_FRAME`/`GOLDEN_FRAME`: same envelope and pin-on-mismatch
5251 /// pattern as
5252 /// [`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`],
5253 /// generalised over `(target_ref, extra_args, frame_count)` so each of
5254 /// `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` gets its own attempt pool
5255 /// and its own proof that `decode::ref_hits(target_ref)` -- not just
5256 /// `non_last_ref_hits`, which cannot distinguish one reference from
5257 /// another -- actually advanced. `--max-reference-frames=3
5258 /// --reduced-reference-set=1` (the golden gate's own narrowing) is
5259 /// DROPPED here: both suppress exactly the references this gate needs
5260 /// aomenc's RD to reach.
5261 fn a_real_aomenc_single_ref_gate(
5262 gate_name: &str,
5263 target_ref: i8,
5264 target_ref_name: &str,
5265 extra_args: &[&str],
5266 width: usize,
5267 height: usize,
5268 frame_count: usize,
5269 attempts: u32,
5270 ) {
5271 let _gate_lock = lock_gate_counters();
5272 if !have_ffmpeg() {
5273 eprintln!("SKIP {gate_name}: no ffmpeg");
5274 return;
5275 }
5276 if !have_aomenc() {
5277 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
5278 return;
5279 }
5280 let mut refusals = Vec::new();
5281 let mut never_fired = 0u32;
5282 for attempt in 0..attempts {
5283 let seed = 42 + attempt % 40;
5284 let duration = frame_count as f64 / 25.0;
5285 let source =
5286 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
5287 let y4m = Command::new("ffmpeg")
5288 .args([
5289 "-v",
5290 "error",
5291 "-f",
5292 "lavfi",
5293 "-i",
5294 &source,
5295 "-pix_fmt",
5296 "yuv420p",
5297 "-f",
5298 "yuv4mpegpipe",
5299 "-",
5300 ])
5301 .stdin(Stdio::null())
5302 .stdout(Stdio::piped())
5303 .stderr(Stdio::piped())
5304 .output()
5305 .expect("ffmpeg failed to run");
5306 assert!(
5307 y4m.status.success(),
5308 "ffmpeg fixture: {}",
5309 String::from_utf8_lossy(&y4m.stderr)
5310 );
5311 let mut args: Vec<&str> = vec![
5312 "--codec=av1",
5313 "--passes=1",
5314 "--end-usage=q",
5315 "--cq-level=55",
5316 "--cpu-used=0",
5317 "--kf-max-dist=1000",
5318 "--threads=1",
5319 "--row-mt=0",
5320 "--enable-warped-motion=0",
5321 "--enable-obmc=0",
5322 "--enable-masked-comp=0",
5323 "--enable-interintra-comp=0",
5324 "--enable-dist-wtd-comp=0",
5325 "--enable-diff-wtd-comp=0",
5326 "--enable-onesided-comp=0",
5327 "--enable-interintra-wedge=0",
5328 "--enable-smooth-interintra=0",
5329 "--enable-rect-partitions=0",
5330 "--enable-ab-partitions=0",
5331 "--enable-1to4-partitions=0",
5332 "--enable-filter-intra=0",
5333 "--enable-smooth-intra=0",
5334 "--enable-paeth-intra=0",
5335 "--enable-directional-intra=0",
5336 "--enable-angle-delta=0",
5337 "--enable-tx-size-search=0",
5338 "--enable-cdef=0",
5339 "--enable-restoration=0",
5340 "--max-partition-size=32",
5341 "--min-partition-size=32",
5342 "--enable-palette=0",
5343 "--enable-intrabc=0",
5344 "--enable-cfl-intra=0",
5345 // use_ref_frame_mvs (temporal MV projection) is unimplemented in
5346 // mvstack; leaving it on silently desyncs symbols on inter frames.
5347 "--enable-ref-frame-mvs=0",
5348 "--obu",
5349 "-o",
5350 "-",
5351 "-",
5352 ];
5353 // extra_args goes right before the trailing "-o", "-", "-" triple.
5354 let tail = args.split_off(args.len() - 3);
5355 args.extend_from_slice(extra_args);
5356 args.extend_from_slice(&tail);
5357 let mut child = Command::new(aomenc_path())
5358 .args(&args)
5359 .stdin(Stdio::piped())
5360 .stdout(Stdio::piped())
5361 .stderr(Stdio::piped())
5362 .spawn()
5363 .expect("aomenc failed to start");
5364 child
5365 .stdin
5366 .take()
5367 .expect("aomenc stdin")
5368 .write_all(&y4m.stdout)
5369 .expect("writing y4m to aomenc");
5370 let out = child.wait_with_output().expect("aomenc failed to run");
5371 assert!(
5372 out.status.success(),
5373 "aomenc refused the fixture: {}",
5374 String::from_utf8_lossy(&out.stderr)
5375 );
5376 let stream = out.stdout;
5377 let before = decode::ref_hits(target_ref);
5378 let frames = match decode_stream(&stream) {
5379 Err(e) => {
5380 let msg = e.to_string();
5381 assert!(
5382 msg.contains("unsupported"),
5383 "{gate_name} failed outright (seed {seed}): {msg}"
5384 );
5385 refusals.push(format!("seed {seed}: {msg}"));
5386 continue;
5387 }
5388 Ok(frames) => frames,
5389 };
5390 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
5391 // is ALWAYS pixel-compared below; the hit counter only decides whether
5392 // the attempt counts toward the firing total.
5393 let counted = decode::ref_hits(target_ref) != before;
5394 if !counted {
5395 never_fired += 1;
5396 }
5397 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
5398 assert_eq!(frames.len(), frame_count);
5399 let mismatched = frames
5400 .iter()
5401 .zip(&ffmpeg_frames)
5402 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
5403 if mismatched {
5404 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
5405 std::fs::write(&path, &stream).expect("writing pinned stream");
5406 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
5407 }
5408 }
5409 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5410 assert_eq!(
5411 got.y, want.y,
5412 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
5413 );
5414 assert_eq!(
5415 got.u, want.u,
5416 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
5417 );
5418 assert_eq!(
5419 got.v, want.v,
5420 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
5421 );
5422 }
5423 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
5424 // stream again, comparing EVERY decode-order frame -- the hidden
5425 // (show_frame == 0) alt-ref frames the ffmpeg compare above
5426 // cannot see, because both sides of it emit shown frames only.
5427 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, gate_name);
5428 eprintln!(
5429 "{gate_name} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
5430 {hidden_n} hidden, all pixel-exact vs the oracle"
5431 );
5432 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
5433 // libaom's temporal alt-ref filter absorbs this recipe's hidden
5434 // frames, so the compare above is vacuous -- re-encode the same
5435 // fixture with --arnr-maxframes=0 and compare THOSE.
5436 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(gate_name, &y4m.stdout, &args) {
5437 eprintln!(
5438 "{gate_name} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
5439 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
5440 );
5441 }
5442 if counted {
5443 eprintln!(
5444 "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}",
5445 decode::ref_hits(target_ref) - before
5446 );
5447 gate_buckets(gate_name, 1, never_fired, refusals.len());
5448 return;
5449 }
5450 }
5451 gate_buckets(gate_name, 0, never_fired, refusals.len());
5452 eprintln!(
5453 "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \
5454 and every other attempt hit a named refusal:\n{}",
5455 refusals.join("\n")
5456 );
5457 }
5458
5459 /// lane-av1comp: proves `reference_select`/`comp_mode` are actually read
5460 /// off a real bitstream rather than only unit-tested in isolation --
5461 /// `--auto-alt-ref=1 --lag-in-frames=16` gives aomenc a backward
5462 /// reference to pick `COMPOUND_REFERENCE` with, `--enable-order-hint=1`
5463 /// is required for it to ever consider compound at all. Three
5464 /// acceptable outcomes: (a) a stream where `reference_select` never
5465 /// actually drove a block to `COMPOUND_REFERENCE` decodes bit-exact end
5466 /// to end (proving the per-block `comp_mode` read did not desync the
5467 /// single-ref blocks around it); (b) a stream that does fire compound
5468 /// is refused by name with [`decode::comp_mode_hits`] having advanced
5469 /// (proving `comp_mode`/`read_compound_ref_frames` consumed the right
5470 /// symbols before refusing, rather than desyncing and refusing for an
5471 /// unrelated reason) -- masked/wedge compound (`comp_group_idx == 1`)
5472 /// and a partition below 16x16 (a real, separately tracked capability
5473 /// gap) are the two refusal arms this can still legitimately name; (c)
5474 /// r13 wired plain `COMPOUND_AVERAGE` MC for real, so as of r15 a
5475 /// stream that fires compound may also decode fully -- accepted only
5476 /// when every output frame is pixel-exact against ffmpeg.
5477 #[test]
5478 fn a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly() {
5479 const NAME: &str = "a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly";
5480 let _gate_lock = lock_gate_counters();
5481 if !have_ffmpeg() {
5482 eprintln!("SKIP {NAME}: no ffmpeg");
5483 return;
5484 }
5485 if !have_aomenc() {
5486 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5487 return;
5488 }
5489 let (width, height, frame_count) = (64usize, 64usize, 20usize);
5490 let mut refusals = Vec::new();
5491 let mut never_fired = 0u32;
5492 for attempt in 0..60u32 {
5493 let seed = 42 + attempt % 40;
5494 let duration = frame_count as f64 / 25.0;
5495 let source =
5496 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
5497 let y4m = Command::new("ffmpeg")
5498 .args([
5499 "-v",
5500 "error",
5501 "-f",
5502 "lavfi",
5503 "-i",
5504 &source,
5505 "-pix_fmt",
5506 "yuv420p",
5507 "-f",
5508 "yuv4mpegpipe",
5509 "-",
5510 ])
5511 .stdin(Stdio::null())
5512 .stdout(Stdio::piped())
5513 .stderr(Stdio::piped())
5514 .output()
5515 .expect("ffmpeg failed to run");
5516 assert!(
5517 y4m.status.success(),
5518 "ffmpeg fixture: {}",
5519 String::from_utf8_lossy(&y4m.stderr)
5520 );
5521 let args: Vec<&str> = vec![
5522 "--codec=av1",
5523 "--passes=1",
5524 "--end-usage=q",
5525 "--cq-level=45",
5526 "--cpu-used=0",
5527 "--kf-max-dist=1000",
5528 "--threads=1",
5529 "--row-mt=0",
5530 "--auto-alt-ref=1",
5531 "--lag-in-frames=16",
5532 "--enable-order-hint=1",
5533 "--enable-warped-motion=0",
5534 "--enable-obmc=0",
5535 "--enable-masked-comp=0",
5536 "--enable-interintra-comp=0",
5537 "--enable-onesided-comp=0",
5538 "--enable-interintra-wedge=0",
5539 "--enable-smooth-interintra=0",
5540 "--enable-rect-partitions=0",
5541 "--enable-ab-partitions=0",
5542 "--enable-1to4-partitions=0",
5543 "--enable-filter-intra=0",
5544 "--enable-smooth-intra=0",
5545 "--enable-paeth-intra=0",
5546 "--enable-directional-intra=0",
5547 "--enable-angle-delta=0",
5548 "--enable-tx-size-search=0",
5549 "--enable-cdef=0",
5550 "--enable-restoration=0",
5551 "--max-partition-size=32",
5552 "--min-partition-size=32",
5553 "--enable-palette=0",
5554 "--enable-intrabc=0",
5555 "--enable-cfl-intra=0",
5556 "--enable-ref-frame-mvs=0",
5557 "--obu",
5558 "-o",
5559 "-",
5560 "-",
5561 ];
5562 let mut child = Command::new(aomenc_path())
5563 .args(&args)
5564 .stdin(Stdio::piped())
5565 .stdout(Stdio::piped())
5566 .stderr(Stdio::piped())
5567 .spawn()
5568 .expect("aomenc failed to start");
5569 child
5570 .stdin
5571 .take()
5572 .expect("aomenc stdin")
5573 .write_all(&y4m.stdout)
5574 .expect("writing y4m to aomenc");
5575 let out = child.wait_with_output().expect("aomenc failed to run");
5576 assert!(
5577 out.status.success(),
5578 "aomenc refused the fixture: {}",
5579 String::from_utf8_lossy(&out.stderr)
5580 );
5581 let stream = out.stdout;
5582 let before = decode::comp_mode_hits();
5583 match decode_stream(&stream) {
5584 Err(e) => {
5585 let msg = e.to_string();
5586 let fired = decode::comp_mode_hits() > before;
5587 assert!(
5588 msg.contains("unsupported"),
5589 "{NAME} failed outright (seed {seed}): {msg}"
5590 );
5591 if fired {
5592 // `comp_mode` firing does not stop the block walk --
5593 // a later, unrelated block in the same tile can
5594 // still hit any other named refusal this decoder
5595 // carries. A partition below 16x16 is a real, open
5596 // capability gap tracked on its own (not a
5597 // COMPOUND_REFERENCE defect); accept it here too
5598 // rather than fail a compound-specific gate on a
5599 // partition-search coincidence. lane-av1blend r7:
5600 // re-swept the wide gate with the plain-average
5601 // blend unmasked (r6/r7's ref_ctx fix alone) and it
5602 // still mismatches on real streams beyond that one
5603 // bug -- re-masked comp_group_idx == 0 too, so this
5604 // stays a legal named refusal.
5605 assert!(
5606 msg.contains("COMPOUND_REFERENCE") || msg.contains("a partition"),
5607 "{NAME}: comp_mode fired (seed {seed}) but the refusal \
5608 was for something else: {msg}"
5609 );
5610 let advanced = decode::comp_mode_hits() - before;
5611 eprintln!(
5612 "{NAME} FIRING seed {seed}: comp_mode hits advanced by \
5613 {advanced}, refused by name as expected: {msg}"
5614 );
5615 return;
5616 }
5617 refusals.push(format!("seed {seed}: {msg}"));
5618 continue;
5619 }
5620 Ok(frames) => {
5621 // class [[gate-skips-on-its-own-failure]]: a decode that
5622 // succeeded is ALWAYS pixel-compared below; the hit counter
5623 // only decides whether the attempt counts as firing.
5624 let counted = decode::comp_mode_hits() != before;
5625 if !counted {
5626 never_fired += 1;
5627 }
5628 // Outcome (c): plain COMPOUND_AVERAGE decoded fully --
5629 // non-negotiable pixel exactness, no tolerance.
5630 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
5631 assert_eq!(frames.len(), frame_count);
5632 let mismatched = frames
5633 .iter()
5634 .zip(&ffmpeg_frames)
5635 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
5636 if mismatched {
5637 let pin = std::env::temp_dir().join("ec-av1-reference-select-gate-fail.obu");
5638 let _ = std::fs::write(&pin, &stream);
5639 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
5640 std::fs::write(&path, &stream).expect("writing pinned stream");
5641 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
5642 }
5643 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5644 assert_eq!(
5645 got.y, want.y,
5646 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
5647 pin.display()
5648 );
5649 assert_eq!(
5650 got.u, want.u,
5651 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
5652 pin.display()
5653 );
5654 assert_eq!(
5655 got.v, want.v,
5656 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
5657 pin.display()
5658 );
5659 }
5660 } else {
5661 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5662 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
5663 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
5664 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
5665 }
5666 }
5667 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
5668 // stream again, comparing EVERY decode-order frame -- the hidden
5669 // (show_frame == 0) alt-ref frames the ffmpeg compare above
5670 // cannot see, because both sides of it emit shown frames only.
5671 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
5672 eprintln!(
5673 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
5674 {hidden_n} hidden, all pixel-exact vs the oracle"
5675 );
5676 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
5677 // libaom's temporal alt-ref filter absorbs this recipe's hidden
5678 // frames, so the compare above is vacuous -- re-encode the same
5679 // fixture with --arnr-maxframes=0 and compare THOSE.
5680 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
5681 eprintln!(
5682 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
5683 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
5684 );
5685 }
5686 if counted {
5687 eprintln!(
5688 "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \
5689 fully and pixel-exact",
5690 decode::comp_mode_hits() - before
5691 );
5692 gate_buckets(NAME, 1, never_fired, refusals.len());
5693 return;
5694 }
5695 }
5696 }
5697 }
5698 gate_buckets(NAME, 0, never_fired, refusals.len());
5699 eprintln!(
5700 "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \
5701 block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \
5702 reached comp_mode:\n{}",
5703 refusals.join("\n")
5704 );
5705 }
5706
5707 /// lane-av1comp round 14's decisive gate for `skip_mode`: same
5708 /// pin-on-mismatch pattern as [`a_real_aomenc_single_ref_gate`], proving
5709 /// [`decode::skip_mode_hits`] actually advanced (a real block picked
5710 /// `skip_mode`, not just that the frame header bit was set) and that the
5711 /// resulting forced-compound `NEAREST_NEARESTMV` decode is still
5712 /// pixel-exact against ffmpeg. `--auto-alt-ref=1 --lag-in-frames=16
5713 /// --enable-fwd-kf=0` (backward references) plus
5714 /// `--enable-ref-frame-mvs=0` (unimplemented temporal MV projection,
5715 /// same as every other gate here) is aomenc's own requirement for
5716 /// `skip_mode_present` to ever be considered at all (spec 5.9.22 needs
5717 /// both a forward and a backward reference candidate).
5718 #[test]
5719 fn a_real_aomenc_stream_with_compound_references_decodes_pixel_exact() {
5720 const NAME: &str = "a_real_aomenc_stream_with_compound_references_decodes_pixel_exact";
5721 let _gate_lock = lock_gate_counters();
5722 if !have_ffmpeg() {
5723 eprintln!("SKIP {NAME}: no ffmpeg");
5724 return;
5725 }
5726 if !have_aomenc() {
5727 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5728 return;
5729 }
5730 let (width, height, frame_count) = (64usize, 64usize, 24usize);
5731 let mut refusals = Vec::new();
5732 let mut never_fired = 0u32;
5733 for attempt in 0..80u32 {
5734 let seed = 42 + attempt % 40;
5735 let duration = frame_count as f64 / 25.0;
5736 let source =
5737 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
5738 let y4m = Command::new("ffmpeg")
5739 .args([
5740 "-v",
5741 "error",
5742 "-f",
5743 "lavfi",
5744 "-i",
5745 &source,
5746 "-pix_fmt",
5747 "yuv420p",
5748 "-f",
5749 "yuv4mpegpipe",
5750 "-",
5751 ])
5752 .stdin(Stdio::null())
5753 .stdout(Stdio::piped())
5754 .stderr(Stdio::piped())
5755 .output()
5756 .expect("ffmpeg failed to run");
5757 assert!(
5758 y4m.status.success(),
5759 "ffmpeg fixture: {}",
5760 String::from_utf8_lossy(&y4m.stderr)
5761 );
5762 let args: Vec<&str> = vec![
5763 "--codec=av1",
5764 "--passes=1",
5765 "--end-usage=q",
5766 "--cq-level=45",
5767 "--cpu-used=0",
5768 "--kf-max-dist=1000",
5769 "--threads=1",
5770 "--row-mt=0",
5771 "--auto-alt-ref=1",
5772 "--lag-in-frames=16",
5773 "--enable-fwd-kf=0",
5774 "--enable-order-hint=1",
5775 "--enable-warped-motion=0",
5776 "--enable-obmc=0",
5777 "--enable-masked-comp=0",
5778 "--enable-interintra-comp=0",
5779 "--enable-onesided-comp=0",
5780 "--enable-interintra-wedge=0",
5781 "--enable-smooth-interintra=0",
5782 "--enable-rect-partitions=0",
5783 "--enable-ab-partitions=0",
5784 "--enable-1to4-partitions=0",
5785 "--enable-filter-intra=0",
5786 "--enable-smooth-intra=0",
5787 "--enable-paeth-intra=0",
5788 "--enable-directional-intra=0",
5789 "--enable-angle-delta=0",
5790 "--enable-tx-size-search=0",
5791 "--enable-cdef=0",
5792 "--enable-restoration=0",
5793 "--max-partition-size=32",
5794 "--min-partition-size=32",
5795 "--enable-palette=0",
5796 "--enable-intrabc=0",
5797 "--enable-cfl-intra=0",
5798 "--enable-ref-frame-mvs=0",
5799 "--obu",
5800 "-o",
5801 "-",
5802 "-",
5803 ];
5804 let mut child = Command::new(aomenc_path())
5805 .args(&args)
5806 .stdin(Stdio::piped())
5807 .stdout(Stdio::piped())
5808 .stderr(Stdio::piped())
5809 .spawn()
5810 .expect("aomenc failed to start");
5811 child
5812 .stdin
5813 .take()
5814 .expect("aomenc stdin")
5815 .write_all(&y4m.stdout)
5816 .expect("writing y4m to aomenc");
5817 let out = child.wait_with_output().expect("aomenc failed to run");
5818 assert!(
5819 out.status.success(),
5820 "aomenc refused the fixture: {}",
5821 String::from_utf8_lossy(&out.stderr)
5822 );
5823 let stream = out.stdout;
5824 let before = decode::skip_mode_hits();
5825 let frames = match decode_stream(&stream) {
5826 Err(e) => {
5827 let msg = e.to_string();
5828 assert!(
5829 msg.contains("unsupported"),
5830 "{NAME} failed outright (seed {seed}): {msg}"
5831 );
5832 refusals.push(format!("seed {seed}: {msg}"));
5833 continue;
5834 }
5835 Ok(frames) => frames,
5836 };
5837 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
5838 // is ALWAYS pixel-compared below; the hit counter only decides whether
5839 // the attempt counts toward the firing total.
5840 let counted = decode::skip_mode_hits() != before;
5841 if !counted {
5842 never_fired += 1;
5843 }
5844 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
5845 assert_eq!(frames.len(), frame_count);
5846 let mismatched = frames
5847 .iter()
5848 .zip(&ffmpeg_frames)
5849 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
5850 if mismatched {
5851 let pin = std::env::temp_dir().join("ec-av1-compound-refs-gate-fail.obu");
5852 let _ = std::fs::write(&pin, &stream);
5853 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
5854 std::fs::write(&path, &stream).expect("writing pinned stream");
5855 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
5856 }
5857 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5858 assert_eq!(
5859 got.y, want.y,
5860 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
5861 pin.display()
5862 );
5863 assert_eq!(
5864 got.u, want.u,
5865 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
5866 pin.display()
5867 );
5868 assert_eq!(
5869 got.v, want.v,
5870 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
5871 pin.display()
5872 );
5873 }
5874 }
5875 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
5876 // stream again, comparing EVERY decode-order frame -- the hidden
5877 // (show_frame == 0) alt-ref frames the ffmpeg compare above
5878 // cannot see, because both sides of it emit shown frames only.
5879 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
5880 eprintln!(
5881 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
5882 {hidden_n} hidden, all pixel-exact vs the oracle"
5883 );
5884 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
5885 // libaom's temporal alt-ref filter absorbs this recipe's hidden
5886 // frames, so the compare above is vacuous -- re-encode the same
5887 // fixture with --arnr-maxframes=0 and compare THOSE.
5888 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
5889 eprintln!(
5890 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
5891 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
5892 );
5893 }
5894 if counted {
5895 eprintln!(
5896 "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}",
5897 decode::skip_mode_hits() - before
5898 );
5899 gate_buckets(NAME, 1, never_fired, refusals.len());
5900 return;
5901 }
5902 }
5903 gate_buckets(NAME, 0, never_fired, refusals.len());
5904 eprintln!(
5905 "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \
5906 other attempt hit a named refusal:\n{}",
5907 refusals.join("\n")
5908 );
5909 }
5910
5911 /// lane-motionmode round 1: `--enable-obmc=1 --enable-warped-motion=0`
5912 /// on the base recipe (`--auto-alt-ref=1 --lag-in-frames=16
5913 /// --enable-fwd-kf=0 --enable-ref-frame-mvs=0`) -- pixel-exact against
5914 /// ffmpeg, gated on [`decode::obmc_hits`] actually advancing (a real
5915 /// block picked `OBMC_CAUSAL`, not just that the header bit was set).
5916 /// Structure copied from
5917 /// `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`:
5918 /// a seed sweep with a named-refusal escape hatch and an
5919 /// `EC_AV1_GATE_DUMP` pin on mismatch.
5920 #[test]
5921 fn a_real_aomenc_stream_with_obmc_decodes_pixel_exact() {
5922 const NAME: &str = "a_real_aomenc_stream_with_obmc_decodes_pixel_exact";
5923 let _gate_lock = lock_gate_counters();
5924 if !have_ffmpeg() {
5925 eprintln!("SKIP {NAME}: no ffmpeg");
5926 return;
5927 }
5928 if !have_aomenc() {
5929 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5930 return;
5931 }
5932 let (width, height, frame_count) = (64usize, 64usize, 24usize);
5933 let mut refusals = Vec::new();
5934 let mut never_fired = 0u32;
5935 for attempt in 0..80u32 {
5936 let seed = 42 + attempt % 40;
5937 let duration = frame_count as f64 / 25.0;
5938 let source =
5939 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
5940 let y4m = Command::new("ffmpeg")
5941 .args([
5942 "-v",
5943 "error",
5944 "-f",
5945 "lavfi",
5946 "-i",
5947 &source,
5948 "-pix_fmt",
5949 "yuv420p",
5950 "-f",
5951 "yuv4mpegpipe",
5952 "-",
5953 ])
5954 .stdin(Stdio::null())
5955 .stdout(Stdio::piped())
5956 .stderr(Stdio::piped())
5957 .output()
5958 .expect("ffmpeg failed to run");
5959 assert!(
5960 y4m.status.success(),
5961 "ffmpeg fixture: {}",
5962 String::from_utf8_lossy(&y4m.stderr)
5963 );
5964 let args: Vec<&str> = vec![
5965 "--codec=av1",
5966 "--passes=1",
5967 "--end-usage=q",
5968 "--cq-level=45",
5969 "--cpu-used=0",
5970 "--kf-max-dist=1000",
5971 "--threads=1",
5972 "--row-mt=0",
5973 "--auto-alt-ref=1",
5974 "--lag-in-frames=16",
5975 "--enable-fwd-kf=0",
5976 "--enable-order-hint=1",
5977 "--enable-warped-motion=0",
5978 "--enable-obmc=1",
5979 "--enable-masked-comp=0",
5980 "--enable-interintra-comp=0",
5981 "--enable-onesided-comp=0",
5982 "--enable-interintra-wedge=0",
5983 "--enable-smooth-interintra=0",
5984 "--enable-rect-partitions=0",
5985 "--enable-ab-partitions=0",
5986 "--enable-1to4-partitions=0",
5987 "--enable-filter-intra=0",
5988 "--enable-smooth-intra=0",
5989 "--enable-paeth-intra=0",
5990 "--enable-directional-intra=0",
5991 "--enable-angle-delta=0",
5992 "--enable-tx-size-search=0",
5993 "--enable-cdef=0",
5994 "--enable-restoration=0",
5995 "--max-partition-size=32",
5996 "--min-partition-size=32",
5997 "--enable-palette=0",
5998 "--enable-intrabc=0",
5999 "--enable-cfl-intra=0",
6000 "--enable-ref-frame-mvs=0",
6001 "--obu",
6002 "-o",
6003 "-",
6004 "-",
6005 ];
6006 let mut child = Command::new(aomenc_path())
6007 .args(&args)
6008 .stdin(Stdio::piped())
6009 .stdout(Stdio::piped())
6010 .stderr(Stdio::piped())
6011 .spawn()
6012 .expect("aomenc failed to start");
6013 child
6014 .stdin
6015 .take()
6016 .expect("aomenc stdin")
6017 .write_all(&y4m.stdout)
6018 .expect("writing y4m to aomenc");
6019 let out = child.wait_with_output().expect("aomenc failed to run");
6020 assert!(
6021 out.status.success(),
6022 "aomenc refused the fixture: {}",
6023 String::from_utf8_lossy(&out.stderr)
6024 );
6025 let stream = out.stdout;
6026 let before = decode::obmc_hits();
6027 let frames = match decode_stream(&stream) {
6028 Err(e) => {
6029 let msg = e.to_string();
6030 assert!(
6031 msg.contains("unsupported"),
6032 "{NAME} failed outright (seed {seed}): {msg}"
6033 );
6034 refusals.push(format!("seed {seed}: {msg}"));
6035 continue;
6036 }
6037 Ok(frames) => frames,
6038 };
6039 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
6040 // is ALWAYS pixel-compared below; the hit counter only decides whether
6041 // the attempt counts toward the firing total.
6042 let counted = decode::obmc_hits() != before;
6043 if !counted {
6044 never_fired += 1;
6045 }
6046 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
6047 assert_eq!(frames.len(), frame_count);
6048 let mismatched = frames
6049 .iter()
6050 .zip(&ffmpeg_frames)
6051 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
6052 if mismatched {
6053 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
6054 std::fs::write(&path, &stream).expect("writing pinned stream");
6055 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
6056 }
6057 }
6058 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6059 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
6060 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
6061 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
6062 }
6063 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
6064 // stream again, comparing EVERY decode-order frame -- the hidden
6065 // (show_frame == 0) alt-ref frames the ffmpeg compare above
6066 // cannot see, because both sides of it emit shown frames only.
6067 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
6068 eprintln!(
6069 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
6070 {hidden_n} hidden, all pixel-exact vs the oracle"
6071 );
6072 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
6073 // libaom's temporal alt-ref filter absorbs this recipe's hidden
6074 // frames, so the compare above is vacuous -- re-encode the same
6075 // fixture with --arnr-maxframes=0 and compare THOSE.
6076 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
6077 eprintln!(
6078 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
6079 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
6080 );
6081 }
6082 if counted {
6083 eprintln!(
6084 "{NAME} FIRING seed {seed}: obmc hits advanced by {}",
6085 decode::obmc_hits() - before
6086 );
6087 gate_buckets(NAME, 1, never_fired, refusals.len());
6088 return;
6089 }
6090 }
6091 gate_buckets(NAME, 0, never_fired, refusals.len());
6092 eprintln!(
6093 "SKIP {NAME}: {never_fired} attempts decoded but never fired obmc, and every \
6094 other attempt hit a named refusal:\n{}",
6095 refusals.join("\n")
6096 );
6097 }
6098
6099 /// lane-motionmode round 3: same shape as
6100 /// `a_real_aomenc_stream_with_obmc_decodes_pixel_exact`, but relaxed the
6101 /// `--min-partition-size=32 --max-partition-size=32` clamp (that other
6102 /// gate's own doc: locked to remove partition-depth choice from the
6103 /// search entirely) to `8`/`32`, to make an 8x8-leaf `OBMC_CAUSAL` pick
6104 /// possible at all. Gated on [`decode::obmc_hits_8`] specifically, not
6105 /// the aggregate [`decode::obmc_hits`]. Measured live (round 3, this
6106 /// box): 80 attempts, 0 ever called `decode_inter_block8` at all --
6107 /// `cpu-used=0`'s RD search never once splits a 16x16 down to a clean
6108 /// 4-way 8x8 leaf for this smooth `gradients` fixture (large blocks
6109 /// always win the RD cost there); the handful of named refusals seen
6110 /// are `PARTITION_SPLIT` chosen *at* 8x8 (down to 4x4, already refused
6111 /// at `decode.rs`'s `part8 != PARTITION_NONE` check) or
6112 /// `allow_screen_content_tools`, neither reaching a leaf. Kept anyway
6113 /// (mirrors this file's own `never_fired`-skip convention) as the
6114 /// honest record of the attempt; a real 8x8 OBMC fixture needs
6115 /// higher-frequency content than this gate's fixtures use, out of
6116 /// round-3 budget.
6117 #[test]
6118 fn a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact() {
6119 const NAME: &str = "a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact";
6120 let _gate_lock = lock_gate_counters();
6121 if !have_ffmpeg() {
6122 eprintln!("SKIP {NAME}: no ffmpeg");
6123 return;
6124 }
6125 if !have_aomenc() {
6126 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6127 return;
6128 }
6129 let (width, height, frame_count) = (64usize, 64usize, 24usize);
6130 let mut refusals = Vec::new();
6131 let mut never_fired = 0u32;
6132 let mut total_obmc8 = 0usize;
6133 let n_attempts: u32 = std::env::var("EC_OBMC8_ATTEMPTS")
6134 .ok()
6135 .and_then(|s| s.parse().ok())
6136 .unwrap_or(80);
6137 for attempt in 0..n_attempts {
6138 let seed = 42 + attempt % 40;
6139 let duration = frame_count as f64 / 25.0;
6140 // Recipe search hook: `gradients` is smooth, so aomenc's RD never
6141 // splits below 16x16 and this gate never fired one 8x8 OBMC block
6142 // in 45 attempts -- it "passed" by skipping (gate-blind-to-feature).
6143 // EC_AV1_OBMC8_SOURCE overrides the lavfi source so a firing recipe
6144 // can be searched for without a rebuild.
6145 let source = std::env::var("EC_AV1_OBMC8_SOURCE").unwrap_or_else(|_| {
6146 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
6147 });
6148 // A source supplied through EC_AV1_OBMC8_SOURCE need not carry its
6149 // own `duration=`; `-t` is the bound that always holds. Without it
6150 // an endless source (`testsrc2`) fills the pipe forever and the
6151 // gate hangs to its 300 s timeout.
6152 let duration_arg = format!("{duration}");
6153 let y4m = Command::new("ffmpeg")
6154 .args([
6155 "-v",
6156 "error",
6157 "-f",
6158 "lavfi",
6159 "-i",
6160 &source,
6161 "-t",
6162 &duration_arg,
6163 "-pix_fmt",
6164 "yuv420p",
6165 "-f",
6166 "yuv4mpegpipe",
6167 "-",
6168 ])
6169 .stdin(Stdio::null())
6170 .stdout(Stdio::piped())
6171 .stderr(Stdio::piped())
6172 .output()
6173 .expect("ffmpeg failed to run");
6174 assert!(
6175 y4m.status.success(),
6176 "ffmpeg fixture: {}",
6177 String::from_utf8_lossy(&y4m.stderr)
6178 );
6179 let args: Vec<&str> = vec![
6180 "--codec=av1",
6181 "--passes=1",
6182 "--end-usage=q",
6183 "--cq-level=45",
6184 "--cpu-used=0",
6185 "--kf-max-dist=1000",
6186 "--threads=1",
6187 "--row-mt=0",
6188 "--auto-alt-ref=1",
6189 "--lag-in-frames=16",
6190 "--enable-fwd-kf=0",
6191 "--enable-order-hint=1",
6192 "--enable-warped-motion=0",
6193 "--enable-obmc=1",
6194 "--enable-masked-comp=0",
6195 "--enable-interintra-comp=0",
6196 "--enable-onesided-comp=0",
6197 "--enable-interintra-wedge=0",
6198 "--enable-smooth-interintra=0",
6199 "--enable-rect-partitions=0",
6200 "--enable-ab-partitions=0",
6201 "--enable-1to4-partitions=0",
6202 "--enable-filter-intra=0",
6203 "--enable-smooth-intra=0",
6204 "--enable-paeth-intra=0",
6205 "--enable-directional-intra=0",
6206 "--enable-angle-delta=0",
6207 "--enable-tx-size-search=0",
6208 "--enable-cdef=0",
6209 "--enable-restoration=0",
6210 "--min-partition-size=8",
6211 "--max-partition-size=32",
6212 "--enable-palette=0",
6213 "--enable-intrabc=0",
6214 "--enable-cfl-intra=0",
6215 "--enable-ref-frame-mvs=0",
6216 "--obu",
6217 "-o",
6218 "-",
6219 "-",
6220 ];
6221 let mut child = Command::new(aomenc_path())
6222 .args(&args)
6223 .stdin(Stdio::piped())
6224 .stdout(Stdio::piped())
6225 .stderr(Stdio::piped())
6226 .spawn()
6227 .expect("aomenc failed to start");
6228 child
6229 .stdin
6230 .take()
6231 .expect("aomenc stdin")
6232 .write_all(&y4m.stdout)
6233 .expect("writing y4m to aomenc");
6234 let out = child.wait_with_output().expect("aomenc failed to run");
6235 assert!(
6236 out.status.success(),
6237 "aomenc refused the fixture: {}",
6238 String::from_utf8_lossy(&out.stderr)
6239 );
6240 let stream = out.stdout;
6241 let before8 = decode::obmc_hits_8();
6242 let frames = match decode_stream(&stream) {
6243 Err(e) => {
6244 let msg = e.to_string();
6245 assert!(
6246 msg.contains("unsupported"),
6247 "{NAME} failed outright (seed {seed}): {msg}"
6248 );
6249 refusals.push(format!("seed {seed}: {msg}"));
6250 continue;
6251 }
6252 Ok(frames) => frames,
6253 };
6254 let fired8 = decode::obmc_hits_8() - before8;
6255 total_obmc8 += fired8;
6256 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
6257 // is ALWAYS pixel-compared below; the hit counter only decides whether
6258 // the attempt counts toward the firing total.
6259 let counted = fired8 != 0;
6260 if !counted {
6261 never_fired += 1;
6262 }
6263 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
6264 assert_eq!(frames.len(), frame_count);
6265 let mismatched = frames
6266 .iter()
6267 .zip(&ffmpeg_frames)
6268 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
6269 if mismatched {
6270 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
6271 std::fs::write(&path, &stream).expect("writing pinned stream");
6272 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
6273 }
6274 }
6275 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6276 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
6277 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
6278 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
6279 }
6280 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
6281 // stream again, comparing EVERY decode-order frame -- the hidden
6282 // (show_frame == 0) alt-ref frames the ffmpeg compare above
6283 // cannot see, because both sides of it emit shown frames only.
6284 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
6285 eprintln!(
6286 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
6287 {hidden_n} hidden, all pixel-exact vs the oracle"
6288 );
6289 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
6290 // libaom's temporal alt-ref filter absorbs this recipe's hidden
6291 // frames, so the compare above is vacuous -- re-encode the same
6292 // fixture with --arnr-maxframes=0 and compare THOSE.
6293 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
6294 eprintln!(
6295 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
6296 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
6297 );
6298 }
6299 if counted {
6300 eprintln!(
6301 "{NAME} FIRING seed {seed}: 8x8 obmc hits {fired8} (total across attempts so far {total_obmc8})"
6302 );
6303 gate_buckets(NAME, 1, never_fired, refusals.len());
6304 return;
6305 }
6306 }
6307 gate_buckets(NAME, 0, never_fired, refusals.len());
6308 eprintln!(
6309 "SKIP {NAME}: {never_fired} attempts decoded but never fired an 8x8 obmc block \
6310 ({total_obmc8} total 8x8 obmc hits across all attempts), and every other attempt \
6311 hit a named refusal:\n{}",
6312 refusals.join("\n")
6313 );
6314 }
6315
6316 /// lane-warp r5e (flipped from lane-motionmode r1's refuses-or-matches):
6317 /// `--enable-warped-motion=1` streams must DECODE pixel-exact --
6318 /// `av1_findSamples`/`num_proj_ref`, the 3-symbol `motion_mode` read,
6319 /// the affine projection/filter, and the WARPED_CAUSAL interp-filter
6320 /// derivation are all ported. A refusal naming warp, or any pixel
6321 /// mismatch, fails the gate; refusals for OTHER named capabilities
6322 /// (screen content tools) still skip that seed. The sweep must also
6323 /// actually exercise warp (`warp_selected_hits > 0`) so a decoder that
6324 /// silently stops selecting WARPED_CAUSAL cannot pass vacuously.
6325 #[test]
6326 fn a_real_aomenc_stream_with_warped_motion_refuses_or_matches() {
6327 const NAME: &str = "a_real_aomenc_stream_with_warped_motion_refuses_or_matches";
6328 let _gate_lock = lock_gate_counters();
6329 if !have_ffmpeg() {
6330 eprintln!("SKIP {NAME}: no ffmpeg");
6331 return;
6332 }
6333 if !have_aomenc() {
6334 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6335 return;
6336 }
6337 let (width, height, frame_count) = (64usize, 64usize, 24usize);
6338 let mut named_refusals = 0u32;
6339 let mut matched = 0u32;
6340 let n_attempts: u32 = std::env::var("EC_WARP_GATE_ATTEMPTS")
6341 .ok()
6342 .and_then(|s| s.parse().ok())
6343 .unwrap_or(40);
6344 for attempt in 0..n_attempts {
6345 let seed = 42 + attempt;
6346 let duration = frame_count as f64 / 25.0;
6347 let source =
6348 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
6349 let y4m = Command::new("ffmpeg")
6350 .args([
6351 "-v",
6352 "error",
6353 "-f",
6354 "lavfi",
6355 "-i",
6356 &source,
6357 "-pix_fmt",
6358 "yuv420p",
6359 "-f",
6360 "yuv4mpegpipe",
6361 "-",
6362 ])
6363 .stdin(Stdio::null())
6364 .stdout(Stdio::piped())
6365 .stderr(Stdio::piped())
6366 .output()
6367 .expect("ffmpeg failed to run");
6368 assert!(
6369 y4m.status.success(),
6370 "ffmpeg fixture: {}",
6371 String::from_utf8_lossy(&y4m.stderr)
6372 );
6373 let args: Vec<&str> = vec![
6374 "--codec=av1",
6375 "--passes=1",
6376 "--end-usage=q",
6377 "--cq-level=45",
6378 "--cpu-used=0",
6379 "--kf-max-dist=1000",
6380 "--threads=1",
6381 "--row-mt=0",
6382 "--auto-alt-ref=1",
6383 "--lag-in-frames=16",
6384 "--enable-fwd-kf=0",
6385 "--enable-order-hint=1",
6386 "--enable-warped-motion=1",
6387 "--enable-obmc=1",
6388 "--tune-content=default",
6389 "--enable-masked-comp=0",
6390 "--enable-interintra-comp=0",
6391 "--enable-onesided-comp=0",
6392 "--enable-interintra-wedge=0",
6393 "--enable-smooth-interintra=0",
6394 "--enable-rect-partitions=0",
6395 "--enable-ab-partitions=0",
6396 "--enable-1to4-partitions=0",
6397 "--enable-filter-intra=0",
6398 "--enable-smooth-intra=0",
6399 "--enable-paeth-intra=0",
6400 "--enable-directional-intra=0",
6401 "--enable-angle-delta=0",
6402 "--enable-tx-size-search=0",
6403 "--enable-cdef=0",
6404 "--enable-restoration=0",
6405 "--max-partition-size=32",
6406 "--min-partition-size=32",
6407 "--enable-palette=0",
6408 "--enable-intrabc=0",
6409 "--enable-cfl-intra=0",
6410 "--enable-ref-frame-mvs=0",
6411 "--obu",
6412 "-o",
6413 "-",
6414 "-",
6415 ];
6416 let mut child = Command::new(aomenc_path())
6417 .args(&args)
6418 .stdin(Stdio::piped())
6419 .stdout(Stdio::piped())
6420 .stderr(Stdio::piped())
6421 .spawn()
6422 .expect("aomenc failed to start");
6423 child
6424 .stdin
6425 .take()
6426 .expect("aomenc stdin")
6427 .write_all(&y4m.stdout)
6428 .expect("writing y4m to aomenc");
6429 let out = child.wait_with_output().expect("aomenc failed to run");
6430 assert!(
6431 out.status.success(),
6432 "aomenc refused the fixture: {}",
6433 String::from_utf8_lossy(&out.stderr)
6434 );
6435 let stream = out.stdout;
6436 let frames = match decode_stream(&stream) {
6437 Err(e) => {
6438 let msg = e.to_string();
6439 assert!(
6440 msg.contains("unsupported"),
6441 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
6442 );
6443 assert!(
6444 !msg.contains("warp"),
6445 "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \
6446 refusal must not exist: {msg}"
6447 );
6448 named_refusals += 1;
6449 eprintln!("seed {seed} refusal (non-warp capability): {msg}");
6450 continue;
6451 }
6452 Ok(frames) => frames,
6453 };
6454 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
6455 assert_eq!(frames.len(), frame_count);
6456 let mismatched = frames
6457 .iter()
6458 .zip(&ffmpeg_frames)
6459 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
6460 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
6461 std::fs::write(&path, &stream).expect("writing pinned stream");
6462 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
6463 }
6464 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6465 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
6466 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
6467 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
6468 }
6469 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
6470 // stream again, comparing EVERY decode-order frame -- the hidden
6471 // (show_frame == 0) alt-ref frames the ffmpeg compare above
6472 // cannot see, because both sides of it emit shown frames only.
6473 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
6474 eprintln!(
6475 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
6476 {hidden_n} hidden, all pixel-exact vs the oracle"
6477 );
6478 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
6479 // libaom's temporal alt-ref filter absorbs this recipe's hidden
6480 // frames, so the compare above is vacuous -- re-encode the same
6481 // fixture with --arnr-maxframes=0 and compare THOSE.
6482 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
6483 eprintln!(
6484 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
6485 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
6486 );
6487 }
6488 matched += 1;
6489 }
6490 assert!(
6491 matched > 0,
6492 "{NAME}: every attempt refused on other capabilities; the gate never exercised warp"
6493 );
6494 assert!(
6495 crate::decode::warp_selected_hits() > 0,
6496 "{NAME}: {matched} matches but zero WARPED_CAUSAL blocks fired -- the gate decodes \
6497 warp streams without ever selecting warp, so it proves nothing about warp"
6498 );
6499 eprintln!(
6500 "{NAME}: {named_refusals} non-warp refusals, {matched} pixel-exact matches out of {n_attempts}, warp_selected_hits={}",
6501 crate::decode::warp_selected_hits()
6502 );
6503 }
6504
6505 /// lane-superres stage 3: a real aomenc `--superres-mode=1` key-frame
6506 /// sequence must decode pixel-exact vs ffmpeg/dav1d's own upscaled
6507 /// output, and must actually run [`crate::superres::upscale_picture`]
6508 /// (`superres_hits > 0`) -- a decoder that silently stopped upscaling
6509 /// would otherwise pass vacuously (class `gate-blind-to-feature`).
6510 /// `--kf-max-dist` set to the frame count keeps every frame a key
6511 /// frame: inter-frame superres (a differently-scaled reference) is a
6512 /// later stage of this lane, refused by name today.
6513 #[test]
6514 fn a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact() {
6515 const NAME: &str = "a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact";
6516 let _gate_lock = lock_gate_counters();
6517 if !have_ffmpeg() {
6518 eprintln!("SKIP {NAME}: no ffmpeg");
6519 return;
6520 }
6521 if !have_aomenc() {
6522 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6523 return;
6524 }
6525 let (width, height, frame_count) = (64usize, 64usize, 3usize);
6526 let duration = frame_count as f64 / 25.0;
6527 let source = gradients_source(7, width, height, &format!("duration={duration}:rate=25"));
6528 let y4m = Command::new("ffmpeg")
6529 .args([
6530 "-v",
6531 "error",
6532 "-f",
6533 "lavfi",
6534 "-i",
6535 &source,
6536 "-pix_fmt",
6537 "yuv420p",
6538 "-f",
6539 "yuv4mpegpipe",
6540 "-",
6541 ])
6542 .stdin(Stdio::null())
6543 .stdout(Stdio::piped())
6544 .stderr(Stdio::piped())
6545 .output()
6546 .expect("ffmpeg failed to run");
6547 assert!(
6548 y4m.status.success(),
6549 "ffmpeg fixture: {}",
6550 String::from_utf8_lossy(&y4m.stderr)
6551 );
6552 let args: Vec<&str> = vec![
6553 "--codec=av1",
6554 "--passes=1",
6555 "--end-usage=q",
6556 "--cq-level=32",
6557 "--cpu-used=0",
6558 "--kf-max-dist=0",
6559 "--threads=1",
6560 "--row-mt=0",
6561 "--superres-mode=1",
6562 "--superres-denominator=12",
6563 "--superres-kf-denominator=12",
6564 "--enable-rect-partitions=0",
6565 "--enable-ab-partitions=0",
6566 "--enable-1to4-partitions=0",
6567 "--enable-filter-intra=0",
6568 "--enable-smooth-intra=0",
6569 "--enable-paeth-intra=0",
6570 "--enable-directional-intra=0",
6571 "--enable-angle-delta=0",
6572 "--enable-tx-size-search=0",
6573 "--enable-cdef=0",
6574 "--enable-restoration=0",
6575 "--max-partition-size=32",
6576 "--min-partition-size=32",
6577 "--enable-palette=0",
6578 "--enable-intrabc=0",
6579 "--enable-cfl-intra=0",
6580 "--obu",
6581 "-o",
6582 "-",
6583 "-",
6584 ];
6585 let mut child = Command::new(aomenc_path())
6586 .args(&args)
6587 .stdin(Stdio::piped())
6588 .stdout(Stdio::piped())
6589 .stderr(Stdio::piped())
6590 .spawn()
6591 .expect("aomenc failed to start");
6592 child
6593 .stdin
6594 .take()
6595 .expect("aomenc stdin")
6596 .write_all(&y4m.stdout)
6597 .expect("writing y4m to aomenc");
6598 let out = child.wait_with_output().expect("aomenc failed to run");
6599 assert!(
6600 out.status.success(),
6601 "aomenc refused the fixture: {}",
6602 String::from_utf8_lossy(&out.stderr)
6603 );
6604 let stream = out.stdout;
6605 if let Ok(path) = std::env::var("EC_SUPERRES_STREAM_DUMP") {
6606 std::fs::write(path, &stream).expect("dump stream");
6607 }
6608 let frames =
6609 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}"));
6610 assert_eq!(frames.len(), frame_count);
6611 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
6612 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6613 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg");
6614 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
6615 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
6616 }
6617 assert!(
6618 crate::superres::superres_hits() > 0,
6619 "{NAME}: matched but zero superres_hits -- the gate never actually exercised the \
6620 upscaler, it proves nothing"
6621 );
6622 eprintln!(
6623 "{NAME}: {frame_count} frames pixel-exact, superres_hits={}",
6624 crate::superres::superres_hits()
6625 );
6626 }
6627
6628 /// lane-superres r10: a real aomenc key+inter `--superres-mode=1`
6629 /// sequence must DECODE pixel-exact vs ffmpeg, with the frame-level
6630 /// `use_superres` refusal LIFTED for inter frames -- `mc::predict_scaled`
6631 /// (spec 7.11.3.3) is the only path this recipe can reach (warp/OBMC/
6632 /// compound/interintra/palette/intrabc/CDEF/LR are all off, matching the
6633 /// scoped refusals' own unimplemented list). A pixel match alone would
6634 /// pass just as well with an unscaled reference and prove nothing
6635 /// (class `gate-blind-to-feature`) -- hard-assert
6636 /// `crate::mc::predict_scaled_hits() > 0` so the gate can only pass if the
6637 /// scaled MC path actually ran.
6638 #[test]
6639 fn a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact() {
6640 const NAME: &str = "a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact";
6641 let _gate_lock = lock_gate_counters();
6642 if !have_ffmpeg() {
6643 eprintln!("SKIP {NAME}: no ffmpeg");
6644 return;
6645 }
6646 if !have_aomenc() {
6647 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6648 return;
6649 }
6650 let (width, height, frame_count) = (64usize, 64usize, 3usize);
6651 let duration = frame_count as f64 / 25.0;
6652 let source = gradients_source(11, width, height, &format!("duration={duration}:rate=25"));
6653 let y4m = Command::new("ffmpeg")
6654 .args([
6655 "-v",
6656 "error",
6657 "-f",
6658 "lavfi",
6659 "-i",
6660 &source,
6661 "-pix_fmt",
6662 "yuv420p",
6663 "-f",
6664 "yuv4mpegpipe",
6665 "-",
6666 ])
6667 .stdin(Stdio::null())
6668 .stdout(Stdio::piped())
6669 .stderr(Stdio::piped())
6670 .output()
6671 .expect("ffmpeg failed to run");
6672 assert!(
6673 y4m.status.success(),
6674 "ffmpeg fixture: {}",
6675 String::from_utf8_lossy(&y4m.stderr)
6676 );
6677 let args: Vec<&str> = vec![
6678 "--codec=av1",
6679 "--passes=1",
6680 "--end-usage=q",
6681 "--cq-level=32",
6682 "--cpu-used=0",
6683 // `--kf-max-dist` above `frame_count` keeps only frame 0 a key
6684 // frame -- frames 1/2 are the inter frames whose `use_superres`
6685 // refusal this round lifts.
6686 "--kf-max-dist=1000",
6687 "--lag-in-frames=0",
6688 "--auto-alt-ref=0",
6689 "--threads=1",
6690 "--row-mt=0",
6691 "--sb-size=64",
6692 "--superres-mode=1",
6693 "--superres-denominator=12",
6694 "--superres-kf-denominator=12",
6695 // Forces every inter block onto the single-ref, non-warp/OBMC/
6696 // interintra branch `decode_inter_block` threads `predict_scaled`
6697 // through -- the only branch this round's scoped refusals leave
6698 // unrefused under a scaled reference.
6699 "--enable-warped-motion=0",
6700 "--enable-obmc=0",
6701 "--enable-masked-comp=0",
6702 "--enable-interintra-comp=0",
6703 "--enable-dist-wtd-comp=0",
6704 "--enable-diff-wtd-comp=0",
6705 "--enable-onesided-comp=0",
6706 "--enable-interintra-wedge=0",
6707 "--enable-smooth-interintra=0",
6708 "--enable-order-hint=0",
6709 "--enable-ref-frame-mvs=0",
6710 "--enable-rect-partitions=0",
6711 "--enable-ab-partitions=0",
6712 "--enable-1to4-partitions=0",
6713 "--enable-filter-intra=0",
6714 "--enable-smooth-intra=0",
6715 "--enable-paeth-intra=0",
6716 "--enable-directional-intra=0",
6717 "--enable-angle-delta=0",
6718 "--enable-tx-size-search=0",
6719 "--enable-cdef=0",
6720 "--enable-restoration=0",
6721 "--max-partition-size=32",
6722 "--min-partition-size=32",
6723 "--enable-palette=0",
6724 "--enable-intrabc=0",
6725 "--enable-cfl-intra=0",
6726 "--obu",
6727 "-o",
6728 "-",
6729 "-",
6730 ];
6731 let mut child = Command::new(aomenc_path())
6732 .args(&args)
6733 .stdin(Stdio::piped())
6734 .stdout(Stdio::piped())
6735 .stderr(Stdio::piped())
6736 .spawn()
6737 .expect("aomenc failed to start");
6738 child
6739 .stdin
6740 .take()
6741 .expect("aomenc stdin")
6742 .write_all(&y4m.stdout)
6743 .expect("writing y4m to aomenc");
6744 let out = child.wait_with_output().expect("aomenc failed to run");
6745 assert!(
6746 out.status.success(),
6747 "aomenc refused the fixture: {}",
6748 String::from_utf8_lossy(&out.stderr)
6749 );
6750 let stream = out.stdout;
6751 if let Ok(path) = std::env::var("EC_SUPERRES_INTER_STREAM_DUMP") {
6752 std::fs::write(&path, &stream).expect("dump stream");
6753 }
6754 let frames =
6755 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}"));
6756 assert_eq!(frames.len(), frame_count);
6757 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
6758 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6759 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg");
6760 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
6761 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
6762 }
6763 assert!(
6764 crate::superres::superres_hits() > 0,
6765 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
6766 );
6767 assert!(
6768 crate::mc::predict_scaled_hits() > 0,
6769 "{NAME}: matched but zero predict_scaled_hits -- every block took the unscaled MC \
6770 path, which proves nothing about the scaled-reference code this round adds \
6771 (class gate-blind-to-feature)"
6772 );
6773 eprintln!(
6774 "{NAME}: {frame_count} frames pixel-exact, superres_hits={}, predict_scaled_hits={}",
6775 crate::superres::superres_hits(),
6776 crate::mc::predict_scaled_hits()
6777 );
6778 }
6779
6780 /// lane-interintra r1: `--enable-interintra-comp=1` streams must DECODE
6781 /// pixel-exact -- the interintra flag/mode/wedge-flag syntax and the
6782 /// non-wedge smooth blend are ported. A refusal naming interintra fails
6783 /// the gate UNLESS it is the wedge refusal (`use_wedge_interintra == 1`
6784 /// is r2, and this recipe encodes with wedge off so it must not fire
6785 /// either); warp/obmc are enabled and supported; refusals for OTHER
6786 /// named capabilities (screen content tools) still skip that seed. The
6787 /// sweep must actually exercise interintra (`interintra_hits > 0`).
6788 #[test]
6789 fn a_real_aomenc_stream_with_interintra_decodes_pixel_exact() {
6790 const NAME: &str = "a_real_aomenc_stream_with_interintra_decodes_pixel_exact";
6791 let _gate_lock = lock_gate_counters();
6792 if !have_ffmpeg() {
6793 eprintln!("SKIP {NAME}: no ffmpeg");
6794 return;
6795 }
6796 if !have_aomenc() {
6797 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6798 return;
6799 }
6800 let (width, height, frame_count) = (64usize, 64usize, 24usize);
6801 let mut named_refusals = 0u32;
6802 let mut matched = 0u32;
6803 let n_attempts: u32 = std::env::var("EC_INTERINTRA_GATE_ATTEMPTS")
6804 .ok()
6805 .and_then(|s| s.parse().ok())
6806 .unwrap_or(40);
6807 for attempt in 0..n_attempts {
6808 let seed = 42 + attempt;
6809 let duration = frame_count as f64 / 25.0;
6810 let source =
6811 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
6812 let y4m = Command::new("ffmpeg")
6813 .args([
6814 "-v",
6815 "error",
6816 "-f",
6817 "lavfi",
6818 "-i",
6819 &source,
6820 "-pix_fmt",
6821 "yuv420p",
6822 "-f",
6823 "yuv4mpegpipe",
6824 "-",
6825 ])
6826 .stdin(Stdio::null())
6827 .stdout(Stdio::piped())
6828 .stderr(Stdio::piped())
6829 .output()
6830 .expect("ffmpeg failed to run");
6831 assert!(
6832 y4m.status.success(),
6833 "ffmpeg fixture: {}",
6834 String::from_utf8_lossy(&y4m.stderr)
6835 );
6836 let args: Vec<&str> = vec![
6837 "--codec=av1",
6838 "--passes=1",
6839 "--end-usage=q",
6840 "--cq-level=45",
6841 "--cpu-used=0",
6842 "--kf-max-dist=1000",
6843 "--threads=1",
6844 "--row-mt=0",
6845 "--auto-alt-ref=1",
6846 "--lag-in-frames=16",
6847 "--enable-fwd-kf=0",
6848 "--enable-order-hint=1",
6849 "--enable-warped-motion=1",
6850 "--enable-obmc=1",
6851 "--tune-content=default",
6852 "--enable-masked-comp=0",
6853 "--enable-interintra-comp=1",
6854 "--enable-onesided-comp=0",
6855 "--enable-interintra-wedge=0",
6856 "--enable-smooth-interintra=1",
6857 "--enable-rect-partitions=0",
6858 "--enable-ab-partitions=0",
6859 "--enable-1to4-partitions=0",
6860 "--enable-filter-intra=0",
6861 "--enable-smooth-intra=0",
6862 "--enable-paeth-intra=0",
6863 "--enable-directional-intra=0",
6864 "--enable-angle-delta=0",
6865 "--enable-tx-size-search=0",
6866 "--enable-cdef=0",
6867 "--enable-restoration=0",
6868 "--max-partition-size=32",
6869 "--min-partition-size=32",
6870 "--enable-palette=0",
6871 "--enable-intrabc=0",
6872 "--enable-cfl-intra=0",
6873 "--enable-ref-frame-mvs=0",
6874 "--obu",
6875 "-o",
6876 "-",
6877 "-",
6878 ];
6879 let mut child = Command::new(aomenc_path())
6880 .args(&args)
6881 .stdin(Stdio::piped())
6882 .stdout(Stdio::piped())
6883 .stderr(Stdio::piped())
6884 .spawn()
6885 .expect("aomenc failed to start");
6886 child
6887 .stdin
6888 .take()
6889 .expect("aomenc stdin")
6890 .write_all(&y4m.stdout)
6891 .expect("writing y4m to aomenc");
6892 let out = child.wait_with_output().expect("aomenc failed to run");
6893 assert!(
6894 out.status.success(),
6895 "aomenc refused the fixture: {}",
6896 String::from_utf8_lossy(&out.stderr)
6897 );
6898 let stream = out.stdout;
6899 let frames = match decode_stream(&stream) {
6900 Err(e) => {
6901 let msg = e.to_string();
6902 assert!(
6903 msg.contains("unsupported"),
6904 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
6905 );
6906 assert!(
6907 !msg.contains("warp"),
6908 "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \
6909 refusal must not exist: {msg}"
6910 );
6911 assert!(
6912 !msg.contains("interintra"),
6913 "{NAME} refused on interintra (seed {seed}) -- non-wedge interintra \
6914 is ported and this recipe encodes with wedge off: {msg}"
6915 );
6916 named_refusals += 1;
6917 eprintln!("seed {seed} refusal (non-warp capability): {msg}");
6918 continue;
6919 }
6920 Ok(frames) => frames,
6921 };
6922 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
6923 assert_eq!(frames.len(), frame_count);
6924 let mismatched = frames
6925 .iter()
6926 .zip(&ffmpeg_frames)
6927 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
6928 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
6929 std::fs::write(&path, &stream).expect("writing pinned stream");
6930 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
6931 }
6932 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
6933 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
6934 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
6935 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
6936 }
6937 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
6938 // stream again, comparing EVERY decode-order frame -- the hidden
6939 // (show_frame == 0) alt-ref frames the ffmpeg compare above
6940 // cannot see, because both sides of it emit shown frames only.
6941 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
6942 eprintln!(
6943 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
6944 {hidden_n} hidden, all pixel-exact vs the oracle"
6945 );
6946 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
6947 // libaom's temporal alt-ref filter absorbs this recipe's hidden
6948 // frames, so the compare above is vacuous -- re-encode the same
6949 // fixture with --arnr-maxframes=0 and compare THOSE.
6950 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
6951 eprintln!(
6952 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
6953 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
6954 );
6955 }
6956 matched += 1;
6957 }
6958 assert!(
6959 matched > 0,
6960 "{NAME}: every attempt refused on other capabilities; the gate never exercised warp"
6961 );
6962 assert!(
6963 crate::decode::interintra_hits() > 0,
6964 "{NAME}: {matched} matches but zero interintra blocks fired -- the gate decodes \
6965 these streams without ever taking interintra, so it proves nothing"
6966 );
6967 eprintln!(
6968 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, interintra_hits={}",
6969 crate::decode::interintra_hits()
6970 );
6971 }
6972
6973 /// lane-scaledref r1: a real aomenc `--superres-mode=1` sequence with
6974 /// compound, OBMC, interintra and 8x8 leaves ALL enabled must decode
6975 /// pixel-exact -- these are the combinations the three
6976 /// "... with a scaled reference (superres, unimplemented)" refusals used
6977 /// to cover. Each combination gets its OWN hard-asserted hit counter
6978 /// (`crate::decode::scaled_*_hits`), because an unscaled reference would
6979 /// pass the pixels and prove nothing (class `gate-blind-to-feature`), and
6980 /// a stream that scales but never takes compound/OBMC/interintra/8x8
6981 /// would prove nothing about the code this round adds either. A refusal
6982 /// naming a scaled reference is a hard failure: those are exactly the
6983 /// strings this round lifts. Other named capabilities skip that seed.
6984 #[test]
6985 fn a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact()
6986 {
6987 const NAME: &str = "a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact";
6988 let _gate_lock = lock_gate_counters();
6989 if !have_ffmpeg() {
6990 eprintln!("SKIP {NAME}: no ffmpeg");
6991 return;
6992 }
6993 if !have_aomenc() {
6994 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6995 return;
6996 }
6997 let (width, height, frame_count) = (64usize, 64usize, 24usize);
6998 let mut named_refusals = 0u32;
6999 let mut matched = 0u32;
7000 let n_attempts: u32 = std::env::var("EC_SCALEDREF_GATE_ATTEMPTS")
7001 .ok()
7002 .and_then(|s| s.parse().ok())
7003 .unwrap_or(12);
7004 for attempt in 0..n_attempts {
7005 let seed = 42 + attempt;
7006 let duration = frame_count as f64 / 25.0;
7007 let source =
7008 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
7009 let y4m = Command::new("ffmpeg")
7010 .args([
7011 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
7012 "yuv4mpegpipe", "-",
7013 ])
7014 .stdin(Stdio::null())
7015 .stdout(Stdio::piped())
7016 .stderr(Stdio::piped())
7017 .output()
7018 .expect("ffmpeg failed to run");
7019 assert!(
7020 y4m.status.success(),
7021 "ffmpeg fixture: {}",
7022 String::from_utf8_lossy(&y4m.stderr)
7023 );
7024 let on = |name: &str| {
7025 if std::env::var(name).as_deref() == Ok("0") { "0" } else { "1" }
7026 };
7027 // lane-scaledref r2: warp is ON. A warp-capable frame header
7028 // under a scaled reference is exactly the case r1 got wrong
7029 // (the block must read the 2-symbol `obmc_cdf`, not the
7030 // 3-symbol `motion_mode_cdf` -- libaom `motion_mode_allowed`,
7031 // blockd.h:1484), and it decoded silently wrong pixels rather
7032 // than refusing. `EC_SCALEDREF_WARP=0` turns it off for
7033 // bisecting only.
7034 let warp = format!("--enable-warped-motion={}", on("EC_SCALEDREF_WARP"));
7035 // lane-scaledref r2: `EC_SCALEDREF_MODE=3` (qthresh) lets
7036 // superres switch on and off per frame, so a compound block can
7037 // reference one scaled and one unscaled reference -- the mixed
7038 // case mode 1 (every frame scaled) never produces.
7039 let superres_mode = format!(
7040 "--superres-mode={}",
7041 std::env::var("EC_SCALEDREF_MODE").unwrap_or_else(|_| "1".into())
7042 );
7043 let obmc = format!("--enable-obmc={}", on("EC_SCALEDREF_OBMC"));
7044 let interintra = format!("--enable-interintra-comp={}", on("EC_SCALEDREF_II"));
7045 let lag = format!(
7046 "--lag-in-frames={}",
7047 if on("EC_SCALEDREF_COMP") == "0" { "0" } else { "25" }
7048 );
7049 let alt_ref = format!("--auto-alt-ref={}", on("EC_SCALEDREF_COMP"));
7050 let args: Vec<&str> = vec![
7051 "--codec=av1",
7052 "--passes=1",
7053 "--end-usage=q",
7054 "--cq-level=45",
7055 "--cpu-used=0",
7056 "--kf-max-dist=1000",
7057 "--threads=1",
7058 "--row-mt=0",
7059 "--sb-size=64",
7060 // superres on every frame, key and inter alike -- the scaled
7061 // reference this gate is about.
7062 // denominator 16 (the maximum) keeps the CODED frame
7063 // 32x64 -- a multiple of 16 both ways, so no frame-edge
7064 // 16x16 straddle forces a sub-16x16 partition this decoder
7065 // still refuses on the aligned path ("an inter partition
7066 // below 16x16"). Denominator 12 codes 43 columns and every
7067 // seed refused there.
7068 &superres_mode,
7069 "--superres-denominator=16",
7070 "--superres-kf-denominator=16",
7071 // the four combinations this round lifts (each switchable
7072 // by env for bisecting a mismatch without a rebuild)
7073 &alt_ref,
7074 &lag,
7075 "--enable-order-hint=1",
7076 &warp,
7077 &obmc,
7078 &interintra,
7079 "--enable-smooth-interintra=1",
7080 "--enable-interintra-wedge=0",
7081 "--enable-masked-comp=0",
7082 "--enable-onesided-comp=0",
7083 "--enable-fwd-kf=0",
7084 "--tune-content=default",
7085 "--max-partition-size=32",
7086 "--min-partition-size=32",
7087 // everything this decoder still refuses under any reference
7088 "--enable-rect-partitions=0",
7089 "--enable-ab-partitions=0",
7090 "--enable-1to4-partitions=0",
7091 "--enable-filter-intra=0",
7092 "--enable-smooth-intra=0",
7093 "--enable-paeth-intra=0",
7094 "--enable-directional-intra=0",
7095 "--enable-angle-delta=0",
7096 "--enable-tx-size-search=0",
7097 "--enable-cdef=0",
7098 "--enable-restoration=0",
7099 "--enable-palette=0",
7100 "--enable-intrabc=0",
7101 "--enable-cfl-intra=0",
7102 "--enable-ref-frame-mvs=0",
7103 "--obu",
7104 "-o",
7105 "-",
7106 "-",
7107 ];
7108 let mut child = Command::new(aomenc_path())
7109 .args(&args)
7110 .stdin(Stdio::piped())
7111 .stdout(Stdio::piped())
7112 .stderr(Stdio::piped())
7113 .spawn()
7114 .expect("aomenc failed to start");
7115 child
7116 .stdin
7117 .take()
7118 .expect("aomenc stdin")
7119 .write_all(&y4m.stdout)
7120 .expect("writing y4m to aomenc");
7121 let out = child.wait_with_output().expect("aomenc failed to run");
7122 assert!(
7123 out.status.success(),
7124 "aomenc refused the fixture: {}",
7125 String::from_utf8_lossy(&out.stderr)
7126 );
7127 let stream = out.stdout;
7128 let frames = match decode_stream(&stream) {
7129 Err(e) => {
7130 let msg = e.to_string();
7131 assert!(
7132 msg.contains("unsupported"),
7133 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
7134 );
7135 assert!(
7136 !msg.contains("scaled reference"),
7137 "{NAME} refused on a scaled reference (seed {seed}) -- those refusals \
7138 are exactly what this round lifts: {msg}"
7139 );
7140 named_refusals += 1;
7141 eprintln!("seed {seed} refusal (other capability): {msg}");
7142 continue;
7143 }
7144 Ok(frames) => frames,
7145 };
7146 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
7147 assert_eq!(frames.len(), frame_count);
7148 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
7149 let mismatched = frames
7150 .iter()
7151 .zip(&ffmpeg_frames)
7152 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
7153 if mismatched {
7154 std::fs::write(&path, &stream).expect("writing pinned stream");
7155 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
7156 }
7157 }
7158 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
7159 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
7160 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
7161 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
7162 }
7163 matched += 1;
7164 }
7165 eprintln!(
7166 "{NAME}: {named_refusals} other-capability refusals, {matched}/{n_attempts} pixel-exact, \
7167 superres_hits={} predict_scaled_hits={} scaled_compound={} scaled_warp_fallback={} \
7168 scaled_obmc={} scaled_interintra={} scaled_block8={} scaled_warp_suppressed={} mixed_scale_compound={}",
7169 crate::superres::superres_hits(),
7170 crate::mc::predict_scaled_hits(),
7171 crate::decode::scaled_compound_hits(),
7172 crate::decode::scaled_warp_fallback_hits(),
7173 crate::decode::scaled_obmc_hits(),
7174 crate::decode::scaled_interintra_hits(),
7175 crate::decode::scaled_block8_hits(),
7176 crate::decode::scaled_warp_suppressed_hits(),
7177 crate::decode::mixed_scale_compound_hits(),
7178 );
7179 assert!(
7180 matched > 0,
7181 "{NAME}: every attempt refused on other capabilities; the gate proves nothing"
7182 );
7183 assert!(
7184 crate::mc::predict_scaled_hits() > 0,
7185 "{NAME}: matched but zero predict_scaled_hits -- no block took the scaled MC path"
7186 );
7187 // The 8x8 leaf is NOT asserted here: it stays refused (no recipe
7188 // produced an 8x8 inter leaf at all), so its counter is a
7189 // diagnostic only -- see this gate's own doc and decode.rs.
7190 // `scaled_warp_suppressed` IS asserted: it counts the blocks whose
7191 // WARPED_CAUSAL eligibility libaom drops because the reference is
7192 // scaled, i.e. the blocks that must read `obmc_cdf`. Zero of them
7193 // would mean this gate's `--enable-warped-motion=1` never reached a
7194 // warp-eligible block and proves nothing about r2's fix.
7195 assert!(
7196 crate::decode::scaled_warp_suppressed_hits() > 0,
7197 "{NAME}: {matched} matches but no block had its warp eligibility \
7198 suppressed by a scaled reference -- the warp arm proves nothing"
7199 );
7200 for (hits, what) in [
7201 (crate::decode::scaled_compound_hits(), "compound with a scaled reference"),
7202 (crate::decode::scaled_obmc_hits(), "OBMC with a scaled reference"),
7203 (crate::decode::scaled_interintra_hits(), "interintra with a scaled reference"),
7204 ] {
7205 assert!(hits > 0, "{NAME}: {matched} matches but zero blocks took {what}");
7206 }
7207 }
7208
7209 /// lane-wii r2: `--enable-interintra-wedge=1` streams must DECODE
7210 /// pixel-exact -- the wedge-interintra syntax (adapting `wedge_index`
7211 /// CDF symbol, fixed sign 0) and the wedge mask blend are ported over
7212 /// the checksum-verified codebook. `--enable-masked-comp=0` stays so
7213 /// the encoder cannot route inter blocks through the still-unported
7214 /// COMPOUND_WEDGE/DIFFWTD path. A refusal naming interintra/wedge
7215 /// fails the gate; refusals for OTHER named capabilities still skip
7216 /// that seed. Zero `wii_hits` on a run means the encoder never
7217 /// selected wedge-interintra -- soft-skipped (warned), not failed:
7218 /// that is encoder choice, not a decoder bug.
7219 #[test]
7220 fn a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact() {
7221 const NAME: &str = "a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact";
7222 let _gate_lock = lock_gate_counters();
7223 if !have_ffmpeg() {
7224 eprintln!("SKIP {NAME}: no ffmpeg");
7225 return;
7226 }
7227 if !have_aomenc() {
7228 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7229 return;
7230 }
7231 let (width, height, frame_count) = (64usize, 64usize, 24usize);
7232 let mut named_refusals = 0u32;
7233 let mut matched = 0u32;
7234 let n_attempts: u32 = std::env::var("EC_WEDGE_GATE_ATTEMPTS")
7235 .ok()
7236 .and_then(|s| s.parse().ok())
7237 .unwrap_or(40);
7238 for attempt in 0..n_attempts {
7239 let seed = 42 + attempt;
7240 let duration = frame_count as f64 / 25.0;
7241 let source = if attempt % 2 == 0 {
7242 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
7243 } else {
7244 // `end_pts` does NOT bound mandelbrot (it generated 300+
7245 // frames and hung the gate for an hour); `-t` below is the
7246 // real bound, matching every other mandelbrot gate recipe.
7247 format!("mandelbrot=size={width}x{height}:rate=25")
7248 };
7249 let duration_arg = format!("{duration}");
7250 let y4m = Command::new("ffmpeg")
7251 .args([
7252 "-v",
7253 "error",
7254 "-f",
7255 "lavfi",
7256 "-i",
7257 &source,
7258 "-pix_fmt",
7259 "yuv420p",
7260 "-t",
7261 &duration_arg,
7262 "-f",
7263 "yuv4mpegpipe",
7264 "-",
7265 ])
7266 .stdin(Stdio::null())
7267 .stdout(Stdio::piped())
7268 .stderr(Stdio::piped())
7269 .output()
7270 .expect("ffmpeg failed to run");
7271 assert!(
7272 y4m.status.success(),
7273 "ffmpeg fixture: {}",
7274 String::from_utf8_lossy(&y4m.stderr)
7275 );
7276 let args: Vec<&str> = vec![
7277 "--codec=av1",
7278 "--passes=1",
7279 "--end-usage=q",
7280 "--cq-level=45",
7281 "--cpu-used=0",
7282 "--kf-max-dist=1000",
7283 "--threads=1",
7284 "--row-mt=0",
7285 "--auto-alt-ref=1",
7286 "--lag-in-frames=16",
7287 "--enable-fwd-kf=0",
7288 "--enable-order-hint=1",
7289 "--enable-warped-motion=1",
7290 "--enable-obmc=1",
7291 "--tune-content=default",
7292 "--enable-masked-comp=0",
7293 "--enable-interintra-comp=1",
7294 "--enable-onesided-comp=0",
7295 "--enable-interintra-wedge=1",
7296 "--enable-smooth-interintra=1",
7297 "--enable-rect-partitions=0",
7298 "--enable-ab-partitions=0",
7299 "--enable-1to4-partitions=0",
7300 "--enable-filter-intra=0",
7301 "--enable-smooth-intra=0",
7302 "--enable-paeth-intra=0",
7303 "--enable-directional-intra=0",
7304 "--enable-angle-delta=0",
7305 "--enable-tx-size-search=0",
7306 "--enable-cdef=0",
7307 "--enable-restoration=0",
7308 "--max-partition-size=32",
7309 "--min-partition-size=32",
7310 "--enable-palette=0",
7311 "--enable-intrabc=0",
7312 "--enable-cfl-intra=0",
7313 "--enable-ref-frame-mvs=0",
7314 "--obu",
7315 "-o",
7316 "-",
7317 "-",
7318 ];
7319 let mut child = Command::new(aomenc_path())
7320 .args(&args)
7321 .stdin(Stdio::piped())
7322 .stdout(Stdio::piped())
7323 .stderr(Stdio::piped())
7324 .spawn()
7325 .expect("aomenc failed to start");
7326 child
7327 .stdin
7328 .take()
7329 .expect("aomenc stdin")
7330 .write_all(&y4m.stdout)
7331 .expect("writing y4m to aomenc");
7332 let out = child.wait_with_output().expect("aomenc failed to run");
7333 assert!(
7334 out.status.success(),
7335 "aomenc refused the fixture: {}",
7336 String::from_utf8_lossy(&out.stderr)
7337 );
7338 let stream = out.stdout;
7339 let frames = match decode_stream(&stream) {
7340 Err(e) => {
7341 let msg = e.to_string();
7342 assert!(
7343 msg.contains("unsupported"),
7344 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
7345 );
7346 // Verifier note (lane-wii r2): no refusal string containing
7347 // "wedge"/"interintra" exists in the decoder any more, so
7348 // string-forbidding asserts here would be vacuous (class
7349 // gate-blind-to-feature). The proof this gate carries is
7350 // pixel-exact decode plus the wii_hits count printed below.
7351 named_refusals += 1;
7352 eprintln!("seed {seed} refusal (non-wedge capability): {msg}");
7353 continue;
7354 }
7355 Ok(frames) => frames,
7356 };
7357 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
7358 assert_eq!(frames.len(), frame_count);
7359 let mismatched = frames
7360 .iter()
7361 .zip(&ffmpeg_frames)
7362 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
7363 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
7364 std::fs::write(&path, &stream).expect("writing pinned stream");
7365 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
7366 }
7367 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
7368 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
7369 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
7370 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
7371 }
7372 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
7373 // stream again, comparing EVERY decode-order frame -- the hidden
7374 // (show_frame == 0) alt-ref frames the ffmpeg compare above
7375 // cannot see, because both sides of it emit shown frames only.
7376 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
7377 eprintln!(
7378 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
7379 {hidden_n} hidden, all pixel-exact vs the oracle"
7380 );
7381 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
7382 // libaom's temporal alt-ref filter absorbs this recipe's hidden
7383 // frames, so the compare above is vacuous -- re-encode the same
7384 // fixture with --arnr-maxframes=0 and compare THOSE.
7385 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
7386 eprintln!(
7387 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
7388 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
7389 );
7390 }
7391 matched += 1;
7392 }
7393 assert!(
7394 matched > 0,
7395 "{NAME}: every attempt refused on other capabilities; the gate never exercised wedge-interintra"
7396 );
7397 // Hardened from a soft-note (verifier: gate-blind-to-feature): the
7398 // recipe fired wedge-interintra on EVERY one of 6 hammer runs
7399 // (wii_hits 2-7), so a zero-hit run is a regression, not sampling.
7400 assert!(
7401 crate::decode::wii_hits() > 0,
7402 "{NAME}: {matched} pixel-exact matches but zero wedge-interintra blocks fired -- \
7403 the blend is unexercised (recipe fired 2-7 hits per run when landed)"
7404 );
7405 eprintln!(
7406 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, wii_hits={}",
7407 crate::decode::wii_hits()
7408 );
7409 }
7410
7411 /// lane-rect16 r1/r2: a plain default-settings aomenc run over lavfi
7412 /// `mandelbrot` (`--cpu-used=4 --end-usage=q --cq-level=32`, no
7413 /// `--enable-*` flags) used to refuse frame 0 outright with "a partition
7414 /// below 16x16 other than a clean split". r1 root-caused the FIRST hit to
7415 /// a `PARTITION_VERT_B` `partition_w16` symbol at mi=(3,2) and wired it
7416 /// (left 8x16 real `decode_block_rect` strip + two stacked 8x8
7417 /// `decode_leaf8` leaves on the right). r2 re-measured after that fix
7418 /// (`decision-before-quantiser`-shaped: don't trust a stale premise) and
7419 /// found this stream's REAL first-hit blocker in z-order is earlier, at
7420 /// mi=(0,7): a plain `PARTITION_HORZ`. That arm is now wired too
7421 /// (`decode_leaf_rect`, sibling to `decode_leaf8` but real-mi-addressed
7422 /// for a non-square strip) -- `horz_vert_intra_hits` proves it fires.
7423 /// This exact stream's own HORZ block at mi=(0,7) is *coded* (real
7424 /// coefficients), which is NOT ported (same ceiling as VERT_B's own
7425 /// non-skip refusal -- no rectangular-transform coefficient tables at
7426 /// this size), so decode still stops there and `vert_b_intra_hits`
7427 /// never gets a chance to increment on this particular stream. This gate
7428 /// proves the HORZ arm fires and the OLD (now-false) two-clause refusal
7429 /// never reappears, not a pixel-exact decode of this stream.
7430 #[test]
7431 fn a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm() {
7432 const NAME: &str = "a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm";
7433 let _gate_lock = lock_gate_counters();
7434 if !have_ffmpeg() {
7435 eprintln!("SKIP {NAME}: no ffmpeg");
7436 return;
7437 }
7438 if !have_aomenc() {
7439 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7440 return;
7441 }
7442 let (width, height) = (192usize, 128usize);
7443 let y4m = Command::new("ffmpeg")
7444 .args([
7445 "-v",
7446 "error",
7447 "-f",
7448 "lavfi",
7449 "-i",
7450 &format!("mandelbrot=size={width}x{height}"),
7451 "-pix_fmt",
7452 "yuv420p",
7453 "-t",
7454 "1",
7455 "-f",
7456 "yuv4mpegpipe",
7457 "-",
7458 ])
7459 .stdin(Stdio::null())
7460 .stdout(Stdio::piped())
7461 .stderr(Stdio::piped())
7462 .output()
7463 .expect("ffmpeg failed to run");
7464 assert!(
7465 y4m.status.success(),
7466 "ffmpeg fixture: {}",
7467 String::from_utf8_lossy(&y4m.stderr)
7468 );
7469 let mut child = Command::new(aomenc_path())
7470 .args([
7471 "--threads=1",
7472 "--row-mt=0",
7473 "--sb-size=64",
7474 "--cpu-used=4",
7475 "--end-usage=q",
7476 "--cq-level=32",
7477 "--passes=1",
7478 "--obu",
7479 "-o",
7480 "-",
7481 "-",
7482 ])
7483 .stdin(Stdio::piped())
7484 .stdout(Stdio::piped())
7485 .stderr(Stdio::piped())
7486 .spawn()
7487 .expect("aomenc failed to start");
7488 child
7489 .stdin
7490 .take()
7491 .expect("aomenc stdin")
7492 .write_all(&y4m.stdout)
7493 .expect("writing y4m to aomenc");
7494 let out = child.wait_with_output().expect("aomenc failed to run");
7495 assert!(
7496 out.status.success(),
7497 "aomenc refused the fixture: {}",
7498 String::from_utf8_lossy(&out.stderr)
7499 );
7500 let stream = out.stdout;
7501 // lane-rect16 r2: the recipe above was missing `--passes=1` --
7502 // without it aomenc silently ran 2-pass and wrote nothing to stdout
7503 // on pass 1 (still exit 0), so this gate always decoded an EMPTY
7504 // stream and never actually exercised the arm it claims to gate.
7505 assert!(
7506 !stream.is_empty(),
7507 "{NAME}: aomenc wrote an empty stream (missing --passes=1?)"
7508 );
7509 let result = decode_stream(&stream);
7510 // The now-lifted false claim ("codes only the square arms below
7511 // 16x16") must never appear again.
7512 if let Err(e) = &result {
7513 let msg = e.to_string();
7514 assert!(
7515 !msg.contains("this decoder codes only the square arms below 16x16"),
7516 "{NAME}: the OLD (disproved) refusal reappeared: {msg}"
7517 );
7518 }
7519 assert!(
7520 crate::decode::horz_vert_intra_hits() > 0,
7521 "{NAME}: the plain PARTITION_HORZ/VERT arm never fired on this stream (regression -- \
7522 it fired deterministically at mi=(0,7) when this gate was written)"
7523 );
7524 eprintln!(
7525 "{NAME}: horz_vert_intra_hits={}, vert_b_intra_hits={}, decode result: {:?}",
7526 crate::decode::horz_vert_intra_hits(),
7527 crate::decode::vert_b_intra_hits(),
7528 result.as_ref().map(|f| f.len()).map_err(|e| e.to_string())
7529 );
7530 }
7531 /// lane-rectgate r1: every prior gate pins `--enable-rect-partitions=0
7532 /// --enable-ab-partitions=0 --min/max-partition-size=32` so aomenc never
7533 /// gets to choose a real rect/ab split. This charter's premise ("rect
7534 /// HORZ/VERT + HORZ_A/HORZ_B/VERT_A/VERT_B landed during the warp lane")
7535 /// does NOT hold: `decode_frame`'s inter-tile `match part32` only has
7536 /// arms for `PARTITION_NONE`/`SPLIT`/`HORZ_B` -- `HORZ`, `VERT`,
7537 /// `HORZ_A`, `VERT_A`, `VERT_B`, `HORZ_4`, `VERT_4` all fall into the
7538 /// generic "a partition type this encoder never writes" `_` arm. Two
7539 /// recipes were swept empirically (40 attempts each) to characterize the
7540 /// gap:
7541 /// - `--enable-rect-partitions=1 --enable-ab-partitions=1`, no
7542 /// min/max clamp: 0/40 matched -- every attempt hit either the
7543 /// screen-content refusal or a genuinely-unimplemented partition value
7544 /// (1/2/6/7/9 all observed), always somewhere in the 24-frame stream.
7545 /// - Same, but `--enable-1to4-partitions=0` explicit and
7546 /// `--min-partition-size=16`: still 0/40, `value=9` (`VERT_4`)
7547 /// dominates -- this build's `--enable-1to4-partitions=0` does NOT
7548 /// suppress `VERT_4` selection (aomenc-side, confirmed by direct flag
7549 /// toggle; outside this decoder). This recipe (below) restores the
7550 /// `--enable-rect-partitions=0 --min/max-partition-size=32` pin every
7551 /// other gate uses, flipping only `--enable-ab-partitions=1`: matches
7552 /// cleanly (33/40, rest screen-content refusals) but
7553 /// `extended_partition_hits` stayed 0 -- confirmed with the same probe
7554 /// wired into the already-green warp gate too (144 `warp_selected_hits`,
7555 /// 0 `extended_partition_hits`), so `PARTITION_HORZ_B` itself is
7556 /// apparently never chosen by aomenc for this small gradient fixture at
7557 /// `cq-level=45` regardless of clamp. No decode defect (crash or pixel
7558 /// mismatch) was found in any sweep -- every refusal is a correctly
7559 /// named, non-silent "unsupported" error. A refusal or mismatch naming
7560 /// any OTHER already-ported capability (warp, obmc, interintra) still
7561 /// fails the gate outright.
7562 #[test]
7563 fn a_real_aomenc_stream_with_free_partitions_decodes_pixel_exact() {
7564 const NAME: &str = "a_real_aomenc_stream_with_free_partitions_decodes_pixel_exact";
7565 let _gate_lock = lock_gate_counters();
7566 if !have_ffmpeg() {
7567 eprintln!("SKIP {NAME}: no ffmpeg");
7568 return;
7569 }
7570 if !have_aomenc() {
7571 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7572 return;
7573 }
7574 let (width, height, frame_count) = (64usize, 64usize, 24usize);
7575 let mut named_refusals = 0u32;
7576 let mut matched = 0u32;
7577 let n_attempts: u32 = std::env::var("EC_RECTGATE_ATTEMPTS")
7578 .ok()
7579 .and_then(|s| s.parse().ok())
7580 .unwrap_or(40);
7581 for attempt in 0..n_attempts {
7582 let seed = 42 + attempt;
7583 let duration = frame_count as f64 / 25.0;
7584 let source =
7585 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
7586 let y4m = Command::new("ffmpeg")
7587 .args([
7588 "-v",
7589 "error",
7590 "-f",
7591 "lavfi",
7592 "-i",
7593 &source,
7594 "-pix_fmt",
7595 "yuv420p",
7596 "-f",
7597 "yuv4mpegpipe",
7598 "-",
7599 ])
7600 .stdin(Stdio::null())
7601 .stdout(Stdio::piped())
7602 .stderr(Stdio::piped())
7603 .output()
7604 .expect("ffmpeg failed to run");
7605 assert!(
7606 y4m.status.success(),
7607 "ffmpeg fixture: {}",
7608 String::from_utf8_lossy(&y4m.stderr)
7609 );
7610 let args: Vec<&str> = vec![
7611 "--codec=av1",
7612 "--passes=1",
7613 "--end-usage=q",
7614 "--cq-level=45",
7615 "--cpu-used=0",
7616 "--kf-max-dist=1000",
7617 "--threads=1",
7618 "--row-mt=0",
7619 "--auto-alt-ref=1",
7620 "--lag-in-frames=16",
7621 "--enable-fwd-kf=0",
7622 "--enable-order-hint=1",
7623 "--enable-warped-motion=1",
7624 "--enable-obmc=1",
7625 "--tune-content=default",
7626 "--enable-masked-comp=0",
7627 "--enable-interintra-comp=0",
7628 "--enable-onesided-comp=0",
7629 "--enable-interintra-wedge=0",
7630 "--enable-smooth-interintra=0",
7631 // lane-rect r2: HORZ/VERT decode for real (rect-flake-1
7632 // byte-exact: size_h + warp dims + OBMC overlap + tx height)
7633 // -- free recipe restored; remaining partition kinds refuse
7634 // by name and skip their seeds.
7635 "--enable-rect-partitions=1",
7636 "--enable-ab-partitions=1",
7637 "--enable-1to4-partitions=0",
7638 "--enable-filter-intra=0",
7639 "--enable-smooth-intra=0",
7640 "--enable-paeth-intra=0",
7641 "--enable-directional-intra=0",
7642 "--enable-angle-delta=0",
7643 "--enable-tx-size-search=0",
7644 "--enable-cdef=0",
7645 "--enable-restoration=0",
7646 "--max-partition-size=32",
7647 "--min-partition-size=16",
7648 "--enable-palette=0",
7649 "--enable-intrabc=0",
7650 "--enable-cfl-intra=0",
7651 "--enable-ref-frame-mvs=0",
7652 "--obu",
7653 "-o",
7654 "-",
7655 "-",
7656 ];
7657 let mut child = Command::new(aomenc_path())
7658 .args(&args)
7659 .stdin(Stdio::piped())
7660 .stdout(Stdio::piped())
7661 .stderr(Stdio::piped())
7662 .spawn()
7663 .expect("aomenc failed to start");
7664 child
7665 .stdin
7666 .take()
7667 .expect("aomenc stdin")
7668 .write_all(&y4m.stdout)
7669 .expect("writing y4m to aomenc");
7670 let out = child.wait_with_output().expect("aomenc failed to run");
7671 assert!(
7672 out.status.success(),
7673 "aomenc refused the fixture: {}",
7674 String::from_utf8_lossy(&out.stderr)
7675 );
7676 let stream = out.stdout;
7677 let frames = match decode_stream(&stream) {
7678 Err(e) => {
7679 let msg = e.to_string();
7680 assert!(
7681 msg.contains("unsupported"),
7682 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
7683 );
7684 for banned in ["warp", "obmc", "interintra"] {
7685 assert!(
7686 !msg.contains(banned),
7687 "{NAME} refused on {banned} (seed {seed}) -- that capability is \
7688 ported and this recipe does not need it: {msg}"
7689 );
7690 }
7691 named_refusals += 1;
7692 eprintln!("seed {seed} refusal: {msg}");
7693 continue;
7694 }
7695 Ok(frames) => frames,
7696 };
7697 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
7698 assert_eq!(frames.len(), frame_count);
7699 let mismatched = frames
7700 .iter()
7701 .zip(&ffmpeg_frames)
7702 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
7703 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
7704 std::fs::write(&path, &stream).expect("writing pinned stream");
7705 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
7706 }
7707 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
7708 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
7709 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
7710 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
7711 }
7712 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
7713 // stream again, comparing EVERY decode-order frame -- the hidden
7714 // (show_frame == 0) alt-ref frames the ffmpeg compare above
7715 // cannot see, because both sides of it emit shown frames only.
7716 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
7717 eprintln!(
7718 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
7719 {hidden_n} hidden, all pixel-exact vs the oracle"
7720 );
7721 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
7722 // libaom's temporal alt-ref filter absorbs this recipe's hidden
7723 // frames, so the compare above is vacuous -- re-encode the same
7724 // fixture with --arnr-maxframes=0 and compare THOSE.
7725 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
7726 eprintln!(
7727 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
7728 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
7729 );
7730 }
7731 matched += 1;
7732 }
7733 assert!(
7734 matched > 0,
7735 "{NAME}: every attempt refused; the gate never decoded a free-partition stream"
7736 );
7737 // lane-partitions r1: HORZ/VERT arms landed, so the diversity probe
7738 // graduates from rectgate r1's eprintln to a report line on
7739 // `rect_partition_hits`; a zero-hit run SOFT-reports (aomenc RD may
7740 // legitimately never pick a rect split in a small window -- same
7741 // sampling caveat as the masked-compound gate's zero-hit runs).
7742 // `extended_partition_hits` (HORZ_B) stays unasserted per rectgate r1.
7743 if crate::decode::rect_partition_hits() == 0 {
7744 eprintln!(
7745 "{NAME}: SOFT-NOTE -- zero HORZ/VERT strips fired this run \
7746 ({matched} matches, {named_refusals} refusals); sampling, not a regression"
7747 );
7748 } else {
7749 // r5: the desync was the tx-depth symbol being read
7750 // unconditionally where both square paths gate it on `tx_select`
7751 // -- with --enable-tx-size-search=0 the encoder writes no such
7752 // symbol and the decoder consumed one that was never there. With
7753 // that fixed the real coefficient decode is pixel-exact, so this
7754 // is a HARD assert again: strips fired but no coefficients read
7755 // would mean the coded path silently stopped being exercised.
7756 assert!(
7757 crate::decode::rect_coeff_hits() > 0,
7758 "{NAME}: {} HORZ/VERT strips fired but rect_coeff_hits==0 -- the \
7759 coded rect path is no longer exercised",
7760 crate::decode::rect_partition_hits()
7761 );
7762 }
7763 eprintln!(
7764 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of {n_attempts}, rect_partition_hits={} rect_coeff_hits={} extended_partition_hits={} partab_hits={}",
7765 crate::decode::rect_partition_hits(),
7766 crate::decode::rect_coeff_hits(),
7767 crate::decode::extended_partition_hits(),
7768 crate::decode::partab_hits()
7769 );
7770 }
7771
7772 /// lane-partab r1: `--enable-ab-partitions=1` (aomenc default-on) INTER
7773 /// streams must consume PARTITION_HORZ_A/VERT_A/VERT_B entropy-exact AND
7774 /// decode pixel-exact -- `partab_hits() > 0` is soft-skipped on a
7775 /// zero-hit run (aomenc RD may legitimately never pick an AB split in a
7776 /// small window, same sampling caveat as wedge/rect). The INTER AB
7777 /// refusal is FORBIDDEN (decode.rs names it "an INTER 32x32 partition
7778 /// ..."); intra-frame AB refusals stay accepted named refusals -- the
7779 /// intra dispatch is a later lane. Recipe = the free-partition gate's,
7780 /// which fires AB live (r1: partab_hits 6/2/4/3/1/5 over six
7781 /// 40-attempt runs).
7782 #[test]
7783 fn a_real_aomenc_stream_with_ab_partitions_decodes_pixel_exact() {
7784 const NAME: &str = "a_real_aomenc_stream_with_ab_partitions_decodes_pixel_exact";
7785 let _gate_lock = lock_gate_counters();
7786 if !have_ffmpeg() {
7787 eprintln!("SKIP {NAME}: no ffmpeg");
7788 return;
7789 }
7790 if !have_aomenc() {
7791 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7792 return;
7793 }
7794 let (width, height, frame_count) = (64usize, 64usize, 24usize);
7795 let mut named_refusals = 0u32;
7796 let mut matched = 0u32;
7797 let n_attempts: u32 = std::env::var("EC_RECTGATE_ATTEMPTS")
7798 .ok()
7799 .and_then(|s| s.parse().ok())
7800 .unwrap_or(40);
7801 for attempt in 0..n_attempts {
7802 let seed = 42 + attempt;
7803 let duration = frame_count as f64 / 25.0;
7804 let source =
7805 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
7806 let y4m = Command::new("ffmpeg")
7807 .args([
7808 "-v",
7809 "error",
7810 "-f",
7811 "lavfi",
7812 "-i",
7813 &source,
7814 "-pix_fmt",
7815 "yuv420p",
7816 "-f",
7817 "yuv4mpegpipe",
7818 "-",
7819 ])
7820 .stdin(Stdio::null())
7821 .stdout(Stdio::piped())
7822 .stderr(Stdio::piped())
7823 .output()
7824 .expect("ffmpeg failed to run");
7825 assert!(
7826 y4m.status.success(),
7827 "ffmpeg fixture: {}",
7828 String::from_utf8_lossy(&y4m.stderr)
7829 );
7830 let args: Vec<&str> = vec![
7831 "--codec=av1",
7832 "--passes=1",
7833 "--end-usage=q",
7834 "--cq-level=45",
7835 "--cpu-used=0",
7836 "--kf-max-dist=1000",
7837 "--threads=1",
7838 "--row-mt=0",
7839 "--auto-alt-ref=1",
7840 "--lag-in-frames=16",
7841 "--enable-fwd-kf=0",
7842 "--enable-order-hint=1",
7843 "--enable-warped-motion=1",
7844 "--enable-obmc=1",
7845 "--tune-content=default",
7846 "--enable-masked-comp=0",
7847 "--enable-interintra-comp=0",
7848 "--enable-onesided-comp=0",
7849 "--enable-interintra-wedge=0",
7850 "--enable-smooth-interintra=0",
7851 // lane-rect r2 recipe, kept byte-identical by lane-partab
7852 // r1: free partition search, 1to4 off, intra tools off.
7853 "--enable-rect-partitions=1",
7854 "--enable-ab-partitions=1",
7855 "--enable-1to4-partitions=0",
7856 "--enable-filter-intra=0",
7857 "--enable-smooth-intra=0",
7858 "--enable-paeth-intra=0",
7859 "--enable-directional-intra=0",
7860 "--enable-angle-delta=0",
7861 "--enable-tx-size-search=0",
7862 "--enable-cdef=0",
7863 "--enable-restoration=0",
7864 "--max-partition-size=32",
7865 "--min-partition-size=16",
7866 "--enable-palette=0",
7867 "--enable-intrabc=0",
7868 "--enable-cfl-intra=0",
7869 "--enable-ref-frame-mvs=0",
7870 "--obu",
7871 "-o",
7872 "-",
7873 "-",
7874 ];
7875 let mut child = Command::new(aomenc_path())
7876 .args(&args)
7877 .stdin(Stdio::piped())
7878 .stdout(Stdio::piped())
7879 .stderr(Stdio::piped())
7880 .spawn()
7881 .expect("aomenc failed to start");
7882 child
7883 .stdin
7884 .take()
7885 .expect("aomenc stdin")
7886 .write_all(&y4m.stdout)
7887 .expect("writing y4m to aomenc");
7888 let out = child.wait_with_output().expect("aomenc failed to run");
7889 assert!(
7890 out.status.success(),
7891 "aomenc refused the fixture: {}",
7892 String::from_utf8_lossy(&out.stderr)
7893 );
7894 let stream = out.stdout;
7895 let frames = match decode_stream(&stream) {
7896 Err(e) => {
7897 let msg = e.to_string();
7898 assert!(
7899 msg.contains("unsupported"),
7900 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
7901 );
7902 for banned in ["warp", "obmc", "interintra"] {
7903 assert!(
7904 !msg.contains(banned),
7905 "{NAME} refused on {banned} (seed {seed}) -- that capability is \
7906 ported and this recipe does not need it: {msg}"
7907 );
7908 }
7909 for v in [4, 6, 7] {
7910 assert!(
7911 !msg.contains(&format!(
7912 "an INTER 32x32 partition type this encoder never writes \
7913 (value={v})"
7914 )),
7915 "{NAME} refused an INTER AB partition (value={v}, seed {seed}) -- \
7916 all three AB arms are ported, this refusal is forbidden: {msg}"
7917 );
7918 }
7919 named_refusals += 1;
7920 eprintln!("seed {seed} refusal: {msg}");
7921 continue;
7922 }
7923 Ok(frames) => frames,
7924 };
7925 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
7926 assert_eq!(frames.len(), frame_count);
7927 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
7928 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
7929 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
7930 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
7931 }
7932 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
7933 // stream again, comparing EVERY decode-order frame -- the hidden
7934 // (show_frame == 0) alt-ref frames the ffmpeg compare above
7935 // cannot see, because both sides of it emit shown frames only.
7936 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
7937 eprintln!(
7938 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
7939 {hidden_n} hidden, all pixel-exact vs the oracle"
7940 );
7941 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
7942 // libaom's temporal alt-ref filter absorbs this recipe's hidden
7943 // frames, so the compare above is vacuous -- re-encode the same
7944 // fixture with --arnr-maxframes=0 and compare THOSE.
7945 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
7946 eprintln!(
7947 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
7948 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
7949 );
7950 }
7951 matched += 1;
7952 }
7953 assert!(
7954 matched > 0,
7955 "{NAME}: every attempt refused; the gate never decoded a stream"
7956 );
7957 if crate::decode::partab_hits() == 0 {
7958 eprintln!(
7959 "{NAME}: SOFT-NOTE -- zero AB partitions fired this run \
7960 ({matched} matches, {named_refusals} refusals); sampling, not a regression"
7961 );
7962 }
7963 eprintln!(
7964 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of {n_attempts}, partab_hits={}",
7965 crate::decode::partab_hits()
7966 );
7967 }
7968
7969 /// lane-cwarp r1: a real `--enable-global-motion=1 --enable-dist-wtd-comp=1`
7970 /// stream over a rotating/zooming source, so a `GLOBAL_GLOBALMV` compound
7971 /// block lands under a ROTZOOM/AFFINE model and each of its two references
7972 /// is predicted through its OWN global warp
7973 /// (`crate::warp::warp_affine_compound`, libaom `av1_warp_plane` with
7974 /// `conv_params->is_compound`) rather than translationally. Before r1 that
7975 /// path was SILENTLY WRONG -- no refusal named it, both taps went through
7976 /// `mc::predict_compound_intermediate`. `compound_warp_hits() > 0` is a
7977 /// hard assert: a run where the encoder never emitted one proves nothing.
7978 /// A decode error or a pixel mismatch is a FAILURE, never a skip.
7979 fn run_compound_global_warp_gate(name: &str, ten_bit: bool) {
7980 let _gate_lock = lock_gate_counters();
7981 assert!(have_ffmpeg(), "{name}: ffmpeg required");
7982 assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
7983 let (width, height, frame_count) = (64usize, 64usize, 24usize);
7984 let before = crate::decode::compound_warp_hits();
7985 let mut matched = 0u32;
7986 let mut named_refusals = 0u32;
7987 let mut attempts = 0u32;
7988 for cq in [32u32, 45, 55] {
7989 for (i, rate) in [0.010f64, 0.022].iter().enumerate() {
7990 attempts += 1;
7991 let duration = frame_count as f64 / 25.0;
7992 // A rotation about the frame centre plus a slow zoom is what
7993 // aomenc's global-motion search fits a ROTZOOM/AFFINE model to;
7994 // mandelbrot gives it real, non-flat texture to track.
7995 let source = format!(
7996 "mandelbrot=size={w}x{h}:rate=25:start_x={sx}:start_y=-0.4,\
7997 rotate=a={rate}*n:ow={w}:oh={h}:c=black,scale={width}:{height}",
7998 w = width * 2,
7999 h = height * 2,
8000 sx = -0.6 + 0.01 * (i as f64),
8001 );
8002 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
8003 let y4m = Command::new("ffmpeg")
8004 .args([
8005 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
8006 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
8007 "-f", "yuv4mpegpipe", "-",
8008 ])
8009 .stdin(Stdio::null())
8010 .stdout(Stdio::piped())
8011 .stderr(Stdio::piped())
8012 .output()
8013 .expect("ffmpeg failed to run");
8014 assert!(
8015 y4m.status.success(),
8016 "ffmpeg fixture: {}",
8017 String::from_utf8_lossy(&y4m.stderr)
8018 );
8019 let cq_arg = format!("--cq-level={cq}");
8020 let mut args: Vec<&str> = vec![
8021 "--codec=av1",
8022 "--passes=1",
8023 "--end-usage=q",
8024 &cq_arg,
8025 "--cpu-used=0",
8026 "--kf-max-dist=1000",
8027 "--threads=1",
8028 "--row-mt=0",
8029 "--auto-alt-ref=1",
8030 "--lag-in-frames=25",
8031 "--enable-fwd-kf=0",
8032 "--enable-order-hint=1",
8033 // the two tools this gate exists for
8034 "--enable-global-motion=1",
8035 "--enable-dist-wtd-comp=1",
8036 "--enable-warped-motion=1",
8037 "--enable-obmc=1",
8038 "--enable-masked-comp=1",
8039 "--enable-onesided-comp=0",
8040 "--enable-interintra-comp=1",
8041 "--enable-interintra-wedge=0",
8042 "--enable-smooth-interintra=1",
8043 "--tune-content=default",
8044 // partition/intra tools this decoder does not code yet --
8045 // same exclusion list every compound gate carries.
8046 "--enable-rect-partitions=0",
8047 "--enable-ab-partitions=0",
8048 "--enable-1to4-partitions=0",
8049 "--enable-filter-intra=0",
8050 "--enable-smooth-intra=0",
8051 "--enable-paeth-intra=0",
8052 "--enable-directional-intra=0",
8053 "--enable-angle-delta=0",
8054 "--enable-tx-size-search=0",
8055 "--enable-cdef=0",
8056 "--enable-restoration=0",
8057 "--max-partition-size=32",
8058 "--min-partition-size=32",
8059 "--enable-palette=0",
8060 "--enable-intrabc=0",
8061 "--enable-cfl-intra=0",
8062 "--enable-ref-frame-mvs=0",
8063 ];
8064 if ten_bit {
8065 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
8066 }
8067 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
8068 let mut child = Command::new(aomenc_path())
8069 .args(&args)
8070 .stdin(Stdio::piped())
8071 .stdout(Stdio::piped())
8072 .stderr(Stdio::piped())
8073 .spawn()
8074 .expect("aomenc failed to start");
8075 child
8076 .stdin
8077 .take()
8078 .expect("aomenc stdin")
8079 .write_all(&y4m.stdout)
8080 .expect("writing y4m to aomenc");
8081 let out = child.wait_with_output().expect("aomenc failed to run");
8082 assert!(
8083 out.status.success(),
8084 "aomenc refused the fixture: {}",
8085 String::from_utf8_lossy(&out.stderr)
8086 );
8087 let stream = out.stdout;
8088 let frames = match decode_stream(&stream) {
8089 Err(e) => {
8090 let msg = e.to_string();
8091 assert!(
8092 msg.contains("unsupported"),
8093 "{name} failed outright, not a named refusal (cq {cq}): {msg}"
8094 );
8095 assert!(
8096 !msg.contains("warp"),
8097 "{name} refused on warp (cq {cq}) -- warp decode is ported: {msg}"
8098 );
8099 named_refusals += 1;
8100 eprintln!("{name} cq {cq} rate {rate} refusal: {msg}");
8101 continue;
8102 }
8103 Ok(frames) => frames,
8104 };
8105 let want = if ten_bit {
8106 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
8107 } else {
8108 ffmpeg_decode_sequence(&stream, width, height, frame_count)
8109 };
8110 assert_eq!(frames.len(), frame_count);
8111 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
8112 && frames
8113 .iter()
8114 .zip(&want)
8115 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
8116 {
8117 std::fs::write(&path, &stream).expect("writing pinned stream");
8118 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
8119 }
8120 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
8121 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq})");
8122 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq})");
8123 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq})");
8124 }
8125 matched += 1;
8126 }
8127 }
8128 let hits = crate::decode::compound_warp_hits() - before;
8129 eprintln!(
8130 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
8131 compound_warp_hits={hits}"
8132 );
8133 assert!(
8134 hits > 0,
8135 "{name}: no compound block was predicted through a per-ref global warp \
8136 ({matched} matches, {named_refusals} refusals of {attempts}) -- gate vacuous"
8137 );
8138 assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran");
8139 }
8140
8141 /// lane-fimv r1 (class `wrong-alphabet-same-value`): libaom
8142 /// `motion_mode_allowed` (blockd.h ~1484) only returns `WARPED_CAUSAL`
8143 /// when `!xd->cur_frame_force_integer_mv`, so on a frame whose header set
8144 /// `force_integer_mv` an otherwise warp-eligible block reads the 2-symbol
8145 /// `obmc_cdf`, not the 3-symbol `motion_mode_cdf`. This decoder read the
8146 /// 3-symbol alphabet there (silent tile desync, no refusal named it).
8147 ///
8148 /// The fixture is screen content that is mostly static with only
8149 /// whole-pixel motion, which is exactly what aomenc's own
8150 /// `av1_is_integer_mv` (`encoder_utils.c:1357`, >=80% of blocks matching
8151 /// their collocated block) needs to set `cur_frame_force_integer_mv`
8152 /// under `--tune-content=screen` (seq `force_integer_mv == 2`, adaptive:
8153 /// `encoder.c:4171`). Two hard asserts, both class
8154 /// `gate-blind-to-feature`: at least one decoded frame header carried
8155 /// `force_integer_mv = 1`, and at least one block took the 2-symbol
8156 /// alphabet where `allow_warped_motion = 1` and `num_proj_ref >= 1` would
8157 /// have picked the 3-symbol one. A decode error or a pixel mismatch is a
8158 /// FAILURE, never a skip.
8159 #[track_caller]
8160 fn run_fimv_motion_mode_gate(name: &str, ten_bit: bool) {
8161 let _gate_lock = lock_gate_counters();
8162 assert!(have_ffmpeg(), "{name}: ffmpeg required");
8163 assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
8164 let (width, height, frame_count) = (64usize, 64usize, 20usize);
8165 let fimv_frames_before = crate::decode::fimv_frame_hits();
8166 let alphabet_before = crate::decode::fimv_alphabet_hits();
8167 let mut matched = 0u32;
8168 let mut named_refusals = 0u32;
8169 let mut attempts = 0u32;
8170 let mut refusals = Vec::new();
8171 for cq in [32u32, 45, 55] {
8172 for step in [4u32, 8] {
8173 attempts += 1;
8174 // lane-fimv r1: per-attempt snapshots. The aggregate
8175 // assertions below are satisfied by a single lucky cq/step
8176 // cell; these prove EVERY attempt that decoded and
8177 // pixel-compared really carried the header state and the
8178 // forced alphabet under test (class gate-blind-to-feature).
8179 let attempt_fimv_before = crate::decode::fimv_frame_hits();
8180 let attempt_alphabet_before = crate::decode::fimv_alphabet_hits();
8181 let duration = frame_count as f64 / 25.0;
8182 // Flat screen-content tiles with hard edges, translating by a
8183 // whole number of pixels per frame: static enough for
8184 // `av1_is_integer_mv`, moving enough for a real inter block
8185 // with overlappable neighbours.
8186 let source = format!(
8187 "color=c=black:s={width}x{height}:r=25,\
8188 drawbox=x='8+{step}*mod(trunc(t*25)\\,3)':y=8:w=20:h=20:color=white:t=fill,\
8189 drawbox=x=36:y='6+{step}*mod(trunc(t*25)+1\\,3)':w=16:h=16:color=0x808080:t=fill,\
8190 drawbox=x=4:y=44:w=56:h=12:color=0xC0C0C0:t=fill"
8191 );
8192 let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
8193 let y4m = Command::new("ffmpeg")
8194 .args([
8195 "-v", "error", "-f", "lavfi", "-i", &source, "-t",
8196 &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
8197 "-f", "yuv4mpegpipe", "-",
8198 ])
8199 .stdin(Stdio::null())
8200 .stdout(Stdio::piped())
8201 .stderr(Stdio::piped())
8202 .output()
8203 .expect("ffmpeg failed to run");
8204 assert!(
8205 y4m.status.success(),
8206 "ffmpeg fixture: {}",
8207 String::from_utf8_lossy(&y4m.stderr)
8208 );
8209 let cq_arg = format!("--cq-level={cq}");
8210 let mut args: Vec<&str> = vec![
8211 "--codec=av1",
8212 "--passes=1",
8213 "--end-usage=q",
8214 &cq_arg,
8215 "--cpu-used=0",
8216 "--kf-max-dist=1000",
8217 "--threads=1",
8218 "--row-mt=0",
8219 // single reference only: the 10-bit compound MC defect
8220 // (see `a_real_compound_global_warp_10bit_stream_...`)
8221 // is unrelated to this lane and would mask it.
8222 "--auto-alt-ref=0",
8223 "--lag-in-frames=0",
8224 "--enable-fwd-kf=0",
8225 "--enable-order-hint=1",
8226 // the flag combination this gate exists for: warp allowed
8227 // by the header, OBMC available, global motion off (so the
8228 // GLOBALMV suppression is not what picks the alphabet).
8229 "--tune-content=screen",
8230 "--enable-warped-motion=1",
8231 "--enable-obmc=1",
8232 "--enable-global-motion=0",
8233 "--enable-masked-comp=0",
8234 "--enable-onesided-comp=0",
8235 "--enable-interintra-comp=0",
8236 "--enable-interintra-wedge=0",
8237 "--enable-smooth-interintra=0",
8238 "--enable-dist-wtd-comp=0",
8239 // partition/intra tools this decoder does not code yet --
8240 // the same exclusion list every inter gate here carries.
8241 "--enable-rect-partitions=0",
8242 "--enable-ab-partitions=0",
8243 "--enable-1to4-partitions=0",
8244 "--enable-filter-intra=0",
8245 "--enable-smooth-intra=0",
8246 "--enable-paeth-intra=0",
8247 "--enable-directional-intra=0",
8248 "--enable-angle-delta=0",
8249 "--enable-tx-size-search=0",
8250 "--enable-cdef=0",
8251 "--enable-restoration=0",
8252 "--max-partition-size=32",
8253 "--min-partition-size=32",
8254 "--enable-palette=0",
8255 "--enable-intrabc=0",
8256 "--enable-cfl-intra=0",
8257 "--enable-ref-frame-mvs=0",
8258 ];
8259 if ten_bit {
8260 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
8261 }
8262 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
8263 let mut child = Command::new(aomenc_path())
8264 .args(&args)
8265 .stdin(Stdio::piped())
8266 .stdout(Stdio::piped())
8267 .stderr(Stdio::piped())
8268 .spawn()
8269 .expect("aomenc failed to start");
8270 child
8271 .stdin
8272 .take()
8273 .expect("aomenc stdin")
8274 .write_all(&y4m.stdout)
8275 .expect("writing y4m to aomenc");
8276 let out = child.wait_with_output().expect("aomenc failed to run");
8277 assert!(
8278 out.status.success(),
8279 "aomenc refused the fixture: {}",
8280 String::from_utf8_lossy(&out.stderr)
8281 );
8282 let stream = out.stdout;
8283 let frames = match decode_stream(&stream) {
8284 Err(e) => {
8285 let msg = e.to_string();
8286 assert!(
8287 msg.contains("unsupported"),
8288 "{name} failed outright (cq {cq} step {step}): {msg}"
8289 );
8290 named_refusals += 1;
8291 refusals.push(format!("cq {cq} step {step}: {msg}"));
8292 continue;
8293 }
8294 Ok(frames) => frames,
8295 };
8296 let want = if ten_bit {
8297 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
8298 } else {
8299 ffmpeg_decode_sequence(&stream, width, height, frame_count)
8300 };
8301 assert_eq!(frames.len(), frame_count);
8302 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
8303 && frames
8304 .iter()
8305 .zip(&want)
8306 .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
8307 {
8308 std::fs::write(&path, &stream).expect("writing pinned stream");
8309 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
8310 }
8311 for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
8312 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq} step {step})");
8313 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq} step {step})");
8314 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq} step {step})");
8315 }
8316 assert!(
8317 crate::decode::fimv_frame_hits() > attempt_fimv_before,
8318 "{name} (cq {cq} step {step}): decoded and compared all \
8319 frames but no frame header had force_integer_mv=1 -- \
8320 this attempt is vacuous"
8321 );
8322 assert!(
8323 crate::decode::fimv_alphabet_hits() > attempt_alphabet_before,
8324 "{name} (cq {cq} step {step}): no block was forced onto the \
8325 2-symbol obmc alphabet by force_integer_mv while \
8326 allow_warped_motion=1 and num_proj_ref>=1 -- this attempt \
8327 is vacuous"
8328 );
8329 matched += 1;
8330 }
8331 }
8332 let fimv_frames = crate::decode::fimv_frame_hits() - fimv_frames_before;
8333 let alphabet = crate::decode::fimv_alphabet_hits() - alphabet_before;
8334 eprintln!(
8335 "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
8336 force_integer_mv frames={fimv_frames}, forced-2-symbol blocks={alphabet}\n{}",
8337 refusals.join("\n")
8338 );
8339 assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran");
8340 assert!(
8341 fimv_frames > 0,
8342 "{name}: no decoded frame header had force_integer_mv=1 \
8343 ({matched} matches of {attempts}) -- gate vacuous"
8344 );
8345 assert!(
8346 alphabet > 0,
8347 "{name}: no block read the 2-symbol obmc alphabet where \
8348 allow_warped_motion=1 and num_proj_ref>=1 would have picked the \
8349 3-symbol motion_mode alphabet -- gate vacuous"
8350 );
8351 }
8352
8353 /// 8-bit arm of [`run_fimv_motion_mode_gate`].
8354 #[test]
8355 fn a_real_force_integer_mv_warp_stream_decodes_pixel_exact() {
8356 run_fimv_motion_mode_gate("a_real_force_integer_mv_warp_stream_decodes_pixel_exact", false);
8357 }
8358
8359 /// 10-bit arm of [`run_fimv_motion_mode_gate`] -- both of his films are
8360 /// `yuv420p10le`.
8361 #[test]
8362 fn a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact() {
8363 run_fimv_motion_mode_gate(
8364 "a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact",
8365 true,
8366 );
8367 }
8368
8369 /// 8-bit arm of [`run_compound_global_warp_gate`].
8370 #[test]
8371 fn a_real_compound_global_warp_stream_decodes_pixel_exact() {
8372 run_compound_global_warp_gate("a_real_compound_global_warp_stream_decodes_pixel_exact", false);
8373 }
8374
8375 /// 10-bit arm of [`run_compound_global_warp_gate`] -- both of his films are
8376 /// `yuv420p10le`, and `warp_affine`'s `bd` was hardcoded 8 before r1.
8377 ///
8378 /// IGNORED, blocked by a PRE-EXISTING 10-bit COMPOUND defect this lane did
8379 /// not introduce and does not own. Ablation run by lane-cwarp r1 on this
8380 /// very recipe: with `--enable-global-motion=0 --enable-warped-motion=0`
8381 /// (no warp of any kind reachable) the 10-bit stream STILL mismatches at
8382 /// frame 1 luma, cq 32; with `--auto-alt-ref=0 --lag-in-frames=0
8383 /// --enable-dist-wtd-comp=0` (single-reference 10-bit inter only) the same
8384 /// recipe is 6/6 pixel-exact. So: 10-bit single-ref inter is exact, 10-bit
8385 /// compound is not. `mc::diffwtd_mask`'s missing `(bd - 8)` round term was
8386 /// found and fixed while bisecting this, but is NOT the whole defect.
8387 /// Un-ignore the moment the 10-bit compound path is fixed -- the warp
8388 /// wiring under test here is bit-depth generic already.
8389 #[test]
8390 #[ignore = "blocked by a pre-existing 10-bit compound MC defect (see doc comment)"]
8391 fn a_real_compound_global_warp_10bit_stream_decodes_pixel_exact() {
8392 run_compound_global_warp_gate(
8393 "a_real_compound_global_warp_10bit_stream_decodes_pixel_exact",
8394 true,
8395 );
8396 }
8397
8398 /// lane-maskcomp r2 / lane-wedge r3: `--enable-masked-comp=1` streams
8399 /// must consume `compound_type`/`wedge_idx`/`wedge_sign`/`mask_type`
8400 /// entropy-exact AND build the real blend, DIFFWTD or WEDGE --
8401 /// `masked_compound_hits() > 0` is a hard assert and BOTH
8402 /// `COMPOUND_DIFFWTD` and `COMPOUND_WEDGE` refusals are now FORBIDDEN
8403 /// (matches interintra's own gate). r3: `--enable-dist-wtd-comp=0`
8404 /// (forces the masked choice toward wedge when comp_group_idx==1) plus
8405 /// a hard-diagonal-edge `geq` source (wedge's OBLIQUE directions favor
8406 /// a real diagonal edge over the r2 gradients content) to fire
8407 /// COMPOUND_WEDGE live; `wedge_hits()` is soft-skipped (not hard
8408 /// asserted) on a zero-hit run -- the recipe search is not proven to
8409 /// converge every run, see charter's "if no recipe fires" fallback.
8410 #[test]
8411 fn a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact() {
8412 const NAME: &str = "a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact";
8413 let _gate_lock = lock_gate_counters();
8414 if !have_ffmpeg() {
8415 eprintln!("SKIP {NAME}: no ffmpeg");
8416 return;
8417 }
8418 if !have_aomenc() {
8419 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8420 return;
8421 }
8422 let (width, height, frame_count) = (64usize, 64usize, 24usize);
8423 let mut named_refusals = 0u32;
8424 let mut matched = 0u32;
8425 let n_attempts: u32 = std::env::var("EC_MASKCOMP_GATE_ATTEMPTS")
8426 .ok()
8427 .and_then(|s| s.parse().ok())
8428 .unwrap_or(80);
8429 for attempt in 0..n_attempts {
8430 let seed = 42 + attempt;
8431 let duration = frame_count as f64 / 25.0;
8432 // lane-wedge r3: a hard diagonal edge (not a smooth gradient)
8433 // is the content wedge's OBLIQUE master masks are shaped for --
8434 // `mandelbrot`'s pan position varies the edge angle/position
8435 // across attempts the way the r2 gradients seed did.
8436 let source = format!(
8437 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
8438 sx = -0.6 + 0.005 * (attempt as f64),
8439 sy = -0.4 + 0.005 * (attempt as f64)
8440 );
8441 let y4m = Command::new("ffmpeg")
8442 .args([
8443 "-v",
8444 "error",
8445 "-f",
8446 "lavfi",
8447 "-i",
8448 &source,
8449 "-t",
8450 &duration.to_string(),
8451 "-pix_fmt",
8452 "yuv420p",
8453 "-f",
8454 "yuv4mpegpipe",
8455 "-",
8456 ])
8457 .stdin(Stdio::null())
8458 .stdout(Stdio::piped())
8459 .stderr(Stdio::piped())
8460 .output()
8461 .expect("ffmpeg failed to run");
8462 assert!(
8463 y4m.status.success(),
8464 "ffmpeg fixture: {}",
8465 String::from_utf8_lossy(&y4m.stderr)
8466 );
8467 let args: Vec<&str> = vec![
8468 "--codec=av1",
8469 "--passes=1",
8470 "--end-usage=q",
8471 "--cq-level=45",
8472 "--cpu-used=0",
8473 "--kf-max-dist=1000",
8474 "--threads=1",
8475 "--row-mt=0",
8476 "--auto-alt-ref=1",
8477 "--lag-in-frames=16",
8478 "--enable-fwd-kf=0",
8479 "--enable-order-hint=1",
8480 "--enable-warped-motion=1",
8481 // r3: mandelbrot's pan/zoom triggers aomenc's single-ref
8482 // GLOBALMV global-motion search (a capability distinct from
8483 // and outside this lane's scope) -- off, matching this
8484 // gate's own goal of exercising masked compound, not GM.
8485 "--enable-global-motion=0",
8486 "--enable-obmc=1",
8487 "--tune-content=default",
8488 "--enable-masked-comp=1",
8489 // r3: force the masked choice toward wedge (r2 always set
8490 // this =1; distance-weighted compound competes with the
8491 // wedge/diffwtd choice for the same comp_group_idx==1 slot).
8492 "--enable-dist-wtd-comp=0",
8493 "--enable-interintra-comp=1",
8494 "--enable-onesided-comp=0",
8495 "--enable-interintra-wedge=0",
8496 "--enable-smooth-interintra=1",
8497 "--enable-rect-partitions=0",
8498 "--enable-ab-partitions=0",
8499 "--enable-1to4-partitions=0",
8500 "--enable-filter-intra=0",
8501 "--enable-smooth-intra=0",
8502 "--enable-paeth-intra=0",
8503 "--enable-directional-intra=0",
8504 "--enable-angle-delta=0",
8505 "--enable-tx-size-search=0",
8506 "--enable-cdef=0",
8507 "--enable-restoration=0",
8508 "--max-partition-size=32",
8509 "--min-partition-size=32",
8510 "--enable-palette=0",
8511 "--enable-intrabc=0",
8512 "--enable-cfl-intra=0",
8513 "--enable-ref-frame-mvs=0",
8514 "--obu",
8515 "-o",
8516 "-",
8517 "-",
8518 ];
8519 let mut child = Command::new(aomenc_path())
8520 .args(&args)
8521 .stdin(Stdio::piped())
8522 .stdout(Stdio::piped())
8523 .stderr(Stdio::piped())
8524 .spawn()
8525 .expect("aomenc failed to start");
8526 child
8527 .stdin
8528 .take()
8529 .expect("aomenc stdin")
8530 .write_all(&y4m.stdout)
8531 .expect("writing y4m to aomenc");
8532 let out = child.wait_with_output().expect("aomenc failed to run");
8533 assert!(
8534 out.status.success(),
8535 "aomenc refused the fixture: {}",
8536 String::from_utf8_lossy(&out.stderr)
8537 );
8538 let stream = out.stdout;
8539 let frames = match decode_stream(&stream) {
8540 Err(e) => {
8541 let msg = e.to_string();
8542 assert!(
8543 msg.contains("unsupported"),
8544 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
8545 );
8546 assert!(
8547 !msg.contains("warp"),
8548 "{NAME} refused on warp (seed {seed}) -- warp decode is ported: {msg}"
8549 );
8550 assert!(
8551 !msg.contains("masked COMPOUND_REFERENCE"),
8552 "{NAME} refused a masked-compound block (seed {seed}) -- both DIFFWTD \
8553 and WEDGE blends are ported, this refusal is forbidden: {msg}"
8554 );
8555 assert!(
8556 !msg.contains("interintra"),
8557 "{NAME} refused on interintra (seed {seed}) -- non-wedge \
8558 interintra is ported: {msg}"
8559 );
8560 named_refusals += 1;
8561 eprintln!("seed {seed} refusal: {msg}");
8562 if std::env::var_os("EC_AV1_GATE_DUMP").is_some() {
8563 // r1's self-pin is armed via EC_AV1_GATE_DUMP=<path>
8564 // only for a real pixel MISMATCH below, not for this
8565 // still-expected named refusal.
8566 }
8567 continue;
8568 }
8569 Ok(frames) => frames,
8570 };
8571 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
8572 assert_eq!(frames.len(), frame_count);
8573 let mismatched = frames
8574 .iter()
8575 .zip(&ffmpeg_frames)
8576 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
8577 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
8578 std::fs::write(&path, &stream).expect("writing pinned stream");
8579 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
8580 }
8581 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8582 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
8583 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
8584 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
8585 }
8586 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
8587 // stream again, comparing EVERY decode-order frame -- the hidden
8588 // (show_frame == 0) alt-ref frames the ffmpeg compare above
8589 // cannot see, because both sides of it emit shown frames only.
8590 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
8591 eprintln!(
8592 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
8593 {hidden_n} hidden, all pixel-exact vs the oracle"
8594 );
8595 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
8596 // libaom's temporal alt-ref filter absorbs this recipe's hidden
8597 // frames, so the compare above is vacuous -- re-encode the same
8598 // fixture with --arnr-maxframes=0 and compare THOSE.
8599 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
8600 eprintln!(
8601 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
8602 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
8603 );
8604 }
8605 matched += 1;
8606 }
8607 // r1: observed flaky at 40 attempts -- aomenc's cpu-used=0 RD is
8608 // run-to-run nondeterministic in whether it ever picks
8609 // comp_group_idx == 1 for this synthetic gradients content, and
8610 // allow_screen_content_tools sometimes eats most of a small seed
8611 // window (class gate-recipe-confound / never-fired-gate, memory).
8612 // 80 attempts is the mitigation, not a fix; a still-zero run here
8613 // is that sampling flake, not a decode regression -- check
8614 // masked_compound_hits/named_refusals in the panic message before
8615 // assuming a real bug.
8616 // r2: DIFFWTD is ported and gated, so a zero-hit run is no longer
8617 // soft-skipped -- hard assert, matching the interintra gate.
8618 assert!(
8619 crate::decode::masked_compound_hits() > 0,
8620 "{NAME}: zero masked-compound blocks fired ({matched} matches, {named_refusals} \
8621 other refusals out of {n_attempts}) -- gate proved nothing this run"
8622 );
8623 // r3: wedge_hits() is soft-skipped, not hard-asserted -- the recipe
8624 // search (dist-wtd-comp=0 + diagonal mandelbrot content) is not
8625 // proven to fire wedge on every run; charter's fallback is to land
8626 // the checksum-verified codebook + blend with this soft path.
8627 if crate::decode::wedge_hits() == 0 {
8628 eprintln!(
8629 "{NAME}: WARNING wedge_hits()==0 this run -- COMPOUND_WEDGE never fired \
8630 ({matched} matches, {named_refusals} refusals out of {n_attempts}); codebook \
8631 is checksum-verified but unexercised live this run"
8632 );
8633 }
8634 eprintln!(
8635 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
8636 out of {n_attempts}, masked_compound_hits={} wedge_hits={}",
8637 crate::decode::masked_compound_hits(),
8638 crate::decode::wedge_hits()
8639 );
8640 }
8641
8642
8643 /// lane-lr r3: proves stage 1/2's exit criterion -- a real
8644 /// `--enable-restoration=1` aomenc stream must survive the whole
8645 /// partition walk (every symbol read entropy-exact) and land on the
8646 /// NEW, narrowed refusal ("read but not applied"), never desync into
8647 /// some other named refusal or an outright decode panic. Multi-superblock
8648 /// fixture (192x128 = 3x2 SBs of 64px) per the charter's own trap
8649 /// warning -- a single-SB fixture can never re-enter `read_lr` a second
8650 /// time and would leave `SWITCHABLE_HITS`/etc. proving only one call
8651 /// site, not the per-SB loop.
8652 #[test]
8653 fn a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly() {
8654 const NAME: &str = "a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly";
8655 let _gate_lock = lock_gate_counters();
8656 if !have_ffmpeg() {
8657 eprintln!("SKIP {NAME}: no ffmpeg");
8658 return;
8659 }
8660 if !have_aomenc() {
8661 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8662 return;
8663 }
8664 let (width, height) = (192usize, 128usize);
8665 let n_attempts: u32 = std::env::var("EC_LR_GATE_ATTEMPTS")
8666 .ok()
8667 .and_then(|s| s.parse().ok())
8668 .unwrap_or(40);
8669 let mut lr_refusals = 0u32;
8670 let mut other_refusals = Vec::new();
8671 for attempt in 0..n_attempts {
8672 let seed = 42 + attempt;
8673 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
8674 let y4m = Command::new("ffmpeg")
8675 .args(["-v", "error", "-f", "lavfi", "-i"])
8676 .arg(&source)
8677 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
8678 .stdin(Stdio::null())
8679 .stdout(Stdio::piped())
8680 .stderr(Stdio::piped())
8681 .output()
8682 .expect("ffmpeg failed to run");
8683 assert!(
8684 y4m.status.success(),
8685 "ffmpeg fixture: {}",
8686 String::from_utf8_lossy(&y4m.stderr)
8687 );
8688 let mut child = Command::new(aomenc_path())
8689 .args([
8690 "--codec=av1",
8691 "--passes=1",
8692 "--end-usage=q",
8693 // r3: a low cq-level (high quality/bitrate) is load-bearing --
8694 // sampled live (2026-08-30) that aomenc's RD only ever picks a
8695 // non-`RESTORE_NONE` frame_restoration_type at cq-level<=20 for
8696 // this fixture; cq-level=45 (this gate's sibling gates' usual
8697 // value) landed `uses_lr=false` on every attempt.
8698 "--cq-level=15",
8699 "--cpu-used=0",
8700 "--threads=1",
8701 "--row-mt=0",
8702 // r3: this decoder always assumes 64px superblocks
8703 // (`decode.rs` hardcodes `SB_MI=16`, ledger `lane-sb128`
8704 // dead-ends) -- force aomenc to match rather than risk
8705 // the unrelated sb128 gap eating this gate's own window.
8706 "--sb-size=64",
8707 "--enable-restoration=1",
8708 "--enable-cdef=0",
8709 "--enable-rect-partitions=0",
8710 "--enable-ab-partitions=0",
8711 "--enable-1to4-partitions=0",
8712 "--enable-filter-intra=0",
8713 "--enable-smooth-intra=0",
8714 "--enable-paeth-intra=0",
8715 "--enable-tx-size-search=0",
8716 "--max-partition-size=32",
8717 "--min-partition-size=16",
8718 "--enable-palette=0",
8719 "--enable-intrabc=0",
8720 "--enable-cfl-intra=0",
8721 "--enable-ref-frame-mvs=0",
8722 "--enable-warped-motion=0",
8723 "--enable-global-motion=0",
8724 "--enable-masked-comp=0",
8725 "--enable-interintra-comp=0",
8726 "--enable-obmc=0",
8727 "--obu",
8728 "-o",
8729 "-",
8730 "-",
8731 ])
8732 .stdin(Stdio::piped())
8733 .stdout(Stdio::piped())
8734 .stderr(Stdio::piped())
8735 .spawn()
8736 .expect("aomenc failed to start");
8737 child
8738 .stdin
8739 .take()
8740 .expect("aomenc stdin")
8741 .write_all(&y4m.stdout)
8742 .expect("writing y4m to aomenc");
8743 let out = child.wait_with_output().expect("aomenc failed to run");
8744 assert!(
8745 out.status.success(),
8746 "aomenc refused the fixture: {}",
8747 String::from_utf8_lossy(&out.stderr)
8748 );
8749 let stream = out.stdout;
8750 match decode_stream(&stream) {
8751 Ok(pics) => {
8752 // r4: the pixel filters are wired -- every `uses_lr`
8753 // frame must now decode Ok AND match an independent
8754 // decoder pixel-exact, not just refuse cleanly.
8755 let reference = ffmpeg_decode_sequence(&stream, width, height, pics.len());
8756 let mismatched = pics
8757 .iter()
8758 .zip(&reference)
8759 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
8760 // r7: pin a mismatching stream the same way the
8761 // masked-compound gate does -- lets a follow-up round
8762 // decode this exact seed's bytes directly instead of
8763 // re-deriving them from a live 40-attempt sweep.
8764 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
8765 std::fs::write(&path, &stream).expect("writing pinned stream");
8766 eprintln!(
8767 "EC_AV1_GATE_DUMP: wrote mismatching LR stream (seed {seed}) to {path}"
8768 );
8769 }
8770 for (i, (pic, refpic)) in pics.iter().zip(reference.iter()).enumerate() {
8771 assert_eq!(pic.y, refpic.y, "{NAME}: luma mismatch (seed {seed} frame {i})");
8772 assert_eq!(pic.u, refpic.u, "{NAME}: U mismatch (seed {seed} frame {i})");
8773 assert_eq!(pic.v, refpic.v, "{NAME}: V mismatch (seed {seed} frame {i})");
8774 }
8775 lr_refusals += 1; // reused below as "attempts that actually exercised LR pixels"
8776 }
8777 Err(e) => {
8778 let msg = e.to_string();
8779 other_refusals.push(format!("seed {seed}: {msg}"));
8780 }
8781 }
8782 }
8783 assert!(
8784 other_refusals.is_empty(),
8785 "{NAME}: {} attempts failed outright instead of decoding:\n{}",
8786 other_refusals.len(),
8787 other_refusals.join("\n")
8788 );
8789 assert!(
8790 lr_refusals > 0,
8791 "{NAME}: no attempt ever decoded pixel-exact ({n_attempts} attempts)"
8792 );
8793 // Any real (non-`RESTORE_NONE`) filter kind is acceptable proof --
8794 // aomenc's RD picks the frame-level `restoration_type` itself (not
8795 // always `Switchable`; observed `Sgrproj` live at cq-level=15 for
8796 // this fixture), so hard-requiring one specific arm would be the
8797 // gate-recipe-confound class (ledger).
8798 let total_hits = crate::restoration::wiener_hits()
8799 + crate::restoration::sgrproj_hits()
8800 + crate::restoration::switchable_hits();
8801 assert!(
8802 total_hits > 0,
8803 "{NAME}: {lr_refusals} LR refusals fired but read_lr_unit never decoded a real \
8804 (non-None) filter -- gate proved nothing about the symbol path"
8805 );
8806 eprintln!(
8807 "{NAME}: {lr_refusals} LR refusals, {} other refusals out of {n_attempts}, \
8808 wiener_hits={} sgrproj_hits={} switchable_hits={}",
8809 other_refusals.len(),
8810 crate::restoration::wiener_hits(),
8811 crate::restoration::sgrproj_hits(),
8812 crate::restoration::switchable_hits()
8813 );
8814 }
8815
8816 /// r8: decode the ONE pinned stream `EC_AV1_GATE_DUMP` captured in r7
8817 /// (`fixtures/lr-sgr-r7.obu`, seed 46) directly -- not the live
8818 /// 40-attempt sweep, which reuses `v_start` coordinates across unrelated
8819 /// seeds/frames and made r6's captured 9 bytes unprovable. Run with
8820 /// `EC_LR_CALL_DUMP=1` set (see `restoration.rs`'s `apply_sgrproj_stripe`)
8821 /// to get the real window on stderr, call-uniquely keyed to `xqd ==
8822 /// [-16,-32]` rather than any coordinate.
8823 #[test]
8824 #[ignore = "reads a pinned fixture under the gitignored fixtures dir; run manually with EC_LR_CALL_DUMP=1"]
8825 fn pinned_lr_sgr_stream_call_unique_dump() {
8826 let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/lr-sgr-r7.obu");
8827 let stream = std::fs::read(path).expect("reading pinned lr-sgr-r7.obu");
8828 let pics = decode_stream(&stream).expect("pinned lr-sgr-r7.obu must decode");
8829 if have_ffmpeg() {
8830 let reference = ffmpeg_decode_sequence(&stream, 192, 128, pics.len());
8831 for (i, (got, want)) in pics.iter().zip(&reference).enumerate() {
8832 let y_mismatch = got.y != want.y;
8833 let u_mismatch = got.u != want.u;
8834 let v_mismatch = got.v != want.v;
8835 eprintln!(
8836 "frame {i}: y_mismatch={y_mismatch} u_mismatch={u_mismatch} v_mismatch={v_mismatch}"
8837 );
8838 if y_mismatch {
8839 let n = got.y.iter().zip(&want.y).filter(|(a, b)| a != b).count();
8840 eprintln!(" {n} luma bytes differ / {}", got.y.len());
8841 }
8842 if v_mismatch {
8843 let w = 96usize; // chroma plane width (192/2)
8844 for (idx, (a, b)) in got.v.iter().zip(&want.v).enumerate() {
8845 if a != b {
8846 eprintln!(" V[{},{}] got={a} want={b}", idx / w, idx % w);
8847 }
8848 }
8849 }
8850 }
8851 }
8852 }
8853
8854 /// lane-realworld r2: `read_cdef` (spec 5.11.56) ported -- per-superblock
8855 /// `cdef_idx`, wired at all five `skip`-decode sites, `apply_cdef` looks
8856 /// up strength through the grid instead of a hardcoded `[0]`. Structure
8857 /// copied from `a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact`
8858 /// but `--enable-cdef=1` (the one thing that gate turns off) and every
8859 /// *other* filter/mode feature this lane doesn't touch disabled, so a
8860 /// mismatch here can only be attributed to CDEF. `cdef_idx_hits()` is a
8861 /// hard assert -- a run that never reads a real cdef_idx symbol proves
8862 /// nothing (class `gate-blind-to-feature`).
8863 #[test]
8864 fn a_real_aomenc_stream_with_cdef_decodes_pixel_exact() {
8865 const NAME: &str = "a_real_aomenc_stream_with_cdef_decodes_pixel_exact";
8866 let _gate_lock = lock_gate_counters();
8867 if !have_ffmpeg() {
8868 eprintln!("SKIP {NAME}: no ffmpeg");
8869 return;
8870 }
8871 if !have_aomenc() {
8872 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8873 return;
8874 }
8875 // cdef_bits selects among PER-SUPERBLOCK strengths -- a single-SB
8876 // 64x64 frame (the other gates' size) gives aomenc nothing to
8877 // differentiate, so it always writes bits=0 and cdef_idx is never
8878 // read. 128x64 = 2 SBs is the minimum that lets aomenc's RD ever
8879 // pick bits > 0. Multi-SB content at --cpu-used=0 (every other
8880 // gate's setting) makes aomenc pick PARTITION_HORZ_4/VERT_B etc.
8881 // at the top SB level regardless of the ab/1to4-partitions=0
8882 // flags below (a real gap: this decoder's intra part64 match only
8883 // covers NONE/SPLIT, and the inter path blindly assumes SPLIT --
8884 // both pre-existing, out of this lane's scope); --cpu-used=4
8885 // avoids that RD path entirely and needs --aq-mode=0
8886 // --deltaq-mode=0 to keep delta_q/delta_lf (next lane step) off.
8887 let (width, height, frame_count) = (128usize, 64usize, 24usize);
8888 let mut named_refusals = 0u32;
8889 let mut matched = 0u32;
8890 let n_attempts: u32 = std::env::var("EC_CDEF_GATE_ATTEMPTS")
8891 .ok()
8892 .and_then(|s| s.parse().ok())
8893 .unwrap_or(40);
8894 for attempt in 0..n_attempts {
8895 let seed = 42 + attempt;
8896 let duration = frame_count as f64 / 25.0;
8897 // mandelbrot's ringing-prone hard edges are what CDEF's RD
8898 // search targets; flat gradients (charter's first guess) may
8899 // never make aomenc choose cdef_bits > 0.
8900 let source = format!(
8901 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
8902 sx = -0.6 + 0.005 * (attempt as f64),
8903 sy = -0.4 + 0.005 * (attempt as f64)
8904 );
8905 let y4m = Command::new("ffmpeg")
8906 .args([
8907 "-v",
8908 "error",
8909 "-f",
8910 "lavfi",
8911 "-i",
8912 &source,
8913 "-t",
8914 &duration.to_string(),
8915 "-pix_fmt",
8916 "yuv420p",
8917 "-f",
8918 "yuv4mpegpipe",
8919 "-",
8920 ])
8921 .stdin(Stdio::null())
8922 .stdout(Stdio::piped())
8923 .stderr(Stdio::piped())
8924 .output()
8925 .expect("ffmpeg failed to run");
8926 assert!(
8927 y4m.status.success(),
8928 "ffmpeg fixture: {}",
8929 String::from_utf8_lossy(&y4m.stderr)
8930 );
8931 let args: Vec<&str> = vec![
8932 "--codec=av1",
8933 "--passes=1",
8934 "--end-usage=q",
8935 "--cq-level=45",
8936 "--cpu-used=4",
8937 "--aq-mode=0",
8938 "--deltaq-mode=0",
8939 "--kf-max-dist=1000",
8940 "--threads=1",
8941 "--row-mt=0",
8942 "--auto-alt-ref=1",
8943 "--lag-in-frames=16",
8944 "--enable-fwd-kf=0",
8945 "--enable-order-hint=1",
8946 // r2: a starved inter toolset (everything below off) pushes
8947 // aomenc's RD toward exotic partition shapes (HORZ_4/VERT_B
8948 // etc.) at the SB(64) level even with those partition
8949 // flags off -- this decoder's part64 8/9/10-way arms and
8950 // the inter path's blind SPLIT assumption don't cover that;
8951 // keeping the same rich toolset the (working, ab/1to4-off)
8952 // masked-compound gate uses avoids it.
8953 "--enable-warped-motion=1",
8954 "--enable-global-motion=0",
8955 "--enable-obmc=1",
8956 "--tune-content=default",
8957 "--enable-masked-comp=1",
8958 "--enable-dist-wtd-comp=0",
8959 "--enable-interintra-comp=1",
8960 "--enable-onesided-comp=0",
8961 "--enable-interintra-wedge=0",
8962 "--enable-smooth-interintra=1",
8963 "--enable-rect-partitions=0",
8964 "--enable-ab-partitions=0",
8965 "--enable-1to4-partitions=0",
8966 "--enable-filter-intra=0",
8967 "--enable-smooth-intra=0",
8968 "--enable-paeth-intra=0",
8969 "--enable-directional-intra=0",
8970 "--enable-angle-delta=0",
8971 "--enable-tx-size-search=0",
8972 "--enable-cdef=1",
8973 "--enable-restoration=0",
8974 "--max-partition-size=32",
8975 "--min-partition-size=32",
8976 "--enable-palette=0",
8977 "--enable-intrabc=0",
8978 "--enable-cfl-intra=0",
8979 "--enable-ref-frame-mvs=0",
8980 "--obu",
8981 "-o",
8982 "-",
8983 "-",
8984 ];
8985 let mut child = Command::new(aomenc_path())
8986 .args(&args)
8987 .stdin(Stdio::piped())
8988 .stdout(Stdio::piped())
8989 .stderr(Stdio::piped())
8990 .spawn()
8991 .expect("aomenc failed to start");
8992 child
8993 .stdin
8994 .take()
8995 .expect("aomenc stdin")
8996 .write_all(&y4m.stdout)
8997 .expect("writing y4m to aomenc");
8998 let out = child.wait_with_output().expect("aomenc failed to run");
8999 assert!(
9000 out.status.success(),
9001 "aomenc refused the fixture: {}",
9002 String::from_utf8_lossy(&out.stderr)
9003 );
9004 let stream = out.stdout;
9005 let frames = match decode_stream(&stream) {
9006 Err(e) => {
9007 let msg = e.to_string();
9008 assert!(
9009 msg.contains("unsupported"),
9010 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
9011 );
9012 assert!(
9013 !msg.contains("cdef"),
9014 "{NAME} refused on cdef (seed {seed}) -- cdef_idx decode is ported: {msg}"
9015 );
9016 named_refusals += 1;
9017 eprintln!("seed {seed} refusal: {msg}");
9018 continue;
9019 }
9020 Ok(frames) => frames,
9021 };
9022 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
9023 assert_eq!(frames.len(), frame_count);
9024 let mismatched = frames
9025 .iter()
9026 .zip(&ffmpeg_frames)
9027 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
9028 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
9029 std::fs::write(&path, &stream).expect("writing pinned stream");
9030 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
9031 }
9032 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9033 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
9034 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
9035 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
9036 }
9037 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
9038 // stream again, comparing EVERY decode-order frame -- the hidden
9039 // (show_frame == 0) alt-ref frames the ffmpeg compare above
9040 // cannot see, because both sides of it emit shown frames only.
9041 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
9042 eprintln!(
9043 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
9044 {hidden_n} hidden, all pixel-exact vs the oracle"
9045 );
9046 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
9047 // libaom's temporal alt-ref filter absorbs this recipe's hidden
9048 // frames, so the compare above is vacuous -- re-encode the same
9049 // fixture with --arnr-maxframes=0 and compare THOSE.
9050 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
9051 eprintln!(
9052 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
9053 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
9054 );
9055 }
9056 matched += 1;
9057 }
9058 assert!(
9059 crate::decode::cdef_idx_hits() > 0,
9060 "{NAME}: zero cdef_idx blocks fired ({matched} matches, {named_refusals} other \
9061 refusals out of {n_attempts}) -- gate proved nothing this run"
9062 );
9063 eprintln!(
9064 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
9065 out of {n_attempts}, cdef_idx_hits={}",
9066 crate::decode::cdef_idx_hits()
9067 );
9068 }
9069 /// lane-tiny r4 GATE (was r1's `#[ignore]`d probe): every tiny key-frame
9070 /// size real aomenc will encode, decoded pixel-exact against ffmpeg.
9071 /// Tiny frames are where every edge/partial-superblock corner case is
9072 /// forced, and this sweep is what found both r3's filter-intra tx_type
9073 /// CDF row and r4's chroma-transform-size deblock defect -- so it
9074 /// hard-asserts now: a decode error, a refusal, or one differing sample
9075 /// at any size/seed fails. Only a genuinely absent oracle skips, and
9076 /// `EC_AV1_REQUIRE_AOMENC=1` turns that into a failure too.
9077 #[test]
9078 fn a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact() {
9079 if !have_ffmpeg() || !have_aomenc() {
9080 eprintln!("SKIP: no ffmpeg/aomenc");
9081 return;
9082 }
9083 let sizes: &[(usize, usize)] =
9084 &[(8, 8), (16, 16), (32, 32), (16, 32), (32, 16), (64, 64), (48, 48), (24, 24)];
9085 let mut total_exact = 0u32;
9086 for &(width, height) in sizes {
9087 let mut ok = 0u32;
9088 let mut bad = 0u32;
9089 let mut refused = 0u32;
9090 let n = 10u32;
9091 for attempt in 0..n {
9092 let seed = 42 + attempt;
9093 let source = format!(
9094 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
9095 sx = -0.6 + 0.005 * (attempt as f64),
9096 sy = -0.4 + 0.005 * (attempt as f64)
9097 );
9098 let y4m = Command::new("ffmpeg")
9099 .args([
9100 "-v", "error", "-f", "lavfi", "-i", &source, "-t", "0.04", "-pix_fmt",
9101 "yuv420p", "-f", "yuv4mpegpipe", "-",
9102 ])
9103 .stdin(Stdio::null())
9104 .stdout(Stdio::piped())
9105 .stderr(Stdio::piped())
9106 .output()
9107 .expect("ffmpeg failed to run");
9108 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
9109 let max_part = width.max(height).min(64).next_power_of_two();
9110 let min_part = width.min(height).next_power_of_two().max(8).min(max_part);
9111 let max_part_arg = format!("--max-partition-size={max_part}");
9112 let min_part_arg = format!("--min-partition-size={min_part}");
9113 let args: Vec<&str> = vec![
9114 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32",
9115 "--cpu-used=4", "--kf-max-dist=0", "--limit=1", "--threads=1",
9116 "--row-mt=0", "--enable-rect-partitions=0", "--enable-ab-partitions=0",
9117 "--enable-1to4-partitions=0",
9118 &max_part_arg, &min_part_arg,
9119 "--obu", "-o", "-", "-",
9120 ];
9121 let mut child = Command::new(aomenc_path())
9122 .args(&args)
9123 .stdin(Stdio::piped())
9124 .stdout(Stdio::piped())
9125 .stderr(Stdio::piped())
9126 .spawn()
9127 .expect("aomenc failed to start");
9128 child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("write y4m");
9129 let out = child.wait_with_output().expect("aomenc failed to run");
9130 assert!(out.status.success(), "aomenc refused: {}", String::from_utf8_lossy(&out.stderr));
9131 let stream = out.stdout;
9132 let frames = match decode_stream(&stream) {
9133 Err(e) => {
9134 // A NAMED refusal is the only non-exact outcome this
9135 // gate tolerates (8x8 still needs a rectangular
9136 // transform); anything else is a hard failure, and
9137 // the floor assert below keeps that from going
9138 // vacuous.
9139 let msg = e.to_string();
9140 assert!(
9141 msg.contains("unsupported"),
9142 "{width}x{height} seed {seed}: failed outright, not a named \
9143 refusal: {msg}"
9144 );
9145 eprintln!(" {width}x{height} seed {seed}: REFUSED {msg}");
9146 refused += 1;
9147 continue;
9148 }
9149 Ok(f) => f,
9150 };
9151 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
9152 if frames.len() == 1
9153 && frames[0].y == ffmpeg_frames[0].y
9154 && frames[0].u == ffmpeg_frames[0].u
9155 && frames[0].v == ffmpeg_frames[0].v
9156 {
9157 ok += 1;
9158 } else {
9159 bad += 1;
9160 let nd = |a: &[u16], b: &[u16]| a.iter().zip(b).filter(|(x, y)| x != y).count();
9161 let (ndy, ndu, ndv) = (
9162 nd(&frames[0].y, &ffmpeg_frames[0].y),
9163 nd(&frames[0].u, &ffmpeg_frames[0].u),
9164 nd(&frames[0].v, &ffmpeg_frames[0].v),
9165 );
9166 let mut first = None;
9167 for row in 0..height {
9168 for col in 0..width {
9169 let i = row * width + col;
9170 if frames[0].y[i] != ffmpeg_frames[0].y[i] {
9171 first = Some((row, col, frames[0].y[i], ffmpeg_frames[0].y[i]));
9172 break;
9173 }
9174 }
9175 if first.is_some() {
9176 break;
9177 }
9178 }
9179 let ndiff = frames[0]
9180 .y
9181 .iter()
9182 .zip(&ffmpeg_frames[0].y)
9183 .filter(|(a, b)| a != b)
9184 .count();
9185 eprintln!(
9186 " {width}x{height} seed {seed}: MISMATCH first_diff={first:?} \
9187 ndiff_luma={ndiff}/{} ndiff y/u/v={ndy}/{ndu}/{ndv}",
9188 width * height
9189 );
9190 }
9191 }
9192 assert_eq!(
9193 bad, 0,
9194 "{width}x{height}: {bad} of {n} seeds decoded to WRONG PIXELS ({ok} exact, \
9195 {refused} named refusals)"
9196 );
9197 eprintln!("{width}x{height}: {ok}/{n} pixel-exact, {refused} named refusals");
9198 total_exact += ok;
9199 }
9200 // Hit counter: the sweep proved nothing unless every size x seed
9201 // attempt really ran end to end (aomenc -> us -> ffmpeg compare).
9202 // Floor (hit counter): 7 of the 8 sizes must decode all 10 seeds
9203 // pixel-exact -- only 8x8 is allowed to refuse outright today. If a
9204 // future change makes sizes refuse instead of decode, this fails
9205 // rather than passing on refusals alone.
9206 assert!(
9207 total_exact >= 70,
9208 "tiny sweep only reached {total_exact} pixel-exact attempts (floor 70) -- \
9209 refusals cannot substitute for decodes"
9210 );
9211 eprintln!("tiny frame sweep: {total_exact} pixel-exact attempts");
9212 }
9213
9214 /// lane-tiny r1: re-decodes the known-failing 32x32 seed 45 fixture with
9215 /// `EC_AV1_TRACE` on to inspect what mode/tx this single-block frame
9216 /// picked. Diagnostic only, `#[ignore]`d, run manually with --nocapture.
9217 #[test]
9218 #[ignore = "diagnostic, run manually with --nocapture"]
9219 fn probe_tiny_32x32_trace() {
9220 if !have_ffmpeg() || !have_aomenc() {
9221 eprintln!("SKIP: no ffmpeg/aomenc");
9222 return;
9223 }
9224 let (width, height) = (32usize, 32usize);
9225 let attempt = 3u32; // seed 45
9226 let source = format!(
9227 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
9228 sx = -0.6 + 0.005 * (attempt as f64),
9229 sy = -0.4 + 0.005 * (attempt as f64)
9230 );
9231 let y4m = Command::new("ffmpeg")
9232 .args([
9233 "-v", "error", "-f", "lavfi", "-i", &source, "-t", "0.04", "-pix_fmt", "yuv420p",
9234 "-f", "yuv4mpegpipe", "-",
9235 ])
9236 .stdin(Stdio::null())
9237 .stdout(Stdio::piped())
9238 .stderr(Stdio::piped())
9239 .output()
9240 .expect("ffmpeg failed to run");
9241 assert!(y4m.status.success());
9242 let args: Vec<&str> = vec![
9243 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32", "--cpu-used=4",
9244 "--kf-max-dist=0", "--limit=1", "--threads=1", "--row-mt=0",
9245 "--enable-rect-partitions=0", "--enable-ab-partitions=0",
9246 "--enable-1to4-partitions=0", "--max-partition-size=32", "--min-partition-size=32",
9247 "--enable-filter-intra=0",
9248 "--obu", "-o", "-", "-",
9249 ];
9250 let mut child = Command::new(aomenc_path())
9251 .args(&args)
9252 .stdin(Stdio::piped())
9253 .stdout(Stdio::piped())
9254 .stderr(Stdio::piped())
9255 .spawn()
9256 .expect("aomenc failed to start");
9257 child.stdin.take().unwrap().write_all(&y4m.stdout).unwrap();
9258 let out = child.wait_with_output().unwrap();
9259 assert!(out.status.success());
9260 let stream = out.stdout;
9261 let frames = decode_stream(&stream).expect("decode");
9262 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
9263 let mismatched = frames[0].y != ffmpeg_frames[0].y;
9264 eprintln!("mismatched={mismatched}");
9265 }
9266
9267 /// lane-tiny r2: decodes a raw OBU stream at `EC_TINY_FIXTURE_PATH` --
9268 /// no ffmpeg/aomenc invocation -- so a range ladder can be run
9269 /// (`EC_TRACE_MODE_STEP=1`) against the exact same bytes fed to the
9270 /// oracle aomdec, byte for byte. `#[ignore]`d diagnostic, no assertion.
9271 #[test]
9272 #[ignore = "diagnostic, run manually with --nocapture and EC_TINY_FIXTURE_PATH set"]
9273 fn probe_tiny_fixture_trace() {
9274 let path = std::env::var("EC_TINY_FIXTURE_PATH")
9275 .expect("set EC_TINY_FIXTURE_PATH to an .obu file");
9276 let stream = std::fs::read(&path).expect("reading fixture");
9277 match decode_stream(&stream) {
9278 Ok(frames) => {
9279 eprintln!("decoded {} frame(s)", frames.len());
9280 if let Ok(dump) = std::env::var("EC_TINY_FIXTURE_Y_DUMP") {
9281 let bytes: Vec<u8> = frames[0].y.iter().map(|&v| v as u8).collect();
9282 std::fs::write(&dump, &bytes).expect("dump y plane");
9283 }
9284 }
9285 Err(e) => eprintln!("REFUSED: {e}"),
9286 }
9287 }
9288 /// Pinned streams captured by `EC_AV1_GATE_DUMP` off
9289 /// `a_real_aomenc_stream_with_warped_motion_refuses_or_matches` -- each
9290 /// one is a former mismatch, kept as a regression pin (warp-mismatch:
9291 /// the WARPED_CAUSAL interp-read suppression; warp-flake-7: the same
9292 /// suppression for skip_mode blocks; warp-flake-5: mvstack entry
9293 /// clamping; ii-flake-1..8: interintra neighbours excluded from
9294 /// warp-sample gathering, ref_frame[1] == INTRA_FRAME in the mi grid).
9295 /// `EC_AV1_GATE_DUMP_PIN` overrides to a single stream.
9296 /// Deterministic and static -- `#[ignore]`d because the gitignored
9297 /// fixtures dir may be absent; run manually.
9298 #[test]
9299 #[ignore = "reads pinned fixture paths under the gitignored fixtures dir; run manually"]
9300 fn pinned_warp_stream_decodes_pixel_exact() {
9301 if !have_ffmpeg() {
9302 eprintln!("SKIP pinned_warp_stream_decodes_pixel_exact: no ffmpeg");
9303 return;
9304 }
9305 let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");
9306 let paths: Vec<String> = match std::env::var("EC_AV1_GATE_DUMP_PIN") {
9307 Ok(p) => vec![p],
9308 Err(_) => [
9309 "warp-mismatch",
9310 "warp-flake-5",
9311 "warp-flake-7",
9312 "ii-flake-1",
9313 "ii-flake-2",
9314 "ii-flake-3",
9315 "ii-flake-5",
9316 "ii-flake-6",
9317 "ii-flake-7",
9318 "ii-flake-8",
9319 // switchable_interp missing from reset_counts (counter
9320 // saturation slowed the adaptation rate) -- unrelated to
9321 // interintra, caught by the same gate.
9322 "ii-flake-9",
9323 // lane-rect r2: HORZ strip rect defects (mvstack size_h,
9324 // warp sample/projection dims, OBMC overlap, deblock tx-h).
9325 "rect-flake-1",
9326 // scan_row/scan_col weight `inc` min'd by the wrong candidate
9327 // axis (width vs height) -- ties reordered DRL entry 1 for a
9328 // block under a 32x16 strip, and suppressed the -5 extended
9329 // row scan.
9330 "rect-flake-2",
9331 // overlappable_left stepped the vertical walk by the
9332 // neighbour's WIDTH: a 32x16 left strip swallowed the strip
9333 // below it, blending the wrong OBMC prediction there.
9334 "rect-flake-3",
9335 ]
9336 .iter()
9337 .map(|n| format!("{fixtures}/{n}.obu"))
9338 .collect(),
9339 };
9340 for path in paths {
9341 eprintln!("pin: {path}");
9342 check_pinned_warp_stream(&path);
9343 }
9344 }
9345
9346 fn check_pinned_warp_stream(path: &str) {
9347 use crate::decode::warp_selected_hits;
9348 let stream = std::fs::read(path).expect("reading pinned stream");
9349 let before = warp_selected_hits();
9350 let frames = decode_stream(&stream).expect("pinned stream must decode");
9351 eprintln!(
9352 "warp_selected_hits before={before} after={}",
9353 warp_selected_hits()
9354 );
9355 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 24);
9356 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9357 if got.y != want.y {
9358 for row in 0..64 {
9359 let mut line = String::new();
9360 for col in 0..64 {
9361 let d = got.y[row * 64 + col] as i32 - want.y[row * 64 + col] as i32;
9362 line.push(if d == 0 {
9363 '.'
9364 } else if d.abs() < 4 {
9365 'o'
9366 } else {
9367 'X'
9368 });
9369 }
9370 eprintln!("{line}");
9371 }
9372 }
9373 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
9374 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
9375 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
9376 }
9377 }
9378
9379 /// `LAST2_FRAME`/`LAST3_FRAME` are just older slots in the same forward
9380 /// reference-buffer ring `LAST_FRAME`/`GOLDEN_FRAME` already prove --
9381 /// dropping the golden gate's `--max-reference-frames=3
9382 /// --reduced-reference-set=1` narrowing (which suppresses exactly these)
9383 /// and running long enough for aomenc's own buffer rotation to reach
9384 /// past the first 2 frames is the whole difference.
9385 #[test]
9386 fn a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact() {
9387 a_real_aomenc_single_ref_gate(
9388 "a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact",
9389 crate::mvstack::LAST2_FRAME,
9390 "LAST2_FRAME",
9391 &["--auto-alt-ref=0", "--lag-in-frames=0"],
9392 64,
9393 64,
9394 8,
9395 120,
9396 );
9397 }
9398
9399 #[test]
9400 fn a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact() {
9401 a_real_aomenc_single_ref_gate(
9402 "a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact",
9403 crate::mvstack::LAST3_FRAME,
9404 "LAST3_FRAME",
9405 &["--auto-alt-ref=0", "--lag-in-frames=0"],
9406 64,
9407 64,
9408 8,
9409 120,
9410 );
9411 }
9412
9413 /// `BWDREF`/`ALTREF2`/`ALTREF` are all backward (display-order-forward)
9414 /// references that only exist once aomenc builds a hierarchical GOP --
9415 /// `--auto-alt-ref=1 --lag-in-frames` (need at least one full mini-GOP
9416 /// of lookahead) is what makes aomenc code them at all; without it
9417 /// every attempt would hit this decoder's own real, still-open
9418 /// per-block sign-bias gap by never drawing the reference in the first
9419 /// place, not by proving it correct.
9420 #[test]
9421 fn a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact() {
9422 a_real_aomenc_single_ref_gate(
9423 "a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact",
9424 crate::mvstack::BWDREF_FRAME,
9425 "BWDREF_FRAME",
9426 &[
9427 "--auto-alt-ref=1",
9428 "--lag-in-frames=16",
9429 "--enable-fwd-kf=0",
9430 ],
9431 64,
9432 64,
9433 16,
9434 120,
9435 );
9436 }
9437
9438 /// lane-altref2 r1: 16 frames was too short for aomenc to ever build a
9439 /// second-level alt-ref pyramid, so this gate ran 86 attempts and fired
9440 /// ALTREF2 exactly zero times (class `gate-blind-to-feature`) -- the
9441 /// flags were already right, only the clip length was wrong. A 64-frame
9442 /// clip at the same `--lag-in-frames=16` gives aomenc enough lookahead
9443 /// to schedule a 2-level GF pyramid and reliably codes ALTREF2 (4/4
9444 /// hits on a plain seed-42 direct-aomenc probe; see
9445 /// lanes/altref2-r1.report.md for the recipe search table). Firing is
9446 /// now HARD-asserted below: the gate fails rather than skips if
9447 /// `ref_hits(ALTREF2_FRAME)` does not advance.
9448 #[test]
9449 fn a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact() {
9450 let before = decode::ref_hits(crate::mvstack::ALTREF2_FRAME);
9451 a_real_aomenc_single_ref_gate(
9452 "a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact",
9453 crate::mvstack::ALTREF2_FRAME,
9454 "ALTREF2_FRAME",
9455 &[
9456 "--auto-alt-ref=1",
9457 "--lag-in-frames=16",
9458 "--enable-fwd-kf=0",
9459 ],
9460 64,
9461 64,
9462 64,
9463 120,
9464 );
9465 let after = decode::ref_hits(crate::mvstack::ALTREF2_FRAME);
9466 assert!(
9467 after > before,
9468 "a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact: \
9469 ALTREF2_FRAME never fired across 120 attempts -- the gate is vacuous \
9470 again (class gate-blind-to-feature); see lanes/altref2-r1.report.md \
9471 for the recipe that is supposed to make this fire"
9472 );
9473 }
9474
9475 #[test]
9476 fn a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact() {
9477 a_real_aomenc_single_ref_gate(
9478 "a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact",
9479 crate::mvstack::ALTREF_FRAME,
9480 "ALTREF_FRAME",
9481 &[
9482 "--auto-alt-ref=1",
9483 "--lag-in-frames=16",
9484 "--enable-fwd-kf=0",
9485 ],
9486 64,
9487 64,
9488 16,
9489 120,
9490 );
9491 }
9492
9493 /// lane-av1tmvp: the temporal-MV gate -- unlike every `_single_ref_gate`
9494 /// attempt above, this one leaves `--enable-ref-frame-mvs` at aomenc's
9495 /// own default (on) instead of pinning it off, so `use_ref_frame_mvs`
9496 /// actually fires and `decode::tmv_hits()` (this gate's own capability
9497 /// proof, not just `non_last_ref_hits`) has to advance for the run to
9498 /// count as a real pass rather than a `never_fired` skip.
9499 fn a_real_aomenc_temporal_mv_gate(seed_base: u32, attempts: u32) {
9500 let gate_name = "a_real_aomenc_temporal_mv_gate";
9501 let _gate_lock = lock_gate_counters();
9502 if !have_ffmpeg() {
9503 eprintln!("SKIP {gate_name}: no ffmpeg");
9504 return;
9505 }
9506 if !have_aomenc() {
9507 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
9508 return;
9509 }
9510 let (width, height, frame_count) = (64usize, 64usize, 16usize);
9511 let mut never_fired = 0u32;
9512 let mut refusals = Vec::new();
9513 for attempt in 0..attempts {
9514 let seed = seed_base + attempt;
9515 let duration = frame_count as f64 / 25.0;
9516 let source =
9517 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
9518 let y4m = Command::new("ffmpeg")
9519 .args([
9520 "-v",
9521 "error",
9522 "-f",
9523 "lavfi",
9524 "-i",
9525 &source,
9526 "-pix_fmt",
9527 "yuv420p",
9528 "-f",
9529 "yuv4mpegpipe",
9530 "-",
9531 ])
9532 .stdin(Stdio::null())
9533 .stdout(Stdio::piped())
9534 .stderr(Stdio::piped())
9535 .output()
9536 .expect("ffmpeg failed to run");
9537 assert!(
9538 y4m.status.success(),
9539 "ffmpeg fixture: {}",
9540 String::from_utf8_lossy(&y4m.stderr)
9541 );
9542 // Same envelope as `a_real_aomenc_single_ref_gate`, minus its
9543 // `--enable-ref-frame-mvs=0` pin -- everything else this decoder
9544 // still cannot code stays refused the same way.
9545 let args: Vec<&str> = vec![
9546 "--codec=av1",
9547 "--passes=1",
9548 "--end-usage=q",
9549 "--cq-level=55",
9550 "--cpu-used=0",
9551 "--kf-max-dist=1000",
9552 "--threads=1",
9553 "--row-mt=0",
9554 "--auto-alt-ref=1",
9555 "--lag-in-frames=16",
9556 "--enable-fwd-kf=0",
9557 "--enable-warped-motion=0",
9558 "--enable-obmc=0",
9559 "--enable-masked-comp=0",
9560 "--enable-interintra-comp=0",
9561 "--enable-dist-wtd-comp=0",
9562 "--enable-diff-wtd-comp=0",
9563 "--enable-onesided-comp=0",
9564 "--enable-interintra-wedge=0",
9565 "--enable-smooth-interintra=0",
9566 "--enable-rect-partitions=0",
9567 "--enable-ab-partitions=0",
9568 "--enable-1to4-partitions=0",
9569 "--enable-filter-intra=0",
9570 "--enable-smooth-intra=0",
9571 "--enable-paeth-intra=0",
9572 "--enable-directional-intra=0",
9573 "--enable-angle-delta=0",
9574 "--enable-tx-size-search=0",
9575 "--enable-cdef=0",
9576 "--enable-restoration=0",
9577 "--max-partition-size=32",
9578 "--min-partition-size=32",
9579 "--enable-palette=0",
9580 "--enable-intrabc=0",
9581 "--enable-cfl-intra=0",
9582 "--obu",
9583 "-o",
9584 "-",
9585 "-",
9586 ];
9587 let mut child = Command::new(aomenc_path())
9588 .args(&args)
9589 .stdin(Stdio::piped())
9590 .stdout(Stdio::piped())
9591 .stderr(Stdio::piped())
9592 .spawn()
9593 .expect("aomenc failed to start");
9594 child
9595 .stdin
9596 .take()
9597 .expect("aomenc stdin")
9598 .write_all(&y4m.stdout)
9599 .expect("writing y4m to aomenc");
9600 let out = child.wait_with_output().expect("aomenc failed to run");
9601 assert!(
9602 out.status.success(),
9603 "aomenc refused the fixture: {}",
9604 String::from_utf8_lossy(&out.stderr)
9605 );
9606 let stream = out.stdout;
9607 let before = decode::tmv_hits();
9608 let frames = match decode_stream(&stream) {
9609 Err(e) => {
9610 let msg = e.to_string();
9611 assert!(
9612 msg.contains("unsupported"),
9613 "{gate_name} failed outright (seed {seed}): {msg}"
9614 );
9615 refusals.push(format!("seed {seed}: {msg}"));
9616 continue;
9617 }
9618 Ok(frames) => frames,
9619 };
9620 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
9621 // is ALWAYS pixel-compared below; the hit counter only decides whether
9622 // the attempt counts toward the firing total.
9623 let counted = decode::tmv_hits() != before;
9624 if !counted {
9625 never_fired += 1;
9626 }
9627 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
9628 assert_eq!(frames.len(), frame_count);
9629 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
9630 let mismatched = frames
9631 .iter()
9632 .zip(&ffmpeg_frames)
9633 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
9634 if mismatched {
9635 std::fs::write(&path, &stream).expect("writing pinned stream");
9636 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
9637 }
9638 }
9639 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9640 assert_eq!(
9641 got.y, want.y,
9642 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
9643 );
9644 assert_eq!(
9645 got.u, want.u,
9646 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
9647 );
9648 assert_eq!(
9649 got.v, want.v,
9650 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
9651 );
9652 }
9653 if counted {
9654 eprintln!(
9655 "{gate_name} FIRING seed {seed}: tmv_hits advanced by {}",
9656 decode::tmv_hits() - before
9657 );
9658 gate_buckets(gate_name, 1, never_fired, refusals.len());
9659 return;
9660 }
9661 }
9662 gate_buckets(gate_name, 0, never_fired, refusals.len());
9663 eprintln!(
9664 "SKIP {gate_name}: {never_fired} attempts decoded but never fired a temporal MV \
9665 candidate, and every other attempt hit a named refusal:\n{}",
9666 refusals.join("\n")
9667 );
9668 }
9669
9670 #[test]
9671 fn a_real_aomenc_stream_with_temporal_mvs_decodes_pixel_exact() {
9672 a_real_aomenc_temporal_mv_gate(42, 40);
9673 }
9674
9675 /// bisect scratch: decode a pinned stream exactly once -- generic
9676 /// pin-repro tool, kept for manual use.
9677 #[test]
9678 #[ignore]
9679 fn scratch_decode_pinned_stream_once() {
9680 let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path");
9681 let stream = std::fs::read(&path).expect("read pinned stream");
9682 match decode_stream(&stream) {
9683 Ok(frames) => eprintln!("OK: {} frames", frames.len()),
9684 Err(e) => eprintln!("ERR: {e}"),
9685 }
9686 }
9687
9688 /// scratch: isolate a pinned mismatching stream's first divergent pixel.
9689 #[test]
9690 #[ignore]
9691 fn scratch_isolate_pinned_mismatch() {
9692 let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path");
9693 let stream = std::fs::read(&path).expect("read pinned stream");
9694 {
9695 let mut p = Av1Parser::new();
9696 let mut pos = 0usize;
9697 while pos < stream.len() {
9698 let obu = p.parse_obu(&stream[pos..]).expect("parse");
9699 pos += obu.total_size;
9700 if let ObuKind::Frame(header, _) = obu.kind {
9701 eprintln!("interpolation_filter: {:?}", header.interpolation_filter);
9702 eprintln!("cdef: {:?}", header.cdef);
9703 eprintln!("quantization: {:?}", header.quantization);
9704 eprintln!(
9705 "coded_lossless: {:?} tx_mode: {:?}",
9706 header.coded_lossless, header.tx_mode
9707 );
9708 eprintln!("delta: {:?}", header.delta);
9709 eprintln!("segmentation: {:?}", header.segmentation);
9710 eprintln!("loop_restoration: {:?}", header.loop_restoration);
9711 eprintln!(
9712 "use_128x128_superblock: {:?} disable_cdf_update: {:?} disable_frame_end_update_cdf: {:?} primary_ref_frame: {:?} allow_high_precision_mv: {:?} force_integer_mv: {:?}",
9713 p.sequence_header().map(|s| s.use_128x128_superblock),
9714 header.disable_cdf_update,
9715 header.disable_frame_end_update_cdf,
9716 header.primary_ref_frame,
9717 header.allow_high_precision_mv,
9718 header.force_integer_mv,
9719 );
9720 }
9721 }
9722 }
9723 let width = std::env::var("EC_AV1_PIN_W")
9724 .map(|s| s.parse().unwrap())
9725 .unwrap_or(64);
9726 let height = std::env::var("EC_AV1_PIN_H")
9727 .map(|s| s.parse().unwrap())
9728 .unwrap_or(64);
9729 let frame_count = std::env::var("EC_AV1_PIN_N")
9730 .map(|s| s.parse().unwrap())
9731 .unwrap_or(4);
9732 let frames = decode_stream(&stream).expect("our decode");
9733 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
9734 for f in 0..frame_count.min(frames.len()).min(ffmpeg_frames.len()) {
9735 let ours = &frames[f];
9736 let theirs = &ffmpeg_frames[f];
9737 for (plane_name, a, b, w) in [
9738 ("y", &ours.y, &theirs.y, width),
9739 ("u", &ours.u, &theirs.u, width / 2),
9740 ("v", &ours.v, &theirs.v, width / 2),
9741 ] {
9742 let mut first = None;
9743 let mut count = 0;
9744 let mut worst = 0i32;
9745 for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
9746 if x != y {
9747 count += 1;
9748 if first.is_none() {
9749 first = Some(i);
9750 }
9751 worst = worst.max((*x as i32 - *y as i32).abs());
9752 }
9753 }
9754 if let Some(i) = first {
9755 eprintln!(
9756 "frame {f} plane {plane_name}: {count} mismatches (worst delta {worst}), first at offset {i} (row {}, col {}) ours={} theirs={}",
9757 i / w,
9758 i % w,
9759 a[i],
9760 b[i]
9761 );
9762 } else {
9763 eprintln!("frame {f} plane {plane_name}: MATCH");
9764 }
9765 }
9766 }
9767 }
9768
9769 /// Final round of the TX4/tx-class lane's own gate: `--min-partition-size=8
9770 /// --max-partition-size=8` pins every leaf to exactly 8x8 (spec
9771 /// 5.11.4's own boundary carve-out aside, which a multiple-of-8 frame
9772 /// never triggers), so a real `aomenc` stream from this recipe can only
9773 /// legitimately read `PARTITION_NONE` at every `bsize=3` node -- any
9774 /// other value this decoder sees there is a genuine desync, not a
9775 /// "partition below 8x8" the encoder actually wrote (traced live against
9776 /// a debug `aomdec` 2026-08-27: the true bitstream's own 8x8 partition
9777 /// reads are all `NONE`; the mismatch was `base_ctx`'s DC-position
9778 /// short-circuit firing for `TX_CLASS_HORIZ`/`VERT` too, off by one
9779 /// `BR` read into a spurious extra Golomb call). The sinusoidal-stripe
9780 /// `geq` source (a smooth luma ramp, not the sharp two-tone stripes that
9781 /// tripped `aomenc`'s screen-content-tools auto-detect) is what actually
9782 /// resolves `V_DCT`/`H_DCT` (`TxClass::of`) on some 8x8 TUs at this
9783 /// content's frequency; the attempt loop moves on from named refusals
9784 /// (`allow_screen_content_tools`, angle-delta) same as every other
9785 /// multi-seed recipe in this file, and only counts a run as a genuine
9786 /// firing when [`decode::tx_class1_hits`] actually moved.
9787 #[test]
9788 fn a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact() {
9789 if !have_ffmpeg() {
9790 eprintln!(
9791 "SKIP a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact: no ffmpeg"
9792 );
9793 return;
9794 }
9795 if !have_aomenc() {
9796 eprintln!(
9797 "SKIP a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact: no aomenc at {}",
9798 aomenc_path().display()
9799 );
9800 return;
9801 }
9802 let (width, height) = (64usize, 64usize);
9803 let mut refusals = Vec::new();
9804 let mut fired_runs = 0u32;
9805 let mut uncounted_exact = 0u32;
9806 for attempt in 0..60u32 {
9807 let cq = 20 + (attempt % 5) * 10;
9808 let period = [4u32, 6, 8, 12, 16][(attempt as usize / 5) % 5];
9809 let y4m = Command::new("ffmpeg")
9810 .args([
9811 "-v",
9812 "error",
9813 "-f",
9814 "lavfi",
9815 "-i",
9816 "testsrc2=size=64x64:rate=25",
9817 "-vf",
9818 &format!(
9819 "geq=lum='128+80*sin(2*PI*Y/{period})':cb=128:cr=128,noise=alls=6:allf=t"
9820 ),
9821 "-pix_fmt",
9822 "yuv420p",
9823 "-t",
9824 "0.04",
9825 "-f",
9826 "yuv4mpegpipe",
9827 "-",
9828 ])
9829 .stdin(Stdio::null())
9830 .stdout(Stdio::piped())
9831 .stderr(Stdio::piped())
9832 .output()
9833 .expect("ffmpeg failed to run");
9834 assert!(
9835 y4m.status.success(),
9836 "ffmpeg fixture: {}",
9837 String::from_utf8_lossy(&y4m.stderr)
9838 );
9839 let mut child = Command::new(aomenc_path())
9840 .args([
9841 "--codec=av1",
9842 "--passes=1",
9843 "--end-usage=q",
9844 &format!("--cq-level={cq}"),
9845 "--cpu-used=0",
9846 "--enable-directional-intra=0",
9847 "--enable-smooth-intra=0",
9848 "--enable-paeth-intra=0",
9849 "--enable-rect-partitions=0",
9850 "--enable-angle-delta=0",
9851 "--enable-palette=0",
9852 "--reduced-tx-type-set=0",
9853 "--enable-restoration=0",
9854 "--enable-cdef=0",
9855 "--loopfilter-control=0",
9856 "--min-partition-size=8",
9857 "--max-partition-size=8",
9858 "--enable-ab-partitions=0",
9859 "--enable-1to4-partitions=0",
9860 "--enable-filter-intra=0",
9861 "--enable-intrabc=0",
9862 "--enable-cfl-intra=0",
9863 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
9864 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
9865 "--enable-ref-frame-mvs=0",
9866 "--tune-content=default",
9867 "--obu",
9868 "-o",
9869 "-",
9870 "-",
9871 ])
9872 .stdin(Stdio::piped())
9873 .stdout(Stdio::piped())
9874 .stderr(Stdio::piped())
9875 .spawn()
9876 .expect("aomenc failed to start");
9877 child
9878 .stdin
9879 .take()
9880 .expect("aomenc stdin")
9881 .write_all(&y4m.stdout)
9882 .expect("writing y4m to aomenc");
9883 let out = child.wait_with_output().expect("aomenc failed to run");
9884 if !out.status.success() {
9885 refusals.push(format!(
9886 "cq={cq} period={period}: aomenc itself refused the fixture"
9887 ));
9888 continue;
9889 }
9890 let stream = out.stdout;
9891 let before = decode::tx_class1_hits();
9892 let frames = match decode_stream(&stream) {
9893 Ok(frames) => frames,
9894 Err(e) => {
9895 refusals.push(format!("cq={cq} period={period}: {e}"));
9896 continue;
9897 }
9898 };
9899 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
9900 // is ALWAYS pixel-compared below; the hit counter only decides whether
9901 // the attempt counts toward the firing total.
9902 let counted = decode::tx_class1_hits() != before;
9903 if !counted {
9904 uncounted_exact += 1;
9905 refusals.push(format!(
9906 "cq={cq} period={period}: decoded and pixel-compared, but no block read a \
9907 V_DCT/H_DCT tx_type"
9908 ));
9909 }
9910 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
9911 assert_eq!(
9912 frames[0].y, ffmpeg_frames[0].y,
9913 "luma vs ffmpeg (cq={cq} period={period})"
9914 );
9915 assert_eq!(
9916 frames[0].u, ffmpeg_frames[0].u,
9917 "U vs ffmpeg (cq={cq} period={period})"
9918 );
9919 assert_eq!(
9920 frames[0].v, ffmpeg_frames[0].v,
9921 "V vs ffmpeg (cq={cq} period={period})"
9922 );
9923 if counted {
9924 fired_runs += 1;
9925 if fired_runs >= 4 {
9926 gate_buckets(
9927 "a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact",
9928 fired_runs,
9929 uncounted_exact,
9930 refusals.len() - uncounted_exact as usize,
9931 );
9932 return;
9933 }
9934 }
9935 }
9936 gate_buckets(
9937 "a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact",
9938 fired_runs,
9939 uncounted_exact,
9940 refusals.len() - uncounted_exact as usize,
9941 );
9942 panic!(
9943 "fewer than 4 firing+pixel-exact runs out of 60 attempts:\n{}",
9944 refusals.join("\n")
9945 );
9946 }
9947
9948 /// lane-av1golden7 r9's decisive fixture: a real aomenc stream (seed 59,
9949 /// `--tune-content=film`, GOLDEN_FRAME firing downstream) whose frame-0
9950 /// *intra keyframe* mismatched ffmpeg on 3855/4096 luma pixels -- traced
9951 /// to `apply_grain=true` (spec 7.18.3 grain synthesis, now implemented in
9952 /// `crate::film_grain`), entirely unrelated to GOLDEN_FRAME or frame
9953 /// ordering. Frames beyond 0 in this fixture hit an unrelated, pre-existing
9954 /// gap (`decode_inter_block`'s GOLDEN_FRAME MC path, lane-av1golden7's own
9955 /// `golden7-forwarding-mismatch.obu`), so this test truncates the stream to
9956 /// the sequence header + frame-0 OBUs only -- exactly the span the
9957 /// mismatch was traced to -- rather than reaching into `decode.rs`/`mc.rs`
9958 /// to widen MC support, which is out of this lane's scope.
9959 #[test]
9960 fn a_real_aomenc_stream_with_film_grain_decodes_pixel_exact() {
9961 if !have_ffmpeg() {
9962 eprintln!("SKIP a_real_aomenc_stream_with_film_grain_decodes_pixel_exact: no ffmpeg");
9963 return;
9964 }
9965 let data = std::fs::read(concat!(
9966 env!("CARGO_MANIFEST_DIR"),
9967 "/../../fixtures/golden6-mismatch.obu"
9968 ))
9969 .unwrap();
9970 // Truncate right after the first `Frame` OBU (the key frame): every
9971 // byte up to there is sequence header + frame-0, which is a complete,
9972 // independently decodable single-frame stream.
9973 let mut parser = Av1Parser::new();
9974 let mut pos = 0usize;
9975 let mut frame0_end = None;
9976 while pos < data.len() {
9977 let obu = parser.parse_obu(&data[pos..]).unwrap();
9978 pos += obu.total_size;
9979 if matches!(obu.kind, ObuKind::Frame(..)) {
9980 frame0_end = Some(pos);
9981 break;
9982 }
9983 }
9984 let data = &data[..frame0_end.expect("fixture has at least one frame OBU")];
9985 let (width, height) = (64usize, 64usize);
9986 let ffmpeg_frames = ffmpeg_decode_sequence(data, width, height, 1);
9987 let decoded = decode_stream(data).unwrap();
9988 assert_eq!(decoded.len(), 1);
9989 let (got, want) = (&decoded[0], &ffmpeg_frames[0]);
9990 assert_eq!(got.y, want.y, "frame 0 luma vs ffmpeg (film grain)");
9991 assert_eq!(got.u, want.u, "frame 0 U vs ffmpeg (film grain)");
9992 assert_eq!(got.v, want.v, "frame 0 V vs ffmpeg (film grain)");
9993 }
9994
9995 /// A real-encoder sweep, not just the one pinned fixture above
9996 /// (fixture-proves-symbol-not-signal class): several fresh
9997 /// `--tune-content=film` draws at different seeds/content, each decoded
9998 /// pixel-exact against ffmpeg's own AV1 decoder (which synthesizes grain
9999 /// by default -- confirmed via `ffmpeg -h decoder=av1`, no
10000 /// `-export_side_data`/grain-disable flag is passed anywhere in this
10001 /// file).
10002 #[test]
10003 fn real_aomenc_film_grain_streams_decode_pixel_exact() {
10004 if !have_ffmpeg() {
10005 eprintln!("SKIP real_aomenc_film_grain_streams_decode_pixel_exact: no ffmpeg");
10006 return;
10007 }
10008 if !have_aomenc() {
10009 eprintln!("SKIP real_aomenc_film_grain_streams_decode_pixel_exact: no aomenc");
10010 return;
10011 }
10012 let (width, height) = (64usize, 64usize);
10013 for seed in [1u64, 2, 3] {
10014 let dir = std::env::temp_dir().join(format!(
10015 "ec-av1-filmgrain-gate-{}-{seed}",
10016 std::process::id()
10017 ));
10018 std::fs::create_dir_all(&dir).unwrap();
10019 let yuv_path = dir.join("in.yuv");
10020 let obu_path = dir.join("out.obu");
10021 let frames = 3usize;
10022 let luma = width * height;
10023 let chroma = luma / 4;
10024 let mut yuv = Vec::with_capacity((luma + 2 * chroma) * frames);
10025 for f in 0..frames {
10026 let card = panned_test_card(width, height, ((f as i32 + seed as i32) * 5) as i64);
10027 yuv.extend(card.y.iter().map(|&v| v as u8));
10028 yuv.extend(card.u.iter().map(|&v| v as u8));
10029 yuv.extend(card.v.iter().map(|&v| v as u8));
10030 }
10031 std::fs::write(&yuv_path, &yuv).unwrap();
10032 let status = Command::new(aomenc_path())
10033 .args([
10034 &format!("--width={width}"),
10035 &format!("--height={height}"),
10036 "--input-bit-depth=8",
10037 "--bit-depth=8",
10038 "--fps=25/1",
10039 &format!("--limit={frames}"),
10040 // The full constraint set of the forwarding/golden gates,
10041 // so the streams stay inside this decoder's supported
10042 // envelope and the gate isolates grain synthesis alone;
10043 // `--tune-content=film` is the one flag under test (it
10044 // enables apply_grain).
10045 "--codec=av1",
10046 "--passes=1",
10047 "--end-usage=q",
10048 "--cq-level=32",
10049 "--cpu-used=0",
10050 "--lag-in-frames=0",
10051 "--auto-alt-ref=0",
10052 "--kf-max-dist=1000",
10053 "--threads=1",
10054 "--row-mt=0",
10055 "--max-reference-frames=3",
10056 "--reduced-reference-set=1",
10057 "--enable-warped-motion=0",
10058 "--enable-obmc=0",
10059 "--enable-masked-comp=0",
10060 "--enable-interintra-comp=0",
10061 "--enable-dist-wtd-comp=0",
10062 "--enable-diff-wtd-comp=0",
10063 "--enable-onesided-comp=0",
10064 "--enable-interintra-wedge=0",
10065 "--enable-smooth-interintra=0",
10066 "--enable-rect-partitions=0",
10067 "--enable-ab-partitions=0",
10068 "--enable-1to4-partitions=0",
10069 "--enable-filter-intra=0",
10070 "--enable-smooth-intra=0",
10071 "--enable-paeth-intra=0",
10072 "--enable-directional-intra=0",
10073 "--enable-angle-delta=0",
10074 "--enable-tx-size-search=0",
10075 "--enable-cdef=0",
10076 "--enable-restoration=0",
10077 "--max-partition-size=32",
10078 "--min-partition-size=32",
10079 "--enable-palette=0",
10080 "--enable-intrabc=0",
10081 "--enable-cfl-intra=0",
10082 // Temporal MV projection (`use_ref_frame_mvs`) has no
10083 // decode path here (`mvstack.rs`'s documented corner-cut:
10084 // `zero_mv_ctx` and the mode-context GLOBALMV_OFFSET bit
10085 // are always computed as if it were off) -- this gate
10086 // isolates grain synthesis, so it must stay inside that
10087 // envelope like every other feature disabled above, not
10088 // silently decode a wrong mode context. Root cause of
10089 // this test's frame-1 mismatch: aomenc turns
10090 // `use_ref_frame_mvs` on by default once order hints are
10091 // enabled, unrelated to `--tune-content=film`.
10092 "--enable-ref-frame-mvs=0",
10093 "--tune-content=film",
10094 "--obu",
10095 "-o",
10096 ])
10097 .arg(&obu_path)
10098 .arg(&yuv_path)
10099 .stdout(Stdio::null())
10100 .stderr(Stdio::null())
10101 .status()
10102 .expect("aomenc failed to start");
10103 assert!(status.success(), "aomenc failed for seed {seed}");
10104 let encoded = std::fs::read(&obu_path).unwrap();
10105 let _ = std::fs::remove_dir_all(&dir);
10106
10107 let mut parser = ec_av1_syntax::Av1Parser::new();
10108 let mut pos = 0usize;
10109 let mut saw_grain = false;
10110 while pos < encoded.len() {
10111 let obu = parser.parse_obu(&encoded[pos..]).unwrap();
10112 pos += obu.total_size;
10113 if let ec_av1_syntax::ObuKind::Frame(header, _) = obu.kind
10114 && header.film_grain.apply_grain
10115 {
10116 saw_grain = true;
10117 }
10118 }
10119 assert!(saw_grain, "seed {seed}: aomenc did not turn on apply_grain");
10120
10121 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded, width, height, frames);
10122 let decoded = decode_stream(&encoded).unwrap();
10123 assert_eq!(decoded.len(), frames, "seed {seed}");
10124 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
10125 assert_eq!(got.y, want.y, "seed {seed} frame {i} luma vs ffmpeg");
10126 assert_eq!(got.u, want.u, "seed {seed} frame {i} U vs ffmpeg");
10127 assert_eq!(got.v, want.v, "seed {seed} frame {i} V vs ffmpeg");
10128 }
10129 }
10130 }
10131
10132 /// lane-tiles r3/r7: a real two-tile-column aomenc key frame, decoded
10133 /// through [`decode_key_frame_tile_with_cdfs`] directly with the whole
10134 /// `tiles: &[&[u8]]` list -- `decode_stream`'s `cols > 1 || rows > 1`
10135 /// refusal (this file, ~line 292) still fires for any stream this wide,
10136 /// so this gate bypasses it on purpose to prove the per-tile loop r2
10137 /// landed (fresh `SymbolDecoder`/CDF copy per tile, `Neighbours::start_tile`,
10138 /// `PlaneBuf::set_tile_origin`) actually decodes both tiles pixel-exact
10139 /// before that refusal is lifted. 128x64 is exactly two 64x64
10140 /// superblocks wide with `--tile-columns=1` (`TileCols=2`), so tile 1 is
10141 /// also the frame's own right edge -- the known gap (`PlaneBuf`'s
10142 /// tile_x0/tile_y0 only clip left/top reach, not a non-last column's
10143 /// right-edge reach) does not apply to this fixture; it would to a
10144 /// 3+-column one, proven separately by the four-tile-column gate below.
10145 /// r7: `--loopfilter-control=0` REMOVED per the charter -- `PlaneBuf`'s
10146 /// `tile_x1`/`tile_y1` clamps now receive real values at every call site
10147 /// (r6's `set_tile_origin` sweep), so this gate now proves real
10148 /// deblocking across the tile boundary too, not just decode with it off.
10149 /// Tile count itself is a structural aomenc param, not
10150 /// RD-dependent content, but this decoder's chroma smooth/paeth gap
10151 /// (`decode.rs` "a smooth or paeth chroma mode (round 2)", unrelated to
10152 /// tiles, pre-dating this lane) is content-dependent -- no aomenc flag
10153 /// disables UV-only smooth/paeth search, so a small seed sweep is
10154 /// needed the same way the sibling `a_real_aomenc_stream_with_*` gates
10155 /// retry past unrelated named refusals (every refusal in this crate is
10156 /// prefixed `"AV1 tile"` regardless of category, so unlike the sibling
10157 /// gates' `warp`/`obmc`/`interintra` banned lists there is no
10158 /// tile-specific substring to forbid here -- `matched > 0` plus the
10159 /// hard `tile_hits > 1`/pixel-exact asserts on any actual decode are
10160 /// the real proof).
10161 #[test]
10162 fn a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact() {
10163 const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact";
10164 if !have_ffmpeg() {
10165 eprintln!("SKIP {NAME}: no ffmpeg");
10166 return;
10167 }
10168 if !have_aomenc() {
10169 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10170 return;
10171 }
10172 let (width, height) = (128usize, 64usize);
10173 let mut matched = 0u32;
10174 let mut named_refusals = 0u32;
10175 for attempt in 0..20u32 {
10176 let seed = 42 + attempt;
10177 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
10178 let y4m = Command::new("ffmpeg")
10179 .args([
10180 "-v",
10181 "error",
10182 "-f",
10183 "lavfi",
10184 "-i",
10185 &source,
10186 "-pix_fmt",
10187 "yuv420p",
10188 "-f",
10189 "yuv4mpegpipe",
10190 "-",
10191 ])
10192 .stdin(Stdio::null())
10193 .stdout(Stdio::piped())
10194 .stderr(Stdio::piped())
10195 .output()
10196 .expect("ffmpeg failed to run");
10197 assert!(
10198 y4m.status.success(),
10199 "ffmpeg fixture: {}",
10200 String::from_utf8_lossy(&y4m.stderr)
10201 );
10202 let mut child = Command::new(aomenc_path())
10203 .args([
10204 "--codec=av1",
10205 "--passes=1",
10206 "--end-usage=q",
10207 "--cq-level=45",
10208 "--cpu-used=0",
10209 "--limit=1",
10210 "--kf-max-dist=1000",
10211 "--threads=1",
10212 "--row-mt=0",
10213 "--tile-columns=1",
10214 "--tile-rows=0",
10215 // This decoder hardcodes SB_MI=16 (64px) superblocks
10216 // everywhere (`decode.rs`'s sb128 dead-end, ledger
10217 // `av1-superblock-contexts`) -- without this, aomenc's
10218 // own default 128x128 superblock makes 128x64 exactly
10219 // ONE superblock wide, so `--tile-columns=1` has nothing
10220 // to split and `cols` comes back 1.
10221 "--sb-size=64",
10222 // Deblocking crosses tile boundaries by default (spec
10223 // `loop_filter_across_tiles_enabled`); `PlaneBuf`'s
10224 // tile_x0/tile_y0 origin only ever clips a tile's own
10225 // left/top reach (r2/r3's documented known gap), so a
10226 // non-last tile column's right-edge deblock would read
10227 // into the next tile's still-undecoded/differently-
10228 // origined samples. Off here since deblocking itself is
10229 // not what this gate is proving.
10230 "--enable-rect-partitions=0",
10231 "--enable-ab-partitions=0",
10232 "--enable-1to4-partitions=0",
10233 "--enable-filter-intra=0",
10234 "--enable-smooth-intra=0",
10235 "--enable-paeth-intra=0",
10236 "--enable-directional-intra=0",
10237 "--enable-angle-delta=0",
10238 "--enable-tx-size-search=0",
10239 "--enable-cdef=0",
10240 "--enable-restoration=0",
10241 "--max-partition-size=32",
10242 "--min-partition-size=32",
10243 "--enable-palette=0",
10244 "--enable-intrabc=0",
10245 "--enable-cfl-intra=0",
10246 "--obu",
10247 "-o",
10248 "-",
10249 "-",
10250 ])
10251 .stdin(Stdio::piped())
10252 .stdout(Stdio::piped())
10253 .stderr(Stdio::piped())
10254 .spawn()
10255 .expect("aomenc failed to start");
10256 child
10257 .stdin
10258 .take()
10259 .expect("aomenc stdin")
10260 .write_all(&y4m.stdout)
10261 .expect("writing y4m to aomenc");
10262 let out = child.wait_with_output().expect("aomenc failed to run");
10263 assert!(
10264 out.status.success(),
10265 "aomenc refused the fixture: {}",
10266 String::from_utf8_lossy(&out.stderr)
10267 );
10268 let stream = out.stdout;
10269
10270 // Parse the stream ourselves (rather than `decode_stream`, whose
10271 // multi-tile refusal is exactly what this gate exists to run
10272 // ahead of) to reach the real `Frame` OBU's `tile_info` and its
10273 // full `Vec<Tile>` -- `Av1Parser::parse_obu` already locates
10274 // every tile in a multi-tile tile group (`parse_tile_group`), it
10275 // is only `decode_stream` that ever narrows this to
10276 // `tiles.first()`.
10277 let mut parser = Av1Parser::new();
10278 let mut pos = 0usize;
10279 let mut frame = None;
10280 while pos < stream.len() {
10281 let obu_offset = pos;
10282 let obu = parser.parse_obu(&stream[pos..]).unwrap();
10283 pos += obu.total_size;
10284 if let ObuKind::Frame(header, tiles) = obu.kind {
10285 frame = Some((header, tiles, obu_offset));
10286 break;
10287 }
10288 }
10289 let (header, tiles, obu_offset) = frame.expect("stream has a Frame OBU");
10290 assert!(
10291 header.tile_info.cols > 1,
10292 "{NAME}: aomenc did not actually split into >1 tile column (cols={}, seed {seed})",
10293 header.tile_info.cols
10294 );
10295 assert_eq!(
10296 tiles.len(),
10297 header.tile_info.cols as usize,
10298 "{NAME}: expected one tile per column (seed {seed})"
10299 );
10300 // `Tile::offset` is relative to the buffer `parse_obu` was
10301 // handed (`&stream[pos..]` at the time this OBU was parsed), so
10302 // it needs `obu_offset` added back -- the same adjustment
10303 // `decode_stream` makes for its own single-tile slice above.
10304 let tile_bufs: Vec<&[u8]> = tiles
10305 .iter()
10306 .map(|t| &stream[obu_offset + t.offset..obu_offset + t.offset + t.size])
10307 .collect();
10308
10309 let enable_filter_intra = parser
10310 .sequence_header()
10311 .is_some_and(|seq| seq.enable_filter_intra);
10312 let enable_edge_filter = parser
10313 .sequence_header()
10314 .is_some_and(|seq| seq.enable_intra_edge_filter);
10315
10316 let before = crate::decode::tile_hits();
10317 let picture = match decode_key_frame_tile_with_cdfs(
10318 &tile_bufs,
10319 &header.tile_info,
10320 header.mi_cols,
10321 header.mi_rows,
10322 header.quantization.base_q_idx,
10323 crate::quant::QuantDeltas {
10324 y_dc: i32::from(header.quantization.delta_q_y_dc),
10325 u_dc: i32::from(header.quantization.delta_q_u_dc),
10326 u_ac: i32::from(header.quantization.delta_q_u_ac),
10327 v_dc: i32::from(header.quantization.delta_q_v_dc),
10328 v_ac: i32::from(header.quantization.delta_q_v_ac),
10329 },
10330 header.frame_width,
10331 header.frame_height,
10332 enable_filter_intra,
10333 enable_edge_filter,
10334 &header.cdef,
10335 &header.loop_filter,
10336 &header.loop_restoration,
10337 None,
10338 header.tx_mode == TxMode::Select,
10339 header.reduced_tx_set,
10340 header.allow_screen_content_tools,
10341 header.allow_intrabc,
10342 header.delta,
10343 ) {
10344 Err(e) => {
10345 let msg = e.to_string();
10346 assert!(
10347 msg.contains("unsupported"),
10348 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
10349 );
10350 named_refusals += 1;
10351 eprintln!("seed {seed} refusal: {msg}");
10352 continue;
10353 }
10354 Ok((picture, _end_cdfs)) => picture,
10355 };
10356 let hits = crate::decode::tile_hits() - before;
10357 assert!(
10358 hits > 1,
10359 "{NAME}: tile_hits delta was {hits}, expected >1 -- both tiles must actually \
10360 decode, not just tile 0 (seed {seed})"
10361 );
10362
10363 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
10364 assert_eq!(picture.y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
10365 assert_eq!(picture.u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
10366 assert_eq!(picture.v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
10367 matched += 1;
10368 }
10369 assert!(
10370 matched > 0,
10371 "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \
10372 a two-tile-column stream"
10373 );
10374 eprintln!(
10375 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
10376 );
10377 }
10378
10379 /// lane-tiles r8 stage 1: the same bypass-the-refusal pattern as the
10380 /// two-tile-column gate above, this time for tile ROWS -- `decode_stream`
10381 /// still refuses any `tile_info.rows > 1` stream, so this gate calls
10382 /// [`decode_key_frame_tile_with_cdfs`] directly to prove the underlying
10383 /// per-tile loop (already row/col-generic: `tile_num / tile_info.cols`
10384 /// gives the row, `mi_row_starts`/`set_tile_origin`'s `y0`/`y1` are
10385 /// exactly symmetric with the column gate's `x0`/`x1`) actually decodes
10386 /// both tile rows pixel-exact before the refusal is lifted. 64x128 is
10387 /// one 64px superblock wide and two tall with `--tile-rows=1`
10388 /// (`TileRows=2`, `--tile-columns=0` keeps `cols=1` so only the row axis
10389 /// is under test). Loop filter is left ON (no
10390 /// `--loopfilter-control=0`) per the charter -- deblocking crosses tile
10391 /// row boundaries by spec default exactly as it crosses column ones, and
10392 /// `deblock_plane` runs once over the whole decoded picture after every
10393 /// tile is in, with no tile-axis distinction, so there is no reason to
10394 /// expect the row boundary to behave differently from the column one r7
10395 /// already proved -- this gate is what actually proves it either way.
10396 #[test]
10397 fn a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact() {
10398 const NAME: &str = "a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact";
10399 if !have_ffmpeg() {
10400 eprintln!("SKIP {NAME}: no ffmpeg");
10401 return;
10402 }
10403 if !have_aomenc() {
10404 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10405 return;
10406 }
10407 let (width, height) = (64usize, 128usize);
10408 let mut matched = 0u32;
10409 let mut named_refusals = 0u32;
10410 for attempt in 0..20u32 {
10411 let seed = 42 + attempt;
10412 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
10413 let y4m = Command::new("ffmpeg")
10414 .args([
10415 "-v",
10416 "error",
10417 "-f",
10418 "lavfi",
10419 "-i",
10420 &source,
10421 "-pix_fmt",
10422 "yuv420p",
10423 "-f",
10424 "yuv4mpegpipe",
10425 "-",
10426 ])
10427 .stdin(Stdio::null())
10428 .stdout(Stdio::piped())
10429 .stderr(Stdio::piped())
10430 .output()
10431 .expect("ffmpeg failed to run");
10432 assert!(
10433 y4m.status.success(),
10434 "ffmpeg fixture: {}",
10435 String::from_utf8_lossy(&y4m.stderr)
10436 );
10437 let mut child = Command::new(aomenc_path())
10438 .args([
10439 "--codec=av1",
10440 "--passes=1",
10441 "--end-usage=q",
10442 "--cq-level=45",
10443 "--cpu-used=0",
10444 "--limit=1",
10445 "--kf-max-dist=1000",
10446 "--threads=1",
10447 "--row-mt=0",
10448 "--tile-columns=0",
10449 "--tile-rows=1",
10450 // This decoder hardcodes SB_MI=16 (64px) superblocks
10451 // everywhere; without this aomenc's own default 128x128
10452 // superblock makes 64x128 exactly ONE superblock tall,
10453 // so `--tile-rows=1` has nothing to split.
10454 "--sb-size=64",
10455 "--enable-rect-partitions=0",
10456 "--enable-ab-partitions=0",
10457 "--enable-1to4-partitions=0",
10458 "--enable-filter-intra=0",
10459 "--enable-smooth-intra=0",
10460 "--enable-paeth-intra=0",
10461 "--enable-directional-intra=0",
10462 "--enable-angle-delta=0",
10463 "--enable-tx-size-search=0",
10464 "--enable-cdef=0",
10465 "--enable-restoration=0",
10466 "--max-partition-size=32",
10467 "--min-partition-size=32",
10468 "--enable-palette=0",
10469 "--enable-intrabc=0",
10470 "--enable-cfl-intra=0",
10471 "--obu",
10472 "-o",
10473 "-",
10474 "-",
10475 ])
10476 .stdin(Stdio::piped())
10477 .stdout(Stdio::piped())
10478 .stderr(Stdio::piped())
10479 .spawn()
10480 .expect("aomenc failed to start");
10481 child
10482 .stdin
10483 .take()
10484 .expect("aomenc stdin")
10485 .write_all(&y4m.stdout)
10486 .expect("writing y4m to aomenc");
10487 let out = child.wait_with_output().expect("aomenc failed to run");
10488 assert!(
10489 out.status.success(),
10490 "aomenc refused the fixture: {}",
10491 String::from_utf8_lossy(&out.stderr)
10492 );
10493 let stream = out.stdout;
10494
10495 let mut parser = Av1Parser::new();
10496 let mut pos = 0usize;
10497 let mut frame = None;
10498 while pos < stream.len() {
10499 let obu_offset = pos;
10500 let obu = parser.parse_obu(&stream[pos..]).unwrap();
10501 pos += obu.total_size;
10502 if let ObuKind::Frame(header, tiles) = obu.kind {
10503 frame = Some((header, tiles, obu_offset));
10504 break;
10505 }
10506 }
10507 let (header, tiles, obu_offset) = frame.expect("stream has a Frame OBU");
10508 assert!(
10509 header.tile_info.rows > 1,
10510 "{NAME}: aomenc did not actually split into >1 tile row (rows={}, seed {seed})",
10511 header.tile_info.rows
10512 );
10513 assert_eq!(
10514 tiles.len(),
10515 header.tile_info.rows as usize,
10516 "{NAME}: expected one tile per row (cols=1, seed {seed})"
10517 );
10518 let tile_bufs: Vec<&[u8]> = tiles
10519 .iter()
10520 .map(|t| &stream[obu_offset + t.offset..obu_offset + t.offset + t.size])
10521 .collect();
10522
10523 let enable_filter_intra = parser
10524 .sequence_header()
10525 .is_some_and(|seq| seq.enable_filter_intra);
10526 let enable_edge_filter = parser
10527 .sequence_header()
10528 .is_some_and(|seq| seq.enable_intra_edge_filter);
10529
10530 let before = crate::decode::tile_hits();
10531 let picture = match decode_key_frame_tile_with_cdfs(
10532 &tile_bufs,
10533 &header.tile_info,
10534 header.mi_cols,
10535 header.mi_rows,
10536 header.quantization.base_q_idx,
10537 crate::quant::QuantDeltas {
10538 y_dc: i32::from(header.quantization.delta_q_y_dc),
10539 u_dc: i32::from(header.quantization.delta_q_u_dc),
10540 u_ac: i32::from(header.quantization.delta_q_u_ac),
10541 v_dc: i32::from(header.quantization.delta_q_v_dc),
10542 v_ac: i32::from(header.quantization.delta_q_v_ac),
10543 },
10544 header.frame_width,
10545 header.frame_height,
10546 enable_filter_intra,
10547 enable_edge_filter,
10548 &header.cdef,
10549 &header.loop_filter,
10550 &header.loop_restoration,
10551 None,
10552 header.tx_mode == TxMode::Select,
10553 header.reduced_tx_set,
10554 header.allow_screen_content_tools,
10555 header.allow_intrabc,
10556 header.delta,
10557 ) {
10558 Err(e) => {
10559 let msg = e.to_string();
10560 assert!(
10561 msg.contains("unsupported"),
10562 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
10563 );
10564 named_refusals += 1;
10565 eprintln!("seed {seed} refusal: {msg}");
10566 continue;
10567 }
10568 Ok((picture, _end_cdfs)) => picture,
10569 };
10570 let hits = crate::decode::tile_hits() - before;
10571 assert!(
10572 hits > 1,
10573 "{NAME}: tile_hits delta was {hits}, expected >1 -- both tile rows must actually \
10574 decode, not just tile 0 (seed {seed})"
10575 );
10576
10577 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
10578 assert_eq!(picture.y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
10579 assert_eq!(picture.u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
10580 assert_eq!(picture.v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
10581 matched += 1;
10582 }
10583 assert!(
10584 matched > 0,
10585 "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \
10586 a two-tile-row stream"
10587 );
10588 eprintln!(
10589 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
10590 );
10591 }
10592
10593 /// lane-tiles r8 stage 2/3: the same two-tile-row stream as the bypass
10594 /// gate above, this time through `decode_stream` itself -- the entry
10595 /// point real callers use, with the `rows > 1` refusal lifted (same
10596 /// commit) so this actually reaches the tile decode instead of
10597 /// refusing by name. Loop filter ON, no `--loopfilter-control=0`.
10598 #[test]
10599 fn a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_stream() {
10600 const NAME: &str = "a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_stream";
10601 if !have_ffmpeg() {
10602 eprintln!("SKIP {NAME}: no ffmpeg");
10603 return;
10604 }
10605 if !have_aomenc() {
10606 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10607 return;
10608 }
10609 let (width, height) = (64usize, 128usize);
10610 let mut matched = 0u32;
10611 let mut named_refusals = 0u32;
10612 for attempt in 0..20u32 {
10613 let seed = 42 + attempt;
10614 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
10615 let y4m = Command::new("ffmpeg")
10616 .args([
10617 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
10618 "yuv4mpegpipe", "-",
10619 ])
10620 .stdin(Stdio::null())
10621 .stdout(Stdio::piped())
10622 .stderr(Stdio::piped())
10623 .output()
10624 .expect("ffmpeg failed to run");
10625 assert!(
10626 y4m.status.success(),
10627 "ffmpeg fixture: {}",
10628 String::from_utf8_lossy(&y4m.stderr)
10629 );
10630 let mut child = Command::new(aomenc_path())
10631 .args([
10632 "--codec=av1",
10633 "--passes=1",
10634 "--end-usage=q",
10635 "--cq-level=45",
10636 "--cpu-used=0",
10637 "--limit=1",
10638 "--kf-max-dist=1000",
10639 "--threads=1",
10640 "--row-mt=0",
10641 "--tile-columns=0",
10642 "--tile-rows=1",
10643 "--sb-size=64",
10644 "--enable-rect-partitions=0",
10645 "--enable-ab-partitions=0",
10646 "--enable-1to4-partitions=0",
10647 "--enable-filter-intra=0",
10648 "--enable-smooth-intra=0",
10649 "--enable-paeth-intra=0",
10650 "--enable-directional-intra=0",
10651 "--enable-angle-delta=0",
10652 "--enable-tx-size-search=0",
10653 "--enable-cdef=0",
10654 "--enable-restoration=0",
10655 "--max-partition-size=32",
10656 "--min-partition-size=32",
10657 "--enable-palette=0",
10658 "--enable-intrabc=0",
10659 "--enable-cfl-intra=0",
10660 "--obu",
10661 "-o",
10662 "-",
10663 "-",
10664 ])
10665 .stdin(Stdio::piped())
10666 .stdout(Stdio::piped())
10667 .stderr(Stdio::piped())
10668 .spawn()
10669 .expect("aomenc failed to start");
10670 child
10671 .stdin
10672 .take()
10673 .expect("aomenc stdin")
10674 .write_all(&y4m.stdout)
10675 .expect("writing y4m to aomenc");
10676 let out = child.wait_with_output().expect("aomenc failed to run");
10677 assert!(
10678 out.status.success(),
10679 "aomenc refused the fixture: {}",
10680 String::from_utf8_lossy(&out.stderr)
10681 );
10682 let stream = out.stdout;
10683
10684 let before = crate::decode::tile_hits();
10685 let pictures = match decode_stream(&stream) {
10686 Err(e) => {
10687 let msg = e.to_string();
10688 assert!(
10689 msg.contains("unsupported"),
10690 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
10691 );
10692 named_refusals += 1;
10693 eprintln!("seed {seed} refusal: {msg}");
10694 continue;
10695 }
10696 Ok(pictures) => pictures,
10697 };
10698 let hits = crate::decode::tile_hits() - before;
10699 assert!(
10700 hits > 1,
10701 "{NAME}: tile_hits delta was {hits}, expected >1 -- both tile rows must actually \
10702 decode, not just tile 0 (seed {seed})"
10703 );
10704 assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})");
10705
10706 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
10707 assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
10708 assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
10709 assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
10710 matched += 1;
10711 }
10712 assert!(
10713 matched > 0,
10714 "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
10715 decoded a two-tile-row stream"
10716 );
10717 eprintln!(
10718 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
10719 );
10720 }
10721
10722 /// lane-tiles r7: the `>2 tile columns` refusal's own capability, proven
10723 /// separately from the 2-column gate above -- `--tile-columns=2` gives
10724 /// aomenc `TileCols=4` (log2), a real non-last-column right-edge case the
10725 /// 2-column fixture cannot exercise (there tile 1 IS the frame's right
10726 /// edge). 256x64 is four 64x64 superblocks wide with `--sb-size=64`, so
10727 /// each tile column is exactly one superblock. Loop filtering stays ON
10728 /// (no `--loopfilter-control=0`) to prove the same reach-bound fix also
10729 /// covers deblocking across an *interior* tile boundary, not just the
10730 /// 2-column case's boundary-that-is-also-the-frame-edge.
10731 #[test]
10732 fn a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact() {
10733 const NAME: &str = "a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact";
10734 if !have_ffmpeg() {
10735 eprintln!("SKIP {NAME}: no ffmpeg");
10736 return;
10737 }
10738 if !have_aomenc() {
10739 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10740 return;
10741 }
10742 let (width, height) = (256usize, 64usize);
10743 let mut matched = 0u32;
10744 let mut named_refusals = 0u32;
10745 for attempt in 0..20u32 {
10746 let seed = 42 + attempt;
10747 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
10748 let y4m = Command::new("ffmpeg")
10749 .args([
10750 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
10751 "yuv4mpegpipe", "-",
10752 ])
10753 .stdin(Stdio::null())
10754 .stdout(Stdio::piped())
10755 .stderr(Stdio::piped())
10756 .output()
10757 .expect("ffmpeg failed to run");
10758 assert!(
10759 y4m.status.success(),
10760 "ffmpeg fixture: {}",
10761 String::from_utf8_lossy(&y4m.stderr)
10762 );
10763 let mut child = Command::new(aomenc_path())
10764 .args([
10765 "--codec=av1",
10766 "--passes=1",
10767 "--end-usage=q",
10768 "--cq-level=45",
10769 "--cpu-used=0",
10770 "--limit=1",
10771 "--kf-max-dist=1000",
10772 "--threads=1",
10773 "--row-mt=0",
10774 "--tile-columns=2",
10775 "--tile-rows=0",
10776 "--sb-size=64",
10777 "--enable-rect-partitions=0",
10778 "--enable-ab-partitions=0",
10779 "--enable-1to4-partitions=0",
10780 "--enable-filter-intra=0",
10781 "--enable-smooth-intra=0",
10782 "--enable-paeth-intra=0",
10783 "--enable-directional-intra=0",
10784 "--enable-angle-delta=0",
10785 "--enable-tx-size-search=0",
10786 "--enable-cdef=0",
10787 "--enable-restoration=0",
10788 "--max-partition-size=32",
10789 "--min-partition-size=32",
10790 "--enable-palette=0",
10791 "--enable-intrabc=0",
10792 "--enable-cfl-intra=0",
10793 "--obu",
10794 "-o",
10795 "-",
10796 "-",
10797 ])
10798 .stdin(Stdio::piped())
10799 .stdout(Stdio::piped())
10800 .stderr(Stdio::piped())
10801 .spawn()
10802 .expect("aomenc failed to start");
10803 child
10804 .stdin
10805 .take()
10806 .expect("aomenc stdin")
10807 .write_all(&y4m.stdout)
10808 .expect("writing y4m to aomenc");
10809 let out = child.wait_with_output().expect("aomenc failed to run");
10810 assert!(
10811 out.status.success(),
10812 "aomenc refused the fixture: {}",
10813 String::from_utf8_lossy(&out.stderr)
10814 );
10815 let stream = out.stdout;
10816
10817 let mut parser = Av1Parser::new();
10818 let mut pos = 0usize;
10819 let mut frame = None;
10820 while pos < stream.len() {
10821 let obu_offset = pos;
10822 let obu = parser.parse_obu(&stream[pos..]).unwrap();
10823 pos += obu.total_size;
10824 if let ObuKind::Frame(header, tiles) = obu.kind {
10825 frame = Some((header, tiles, obu_offset));
10826 break;
10827 }
10828 }
10829 let (header, tiles, obu_offset) = frame.expect("stream has a Frame OBU");
10830 assert!(
10831 header.tile_info.cols > 2,
10832 "{NAME}: aomenc did not actually split into >2 tile columns (cols={}, seed {seed})",
10833 header.tile_info.cols
10834 );
10835 assert_eq!(
10836 tiles.len(),
10837 header.tile_info.cols as usize,
10838 "{NAME}: expected one tile per column (seed {seed})"
10839 );
10840 let tile_bufs: Vec<&[u8]> = tiles
10841 .iter()
10842 .map(|t| &stream[obu_offset + t.offset..obu_offset + t.offset + t.size])
10843 .collect();
10844
10845 let enable_filter_intra = parser
10846 .sequence_header()
10847 .is_some_and(|seq| seq.enable_filter_intra);
10848 let enable_edge_filter = parser
10849 .sequence_header()
10850 .is_some_and(|seq| seq.enable_intra_edge_filter);
10851
10852 let before = crate::decode::tile_hits();
10853 let picture = match decode_key_frame_tile_with_cdfs(
10854 &tile_bufs,
10855 &header.tile_info,
10856 header.mi_cols,
10857 header.mi_rows,
10858 header.quantization.base_q_idx,
10859 crate::quant::QuantDeltas {
10860 y_dc: i32::from(header.quantization.delta_q_y_dc),
10861 u_dc: i32::from(header.quantization.delta_q_u_dc),
10862 u_ac: i32::from(header.quantization.delta_q_u_ac),
10863 v_dc: i32::from(header.quantization.delta_q_v_dc),
10864 v_ac: i32::from(header.quantization.delta_q_v_ac),
10865 },
10866 header.frame_width,
10867 header.frame_height,
10868 enable_filter_intra,
10869 enable_edge_filter,
10870 &header.cdef,
10871 &header.loop_filter,
10872 &header.loop_restoration,
10873 None,
10874 header.tx_mode == TxMode::Select,
10875 header.reduced_tx_set,
10876 header.allow_screen_content_tools,
10877 header.allow_intrabc,
10878 header.delta,
10879 ) {
10880 Err(e) => {
10881 let msg = e.to_string();
10882 assert!(
10883 msg.contains("unsupported"),
10884 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
10885 );
10886 named_refusals += 1;
10887 eprintln!("seed {seed} refusal: {msg}");
10888 continue;
10889 }
10890 Ok((picture, _end_cdfs)) => picture,
10891 };
10892 let hits = crate::decode::tile_hits() - before;
10893 assert!(
10894 hits > 2,
10895 "{NAME}: tile_hits delta was {hits}, expected >2 -- all four tiles must actually \
10896 decode, not just a subset (seed {seed})"
10897 );
10898
10899 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
10900 assert_eq!(picture.y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
10901 assert_eq!(picture.u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
10902 assert_eq!(picture.v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
10903 matched += 1;
10904 }
10905 assert!(
10906 matched > 0,
10907 "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \
10908 a four-tile-column stream"
10909 );
10910 eprintln!(
10911 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
10912 );
10913 }
10914
10915 /// lane-tiles r8: the tile-*row* analogue of the four-tile-column gate
10916 /// above -- `--tile-rows=2` gives aomenc `TileRows=4` (log2; uniform
10917 /// tile spacing is always a power of two, so this is the smallest count
10918 /// that has an interior row neither the top nor bottom frame edge,
10919 /// mirroring why the column gate needed 4 columns rather than 3). 64x256
10920 /// is four 64x64 superblocks tall with `--sb-size=64`, one per tile row.
10921 /// Loop filter ON, run through `decode_stream` itself since the
10922 /// `rows > 1` refusal is already lifted by this commit. Also settles a
10923 /// stale documentation claim found while writing this gate: the old
10924 /// comment above `decode_stream`'s multi-tile block said
10925 /// `context_update_tile_id != 0` was refused "further down" -- no such
10926 /// refusal exists (`decode.rs` reads `tile_info.context_update_tile_id`
10927 /// generically, never hardcoded to tile 0), and this fixture's own
10928 /// aomenc runs pick 1/2/3 as often as 0 (RD-driven tile-size heuristic),
10929 /// all 20/20 pixel-exact -- so the capability was already there,
10930 /// undocumented and unproven; hard-asserted here so the proof can't go
10931 /// unnoticed if it stops firing.
10932 #[test]
10933 fn a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact() {
10934 const NAME: &str = "a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact";
10935 if !have_ffmpeg() {
10936 eprintln!("SKIP {NAME}: no ffmpeg");
10937 return;
10938 }
10939 if !have_aomenc() {
10940 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10941 return;
10942 }
10943 let (width, height) = (64usize, 256usize);
10944 let mut matched = 0u32;
10945 let mut named_refusals = 0u32;
10946 let mut saw_nonzero_context_update_tile_id = false;
10947 for attempt in 0..20u32 {
10948 let seed = 42 + attempt;
10949 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
10950 let y4m = Command::new("ffmpeg")
10951 .args([
10952 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
10953 "yuv4mpegpipe", "-",
10954 ])
10955 .stdin(Stdio::null())
10956 .stdout(Stdio::piped())
10957 .stderr(Stdio::piped())
10958 .output()
10959 .expect("ffmpeg failed to run");
10960 assert!(
10961 y4m.status.success(),
10962 "ffmpeg fixture: {}",
10963 String::from_utf8_lossy(&y4m.stderr)
10964 );
10965 let mut child = Command::new(aomenc_path())
10966 .args([
10967 "--codec=av1",
10968 "--passes=1",
10969 "--end-usage=q",
10970 "--cq-level=45",
10971 "--cpu-used=0",
10972 "--limit=1",
10973 "--kf-max-dist=1000",
10974 "--threads=1",
10975 "--row-mt=0",
10976 "--tile-columns=0",
10977 "--tile-rows=2",
10978 "--sb-size=64",
10979 "--enable-rect-partitions=0",
10980 "--enable-ab-partitions=0",
10981 "--enable-1to4-partitions=0",
10982 "--enable-filter-intra=0",
10983 "--enable-smooth-intra=0",
10984 "--enable-paeth-intra=0",
10985 "--enable-directional-intra=0",
10986 "--enable-angle-delta=0",
10987 "--enable-tx-size-search=0",
10988 "--enable-cdef=0",
10989 "--enable-restoration=0",
10990 "--max-partition-size=32",
10991 "--min-partition-size=32",
10992 "--enable-palette=0",
10993 "--enable-intrabc=0",
10994 "--enable-cfl-intra=0",
10995 "--obu",
10996 "-o",
10997 "-",
10998 "-",
10999 ])
11000 .stdin(Stdio::piped())
11001 .stdout(Stdio::piped())
11002 .stderr(Stdio::piped())
11003 .spawn()
11004 .expect("aomenc failed to start");
11005 child
11006 .stdin
11007 .take()
11008 .expect("aomenc stdin")
11009 .write_all(&y4m.stdout)
11010 .expect("writing y4m to aomenc");
11011 let out = child.wait_with_output().expect("aomenc failed to run");
11012 assert!(
11013 out.status.success(),
11014 "aomenc refused the fixture: {}",
11015 String::from_utf8_lossy(&out.stderr)
11016 );
11017 let stream = out.stdout;
11018
11019 let mut parser = Av1Parser::new();
11020 let mut pos = 0usize;
11021 let mut rows_seen = 0u32;
11022 while pos < stream.len() {
11023 let obu = parser.parse_obu(&stream[pos..]).unwrap();
11024 pos += obu.total_size;
11025 if let ObuKind::Frame(header, _) = &obu.kind {
11026 rows_seen = header.tile_info.rows;
11027 if header.tile_info.context_update_tile_id != 0 {
11028 saw_nonzero_context_update_tile_id = true;
11029 }
11030 }
11031 }
11032 assert!(
11033 rows_seen > 2,
11034 "{NAME}: aomenc did not actually split into >2 tile rows (rows={rows_seen}, seed {seed})"
11035 );
11036
11037 let before = crate::decode::tile_hits();
11038 let pictures = match decode_stream(&stream) {
11039 Err(e) => {
11040 let msg = e.to_string();
11041 assert!(
11042 msg.contains("unsupported"),
11043 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
11044 );
11045 named_refusals += 1;
11046 eprintln!("seed {seed} refusal: {msg}");
11047 continue;
11048 }
11049 Ok(pictures) => pictures,
11050 };
11051 let hits = crate::decode::tile_hits() - before;
11052 assert!(
11053 hits > 2,
11054 "{NAME}: tile_hits delta was {hits}, expected >2 -- all four tile rows must \
11055 actually decode, not just a subset (seed {seed})"
11056 );
11057 assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})");
11058
11059 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
11060 assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
11061 assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
11062 assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
11063 matched += 1;
11064 }
11065 assert!(
11066 matched > 0,
11067 "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \
11068 a four-tile-row stream"
11069 );
11070 assert!(
11071 saw_nonzero_context_update_tile_id,
11072 "{NAME}: every attempt named context_update_tile_id=0 -- this sweep proves nothing \
11073 about the != 0 case (see the stale-refusal note above `decode_stream`'s multi-tile \
11074 comment: aomenc's own tile-size heuristic picks it, seen 1/2/3 live in a prior probe \
11075 run of this exact fixture, so a 20-attempt window not seeing it is the gate's own bug)"
11076 );
11077 eprintln!(
11078 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
11079 );
11080 }
11081
11082 /// lane-tiles r4/r7: the same real two-tile-column stream as the
11083 /// bypass gate above, this time run through `decode_stream` itself --
11084 /// the entry point real callers use. Proves the `cols > 1` refusal is
11085 /// actually lifted (not just that the underlying per-tile loop works)
11086 /// for a key frame; `--loopfilter-control=0` stays here for its own
11087 /// sake (isolating the entry-point wiring from deblocking), but r7's
11088 /// `a_real_aomenc_stream_with_four_tile_columns_decodes_pixel_exact`
11089 /// bypass gate now proves loop filtering ON across a tile boundary too,
11090 /// and the `cols > 1 && loop_filter_on` / `cols > 2` refusals this
11091 /// comment used to describe are gone from `decode_stream`.
11092 #[test]
11093 fn a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream() {
11094 const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream";
11095 if !have_ffmpeg() {
11096 eprintln!("SKIP {NAME}: no ffmpeg");
11097 return;
11098 }
11099 if !have_aomenc() {
11100 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11101 return;
11102 }
11103 let (width, height) = (128usize, 64usize);
11104 let mut matched = 0u32;
11105 let mut named_refusals = 0u32;
11106 for attempt in 0..20u32 {
11107 let seed = 42 + attempt;
11108 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
11109 let y4m = Command::new("ffmpeg")
11110 .args([
11111 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
11112 "yuv4mpegpipe", "-",
11113 ])
11114 .stdin(Stdio::null())
11115 .stdout(Stdio::piped())
11116 .stderr(Stdio::piped())
11117 .output()
11118 .expect("ffmpeg failed to run");
11119 assert!(
11120 y4m.status.success(),
11121 "ffmpeg fixture: {}",
11122 String::from_utf8_lossy(&y4m.stderr)
11123 );
11124 let mut child = Command::new(aomenc_path())
11125 .args([
11126 "--codec=av1",
11127 "--passes=1",
11128 "--end-usage=q",
11129 "--cq-level=45",
11130 "--cpu-used=0",
11131 "--limit=1",
11132 "--kf-max-dist=1000",
11133 "--threads=1",
11134 "--row-mt=0",
11135 "--tile-columns=1",
11136 "--tile-rows=0",
11137 "--sb-size=64",
11138 "--loopfilter-control=0",
11139 "--enable-rect-partitions=0",
11140 "--enable-ab-partitions=0",
11141 "--enable-1to4-partitions=0",
11142 "--enable-filter-intra=0",
11143 "--enable-smooth-intra=0",
11144 "--enable-paeth-intra=0",
11145 "--enable-directional-intra=0",
11146 "--enable-angle-delta=0",
11147 "--enable-tx-size-search=0",
11148 "--enable-cdef=0",
11149 "--enable-restoration=0",
11150 "--max-partition-size=32",
11151 "--min-partition-size=32",
11152 "--enable-palette=0",
11153 "--enable-intrabc=0",
11154 "--enable-cfl-intra=0",
11155 "--obu",
11156 "-o",
11157 "-",
11158 "-",
11159 ])
11160 .stdin(Stdio::piped())
11161 .stdout(Stdio::piped())
11162 .stderr(Stdio::piped())
11163 .spawn()
11164 .expect("aomenc failed to start");
11165 child
11166 .stdin
11167 .take()
11168 .expect("aomenc stdin")
11169 .write_all(&y4m.stdout)
11170 .expect("writing y4m to aomenc");
11171 let out = child.wait_with_output().expect("aomenc failed to run");
11172 assert!(
11173 out.status.success(),
11174 "aomenc refused the fixture: {}",
11175 String::from_utf8_lossy(&out.stderr)
11176 );
11177 let stream = out.stdout;
11178
11179 let before = crate::decode::tile_hits();
11180 let pictures = match decode_stream(&stream) {
11181 Err(e) => {
11182 let msg = e.to_string();
11183 assert!(
11184 msg.contains("unsupported"),
11185 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
11186 );
11187 named_refusals += 1;
11188 eprintln!("seed {seed} refusal: {msg}");
11189 continue;
11190 }
11191 Ok(pictures) => pictures,
11192 };
11193 let hits = crate::decode::tile_hits() - before;
11194 assert!(
11195 hits > 1,
11196 "{NAME}: tile_hits delta was {hits}, expected >1 -- both tiles must actually \
11197 decode, not just tile 0 (seed {seed})"
11198 );
11199 assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})");
11200
11201 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
11202 assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
11203 assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
11204 assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
11205 matched += 1;
11206 }
11207 assert!(
11208 matched > 0,
11209 "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
11210 decoded a two-tile-column stream"
11211 );
11212 eprintln!(
11213 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
11214 );
11215 }
11216 /// lane-realworld r6: r5 ported `maybe_read_delta_q`/`maybe_read_delta_lf`
11217 /// and removed the whole-frame refusal, but no fixture anywhere set
11218 /// `delta_lf_present` -- the removal was unproven. `--deltaq-mode=2`
11219 /// (`DELTA_Q_PERCEPTUAL`, checked against libaom's own
11220 /// `encodeframe.c:2192-2225`) sets `delta_q_present_flag` unconditionally
11221 /// once `base_qindex > 0` (unlike the default `--deltaq-mode=1`
11222 /// `DELTA_Q_OBJECTIVE`, which additionally requires an alt-ref-eligible
11223 /// frame and `allow_deltaq_mode`'s own RD search); `--delta-lf-mode=1`
11224 /// then ANDs `delta_lf_present_flag` on top
11225 /// (`tool_cfg->enable_deltalf_mode`, `av1_cx_iface.c:1269-1270`). 128x64
11226 /// (2 SBs; this decoder hardcodes 64px SBs) is the charter's minimum for
11227 /// a per-superblock symbol to have somewhere to differ; `--cpu-used=4`
11228 /// (not the other gates' `=0`) sidesteps the multi-SB
11229 /// HORZ_4/VERT_B-at-part64 gap the cdef gate's own comment documents
11230 /// (lane-realworld r2 dead-end, part64 only covers NONE/SPLIT). Note:
11231 /// libaom hardcodes `delta_lf_multi = DEFAULT_DELTA_LF_MULTI == 0`
11232 /// (`enums.h:73`) with no CLI flag to set it -- this gate cannot and
11233 /// does not claim to exercise this decoder's `delta_lf_multi` branch;
11234 /// only the single-plane path is gate-proven.
11235 #[test]
11236 fn a_real_aomenc_stream_with_delta_q_and_delta_lf_decodes_pixel_exact() {
11237 const NAME: &str = "a_real_aomenc_stream_with_delta_q_and_delta_lf_decodes_pixel_exact";
11238 let _gate_lock = lock_gate_counters();
11239 if !have_ffmpeg() {
11240 eprintln!("SKIP {NAME}: no ffmpeg");
11241 return;
11242 }
11243 if !have_aomenc() {
11244 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11245 return;
11246 }
11247 let (width, height, frame_count) = (128usize, 64usize, 24usize);
11248 let mut named_refusals = 0u32;
11249 let mut matched = 0u32;
11250 let n_attempts: u32 = std::env::var("EC_DELTAQ_GATE_ATTEMPTS")
11251 .ok()
11252 .and_then(|s| s.parse().ok())
11253 .unwrap_or(40);
11254 for attempt in 0..n_attempts {
11255 let seed = 42 + attempt;
11256 let duration = frame_count as f64 / 25.0;
11257 // Mandelbrot's varying local contrast is what gives
11258 // DELTA_Q_PERCEPTUAL's per-superblock RD something to
11259 // differentiate; flat gradients risk every superblock
11260 // resolving the same delta.
11261 let source = format!(
11262 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
11263 sx = -0.6 + 0.005 * (attempt as f64),
11264 sy = -0.4 + 0.005 * (attempt as f64)
11265 );
11266 let y4m = Command::new("ffmpeg")
11267 .args([
11268 "-v",
11269 "error",
11270 "-f",
11271 "lavfi",
11272 "-i",
11273 &source,
11274 "-t",
11275 &duration.to_string(),
11276 "-pix_fmt",
11277 "yuv420p",
11278 "-f",
11279 "yuv4mpegpipe",
11280 "-",
11281 ])
11282 .stdin(Stdio::null())
11283 .stdout(Stdio::piped())
11284 .stderr(Stdio::piped())
11285 .output()
11286 .expect("ffmpeg failed to run");
11287 assert!(
11288 y4m.status.success(),
11289 "ffmpeg fixture: {}",
11290 String::from_utf8_lossy(&y4m.stderr)
11291 );
11292 let args: Vec<&str> = vec![
11293 "--codec=av1",
11294 "--passes=1",
11295 "--end-usage=q",
11296 "--cq-level=45",
11297 "--cpu-used=4",
11298 "--aq-mode=0",
11299 "--deltaq-mode=2",
11300 "--delta-lf-mode=1",
11301 "--kf-max-dist=1000",
11302 "--threads=1",
11303 "--row-mt=0",
11304 "--sb-size=64",
11305 "--auto-alt-ref=1",
11306 "--lag-in-frames=16",
11307 "--enable-fwd-kf=0",
11308 "--enable-order-hint=1",
11309 "--enable-warped-motion=1",
11310 "--enable-global-motion=0",
11311 "--enable-obmc=1",
11312 "--tune-content=default",
11313 "--enable-masked-comp=1",
11314 "--enable-dist-wtd-comp=0",
11315 "--enable-interintra-comp=1",
11316 "--enable-onesided-comp=0",
11317 "--enable-interintra-wedge=0",
11318 "--enable-smooth-interintra=1",
11319 "--enable-rect-partitions=0",
11320 "--enable-ab-partitions=0",
11321 "--enable-1to4-partitions=0",
11322 "--enable-filter-intra=0",
11323 "--enable-smooth-intra=0",
11324 "--enable-paeth-intra=0",
11325 "--enable-directional-intra=0",
11326 "--enable-angle-delta=0",
11327 "--enable-tx-size-search=0",
11328 "--enable-cdef=1",
11329 "--enable-restoration=0",
11330 "--max-partition-size=32",
11331 "--min-partition-size=32",
11332 "--enable-palette=0",
11333 "--enable-intrabc=0",
11334 "--enable-cfl-intra=0",
11335 "--enable-ref-frame-mvs=0",
11336 "--obu",
11337 "-o",
11338 "-",
11339 "-",
11340 ];
11341 let mut child = Command::new(aomenc_path())
11342 .args(&args)
11343 .stdin(Stdio::piped())
11344 .stdout(Stdio::piped())
11345 .stderr(Stdio::piped())
11346 .spawn()
11347 .expect("aomenc failed to start");
11348 child
11349 .stdin
11350 .take()
11351 .expect("aomenc stdin")
11352 .write_all(&y4m.stdout)
11353 .expect("writing y4m to aomenc");
11354 let out = child.wait_with_output().expect("aomenc failed to run");
11355 assert!(
11356 out.status.success(),
11357 "aomenc refused the fixture: {}",
11358 String::from_utf8_lossy(&out.stderr)
11359 );
11360 let stream = out.stdout;
11361 let frames = match decode_stream(&stream) {
11362 Err(e) => {
11363 let msg = e.to_string();
11364 assert!(
11365 msg.contains("unsupported"),
11366 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
11367 );
11368 assert!(
11369 !msg.contains("delta_q") && !msg.contains("delta_lf"),
11370 "{NAME} refused on delta_q/delta_lf (seed {seed}) -- that read is ported: {msg}"
11371 );
11372 named_refusals += 1;
11373 eprintln!("seed {seed} refusal: {msg}");
11374 continue;
11375 }
11376 Ok(frames) => frames,
11377 };
11378 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
11379 assert_eq!(frames.len(), frame_count);
11380 let mismatched = frames
11381 .iter()
11382 .zip(&ffmpeg_frames)
11383 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
11384 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
11385 std::fs::write(&path, &stream).expect("writing pinned stream");
11386 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
11387 }
11388 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11389 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
11390 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
11391 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
11392 }
11393 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
11394 // stream again, comparing EVERY decode-order frame -- the hidden
11395 // (show_frame == 0) alt-ref frames the ffmpeg compare above
11396 // cannot see, because both sides of it emit shown frames only.
11397 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
11398 eprintln!(
11399 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
11400 {hidden_n} hidden, all pixel-exact vs the oracle"
11401 );
11402 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
11403 // libaom's temporal alt-ref filter absorbs this recipe's hidden
11404 // frames, so the compare above is vacuous -- re-encode the same
11405 // fixture with --arnr-maxframes=0 and compare THOSE.
11406 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
11407 eprintln!(
11408 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
11409 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
11410 );
11411 }
11412 matched += 1;
11413 }
11414 assert!(
11415 matched > 0,
11416 "{NAME}: every attempt refused on other capabilities ({named_refusals} refusals); \
11417 the gate never exercised delta_q/delta_lf"
11418 );
11419 assert!(
11420 crate::decode::delta_q_hits() > 0,
11421 "{NAME}: {matched} pixel-exact matches but zero delta_q symbol groups fired -- \
11422 the reader is unexercised"
11423 );
11424 assert!(
11425 crate::decode::delta_lf_hits() > 0,
11426 "{NAME}: {matched} pixel-exact matches but zero delta_lf symbol groups fired -- \
11427 the reader is unexercised"
11428 );
11429 eprintln!(
11430 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
11431 out of {n_attempts}, delta_q_hits={}, delta_lf_hits={}",
11432 crate::decode::delta_q_hits(),
11433 crate::decode::delta_lf_hits()
11434 );
11435 }
11436
11437 /// lane-seg: a real `aomenc` stream with SEGMENTATION genuinely active.
11438 /// `--aq-mode=1` (variance AQ) / `--aq-mode=2` (complexity AQ) are the two
11439 /// paths libaom uses to switch `segmentation_enabled` on by itself
11440 /// (`av1_vaq_frame_setup`/`av1_setup_in_frame_q_adj`, both of which only
11441 /// ever set `SEG_LVL_ALT_Q`); `--deltaq-mode=0` keeps the per-superblock
11442 /// delta-q reader out of the picture so a mismatch points at the segment
11443 /// map, not at `CurrentQIndex`. Mandelbrot's varying local contrast is
11444 /// what gives variance/complexity AQ different segments to assign --
11445 /// a flat gradient collapses every block onto one segment, which the
11446 /// `segment_ids_seen() >= 2` assert below would catch as a vacuous run.
11447 /// The rest of the recipe is the delta-q gate's own feature-disable
11448 /// envelope, so this gate isolates the segmentation reader.
11449 fn run_segmentation_gate(
11450 name: &str,
11451 aq_mode: &str,
11452 bit_depth: usize,
11453 frame_count: usize,
11454 rate_args: &[&str],
11455 ) {
11456 let _gate_lock = lock_gate_counters();
11457 if !have_ffmpeg() {
11458 eprintln!("SKIP {name}: no ffmpeg");
11459 return;
11460 }
11461 if !have_aomenc() {
11462 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
11463 return;
11464 }
11465 crate::decode::reset_segment_hits();
11466 let (width, height) = (128usize, 64usize);
11467 let mut named_refusals = 0u32;
11468 let mut matched = 0u32;
11469 let n_attempts: u32 = std::env::var("EC_SEG_GATE_ATTEMPTS")
11470 .ok()
11471 .and_then(|s| s.parse().ok())
11472 .unwrap_or(10);
11473 for attempt in 0..n_attempts {
11474 let seed = 42 + attempt;
11475 let duration = frame_count as f64 / 25.0;
11476 let source = format!(
11477 "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
11478 sx = -0.6 + 0.005 * (attempt as f64),
11479 sy = -0.4 + 0.005 * (attempt as f64)
11480 );
11481 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
11482 let y4m = Command::new("ffmpeg")
11483 .args([
11484 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
11485 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
11486 ])
11487 .stdin(Stdio::null())
11488 .stdout(Stdio::piped())
11489 .stderr(Stdio::piped())
11490 .output()
11491 .expect("ffmpeg failed to run");
11492 assert!(
11493 y4m.status.success(),
11494 "ffmpeg fixture: {}",
11495 String::from_utf8_lossy(&y4m.stderr)
11496 );
11497 let depth_args: Vec<String> = if bit_depth == 10 {
11498 vec!["--input-bit-depth=10".to_owned(), "--bit-depth=10".to_owned()]
11499 } else {
11500 Vec::new()
11501 };
11502 let aq = format!("--aq-mode={aq_mode}");
11503 let mut args: Vec<&str> = vec![
11504 "--codec=av1",
11505 "--passes=1",
11506 "--cpu-used=4",
11507 &aq,
11508 "--deltaq-mode=0",
11509 "--kf-max-dist=1000",
11510 "--threads=1",
11511 "--row-mt=0",
11512 "--sb-size=64",
11513 "--auto-alt-ref=1",
11514 "--lag-in-frames=16",
11515 "--enable-fwd-kf=0",
11516 "--enable-order-hint=1",
11517 "--enable-warped-motion=1",
11518 "--enable-global-motion=0",
11519 "--enable-obmc=1",
11520 "--tune-content=default",
11521 "--enable-masked-comp=1",
11522 "--enable-dist-wtd-comp=0",
11523 "--enable-interintra-comp=1",
11524 "--enable-onesided-comp=0",
11525 "--enable-interintra-wedge=0",
11526 "--enable-smooth-interintra=1",
11527 "--enable-rect-partitions=0",
11528 "--enable-ab-partitions=0",
11529 "--enable-1to4-partitions=0",
11530 "--enable-filter-intra=0",
11531 "--enable-smooth-intra=0",
11532 "--enable-paeth-intra=0",
11533 "--enable-directional-intra=0",
11534 "--enable-angle-delta=0",
11535 "--enable-tx-size-search=0",
11536 "--enable-cdef=1",
11537 "--enable-restoration=0",
11538 "--max-partition-size=32",
11539 "--min-partition-size=32",
11540 "--enable-palette=0",
11541 "--enable-intrabc=0",
11542 "--enable-cfl-intra=0",
11543 "--enable-ref-frame-mvs=0",
11544 ];
11545 args.extend(rate_args.iter().copied());
11546 args.extend(depth_args.iter().map(String::as_str));
11547 args.extend(["--obu", "-o", "-", "-"]);
11548 let mut child = Command::new(aomenc_path())
11549 .args(&args)
11550 .stdin(Stdio::piped())
11551 .stdout(Stdio::piped())
11552 .stderr(Stdio::piped())
11553 .spawn()
11554 .expect("aomenc failed to start");
11555 child
11556 .stdin
11557 .take()
11558 .expect("aomenc stdin")
11559 .write_all(&y4m.stdout)
11560 .expect("writing y4m to aomenc");
11561 let out = child.wait_with_output().expect("aomenc failed to run");
11562 assert!(
11563 out.status.success(),
11564 "aomenc refused the fixture: {}",
11565 String::from_utf8_lossy(&out.stderr)
11566 );
11567 let stream = out.stdout;
11568 // The stream must really carry `segmentation_enabled`, or the
11569 // gate proves nothing about the reader.
11570 let mut seg_frames = 0u32;
11571 {
11572 let mut probe = Av1Parser::new();
11573 let mut pos = 0usize;
11574 while pos < stream.len() {
11575 let obu = probe.parse_obu(&stream[pos..]).expect("parsing the gate stream");
11576 pos += obu.total_size;
11577 match &obu.kind {
11578 ObuKind::Frame(h, _) => {
11579 if h.segmentation.enabled {
11580 seg_frames += 1;
11581 }
11582 }
11583 ObuKind::FrameHeader(h) => {
11584 if h.segmentation.enabled {
11585 seg_frames += 1;
11586 }
11587 }
11588 _ => {}
11589 }
11590 }
11591 }
11592 if seg_frames == 0 {
11593 eprintln!("seed {seed}: aomenc wrote no segmentation-enabled frame, skipping attempt");
11594 continue;
11595 }
11596 let frames = match decode_stream(&stream) {
11597 Err(e) => {
11598 let msg = e.to_string();
11599 assert!(
11600 msg.contains("unsupported"),
11601 "{name} failed outright, not a named refusal (seed {seed}): {msg}"
11602 );
11603 assert!(
11604 !msg.contains("segment_id symbol"),
11605 "{name} refused on the segmentation reader itself (seed {seed}): {msg}"
11606 );
11607 named_refusals += 1;
11608 eprintln!("seed {seed} refusal: {msg}");
11609 continue;
11610 }
11611 Ok(frames) => frames,
11612 };
11613 let ffmpeg_frames = if bit_depth == 10 {
11614 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
11615 } else {
11616 ffmpeg_decode_sequence(&stream, width, height, frame_count)
11617 };
11618 assert_eq!(frames.len(), frame_count);
11619 let mismatched = frames
11620 .iter()
11621 .zip(&ffmpeg_frames)
11622 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
11623 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
11624 std::fs::write(&path, &stream).expect("writing pinned stream");
11625 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
11626 }
11627 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11628 assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (seed {seed})");
11629 assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (seed {seed})");
11630 assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (seed {seed})");
11631 }
11632 matched += 1;
11633 }
11634 assert!(
11635 matched > 0,
11636 "{name}: every attempt refused on other capabilities ({named_refusals} refusals); \
11637 the gate never exercised segmentation"
11638 );
11639 assert!(
11640 crate::decode::segment_id_hits() > 0,
11641 "{name}: {matched} pixel-exact matches but zero segment_id symbols fired -- \
11642 the reader is unexercised"
11643 );
11644 assert!(
11645 crate::decode::segment_ids_seen() >= 2,
11646 "{name}: {matched} pixel-exact matches but only {} distinct segment id(s) -- \
11647 every block landed in one segment, so nothing was actually segmented",
11648 crate::decode::segment_ids_seen()
11649 );
11650 // An inter-frame run must also have exercised the TEMPORAL path
11651 // (`seg_id_predicted` against the primary reference's saved map);
11652 // the key-frame-only run has no previous map by construction.
11653 if frame_count > 1 {
11654 assert!(
11655 crate::decode::segment_pred_hits() > 0,
11656 "{name}: {matched} pixel-exact matches over {frame_count} frames but zero \
11657 seg_id_predicted symbols -- the temporal_update path is unexercised"
11658 );
11659 }
11660 eprintln!(
11661 "{name}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
11662 out of {n_attempts}, segment_id_hits={}, distinct segment ids={}, \
11663 seg_id_predicted symbols={}",
11664 crate::decode::segment_id_hits(),
11665 crate::decode::segment_ids_seen(),
11666 crate::decode::segment_pred_hits()
11667 );
11668 }
11669
11670 #[test]
11671 fn a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact() {
11672 run_segmentation_gate(
11673 "a_real_aomenc_stream_with_variance_aq_segmentation_decodes_pixel_exact",
11674 "1",
11675 8,
11676 16,
11677 &["--end-usage=q", "--cq-level=45"],
11678 );
11679 }
11680
11681 // lane-seg r1 DEFERRED: an `--aq-mode=2` (complexity AQ) twin of the gate
11682 // above. libaom only switches segmentation on for complexity AQ once the
11683 // target bits per 64x64 superblock clear `sb64_target_rate >= 256`
11684 // (`aq_complexity.c:is_sb_aq_enabled`), which needs `--end-usage=vbr`;
11685 // every VBR recipe tried (cpu-used 0 and 4, 32x32 and 64x64 fixed
11686 // partitions) makes aomenc pick partition shapes OTHER lanes still refuse
11687 // (AB below 16x16, SB-level HORZ/VERT, part32 values 4/6), so 10/10
11688 // attempts refuse before a pixel is compared. The syntax exercised would
11689 // be identical to variance AQ's (both features only ever set
11690 // `SEG_LVL_ALT_Q` via `update_map`), so this is coverage, not capability.
11691 // Unblocked by the sub-16x16 rect/AB partition lanes.
11692
11693 /// His two AV1 films are both `yuv420p10le`, so every capability lands
11694 /// with a 10-bit twin (memory `his-av1-library-is-10-bit`). KEY FRAME
11695 /// ONLY (`frame_count = 1`): a 10-bit INTER frame does not decode
11696 /// pixel-exact in this crate yet, segmentation or not -- lane-seg r1 ran
11697 /// this same recipe with `--aq-mode=0` (segmentation off entirely) and it
11698 /// still mismatched at frame 2, so the 16-frame 10-bit variant would be
11699 /// gating an unrelated pre-existing gap. Variance AQ segments the key
11700 /// frame too (`aq_variance.c`, `is_frame_aq_enabled` includes
11701 /// `frame_is_intra_only`), so this still proves the 10-bit segment-id
11702 /// read and the per-segment 10-bit dequant.
11703 #[test]
11704 fn a_real_aomenc_10bit_stream_with_aq_segmentation_decodes_pixel_exact() {
11705 run_segmentation_gate(
11706 "a_real_aomenc_10bit_stream_with_aq_segmentation_decodes_pixel_exact",
11707 "1",
11708 10,
11709 1,
11710 &["--end-usage=q", "--cq-level=45"],
11711 );
11712 }
11713
11714 /// lane-tiles r7: the gate stage 2 (r6, commit 8899fc1) shipped without
11715 /// -- a real >1-tile-column stream with a genuine INTER frame (not just
11716 /// the key-frame-only two-column gate above), decoded through
11717 /// `decode_stream` itself. Same recipe as the key-frame gate
11718 /// (`--sb-size=64`, `--tile-columns=1`, `--loopfilter-control=0`, the
11719 /// same feature-disable envelope so the gate isolates the tile loop, not
11720 /// an unrelated unimplemented mode) plus `--limit=2 --kf-max-dist=1000`
11721 /// so frame 1 is a real inter frame, and `gradients_source`'s default
11722 /// `speed=0.01` rotation (undisturbed -- not overridden by the tail)
11723 /// gives it genuine motion against frame 0, so `decode_inter_frame_tile_
11724 /// with_cdfs`'s new per-tile loop and `MiGrid`'s per-tile bound actually
11725 /// have to walk a live MV stack across the tile-column boundary, not
11726 /// just replay skip/zero-mv blocks. Bounded with `duration=0.08` (2
11727 /// frames at rate=25) per the class in ledger
11728 /// `refusal-claim-disproved-by-its-own-gate`/`gate-loader-slurps-whole-
11729 /// file` (never leave an ffmpeg/lavfi generate unbounded).
11730 #[test]
11731 fn a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact() {
11732 const NAME: &str =
11733 "a_real_aomenc_stream_with_two_tile_columns_and_an_inter_frame_decodes_pixel_exact";
11734 if !have_ffmpeg() {
11735 eprintln!("SKIP {NAME}: no ffmpeg");
11736 return;
11737 }
11738 if !have_aomenc() {
11739 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11740 return;
11741 }
11742 let (width, height) = (128usize, 64usize);
11743 let frames = 2usize;
11744 let mut matched = 0u32;
11745 let mut named_refusals = 0u32;
11746 for attempt in 0..20u32 {
11747 let seed = 42 + attempt;
11748 let source = gradients_source(seed, width, height, "duration=0.08:rate=25");
11749 let y4m = Command::new("ffmpeg")
11750 .args([
11751 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
11752 "yuv4mpegpipe", "-",
11753 ])
11754 .stdin(Stdio::null())
11755 .stdout(Stdio::piped())
11756 .stderr(Stdio::piped())
11757 .output()
11758 .expect("ffmpeg failed to run");
11759 assert!(
11760 y4m.status.success(),
11761 "ffmpeg fixture: {}",
11762 String::from_utf8_lossy(&y4m.stderr)
11763 );
11764 let mut child = Command::new(aomenc_path())
11765 .args([
11766 "--codec=av1",
11767 "--passes=1",
11768 "--end-usage=q",
11769 "--cq-level=45",
11770 "--cpu-used=0",
11771 &format!("--limit={frames}"),
11772 "--kf-max-dist=1000",
11773 "--lag-in-frames=0",
11774 "--auto-alt-ref=0",
11775 "--threads=1",
11776 "--row-mt=0",
11777 "--tile-columns=1",
11778 "--tile-rows=0",
11779 "--sb-size=64",
11780 "--loopfilter-control=0",
11781 "--max-reference-frames=3",
11782 "--reduced-reference-set=1",
11783 "--enable-warped-motion=0",
11784 "--enable-obmc=0",
11785 "--enable-masked-comp=0",
11786 "--enable-interintra-comp=0",
11787 "--enable-dist-wtd-comp=0",
11788 "--enable-diff-wtd-comp=0",
11789 "--enable-onesided-comp=0",
11790 "--enable-interintra-wedge=0",
11791 "--enable-smooth-interintra=0",
11792 "--enable-ref-frame-mvs=0",
11793 "--enable-rect-partitions=0",
11794 "--enable-ab-partitions=0",
11795 "--enable-1to4-partitions=0",
11796 "--enable-filter-intra=0",
11797 "--enable-smooth-intra=0",
11798 "--enable-paeth-intra=0",
11799 "--enable-directional-intra=0",
11800 "--enable-angle-delta=0",
11801 "--enable-tx-size-search=0",
11802 "--enable-cdef=0",
11803 "--enable-restoration=0",
11804 "--max-partition-size=32",
11805 "--min-partition-size=32",
11806 "--enable-palette=0",
11807 "--enable-intrabc=0",
11808 "--enable-cfl-intra=0",
11809 "--obu",
11810 "-o",
11811 "-",
11812 "-",
11813 ])
11814 .stdin(Stdio::piped())
11815 .stdout(Stdio::piped())
11816 .stderr(Stdio::piped())
11817 .spawn()
11818 .expect("aomenc failed to start");
11819 child
11820 .stdin
11821 .take()
11822 .expect("aomenc stdin")
11823 .write_all(&y4m.stdout)
11824 .expect("writing y4m to aomenc");
11825 let out = child.wait_with_output().expect("aomenc failed to run");
11826 assert!(
11827 out.status.success(),
11828 "aomenc refused the fixture: {}",
11829 String::from_utf8_lossy(&out.stderr)
11830 );
11831 let stream = out.stdout;
11832
11833 // Confirm aomenc actually split into >1 tile column and that
11834 // frame 1 is a real inter frame before trusting a pixel match --
11835 // otherwise a match could mean "tiles collapsed to 1" or "frame
11836 // 1 fell back to key", not "the inter tile loop ran".
11837 let mut parser = Av1Parser::new();
11838 let mut pos = 0usize;
11839 let mut saw_multi_tile_inter = false;
11840 while pos < stream.len() {
11841 let obu = parser.parse_obu(&stream[pos..]).unwrap();
11842 pos += obu.total_size;
11843 if let ObuKind::Frame(header, _) = obu.kind
11844 && header.frame_type != FrameType::Key
11845 && header.tile_info.cols > 1
11846 {
11847 saw_multi_tile_inter = true;
11848 }
11849 }
11850 assert!(
11851 saw_multi_tile_inter,
11852 "{NAME}: seed {seed} never produced a >1-tile-column inter frame (aomenc \
11853 collapsed tiling or coded frame 1 as key)"
11854 );
11855
11856 let before = crate::decode::tile_hits();
11857 let pictures = match decode_stream(&stream) {
11858 Err(e) => {
11859 let msg = e.to_string();
11860 assert!(
11861 msg.contains("unsupported"),
11862 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
11863 );
11864 named_refusals += 1;
11865 eprintln!("seed {seed} refusal: {msg}");
11866 continue;
11867 }
11868 Ok(pictures) => pictures,
11869 };
11870 let hits = crate::decode::tile_hits() - before;
11871 assert!(
11872 hits > frames,
11873 "{NAME}: tile_hits delta was {hits}, expected > {frames} -- both tiles of both \
11874 frames must actually decode (seed {seed})"
11875 );
11876 assert_eq!(pictures.len(), frames, "{NAME}: expected {frames} pictures (seed {seed})");
11877
11878 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames);
11879 for (i, (got, want)) in pictures.iter().zip(&ffmpeg_frames).enumerate() {
11880 assert_eq!(got.y, want.y, "{NAME}: seed {seed} frame {i} luma vs ffmpeg");
11881 assert_eq!(got.u, want.u, "{NAME}: seed {seed} frame {i} U vs ffmpeg");
11882 assert_eq!(got.v, want.v, "{NAME}: seed {seed} frame {i} V vs ffmpeg");
11883 }
11884 matched += 1;
11885 }
11886 assert!(
11887 matched > 0,
11888 "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
11889 decoded a two-tile-column inter frame"
11890 );
11891 eprintln!(
11892 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
11893 );
11894 }
11895
11896 /// lane-tiles r9: `--num-tile-groups` makes aomenc split one frame's
11897 /// tiles across several `OBU_TILE_GROUP`s instead of folding them into
11898 /// the single `OBU_FRAME` every other gate in this file relies on --
11899 /// verified live (`scratch_probe_num_tile_groups`, this round) to emit a
11900 /// standalone `OBU_FRAME_HEADER` (`show_existing_frame == false`)
11901 /// followed by two `OBU_TILE_GROUP` OBUs, one tile each. Before this
11902 /// round `decode_stream` had no arm for `ObuKind::TileGroup` at all (it
11903 /// fell through the catch-all `continue`, silently dropping the frame),
11904 /// and its `ObuKind::FrameHeader` arm matched *every* frame header
11905 /// unconditionally, so a standalone header was misrouted into the
11906 /// `show_existing_frame` slot lookup and returned the wrong named error
11907 /// ("a show_existing_frame header naming an empty reference slot") for a
11908 /// frame that was never a show_existing_frame header. Both are fixed
11909 /// above: the `FrameHeader` arm now checks `show_existing_frame`, and a
11910 /// `pending_header`/`pending_tiles` accumulator collects tile groups
11911 /// until the frame's `cols * rows` tiles have all arrived.
11912 #[test]
11913 fn a_real_aomenc_stream_with_several_tile_group_obus_decodes_pixel_exact() {
11914 const NAME: &str = "a_real_aomenc_stream_with_several_tile_group_obus_decodes_pixel_exact";
11915 if !have_ffmpeg() {
11916 eprintln!("SKIP {NAME}: no ffmpeg");
11917 return;
11918 }
11919 if !have_aomenc() {
11920 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11921 return;
11922 }
11923 let (width, height) = (64usize, 128usize);
11924 let mut matched = 0u32;
11925 let mut named_refusals = 0u32;
11926 let mut saw_multiple_tile_group_obus = false;
11927 for attempt in 0..20u32 {
11928 let seed = 42 + attempt;
11929 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
11930 let y4m = Command::new("ffmpeg")
11931 .args([
11932 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
11933 "yuv4mpegpipe", "-",
11934 ])
11935 .stdin(Stdio::null())
11936 .stdout(Stdio::piped())
11937 .stderr(Stdio::piped())
11938 .output()
11939 .expect("ffmpeg failed to run");
11940 assert!(
11941 y4m.status.success(),
11942 "ffmpeg fixture: {}",
11943 String::from_utf8_lossy(&y4m.stderr)
11944 );
11945 let mut child = Command::new(aomenc_path())
11946 .args([
11947 "--codec=av1",
11948 "--passes=1",
11949 "--end-usage=q",
11950 "--cq-level=45",
11951 "--cpu-used=0",
11952 "--limit=1",
11953 "--kf-max-dist=1000",
11954 "--threads=1",
11955 "--row-mt=0",
11956 "--tile-columns=0",
11957 "--tile-rows=1",
11958 "--sb-size=64",
11959 "--num-tile-groups=4",
11960 "--loopfilter-control=0",
11961 "--enable-rect-partitions=0",
11962 "--enable-ab-partitions=0",
11963 "--enable-1to4-partitions=0",
11964 "--enable-filter-intra=0",
11965 "--enable-smooth-intra=0",
11966 "--enable-paeth-intra=0",
11967 "--enable-directional-intra=0",
11968 "--enable-angle-delta=0",
11969 "--enable-tx-size-search=0",
11970 "--enable-cdef=0",
11971 "--enable-restoration=0",
11972 "--max-partition-size=32",
11973 "--min-partition-size=32",
11974 "--enable-palette=0",
11975 "--enable-intrabc=0",
11976 "--enable-cfl-intra=0",
11977 "--obu",
11978 "-o",
11979 "-",
11980 "-",
11981 ])
11982 .stdin(Stdio::piped())
11983 .stdout(Stdio::piped())
11984 .stderr(Stdio::piped())
11985 .spawn()
11986 .expect("aomenc failed to start");
11987 child
11988 .stdin
11989 .take()
11990 .expect("aomenc stdin")
11991 .write_all(&y4m.stdout)
11992 .expect("writing y4m to aomenc");
11993 let out = child.wait_with_output().expect("aomenc failed to run");
11994 assert!(
11995 out.status.success(),
11996 "aomenc refused the fixture: {}",
11997 String::from_utf8_lossy(&out.stderr)
11998 );
11999 let stream = out.stdout;
12000
12001 let mut probe = Av1Parser::new();
12002 let mut pos = 0usize;
12003 let mut tile_group_obus = 0u32;
12004 while pos < stream.len() {
12005 let obu = probe.parse_obu(&stream[pos..]).unwrap();
12006 pos += obu.total_size;
12007 if matches!(obu.kind, ObuKind::TileGroup(_)) {
12008 tile_group_obus += 1;
12009 }
12010 }
12011 if tile_group_obus > 1 {
12012 saw_multiple_tile_group_obus = true;
12013 }
12014
12015 let before = crate::decode::tile_hits();
12016 let pictures = match decode_stream(&stream) {
12017 Err(e) => {
12018 let msg = e.to_string();
12019 assert!(
12020 msg.contains("unsupported"),
12021 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
12022 );
12023 named_refusals += 1;
12024 eprintln!("seed {seed} refusal: {msg}");
12025 continue;
12026 }
12027 Ok(pictures) => pictures,
12028 };
12029 let hits = crate::decode::tile_hits() - before;
12030 assert!(
12031 hits > 0,
12032 "{NAME}: tile_hits delta was {hits}, expected >0 (seed {seed})"
12033 );
12034 assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})");
12035
12036 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
12037 assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
12038 assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
12039 assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
12040 matched += 1;
12041 }
12042 assert!(
12043 matched > 0,
12044 "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
12045 decoded a several-tile-group-OBUs stream"
12046 );
12047 assert!(
12048 saw_multiple_tile_group_obus,
12049 "{NAME}: no attempt actually split into more than one OBU_TILE_GROUP -- this sweep \
12050 proves nothing about the multi-tile-group case (aomenc's --num-tile-groups is \
12051 RD/heuristic-driven, same as tile sizing)"
12052 );
12053 eprintln!(
12054 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
12055 );
12056 }
12057
12058 /// lane-tiles r10: non-uniform tile spacing (`uniform_spacing_flag == 0`,
12059 /// spec 5.9.15). aomenc never sets this from `--tile-columns`/
12060 /// `--tile-rows` (those always take the `uniform_spacing = 1` branch in
12061 /// `set_tile_info`, libaom `encoder.c`), and `--auto-tiles` only takes
12062 /// the non-uniform balancing path when `g_threads >= 2` -- this charter's
12063 /// `--threads=1` rules that out. The only CLI surface that reaches
12064 /// libaom's `else { tiles->uniform_spacing = 0; ... }` arm is the
12065 /// explicit per-tile size lists `--tile-width=<sb-list>`/
12066 /// `--tile-height=<sb-list>` (`av1_cx_iface.c` `set_tile_info`, argument
12067 /// parsing at `arg_defs.c`'s `.tile_width`/`.tile_height` -- present in
12068 /// the binary, just not printed by `--help`). Probed live with
12069 /// `aomenc --tile-width=1,3 --tile-height=1 --sb-size=64` on a 256x64
12070 /// source (4 SB columns, 1 SB row): confirmed by hand this round to
12071 /// produce a real OBU stream aomdec/ffmpeg both decode.
12072 ///
12073 /// `decode.rs`'s tile loop was already generic over spacing before this
12074 /// gate existed -- it walks `tile_info.mi_col_starts`/`mi_row_starts`
12075 /// (populated identically by `read_tile_info` for both the uniform and
12076 /// non-uniform branches, spec 5.9.15) and never recomputes tile bounds
12077 /// from `cols_log2`/`rows_log2`. The only place in this crate that ever
12078 /// refused non-uniform spacing is `frame.rs`'s OBU *writer*
12079 /// (`"non-uniform tile spacing is not written"`), an unrelated encode
12080 /// path this gate does not touch. So this is a staleness check, not new
12081 /// machinery: prove the already-generic decode path live and pin it.
12082 #[test]
12083 fn a_real_aomenc_stream_with_non_uniform_tile_spacing_decodes_pixel_exact() {
12084 const NAME: &str = "a_real_aomenc_stream_with_non_uniform_tile_spacing_decodes_pixel_exact";
12085 if !have_ffmpeg() {
12086 eprintln!("SKIP {NAME}: no ffmpeg");
12087 return;
12088 }
12089 if !have_aomenc() {
12090 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12091 return;
12092 }
12093 let (width, height) = (256usize, 64usize);
12094 let mut matched = 0u32;
12095 let mut named_refusals = 0u32;
12096 let mut saw_non_uniform_spacing = false;
12097 for attempt in 0..20u32 {
12098 let seed = 42 + attempt;
12099 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
12100 let y4m = Command::new("ffmpeg")
12101 .args([
12102 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
12103 "yuv4mpegpipe", "-",
12104 ])
12105 .stdin(Stdio::null())
12106 .stdout(Stdio::piped())
12107 .stderr(Stdio::piped())
12108 .output()
12109 .expect("ffmpeg failed to run");
12110 assert!(
12111 y4m.status.success(),
12112 "ffmpeg fixture: {}",
12113 String::from_utf8_lossy(&y4m.stderr)
12114 );
12115 let mut child = Command::new(aomenc_path())
12116 .args([
12117 "--codec=av1",
12118 "--passes=1",
12119 "--end-usage=q",
12120 "--cq-level=45",
12121 "--cpu-used=0",
12122 "--limit=1",
12123 "--kf-max-dist=1000",
12124 "--threads=1",
12125 "--row-mt=0",
12126 "--sb-size=64",
12127 "--tile-width=1,3",
12128 "--tile-height=1",
12129 "--loopfilter-control=0",
12130 "--enable-rect-partitions=0",
12131 "--enable-ab-partitions=0",
12132 "--enable-1to4-partitions=0",
12133 "--enable-filter-intra=0",
12134 "--enable-smooth-intra=0",
12135 "--enable-paeth-intra=0",
12136 "--enable-directional-intra=0",
12137 "--enable-angle-delta=0",
12138 "--enable-tx-size-search=0",
12139 "--enable-cdef=0",
12140 "--enable-restoration=0",
12141 "--max-partition-size=32",
12142 "--min-partition-size=32",
12143 "--enable-palette=0",
12144 "--enable-intrabc=0",
12145 "--enable-cfl-intra=0",
12146 "--obu",
12147 "-o",
12148 "-",
12149 "-",
12150 ])
12151 .stdin(Stdio::piped())
12152 .stdout(Stdio::piped())
12153 .stderr(Stdio::piped())
12154 .spawn()
12155 .expect("aomenc failed to start");
12156 child
12157 .stdin
12158 .take()
12159 .expect("aomenc stdin")
12160 .write_all(&y4m.stdout)
12161 .expect("writing y4m to aomenc");
12162 let out = child.wait_with_output().expect("aomenc failed to run");
12163 assert!(
12164 out.status.success(),
12165 "aomenc refused the fixture: {}",
12166 String::from_utf8_lossy(&out.stderr)
12167 );
12168 let stream = out.stdout;
12169
12170 let mut probe = Av1Parser::new();
12171 let mut pos = 0usize;
12172 while pos < stream.len() {
12173 let obu = probe.parse_obu(&stream[pos..]).unwrap();
12174 pos += obu.total_size;
12175 let tile_info = match &obu.kind {
12176 ObuKind::Frame(header, _) => Some(&header.tile_info),
12177 ObuKind::FrameHeader(header) if !header.show_existing_frame => {
12178 Some(&header.tile_info)
12179 }
12180 _ => None,
12181 };
12182 if let Some(info) = tile_info {
12183 if !info.uniform_spacing {
12184 saw_non_uniform_spacing = true;
12185 }
12186 assert!(
12187 info.cols > 1 || info.rows > 1,
12188 "{NAME}: --tile-width=1,3 --tile-height=1 produced only 1 tile \
12189 (cols={} rows={}, seed {seed}) -- fixture stopped exercising the case",
12190 info.cols,
12191 info.rows
12192 );
12193 }
12194 }
12195
12196 let before = crate::decode::tile_hits();
12197 let pictures = match decode_stream(&stream) {
12198 Err(e) => {
12199 let msg = e.to_string();
12200 assert!(
12201 msg.contains("unsupported"),
12202 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
12203 );
12204 named_refusals += 1;
12205 eprintln!("seed {seed} refusal: {msg}");
12206 continue;
12207 }
12208 Ok(pictures) => pictures,
12209 };
12210 let hits = crate::decode::tile_hits() - before;
12211 assert!(
12212 hits > 0,
12213 "{NAME}: tile_hits delta was {hits}, expected >0 (seed {seed})"
12214 );
12215 assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})");
12216
12217 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
12218 assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
12219 assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
12220 assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
12221 matched += 1;
12222 }
12223 assert!(
12224 matched > 0,
12225 "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
12226 decoded a non-uniform-tile-spacing stream"
12227 );
12228 assert!(
12229 saw_non_uniform_spacing,
12230 "{NAME}: no attempt actually set uniform_spacing_flag == 0 -- this sweep proves \
12231 nothing about the non-uniform case"
12232 );
12233 eprintln!(
12234 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
12235 );
12236 }
12237
12238 /// lane-sbpart r2: a real `aomenc` stream whose superblock-level
12239 /// partition decision is genuinely HORZ/VERT (not NONE/SPLIT) must
12240 /// decode pixel-exact through [`crate::decode::decode_block_rect64`] --
12241 /// `sb_rect_hits() > 0` is a HARD assert (this round's rule: a removed
12242 /// refusal needs a firing gate in the same commit, not a green suite
12243 /// that never took the new path). Recipe = the charter's own, verified
12244 /// live by r1: `--min/max-partition-size=32/64` keeps the RD search
12245 /// from ever recursing below 32x32, so every SB-level decision is
12246 /// genuinely NONE/SPLIT/HORZ/VERT; a `gradients` source blended with
12247 /// `testsrc2` (lavfi `blend=all_mode=average`) keeps the content from
12248 /// being flat enough that the search stops at NONE every time.
12249 #[test]
12250 fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact() {
12251 const NAME: &str =
12252 "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact";
12253 let _gate_lock = lock_gate_counters();
12254 if !have_ffmpeg() {
12255 eprintln!("SKIP {NAME}: no ffmpeg");
12256 return;
12257 }
12258 if !have_aomenc() {
12259 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12260 return;
12261 }
12262 let (width, height, frame_count) = (192usize, 128usize, 1usize);
12263 let mut named_refusals = 0u32;
12264 let mut matched = 0u32;
12265 let n_attempts: u32 = std::env::var("EC_SBPART_GATE_ATTEMPTS")
12266 .ok()
12267 .and_then(|s| s.parse().ok())
12268 .unwrap_or(40);
12269 for attempt in 0..n_attempts {
12270 let seed = 42 + attempt;
12271 let duration = frame_count as f64 / 25.0;
12272 let source =
12273 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
12274 let y4m = Command::new("ffmpeg")
12275 .args([
12276 "-v",
12277 "error",
12278 "-f",
12279 "lavfi",
12280 "-i",
12281 &source,
12282 "-pix_fmt",
12283 "yuv420p",
12284 "-f",
12285 "yuv4mpegpipe",
12286 "-",
12287 ])
12288 .stdin(Stdio::null())
12289 .stdout(Stdio::piped())
12290 .stderr(Stdio::piped())
12291 .output()
12292 .expect("ffmpeg failed to run");
12293 assert!(
12294 y4m.status.success(),
12295 "ffmpeg fixture: {}",
12296 String::from_utf8_lossy(&y4m.stderr)
12297 );
12298 let args: Vec<&str> = vec![
12299 "--codec=av1",
12300 "--passes=1",
12301 "--end-usage=q",
12302 "--cq-level=45",
12303 "--cpu-used=0",
12304 "--threads=1",
12305 "--row-mt=0",
12306 "--sb-size=64",
12307 "--enable-rect-partitions=1",
12308 "--enable-ab-partitions=0",
12309 "--enable-1to4-partitions=0",
12310 "--min-partition-size=32",
12311 "--max-partition-size=64",
12312 "--enable-restoration=0",
12313 "--enable-palette=0",
12314 "--deltaq-mode=0",
12315 "--enable-filter-intra=0",
12316 "--enable-cfl-intra=0",
12317 "--enable-intrabc=0",
12318 "--enable-tx-size-search=0",
12319 "--obu",
12320 "-o",
12321 "-",
12322 "-",
12323 ];
12324 let mut child = Command::new(aomenc_path())
12325 .args(&args)
12326 .stdin(Stdio::piped())
12327 .stdout(Stdio::piped())
12328 .stderr(Stdio::piped())
12329 .spawn()
12330 .expect("aomenc failed to start");
12331 child
12332 .stdin
12333 .take()
12334 .expect("aomenc stdin")
12335 .write_all(&y4m.stdout)
12336 .expect("writing y4m to aomenc");
12337 let out = child.wait_with_output().expect("aomenc failed to run");
12338 assert!(
12339 out.status.success(),
12340 "aomenc refused the fixture: {}",
12341 String::from_utf8_lossy(&out.stderr)
12342 );
12343 let stream = out.stdout;
12344 let frames = match decode_stream(&stream) {
12345 Err(e) => {
12346 let msg = e.to_string();
12347 assert!(
12348 msg.contains("unsupported"),
12349 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
12350 );
12351 // r5: the four SB-level AB arms (`partition_w64` 4-7)
12352 // decode since this round, so the only partition refusal
12353 // left at 64x64 is the 1:4 pair (values 8/9, four
12354 // 64x16/16x64 strips, whose luma TX_64X16 this decoder
12355 // has no transform for); the refusals this loop actually
12356 // counts on these fixtures are the pre-existing
12357 // screen-content-palette strip one. Every refusal is
12358 // named, so a genuine decode failure still fails the
12359 // assert above rather than skipping.
12360 named_refusals += 1;
12361 eprintln!("seed {seed} refusal: {msg}");
12362 continue;
12363 }
12364 Ok(frames) => frames,
12365 };
12366 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
12367 assert_eq!(frames.len(), frame_count);
12368 let mismatched = frames
12369 .iter()
12370 .zip(&ffmpeg_frames)
12371 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
12372 if mismatched {
12373 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
12374 std::fs::write(&path, &stream).expect("writing pinned stream");
12375 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
12376 }
12377 }
12378 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12379 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
12380 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
12381 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
12382 }
12383 matched += 1;
12384 }
12385 assert!(
12386 matched > 0,
12387 "{NAME}: every attempt refused; the gate never decoded a stream"
12388 );
12389 assert!(
12390 crate::decode::sb_rect_hits() > 0,
12391 "{NAME}: zero superblock-level HORZ/VERT blocks fired ({matched} matches, \
12392 {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run"
12393 );
12394 eprintln!(
12395 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
12396 {n_attempts}, sb_rect_hits={}",
12397 crate::decode::sb_rect_hits()
12398 );
12399 }
12400
12401 /// lane-sqchroma r1 gate: a plain SQUARE-partition intra key frame with
12402 /// REAL chroma (no `hue=s=0` guard) and aomenc's tx-size search left at
12403 /// its own DEFAULT (on) -- the combination the user's films hit
12404 /// everywhere and that no gate in this file covered: every older recipe
12405 /// pins `--enable-tx-size-search=0`, and the one that does not
12406 /// (`a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact`)
12407 /// desaturates its fixture. With the search on, RD gives a square block a
12408 /// luma transform smaller than its own side while chroma keeps the
12409 /// block's single `side/2` transform and its own `uv_mode`-derived
12410 /// `tx_type` -- the pair [`crate::decode::sq_chroma_tx_hits`] counts and
12411 /// this gate hard-asserts, so a stream whose split-transform blocks all
12412 /// landed on `DC_PRED` chroma cannot pass for free.
12413 ///
12414 /// Sweeps seeds 8-bit and finishes with one 10-bit stream of the same
12415 /// recipe (his films are `yuv420p10le`), whose sequence header's
12416 /// `bit_depth` is asserted before any pixel is compared. Only a missing
12417 /// tool SKIPs: a decode error that is not a named refusal, and every
12418 /// pixel mismatch, FAIL.
12419 #[test]
12420 fn a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact() {
12421 const NAME: &str =
12422 "a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact";
12423 let _gate_lock = lock_gate_counters();
12424 if !have_ffmpeg() {
12425 eprintln!("SKIP {NAME}: no ffmpeg");
12426 return;
12427 }
12428 if !have_aomenc() {
12429 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12430 return;
12431 }
12432 let (width, height) = (192usize, 128usize);
12433 // NOTE: no `--enable-tx-size-search=0` (the point of this gate), and
12434 // no chroma filter on the fixture (the other point). Square
12435 // partitions only: rect/AB/1to4 all off.
12436 let base_args: Vec<&str> = vec![
12437 "--codec=av1",
12438 "--passes=1",
12439 "--end-usage=q",
12440 "--cpu-used=0",
12441 "--threads=1",
12442 "--row-mt=0",
12443 "--sb-size=64",
12444 "--enable-rect-partitions=0",
12445 "--enable-ab-partitions=0",
12446 "--enable-1to4-partitions=0",
12447 "--min-partition-size=16",
12448 "--max-partition-size=32",
12449 "--enable-restoration=0",
12450 "--enable-palette=0",
12451 "--deltaq-mode=0",
12452 "--enable-intrabc=0",
12453 "--limit=1",
12454 ];
12455 let encode = |y4m: &[u8], extra: &[&str]| -> Vec<u8> {
12456 let mut args = base_args.clone();
12457 args.extend_from_slice(extra);
12458 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
12459 let mut child = Command::new(aomenc_path())
12460 .args(&args)
12461 .stdin(Stdio::piped())
12462 .stdout(Stdio::piped())
12463 .stderr(Stdio::piped())
12464 .spawn()
12465 .expect("aomenc failed to start");
12466 child
12467 .stdin
12468 .take()
12469 .expect("aomenc stdin")
12470 .write_all(y4m)
12471 .expect("writing y4m to aomenc");
12472 let out = child.wait_with_output().expect("aomenc failed to run");
12473 assert!(
12474 out.status.success(),
12475 "aomenc refused the fixture: {}",
12476 String::from_utf8_lossy(&out.stderr)
12477 );
12478 assert!(!out.stdout.is_empty(), "{NAME}: aomenc wrote an empty stream");
12479 out.stdout
12480 };
12481 let render = |source: &str, pix_fmt: &str| -> Vec<u8> {
12482 let y4m = Command::new("ffmpeg")
12483 .args([
12484 "-v", "error", "-f", "lavfi", "-i", source, "-t", "0.04", "-pix_fmt", pix_fmt,
12485 "-strict", "-1", "-f", "yuv4mpegpipe", "-",
12486 ])
12487 .stdin(Stdio::null())
12488 .stdout(Stdio::piped())
12489 .stderr(Stdio::piped())
12490 .output()
12491 .expect("ffmpeg failed to run");
12492 assert!(
12493 y4m.status.success(),
12494 "ffmpeg fixture: {}",
12495 String::from_utf8_lossy(&y4m.stderr)
12496 );
12497 y4m.stdout
12498 };
12499 let mut named_refusals = 0u32;
12500 let mut matched = 0u32;
12501 // Hits counted ONLY over attempts that decoded AND pixel-compared:
12502 // a stream that later refuses must not lend its firings to the
12503 // assertion below (class refusal-hides-a-defect).
12504 let mut firing = 0usize;
12505 let n_attempts: u32 = std::env::var("EC_SQCHROMA_GATE_ATTEMPTS")
12506 .ok()
12507 .and_then(|s| s.parse().ok())
12508 .unwrap_or(10);
12509 for attempt in 0..n_attempts {
12510 let seed = 42 + attempt;
12511 // Two quantisers per seed: the coarse one keeps most blocks on
12512 // one transform, the fine one is what actually splits them.
12513 let cq = if attempt % 2 == 0 { "--cq-level=20" } else { "--cq-level=40" };
12514 let y4m = render(
12515 &gradients_source(seed, width, height, "duration=0.04:rate=25"),
12516 "yuv420p",
12517 );
12518 let stream = encode(&y4m, &[cq]);
12519 let before = crate::decode::sq_chroma_tx_hits();
12520 let frames = match decode_stream(&stream) {
12521 Err(e) => {
12522 let msg = e.to_string();
12523 assert!(
12524 msg.contains("unsupported"),
12525 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
12526 );
12527 named_refusals += 1;
12528 continue;
12529 }
12530 Ok(frames) => frames,
12531 };
12532 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
12533 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
12534 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME} luma vs ffmpeg (seed {seed})");
12535 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME} U vs ffmpeg (seed {seed})");
12536 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME} V vs ffmpeg (seed {seed})");
12537 firing += crate::decode::sq_chroma_tx_hits() - before;
12538 matched += 1;
12539 }
12540 // Same recipe, 10-bit: his two films are both yuv420p10le, so the
12541 // square+tx-search+chroma claim is only worth anything if it holds
12542 // at their bit depth too.
12543 let y4m10 = render(
12544 &gradients_source(42, width, height, "duration=0.04:rate=25"),
12545 "yuv420p10le",
12546 );
12547 let stream10 = encode(&y4m10, &["--cq-level=20", "--input-bit-depth=10", "--bit-depth=10"]);
12548 let mut probe = Av1Parser::new();
12549 let mut pos = 0usize;
12550 while pos < stream10.len() && probe.sequence_header().is_none() {
12551 let obu = probe.parse_obu(&stream10[pos..]).unwrap();
12552 pos += obu.total_size;
12553 }
12554 assert_eq!(
12555 probe
12556 .sequence_header()
12557 .expect("stream has a sequence header OBU")
12558 .color_config
12559 .bit_depth,
12560 10,
12561 "{NAME}: aomenc did not actually write a 10-bit sequence header"
12562 );
12563 let before10 = crate::decode::sq_chroma_tx_hits();
12564 let frames10 = match decode_stream(&stream10) {
12565 Ok(frames) => frames,
12566 Err(e) => panic!("{NAME}: decode_stream refused the 10-bit stream: {e}"),
12567 };
12568 let ffmpeg10 = ffmpeg_decode_sequence_10bit(&stream10, width, height, 1);
12569 assert_eq!(frames10[0].y, ffmpeg10[0].y, "{NAME} luma vs ffmpeg (10-bit)");
12570 assert_eq!(frames10[0].u, ffmpeg10[0].u, "{NAME} U vs ffmpeg (10-bit)");
12571 assert_eq!(frames10[0].v, ffmpeg10[0].v, "{NAME} V vs ffmpeg (10-bit)");
12572 let firing10 = crate::decode::sq_chroma_tx_hits() - before10;
12573 firing += firing10;
12574 matched += 1;
12575 assert!(
12576 matched > 1,
12577 "{NAME}: every 8-bit attempt refused; the gate decoded only the 10-bit stream"
12578 );
12579 assert!(
12580 firing > 0,
12581 "{NAME}: zero square blocks split their luma transform under a non-DC chroma mode \
12582 ({matched} matches, {named_refusals} refusals) -- gate proved nothing this run"
12583 );
12584 eprintln!(
12585 "{NAME}: {matched} pixel-exact decodes ({named_refusals} named refusals out of \
12586 {n_attempts} 8-bit attempts), split-tx-with-chroma blocks: {firing} \
12587 (10-bit stream: {firing10})"
12588 );
12589 }
12590
12591 /// lane-rectsplit r1 gate (a): a real `aomenc` key frame whose 32x32
12592 /// quadrants split HORZ/VERT into true 32x16/16x32 strips, with the
12593 /// tx-size search left at aomenc's own default (ON) -- every sibling
12594 /// recipe in this file pins `--enable-tx-size-search=0`, which is exactly
12595 /// why the split-transform strip was never exercised. RD is then free to
12596 /// give a strip a transform smaller than its own size, the case
12597 /// [`crate::decode::decode_block_rect`] refused by name ("a HORZ/VERT
12598 /// intra strip with a split transform (per-unit rect prediction is not
12599 /// ported)") until this round ported the per-transform-unit predict-and-
12600 /// reconstruct loop. Hard-asserts a nonzero `rect_split_tx_hits()` delta:
12601 /// without it a stream that resolved every `tx_depth` to 0 would
12602 /// pixel-match by construction and prove nothing. A decode error that is
12603 /// not a named refusal, and any pixel mismatch, FAIL -- only a missing
12604 /// tool skips.
12605 #[test]
12606 fn a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact() {
12607 const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact";
12608 let _gate_lock = lock_gate_counters();
12609 if !have_ffmpeg() {
12610 eprintln!("SKIP {NAME}: no ffmpeg");
12611 return;
12612 }
12613 if !have_aomenc() {
12614 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12615 return;
12616 }
12617 let (width, height) = (192usize, 128usize);
12618 let before = crate::decode::rect_split_tx_hits();
12619 let mut named_refusals = 0u32;
12620 let mut matched = 0u32;
12621 // lane-rectsplit r2 (verifier finding): the feature counter is
12622 // sampled PER ATTEMPT and folded in only after that attempt was
12623 // decoded AND pixel-compared. One delta across the whole sweep
12624 // counted strips decoded by attempts that went on to hit a named
12625 // refusal, so the gate could pass with every COMPARED stream
12626 // containing none of the feature at all.
12627 let mut compared_hits = 0usize;
12628 let mut split_so_far = 0usize;
12629 // Bounded sweep: see this gate's own doc for the seed-77 residue and
12630 // why extending it is a diagnosis knob, not a pass/fail one.
12631 let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
12632 .ok()
12633 .and_then(|s| s.parse().ok())
12634 .unwrap_or(20);
12635 for attempt in 0..n_attempts {
12636 let seed = 42 + attempt;
12637 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
12638 let y4m = Command::new("ffmpeg")
12639 .args([
12640 "-v", "error", "-f", "lavfi", "-i", &source,
12641 // REAL chroma (lane-sqchroma r1 dropped the `hue=s=0`
12642 // guard this recipe carried): the "PRE-EXISTING square-path
12643 // chroma defect" that guard named does not reproduce at
12644 // HEAD -- seeds 42..61, cq 12/20/32/45, plus testsrc2 and
12645 // mandelbrot, all decode pixel-exact with
12646 // `--enable-rect-partitions=0`, and this gate is green with
12647 // the filter gone. Its own gate is
12648 // `a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact`.
12649 "-pix_fmt", "yuv420p", "-f",
12650 "yuv4mpegpipe", "-",
12651 ])
12652 .stdin(Stdio::null())
12653 .stdout(Stdio::piped())
12654 .stderr(Stdio::piped())
12655 .output()
12656 .expect("ffmpeg failed to run");
12657 assert!(
12658 y4m.status.success(),
12659 "ffmpeg fixture: {}",
12660 String::from_utf8_lossy(&y4m.stderr)
12661 );
12662 // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's
12663 // own default (search ON) is the entire point of this gate.
12664 let args: Vec<&str> = vec![
12665 "--codec=av1",
12666 "--passes=1",
12667 "--end-usage=q",
12668 "--cq-level=45",
12669 "--cpu-used=0",
12670 "--threads=1",
12671 "--row-mt=0",
12672 "--sb-size=64",
12673 "--enable-rect-partitions=1",
12674 "--enable-ab-partitions=0",
12675 "--enable-1to4-partitions=0",
12676 "--min-partition-size=16",
12677 "--max-partition-size=32",
12678 "--enable-restoration=0",
12679 "--enable-palette=0",
12680 "--deltaq-mode=0",
12681 "--enable-filter-intra=0",
12682 "--enable-cfl-intra=0",
12683 "--enable-intrabc=0",
12684 "--obu",
12685 "-o",
12686 "-",
12687 "-",
12688 ];
12689 let mut child = Command::new(aomenc_path())
12690 .args(&args)
12691 .stdin(Stdio::piped())
12692 .stdout(Stdio::piped())
12693 .stderr(Stdio::piped())
12694 .spawn()
12695 .expect("aomenc failed to start");
12696 child
12697 .stdin
12698 .take()
12699 .expect("aomenc stdin")
12700 .write_all(&y4m.stdout)
12701 .expect("writing y4m to aomenc");
12702 let out = child.wait_with_output().expect("aomenc failed to run");
12703 assert!(
12704 out.status.success(),
12705 "aomenc refused the fixture: {}",
12706 String::from_utf8_lossy(&out.stderr)
12707 );
12708 let stream = out.stdout;
12709 assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})");
12710 let attempt_before = crate::decode::rect_split_tx_hits();
12711 let frames = match decode_stream(&stream) {
12712 Err(e) => {
12713 let msg = e.to_string();
12714 assert!(
12715 msg.contains("unsupported"),
12716 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
12717 );
12718 named_refusals += 1;
12719 continue;
12720 }
12721 Ok(frames) => frames,
12722 };
12723 let after = crate::decode::rect_split_tx_hits();
12724 eprintln!(
12725 "{NAME}: seed {seed} decoded, split-tx strips this stream: {}",
12726 after - before - split_so_far
12727 );
12728 split_so_far = after - before;
12729 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
12730 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
12731 if let Some(i) = frames[0]
12732 .y
12733 .iter()
12734 .zip(&ffmpeg_frames[0].y)
12735 .position(|(a, b)| a != b)
12736 {
12737 let diffs: Vec<usize> = frames[0]
12738 .y
12739 .iter()
12740 .zip(&ffmpeg_frames[0].y)
12741 .enumerate()
12742 .filter(|(_, (a, b))| a != b)
12743 .map(|(j, _)| j)
12744 .collect();
12745 let (x0, x1) = (
12746 diffs.iter().map(|j| j % width).min().unwrap(),
12747 diffs.iter().map(|j| j % width).max().unwrap(),
12748 );
12749 let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width);
12750 eprintln!(
12751 "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \
12752 -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}",
12753 i % width,
12754 i / width,
12755 frames[0].y[i],
12756 ffmpeg_frames[0].y[i],
12757 diffs.len(),
12758 );
12759 }
12760 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
12761 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
12762 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
12763 compared_hits += crate::decode::rect_split_tx_hits() - attempt_before;
12764 matched += 1;
12765 }
12766 let split_hits = compared_hits;
12767 assert!(
12768 matched > 0,
12769 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
12770 );
12771 assert!(
12772 split_hits > 0,
12773 "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \
12774 matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \
12775 this run"
12776 );
12777 eprintln!(
12778 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
12779 rect_split_tx_hits delta={split_hits} out of {n_attempts} attempts"
12780 );
12781 }
12782
12783 /// lane-rectsplit r1 gate (c): gate (a)'s recipe with
12784 /// `--enable-filter-intra=1` (every sibling gate here pins it to 0), so
12785 /// aomenc's RD is free to pick `use_filter_intra` on a 32x16/16x32 strip
12786 /// -- the case [`crate::decode::decode_block_rect`] refused by name
12787 /// ("filter intra on a HORZ/VERT strip (this decoder predicts
12788 /// square-only)") until this round gave `predict_filter_intra` its own
12789 /// `bw`x`bh`. Hard-asserts a nonzero `filter_intra_rect_hits()` delta:
12790 /// a stream where RD never picked filter intra on a strip would
12791 /// pixel-match by construction and prove nothing.
12792 #[test]
12793 fn a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact() {
12794 const NAME: &str =
12795 "a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact";
12796 let _gate_lock = lock_gate_counters();
12797 if !have_ffmpeg() {
12798 eprintln!("SKIP {NAME}: no ffmpeg");
12799 return;
12800 }
12801 if !have_aomenc() {
12802 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12803 return;
12804 }
12805 let (width, height) = (192usize, 128usize);
12806 let rect_before = crate::decode::rect_partition_hits();
12807 let fi_square_before = crate::decode::filter_intra_hits();
12808 let mut named_refusals = 0u32;
12809 let mut matched = 0u32;
12810 // lane-rectsplit r2 (verifier finding): the feature counter is
12811 // sampled PER ATTEMPT and folded in only after that attempt was
12812 // decoded AND pixel-compared. One delta across the whole sweep
12813 // counted strips decoded by attempts that went on to hit a named
12814 // refusal, so the gate could pass with every COMPARED stream
12815 // containing none of the feature at all.
12816 let mut compared_hits = 0usize;
12817 let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
12818 .ok()
12819 .and_then(|s| s.parse().ok())
12820 .unwrap_or(40);
12821 for attempt in 0..n_attempts {
12822 let seed = 42 + attempt;
12823 // Diagnosis knob: which content makes RD pick a HORZ/VERT strip
12824 // AND filter intra on it is a search (see this round's report).
12825 let source = match std::env::var("EC_RECTSPLIT_SRC").unwrap_or_default().as_str() {
12826 "bars" => format!("smptebars=size={width}x{height}:duration=0.04:rate=25"),
12827 "src2" => format!("testsrc2=size={width}x{height}:duration=0.04:rate=25"),
12828 _ => gradients_source(seed, width, height, "duration=0.04:rate=25"),
12829 };
12830 let y4m = Command::new("ffmpeg")
12831 .args([
12832 "-v", "error", "-f", "lavfi", "-i", &source,
12833 // Real chroma: the `hue=s=0` guard gate (a) carried is
12834 // gone (lane-sqchroma r1 -- the square-path chroma defect
12835 // it named does not reproduce at HEAD).
12836 "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-",
12837 ])
12838 .stdin(Stdio::null())
12839 .stdout(Stdio::piped())
12840 .stderr(Stdio::piped())
12841 .output()
12842 .expect("ffmpeg failed to run");
12843 assert!(
12844 y4m.status.success(),
12845 "ffmpeg fixture: {}",
12846 String::from_utf8_lossy(&y4m.stderr)
12847 );
12848 // Diagnosis knob only (default is the gate's pinned recipe):
12849 // which `--cq-level` makes aomenc's RD reach for filter intra on
12850 // a strip is a search, and the sweep that found this one is in
12851 // lanes/rectsplit-r1.report.md.
12852 let cq = format!(
12853 "--cq-level={}",
12854 // Pinned by the sweep in lanes/rectsplit-r1.report.md: at
12855 // cq 45 aomenc's RD picks a strip 18 times in 100 seeds and
12856 // filter intra on none of them; at cq 25 strips are common
12857 // (130/100 seeds) and filter intra lands on one every ~13
12858 // seeds.
12859 std::env::var("EC_RECTSPLIT_CQ").unwrap_or_else(|_| "25".into())
12860 );
12861 let args: Vec<&str> = vec![
12862 "--codec=av1",
12863 "--passes=1",
12864 "--end-usage=q",
12865 &cq,
12866 "--cpu-used=0",
12867 "--threads=1",
12868 "--row-mt=0",
12869 "--sb-size=64",
12870 "--enable-rect-partitions=1",
12871 "--enable-ab-partitions=0",
12872 "--enable-1to4-partitions=0",
12873 "--min-partition-size=16",
12874 "--max-partition-size=32",
12875 "--enable-restoration=0",
12876 "--enable-palette=0",
12877 "--deltaq-mode=0",
12878 // The point of this gate.
12879 "--enable-filter-intra=1",
12880 // NOTE (lane-rectsplit r2, verifier finding): every intra
12881 // mode stays ON here. The square filter-intra gate reaches
12882 // for filter intra by switching the directional/smooth/paeth
12883 // competitors off, and this gate CANNOT: with them off
12884 // aomenc stops picking rect partitions at all (rect
12885 // strips 0/20 seeds, r1's table). What fires filter intra on
12886 // a strip here is the quantiser (`--cq-level=25`), not the
12887 // mode set -- `EC_RECTSPLIT_OFF` below is the diagnosis knob
12888 // that re-runs the subset search.
12889 "--enable-cfl-intra=0",
12890 "--enable-intrabc=0",
12891 "--obu",
12892 "-o",
12893 "-",
12894 "-",
12895 ];
12896 // Diagnosis knob (default: every intra mode on): turning the
12897 // directional/smooth/paeth competitors off is how the square
12898 // filter-intra gate makes RD reach for filter intra, but with all
12899 // four off aomenc stops picking rect partitions here entirely
12900 // (rect strips=0, filter-intra blocks=28, measured this round),
12901 // so the firing recipe is a search over subsets.
12902 let mut args = args;
12903 let off = std::env::var("EC_RECTSPLIT_OFF").unwrap_or_default();
12904 for tool in off.split(',').filter(|t| !t.is_empty()) {
12905 args.push(match tool {
12906 "smooth" => "--enable-smooth-intra=0",
12907 "paeth" => "--enable-paeth-intra=0",
12908 "dir" => "--enable-directional-intra=0",
12909 "angle" => "--enable-angle-delta=0",
12910 other => panic!("unknown EC_RECTSPLIT_OFF entry {other}"),
12911 });
12912 }
12913 let mut child = Command::new(aomenc_path())
12914 .args(&args)
12915 .stdin(Stdio::piped())
12916 .stdout(Stdio::piped())
12917 .stderr(Stdio::piped())
12918 .spawn()
12919 .expect("aomenc failed to start");
12920 child
12921 .stdin
12922 .take()
12923 .expect("aomenc stdin")
12924 .write_all(&y4m.stdout)
12925 .expect("writing y4m to aomenc");
12926 let out = child.wait_with_output().expect("aomenc failed to run");
12927 assert!(
12928 out.status.success(),
12929 "aomenc refused the fixture: {}",
12930 String::from_utf8_lossy(&out.stderr)
12931 );
12932 let stream = out.stdout;
12933 assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})");
12934 let attempt_before = crate::decode::filter_intra_rect_hits();
12935 let frames = match decode_stream(&stream) {
12936 Err(e) => {
12937 let msg = e.to_string();
12938 assert!(
12939 msg.contains("unsupported"),
12940 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
12941 );
12942 named_refusals += 1;
12943 continue;
12944 }
12945 Ok(frames) => frames,
12946 };
12947 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
12948 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
12949 if let Some(i) = frames[0]
12950 .y
12951 .iter()
12952 .zip(&ffmpeg_frames[0].y)
12953 .position(|(a, b)| a != b)
12954 {
12955 let diffs: Vec<usize> = frames[0]
12956 .y
12957 .iter()
12958 .zip(&ffmpeg_frames[0].y)
12959 .enumerate()
12960 .filter(|(_, (a, b))| a != b)
12961 .map(|(j, _)| j)
12962 .collect();
12963 let (x0, x1) = (
12964 diffs.iter().map(|j| j % width).min().unwrap(),
12965 diffs.iter().map(|j| j % width).max().unwrap(),
12966 );
12967 let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width);
12968 eprintln!(
12969 "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \
12970 -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}",
12971 i % width,
12972 i / width,
12973 frames[0].y[i],
12974 ffmpeg_frames[0].y[i],
12975 diffs.len(),
12976 );
12977 }
12978 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
12979 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
12980 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
12981 compared_hits += crate::decode::filter_intra_rect_hits() - attempt_before;
12982 matched += 1;
12983 }
12984 let fi_hits = compared_hits;
12985 eprintln!(
12986 "{NAME}: rect strips this run={}, filter-intra blocks (any shape)={}",
12987 crate::decode::rect_partition_hits() - rect_before,
12988 crate::decode::filter_intra_hits() - fi_square_before
12989 );
12990 assert!(
12991 matched > 0,
12992 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
12993 );
12994 assert!(
12995 fi_hits > 0,
12996 "{NAME}: no HORZ/VERT strip used filter intra ({matched} pixel-exact matches, \
12997 {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run"
12998 );
12999 eprintln!(
13000 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
13001 filter_intra_rect_hits delta={fi_hits} out of {n_attempts} attempts"
13002 );
13003 }
13004
13005 /// lane-rectsplit r1 gate (b): [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]'s
13006 /// own recipe (`--sb-size=64`, `--min/max-partition-size=32/64`, so every
13007 /// SB-level decision is genuinely NONE/SPLIT/HORZ/VERT) with its
13008 /// `--enable-tx-size-search=0` DROPPED: the 64x32/32x64 strips may then
13009 /// carry a split transform, which [`crate::decode::decode_block_rect64`]
13010 /// refused by name ("a superblock-level HORZ/VERT strip with a split
13011 /// transform") until lane-rectsplit r2 lifted it.
13012 ///
13013 /// The hard assert is on [`crate::decode::rect_split_sb_interior_tu_hits`],
13014 /// NOT the shared `rect_split_tx_hits()` gate (a) uses: that counter also
13015 /// counts 32x32-level and depth-1 strips, whose units are all in the
13016 /// first transform-unit row/column. Only a superblock-level strip split
13017 /// past depth 1 has an INTERIOR unit (`row_off > 0 && col_off > 0`),
13018 /// which is the per-unit availability rule this port exists for, and no
13019 /// gate fired one before this round.
13020 ///
13021 /// This gate was `#[ignore]`d RED through r1 (seed 50 luma (171,56)).
13022 /// Root cause, r2: not availability at all -- `av1_nz_map_ctx_offset` is
13023 /// packed COLUMN-major, so [`crate::decode::base_ctx`] read the
13024 /// `TX_32X64`/`TX_64X32` offset tables transposed and desynced the first
13025 /// SB-level strip whose luma corner held a coefficient below row 1 (see
13026 /// that function's comment). The strip's own per-unit prediction was
13027 /// already exact.
13028 #[ignore = "lane-rectsplit r3: RED at seed 50; the nz_map transposition r2 blamed turns the merged SB HORZ/VERT partition gate RED at seed 43, cause still open"]
13029 #[test]
13030 fn a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact() {
13031 const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact";
13032 let _gate_lock = lock_gate_counters();
13033 if !have_ffmpeg() {
13034 eprintln!("SKIP {NAME}: no ffmpeg");
13035 return;
13036 }
13037 if !have_aomenc() {
13038 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13039 return;
13040 }
13041 let (width, height) = (192usize, 128usize);
13042 let before = crate::decode::rect_split_tx_hits();
13043 let mut named_refusals = 0u32;
13044 let mut matched = 0u32;
13045 // lane-rectsplit r2 (verifier finding): the feature counter is
13046 // sampled PER ATTEMPT and folded in only after that attempt was
13047 // decoded AND pixel-compared. One delta across the whole sweep
13048 // counted strips decoded by attempts that went on to hit a named
13049 // refusal, so the gate could pass with every COMPARED stream
13050 // containing none of the feature at all.
13051 let mut compared_hits = 0usize;
13052 let mut split_so_far = 0usize;
13053 // Bounded sweep: see this gate's own doc for the seed-77 residue and
13054 // why extending it is a diagnosis knob, not a pass/fail one.
13055 let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
13056 .ok()
13057 .and_then(|s| s.parse().ok())
13058 .unwrap_or(20);
13059 for attempt in 0..n_attempts {
13060 let seed = 42 + attempt;
13061 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
13062 let y4m = Command::new("ffmpeg")
13063 .args([
13064 "-v", "error", "-f", "lavfi", "-i", &source,
13065 // REAL chroma (lane-sqchroma r1 dropped the `hue=s=0`
13066 // guard this recipe carried): the "PRE-EXISTING square-path
13067 // chroma defect" that guard named does not reproduce at
13068 // HEAD -- seeds 42..61, cq 12/20/32/45, plus testsrc2 and
13069 // mandelbrot, all decode pixel-exact with
13070 // `--enable-rect-partitions=0`, and this gate is green with
13071 // the filter gone. Its own gate is
13072 // `a_real_aomenc_intra_stream_with_tx_size_search_and_chroma_decodes_pixel_exact`.
13073 "-pix_fmt", "yuv420p", "-f",
13074 "yuv4mpegpipe", "-",
13075 ])
13076 .stdin(Stdio::null())
13077 .stdout(Stdio::piped())
13078 .stderr(Stdio::piped())
13079 .output()
13080 .expect("ffmpeg failed to run");
13081 assert!(
13082 y4m.status.success(),
13083 "ffmpeg fixture: {}",
13084 String::from_utf8_lossy(&y4m.stderr)
13085 );
13086 // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's
13087 // own default (search ON) is the entire point of this gate.
13088 let args: Vec<&str> = vec![
13089 "--codec=av1",
13090 "--passes=1",
13091 "--end-usage=q",
13092 "--cq-level=45",
13093 "--cpu-used=0",
13094 "--threads=1",
13095 "--row-mt=0",
13096 "--sb-size=64",
13097 "--enable-rect-partitions=1",
13098 "--enable-ab-partitions=0",
13099 "--enable-1to4-partitions=0",
13100 "--min-partition-size=32",
13101 "--max-partition-size=64",
13102 "--enable-restoration=0",
13103 "--enable-palette=0",
13104 "--deltaq-mode=0",
13105 "--enable-filter-intra=0",
13106 "--enable-cfl-intra=0",
13107 "--enable-intrabc=0",
13108 "--obu",
13109 "-o",
13110 "-",
13111 "-",
13112 ];
13113 let mut child = Command::new(aomenc_path())
13114 .args(&args)
13115 .stdin(Stdio::piped())
13116 .stdout(Stdio::piped())
13117 .stderr(Stdio::piped())
13118 .spawn()
13119 .expect("aomenc failed to start");
13120 child
13121 .stdin
13122 .take()
13123 .expect("aomenc stdin")
13124 .write_all(&y4m.stdout)
13125 .expect("writing y4m to aomenc");
13126 let out = child.wait_with_output().expect("aomenc failed to run");
13127 assert!(
13128 out.status.success(),
13129 "aomenc refused the fixture: {}",
13130 String::from_utf8_lossy(&out.stderr)
13131 );
13132 let stream = out.stdout;
13133 assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})");
13134 let attempt_before = crate::decode::rect_split_sb_interior_tu_hits();
13135 let frames = match decode_stream(&stream) {
13136 Err(e) => {
13137 let msg = e.to_string();
13138 assert!(
13139 msg.contains("unsupported"),
13140 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
13141 );
13142 named_refusals += 1;
13143 continue;
13144 }
13145 Ok(frames) => frames,
13146 };
13147 let after = crate::decode::rect_split_tx_hits();
13148 eprintln!(
13149 "{NAME}: seed {seed} decoded, split-tx strips this stream: {}",
13150 after - before - split_so_far
13151 );
13152 split_so_far = after - before;
13153 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
13154 assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
13155 if let Some(i) = frames[0]
13156 .y
13157 .iter()
13158 .zip(&ffmpeg_frames[0].y)
13159 .position(|(a, b)| a != b)
13160 {
13161 let diffs: Vec<usize> = frames[0]
13162 .y
13163 .iter()
13164 .zip(&ffmpeg_frames[0].y)
13165 .enumerate()
13166 .filter(|(_, (a, b))| a != b)
13167 .map(|(j, _)| j)
13168 .collect();
13169 let (x0, x1) = (
13170 diffs.iter().map(|j| j % width).min().unwrap(),
13171 diffs.iter().map(|j| j % width).max().unwrap(),
13172 );
13173 let (y0, y1) = (diffs[0] / width, diffs[diffs.len() - 1] / width);
13174 eprintln!(
13175 "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={} \
13176 -- {} mismatching samples, bbox x {x0}..={x1} y {y0}..={y1}",
13177 i % width,
13178 i / width,
13179 frames[0].y[i],
13180 ffmpeg_frames[0].y[i],
13181 diffs.len(),
13182 );
13183 }
13184 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
13185 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
13186 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
13187 compared_hits += crate::decode::rect_split_sb_interior_tu_hits() - attempt_before;
13188 matched += 1;
13189 }
13190 let split_hits = compared_hits;
13191 assert!(
13192 matched > 0,
13193 "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
13194 );
13195 assert!(
13196 split_hits > 0,
13197 "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \
13198 matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \
13199 this run"
13200 );
13201 eprintln!(
13202 "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
13203 rect_split_sb_interior_tu_hits delta={split_hits} (over COMPARED streams only) \
13204 out of {n_attempts} attempts"
13205 );
13206 }
13207
13208 /// lane-part32 r4: a real `aomenc` stream whose superblock-level
13209 /// partition decision is one of the four AB arms (`PARTITION_HORZ_A`/
13210 /// `_B`/`VERT_A`/`_B` at 64x64: two 32x32 squares plus one 64x32/32x64
13211 /// strip) must decode pixel-exact. Same recipe as the HORZ/VERT sibling
13212 /// above with `--enable-ab-partitions=1`; `sb_ab_hits() > 0` is a HARD
13213 /// assert, so a run where aomenc's RD never picked an AB arm fails
13214 /// rather than passing vacuously.
13215 #[test]
13216 fn a_real_aomenc_stream_with_a_superblock_level_ab_partition_decodes_pixel_exact() {
13217 const NAME: &str =
13218 "a_real_aomenc_stream_with_a_superblock_level_ab_partition_decodes_pixel_exact";
13219 let _gate_lock = lock_gate_counters();
13220 if !have_ffmpeg() {
13221 eprintln!("SKIP {NAME}: no ffmpeg");
13222 return;
13223 }
13224 if !have_aomenc() {
13225 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13226 return;
13227 }
13228 let (width, height, frame_count) = (192usize, 128usize, 1usize);
13229 let mut named_refusals = 0u32;
13230 let mut matched = 0u32;
13231 let n_attempts: u32 = std::env::var("EC_SBAB_GATE_ATTEMPTS")
13232 .ok()
13233 .and_then(|s| s.parse().ok())
13234 .unwrap_or(40);
13235 for attempt in 0..n_attempts {
13236 let seed = 42 + attempt;
13237 let duration = frame_count as f64 / 25.0;
13238 let source =
13239 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
13240 let y4m = Command::new("ffmpeg")
13241 .args([
13242 "-v",
13243 "error",
13244 "-f",
13245 "lavfi",
13246 "-i",
13247 &source,
13248 "-pix_fmt",
13249 "yuv420p",
13250 "-f",
13251 "yuv4mpegpipe",
13252 "-",
13253 ])
13254 .stdin(Stdio::null())
13255 .stdout(Stdio::piped())
13256 .stderr(Stdio::piped())
13257 .output()
13258 .expect("ffmpeg failed to run");
13259 assert!(
13260 y4m.status.success(),
13261 "ffmpeg fixture: {}",
13262 String::from_utf8_lossy(&y4m.stderr)
13263 );
13264 let args: Vec<&str> = vec![
13265 "--codec=av1",
13266 "--passes=1",
13267 "--end-usage=q",
13268 "--cq-level=45",
13269 "--cpu-used=0",
13270 "--threads=1",
13271 "--row-mt=0",
13272 "--sb-size=64",
13273 "--enable-rect-partitions=1",
13274 "--enable-ab-partitions=1",
13275 "--enable-1to4-partitions=0",
13276 "--min-partition-size=32",
13277 "--max-partition-size=64",
13278 "--enable-restoration=0",
13279 "--enable-palette=0",
13280 "--deltaq-mode=0",
13281 "--enable-filter-intra=0",
13282 "--enable-cfl-intra=0",
13283 "--enable-intrabc=0",
13284 "--enable-tx-size-search=0",
13285 "--obu",
13286 "-o",
13287 "-",
13288 "-",
13289 ];
13290 let mut child = Command::new(aomenc_path())
13291 .args(&args)
13292 .stdin(Stdio::piped())
13293 .stdout(Stdio::piped())
13294 .stderr(Stdio::piped())
13295 .spawn()
13296 .expect("aomenc failed to start");
13297 child
13298 .stdin
13299 .take()
13300 .expect("aomenc stdin")
13301 .write_all(&y4m.stdout)
13302 .expect("writing y4m to aomenc");
13303 let out = child.wait_with_output().expect("aomenc failed to run");
13304 assert!(
13305 out.status.success(),
13306 "aomenc refused the fixture: {}",
13307 String::from_utf8_lossy(&out.stderr)
13308 );
13309 let stream = out.stdout;
13310 let frames = match decode_stream(&stream) {
13311 Err(e) => {
13312 let msg = e.to_string();
13313 assert!(
13314 msg.contains("unsupported"),
13315 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
13316 );
13317 // r5: the four SB-level AB arms (`partition_w64` 4-7)
13318 // decode since this round, so the only partition refusal
13319 // left at 64x64 is the 1:4 pair (values 8/9, four
13320 // 64x16/16x64 strips, whose luma TX_64X16 this decoder
13321 // has no transform for); the refusals this loop actually
13322 // counts on these fixtures are the pre-existing
13323 // screen-content-palette strip one. Every refusal is
13324 // named, so a genuine decode failure still fails the
13325 // assert above rather than skipping.
13326 named_refusals += 1;
13327 eprintln!("seed {seed} refusal: {msg}");
13328 continue;
13329 }
13330 Ok(frames) => frames,
13331 };
13332 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
13333 assert_eq!(frames.len(), frame_count);
13334 let mismatched = frames
13335 .iter()
13336 .zip(&ffmpeg_frames)
13337 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
13338 if mismatched {
13339 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
13340 std::fs::write(&path, &stream).expect("writing pinned stream");
13341 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
13342 }
13343 }
13344 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13345 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
13346 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
13347 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
13348 }
13349 matched += 1;
13350 }
13351 assert!(
13352 matched > 0,
13353 "{NAME}: every attempt refused; the gate never decoded a stream"
13354 );
13355 let arms = crate::decode::sb_ab_hits_by_arm();
13356 for (i, name) in ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"].iter().enumerate() {
13357 assert!(
13358 arms[i] > 0,
13359 "{NAME}: zero superblock-level PARTITION_{name} blocks fired (arms={arms:?}, \
13360 {matched} matches, {named_refusals} refusals out of {n_attempts}) -- that arm \
13361 proved nothing this run"
13362 );
13363 }
13364 eprintln!(
13365 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
13366 {n_attempts}, sb_ab_hits={} arms(HORZ_A,HORZ_B,VERT_A,VERT_B)={arms:?}",
13367 crate::decode::sb_ab_hits()
13368 );
13369 }
13370
13371 /// lane-part32 r2: prints the exact mismatch geometry (block coords,
13372 /// got/want pixels) of the pinned seed-42 stream captured off
13373 /// `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
13374 /// via `EC_AV1_GATE_DUMP`. Debug-only, `#[ignore]`d.
13375 #[test]
13376 #[ignore = "debug harness, run manually with EC_AV1_GATE_DUMP_PIN"]
13377 fn debug_part32_r2_sbpart_pin_mismatch_geometry() {
13378 let path = std::env::var("EC_AV1_GATE_DUMP_PIN").expect("set EC_AV1_GATE_DUMP_PIN");
13379 let stream = std::fs::read(&path).expect("read pinned stream");
13380 let frames = decode_stream(&stream).expect("pinned stream must decode");
13381 if let Ok(dump) = std::env::var("EC_DEBUG_DUMP_Y") {
13382 let bytes: Vec<u8> = frames[0].y.iter().map(|&v| v as u8).collect();
13383 std::fs::write(&dump, bytes).expect("write y dump");
13384 }
13385 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 192, 128, 1);
13386 let got = &frames[0];
13387 let want = &ffmpeg_frames[0];
13388 let width = 192usize;
13389 let mut n = 0;
13390 let (mut min_x, mut max_x, mut min_y, mut max_y) = (width, 0, 128, 0);
13391 for y in 0..128usize {
13392 for x in 0..width {
13393 let idx = y * width + x;
13394 if got.y[idx] != want.y[idx] {
13395 n += 1;
13396 min_x = min_x.min(x);
13397 max_x = max_x.max(x);
13398 min_y = min_y.min(y);
13399 max_y = max_y.max(y);
13400 }
13401 }
13402 }
13403 eprintln!(
13404 "total luma mismatches: {n} bbox x=[{min_x},{max_x}] y=[{min_y},{max_y}] frame=192x128"
13405 );
13406 for y in 0..128usize {
13407 let mut row_first = None;
13408 let mut row_count = 0;
13409 for x in 0..width {
13410 let idx = y * width + x;
13411 if got.y[idx] != want.y[idx] {
13412 if row_first.is_none() {
13413 row_first = Some(x);
13414 }
13415 row_count += 1;
13416 }
13417 }
13418 if let Some(fx) = row_first {
13419 eprintln!("row {y}: first mismatch x={fx} count={row_count}");
13420 }
13421 }
13422 }
13423
13424 /// lane-rect64q r1: same recipe as
13425 /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]
13426 /// minus `--deltaq-mode=0` -- real aomenc's non-realtime default is
13427 /// `DELTA_Q_OBJECTIVE` (`av1_cx_iface.c:271`), so dropping that one flag
13428 /// is enough to make `delta_q_present=1` the norm and drive
13429 /// [`crate::decode::decode_block_rect64`]'s running `CURRENT_Q_IDX` away
13430 /// from the frame-constant `base_q_idx` inside a real rect64 SB --
13431 /// exactly the bug this round's dequant fix targets. Hard-asserts
13432 /// `rect64_qidx_drift_hits() > 0`: without that, this gate could pass
13433 /// vacuously the same way the `--deltaq-mode=0` sibling always did.
13434 ///
13435 /// lane-rect64q r1: measured, does NOT fire -- 15/40 attempts matched
13436 /// but `rect64_qidx_drift_hits()` stayed 0 every time. Real aomenc's RD
13437 /// never chose a nonzero delta-q on this tiny synthetic gradients frame
13438 /// even with `deltaq-mode` left at its default; `#[ignore]`d rather than
13439 /// deleted so the recipe and the negative result both survive for the
13440 /// next attempt (see `lanes/rect64q-r1.report.md`).
13441 #[test]
13442 #[ignore = "drift never observed this round -- see lanes/rect64q-r1.report.md"]
13443 fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact()
13444 {
13445 const NAME: &str =
13446 "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact";
13447 let _gate_lock = lock_gate_counters();
13448 if !have_ffmpeg() {
13449 eprintln!("SKIP {NAME}: no ffmpeg");
13450 return;
13451 }
13452 if !have_aomenc() {
13453 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13454 return;
13455 }
13456 let (width, height, frame_count) = (192usize, 128usize, 1usize);
13457 let mut named_refusals = 0u32;
13458 let mut matched = 0u32;
13459 let n_attempts: u32 = std::env::var("EC_SBPART_DQ_GATE_ATTEMPTS")
13460 .ok()
13461 .and_then(|s| s.parse().ok())
13462 .unwrap_or(40);
13463 for attempt in 0..n_attempts {
13464 let seed = 42 + attempt;
13465 let duration = frame_count as f64 / 25.0;
13466 let source =
13467 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
13468 let y4m = Command::new("ffmpeg")
13469 .args([
13470 "-v",
13471 "error",
13472 "-f",
13473 "lavfi",
13474 "-i",
13475 &source,
13476 "-pix_fmt",
13477 "yuv420p",
13478 "-f",
13479 "yuv4mpegpipe",
13480 "-",
13481 ])
13482 .stdin(Stdio::null())
13483 .stdout(Stdio::piped())
13484 .stderr(Stdio::piped())
13485 .output()
13486 .expect("ffmpeg failed to run");
13487 assert!(
13488 y4m.status.success(),
13489 "ffmpeg fixture: {}",
13490 String::from_utf8_lossy(&y4m.stderr)
13491 );
13492 let args: Vec<&str> = vec![
13493 "--codec=av1",
13494 "--passes=1",
13495 "--end-usage=q",
13496 "--cq-level=45",
13497 "--cpu-used=0",
13498 "--threads=1",
13499 "--row-mt=0",
13500 "--sb-size=64",
13501 "--enable-rect-partitions=1",
13502 "--enable-ab-partitions=0",
13503 "--enable-1to4-partitions=0",
13504 "--min-partition-size=32",
13505 "--max-partition-size=64",
13506 "--enable-restoration=0",
13507 "--enable-palette=0",
13508 "--enable-filter-intra=0",
13509 "--enable-cfl-intra=0",
13510 "--enable-intrabc=0",
13511 "--enable-tx-size-search=0",
13512 "--obu",
13513 "-o",
13514 "-",
13515 "-",
13516 ];
13517 let mut child = Command::new(aomenc_path())
13518 .args(&args)
13519 .stdin(Stdio::piped())
13520 .stdout(Stdio::piped())
13521 .stderr(Stdio::piped())
13522 .spawn()
13523 .expect("aomenc failed to start");
13524 child
13525 .stdin
13526 .take()
13527 .expect("aomenc stdin")
13528 .write_all(&y4m.stdout)
13529 .expect("writing y4m to aomenc");
13530 let out = child.wait_with_output().expect("aomenc failed to run");
13531 assert!(
13532 out.status.success(),
13533 "aomenc refused the fixture: {}",
13534 String::from_utf8_lossy(&out.stderr)
13535 );
13536 let stream = out.stdout;
13537 let frames = match decode_stream(&stream) {
13538 Err(e) => {
13539 let msg = e.to_string();
13540 assert!(
13541 msg.contains("unsupported"),
13542 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
13543 );
13544 named_refusals += 1;
13545 eprintln!("seed {seed} refusal: {msg}");
13546 continue;
13547 }
13548 Ok(frames) => frames,
13549 };
13550 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
13551 assert_eq!(frames.len(), frame_count);
13552 let mismatched = frames
13553 .iter()
13554 .zip(&ffmpeg_frames)
13555 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
13556 if mismatched {
13557 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
13558 std::fs::write(&path, &stream).expect("writing pinned stream");
13559 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
13560 }
13561 }
13562 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13563 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
13564 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
13565 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
13566 }
13567 matched += 1;
13568 }
13569 assert!(
13570 matched > 0,
13571 "{NAME}: every attempt refused; the gate never decoded a stream"
13572 );
13573 assert!(
13574 crate::decode::rect64_qidx_drift_hits() > 0,
13575 "{NAME}: zero rect64 dequant calls ever observed CURRENT_Q_IDX != base_q_idx \
13576 ({matched} matches, {named_refusals} refusals out of {n_attempts}) -- delta_q \
13577 was never actually exercised through decode_block_rect64 this run"
13578 );
13579 eprintln!(
13580 "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \
13581 {n_attempts}, sb_rect_hits={}, rect64_qidx_drift_hits={}",
13582 crate::decode::sb_rect_hits(),
13583 crate::decode::rect64_qidx_drift_hits()
13584 );
13585 }
13586
13587 /// lane-sbpart r4: replays a pinned mismatch byte-for-byte off disk (no
13588 /// aomenc/ffmpeg re-encode), same pattern as `pinned_golden3/4_stream_
13589 /// decodes_pixel_exact` -- fast red/green loop for the bisect, and lets
13590 /// `EC_AV1_TRACE=1` be set for one run without re-driving the encoder.
13591 #[test]
13592 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
13593 fn pinned_sbpart_stream_decodes_pixel_exact() {
13594 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
13595 .map(std::path::PathBuf::from)
13596 .unwrap_or_else(|_| pin_dir().join("sbpart-pin.obu"));
13597 let Ok(stream) = std::fs::read(&path) else {
13598 eprintln!(
13599 "SKIP pinned_sbpart_stream_decodes_pixel_exact: no pinned bytes at {} \
13600 -- re-capture with EC_AV1_GATE_DUMP off the sbpart gate",
13601 path.display()
13602 );
13603 return;
13604 };
13605 if !have_ffmpeg() {
13606 eprintln!("SKIP pinned_sbpart_stream_decodes_pixel_exact: no ffmpeg");
13607 return;
13608 }
13609 let frames = decode_stream(&stream).expect("pinned stream must decode");
13610 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 192, 128, 1);
13611 let (width, height) = (192usize, 128usize);
13612 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13613 if std::env::var_os("EC_SBPART_DIAG").is_some() {
13614 let (mut min_r, mut max_r, mut min_c, mut max_c, mut n) =
13615 (usize::MAX, 0usize, usize::MAX, 0usize, 0usize);
13616 for r in 0..height {
13617 for c in 0..width {
13618 let idx = r * width + c;
13619 if got.y[idx] != want.y[idx] {
13620 min_r = min_r.min(r);
13621 max_r = max_r.max(r);
13622 min_c = min_c.min(c);
13623 max_c = max_c.max(c);
13624 n += 1;
13625 }
13626 }
13627 }
13628 eprintln!(
13629 "DIAG frame {i}: {n} luma mismatches, bbox rows [{min_r}..{max_r}] cols \
13630 [{min_c}..{max_c}] of {width}x{height}"
13631 );
13632 // Per-64px-superblock-column mismatch counts, to see whether
13633 // corruption starts exactly at the rect64 SB or bleeds into
13634 // SBs decoded earlier (raster order).
13635 for sb_col in 0..(width + 63) / 64 {
13636 let c0 = sb_col * 64;
13637 let c1 = (c0 + 64).min(width);
13638 let mut cnt = 0usize;
13639 let mut first = None;
13640 for r in 0..height {
13641 for c in c0..c1 {
13642 let idx = r * width + c;
13643 if got.y[idx] != want.y[idx] {
13644 cnt += 1;
13645 if first.is_none() {
13646 first = Some((r, c));
13647 }
13648 }
13649 }
13650 }
13651 eprintln!(
13652 "DIAG frame {i} sb_col {sb_col} (cols {c0}..{c1}): {cnt} mismatches, \
13653 first={first:?}"
13654 );
13655 }
13656 }
13657 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned sbpart)");
13658 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned sbpart)");
13659 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned sbpart)");
13660 }
13661 }
13662}