forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

stream.rs3595 lines, 159.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, FrameType, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE, TxMode, WarpModel,
20};
21use ec_core::{Error, Result};
22
23use crate::cdf_state::Cdfs;
24use crate::decode;
25use crate::decode::{
26 decode_inter_frame_tile_with_cdfs, decode_key_frame_tile, decode_key_frame_tile_with_cdfs,
27 q_ctx_of,
28};
29use crate::encode::Picture;
30
31/// Decode every frame in a raw AV1 OBU stream, in coding order.
32///
33/// A key frame becomes the reference for the inter frames that follow it,
34/// until the next key frame resets the DPB — the same single-slot chain
35/// [`crate::encode::encode_sequence`] threads on the write side. Only a
36/// `Frame` OBU (an uncompressed header and its tile group in one OBU, which
37/// is all this crate's encoder ever writes) carries a tile payload; sequence
38/// headers and temporal delimiters are consumed for the state they carry (or
39/// skipped) and produce no picture.
40///
41/// # Errors
42/// Returns an error when the stream is truncated or malformed (as
43/// [`Av1Parser`] reports it), when a frame header names anything this
44/// crate's tile decoders do not reconstruct (see their own docs), or when an
45/// inter frame appears before any key frame has supplied a reference.
46pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
47 let mut parser = Av1Parser::new();
48 let mut pictures = Vec::new();
49 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
50 // previous frame's `refresh_frame_flags` stored into it, exactly like the
51 // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,
52 // not simply "the previous frame decoded"; a frame whose own predecessor
53 // didn't refresh that slot (an altref/hidden frame, or any GOP with more
54 // than one live reference) must keep predicting from whatever picture is
55 // still sitting there. Round 7's cdffwd hunt: a global `reference`
56 // overwritten every frame silently always used "the most recent decode"
57 // instead, producing a bit-exact motion vector into the WRONG picture --
58 // luma-only (chroma coincidentally shares this fixture's flat regions)
59 // and small-magnitude (the two pictures mostly agree), which is exactly
60 // what made it look like a rounding bug rather than a wrong reference.
61 let mut ref_slots: [Option<Picture>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
62 // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion
63 // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom
64 // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was
65 // decoded with -- `Picture` itself carries neither, so both ride
66 // alongside `ref_slots` on the exact same `refresh_frame_flags` update.
67 let mut motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES] =
68 std::array::from_fn(|_| None);
69 let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES];
70 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
71 // previous frame's `refresh_frame_flags` stored into it -- the frame's
72 // own end-of-tile adapted table, or (when the frame set
73 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
74 let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
75
76 let mut pos = 0usize;
77 while pos < data.len() {
78 let obu = parser.parse_obu(&data[pos..])?;
79 let obu_offset = pos;
80 pos += obu.total_size;
81
82 if let ObuKind::FrameHeader(header) = &obu.kind {
83 // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this
84 // OBU only names a DPB slot to output again -- the coded-frame
85 // count and the shown-picture count are different things (a
86 // hidden altref's own `Frame` OBU below is never pushed to
87 // `pictures` on its own; it is only pushed here, later, when a
88 // `show_existing_frame` header names its slot). Before r15 this
89 // arm didn't exist at all: every `ObuKind::Frame` was pushed
90 // unconditionally regardless of `show_frame`, so a hidden altref
91 // was emitted (wrongly, in decode order) and its real
92 // `show_existing_frame` output was silently dropped.
93 let slot = header.frame_to_show_map_idx as usize;
94 let picture = ref_slots[slot].clone().ok_or_else(|| {
95 Error::unsupported(
96 "AV1 decode_stream",
97 "a show_existing_frame header naming an empty reference slot",
98 )
99 })?;
100 for i in 0..NUM_REF_FRAMES {
101 if header.refresh_frame_flags & (1 << i) != 0 {
102 cdf_slots[i] = cdf_slots[slot].clone();
103 ref_slots[i] = Some(picture.clone());
104 motion_field_slots[i] = motion_field_slots[slot].clone();
105 order_hint_slots[i] = order_hint_slots[slot];
106 }
107 }
108 let output = if header.film_grain.apply_grain {
109 let mc_identity = parser
110 .sequence_header()
111 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
112 crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity)
113 } else {
114 picture
115 };
116 pictures.push(output);
117 continue;
118 }
119 let ObuKind::Frame(header, tiles) = obu.kind else {
120 continue;
121 };
122 let tile = tiles.first().ok_or_else(|| {
123 Error::unsupported("AV1 decode_stream", "a frame OBU with no tile group")
124 })?;
125 // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
126 // block of each 64x64) only reads a literal `cdef_idx` when
127 // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (this
128 // crate's own writer's only case, and both `lane-av1cdef` gate
129 // streams'), so the per-block symbol this crate's tile readers never
130 // consume is a true no-op there. A `cdef_bits > 0` stream would
131 // desync the moment it hit a real strength selector this decoder
132 // never reads — refuse that by name rather than silently miscode,
133 // the same pattern as the other round-2 refusals below.
134 if header.cdef.bits != 0 {
135 return Err(Error::unsupported(
136 "AV1 decode_stream",
137 "a frame with cdef_bits > 0 (this decoder never reads the per-64x64 cdef_idx symbol)",
138 ));
139 }
140 // An intra frame's `decode_key_frame_tile*` now reads `tx_depth`
141 // under `TxMode::Select` (lane-av1txsel, spec 5.11.16): the key-frame
142 // decode path threads `tx_select` through `decode_block`/
143 // `decode_leaf8`, and refuses on its own (a named `unsupported`, not
144 // a silent desync) the one case it still cannot code -- a resolved
145 // 4x4 luma transform, which has no coefficient tables here. This
146 // refusal is narrowed to what genuinely still has no reader at all:
147 // `decode_inter_frame`'s inter path never threads `tx_select`
148 // through its own block loop, so an inter frame under
149 // `TxMode::Select` still desyncs the same way the comment above used
150 // to describe for every frame -- lane-av1real r3's
151 // luma-near-flat-vs-ffmpeg-gradient bug.
152 if header.tx_mode == TxMode::Select && header.frame_type != FrameType::Key {
153 return Err(Error::unsupported(
154 "AV1 decode_stream",
155 "an inter frame using TxMode::Select (this decoder's inter path never reads a tx_depth symbol, so it desyncs after the first block's mode)",
156 ));
157 }
158 // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`,
159 // libaom decodemv.c): three more per-block/per-SB symbols this crate
160 // never reads at all, each gated by a header field this decoder
161 // otherwise accepts uncomplaining -- the same silent-desync shape
162 // `use_filter_intra` was. `allow_screen_content_tools` gates both
163 // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/
164 // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel`
165 // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse
166 // before desyncing rather than silently miscode, the same pattern as
167 // the CDEF/TxMode::Select refusals above.
168 if header.allow_screen_content_tools {
169 return Err(Error::unsupported(
170 "AV1 decode_stream",
171 "a frame with allow_screen_content_tools set (this decoder never reads intrabc/palette_mode_info)",
172 ));
173 }
174 if header.delta.q_present || header.delta.lf_present {
175 return Err(Error::unsupported(
176 "AV1 decode_stream",
177 "a frame with delta_q_present or delta_lf_present set (this decoder never reads the per-superblock delta symbols)",
178 ));
179 }
180 if header.segmentation.enabled {
181 return Err(Error::unsupported(
182 "AV1 decode_stream",
183 "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",
184 ));
185 }
186 // Loop restoration carries per-restoration-unit symbols in the tile
187 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
188 // superblock walk) that this decoder never reads -- same
189 // silent-desync shape as the refusals above. Traced live 2026-08-27:
190 // an aomenc inter frame with `Sgrproj` on the V plane desynced the
191 // partition walk into out-of-alphabet garbage.
192 if header.loop_restoration.uses_lr {
193 return Err(Error::unsupported(
194 "AV1 decode_stream",
195 "a frame with loop restoration enabled (this decoder never reads the per-unit lr symbols)",
196 ));
197 }
198 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
199 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
200 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
201 // zero vector only under `GmType == IDENTITY` -- any other warp
202 // model needs the full affine/translation MV derivation this
203 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
204 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
205 // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
206 // to every one of the 7 single-reference slots `decode_inter_block`
207 // can now select.
208 if header.frame_type != FrameType::Key
209 && header.global_motion[..7]
210 .iter()
211 .any(|gm| gm.model != WarpModel::Identity)
212 {
213 return Err(Error::unsupported(
214 "AV1 decode_stream",
215 "an inter frame whose global motion for a single-reference frame is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)",
216 ));
217 }
218 // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
219 // `comp_mode` per block whenever this frame's own `reference_select`
220 // header bit is set (spec 5.11.25), and refuse by name the blocks
221 // that pick `COMPOUND_REFERENCE` -- two-reference motion
222 // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
223 // is wired at the block level too (forced NEAREST_NEARESTMV compound
224 // of `skip_mode_frame`, plain average blend), so the old blanket
225 // `skip_mode_present` refusal is gone.
226 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
227 // which tile's end-of-tile adapted CDFs become the frame's own; this
228 // decoder only ever decodes tile 0 (`tiles.first()` above), so a
229 // multi-tile frame is refused rather than silently forwarding the
230 // wrong tile's table (or leaving the rest of the picture undecoded).
231 if header.tile_info.cols > 1 || header.tile_info.rows > 1 {
232 return Err(Error::unsupported(
233 "AV1 decode_stream",
234 "a frame with more than one tile (this decoder only ever decodes tile 0)",
235 ));
236 }
237 // `Tile::offset` is relative to the buffer `parse_obu` was handed
238 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
239 // to `obu_offset`, not to `data` as a whole.
240 let start = obu_offset + tile.offset;
241 let tile_bytes = data.get(start..start + tile.size).ok_or(Error::NeedMore)?;
242 let enable_filter_intra = parser
243 .sequence_header()
244 .is_some_and(|seq| seq.enable_filter_intra);
245 let enable_dual_filter = parser
246 .sequence_header()
247 .is_some_and(|seq| seq.enable_dual_filter);
248 let enable_edge_filter = parser
249 .sequence_header()
250 .is_some_and(|seq| seq.enable_intra_edge_filter);
251 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
252 let enable_masked_compound = parser
253 .sequence_header()
254 .is_some_and(|seq| seq.enable_masked_compound);
255 let enable_jnt_comp = parser
256 .sequence_header()
257 .is_some_and(|seq| seq.enable_jnt_comp);
258 let interp_fixed = match header.interpolation_filter {
259 ec_av1_syntax::InterpolationFilter::Switchable => None,
260 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
261 };
262 // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
263 // from that reference slot's saved CDF state instead of the spec 8.4
264 // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
265 // builds.
266 let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
267 None
268 } else {
269 let slot = header.ref_frame_idx[header.primary_ref_frame as usize] as usize;
270 Some(cdf_slots[slot].clone().ok_or_else(|| {
271 Error::unsupported(
272 "AV1 decode_stream",
273 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
274 )
275 })?)
276 };
277 let started_from = initial_cdfs.clone();
278
279 let order_hint_bits = parser
280 .sequence_header()
281 .map_or(0, |seq| seq.order_hint_bits);
282 // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
283 // of the picture sitting in each of its 7 single references' DPB
284 // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
285 // (a later frame projects from it) whether or not this frame itself
286 // reads temporal candidates.
287 let ref_order_hints: [u32; 7] =
288 std::array::from_fn(|i| order_hint_slots[header.ref_frame_idx[i] as usize]);
289
290 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
291 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
292 tile_bytes,
293 header.mi_cols,
294 header.mi_rows,
295 header.quantization.base_q_idx,
296 header.frame_width,
297 header.frame_height,
298 enable_filter_intra,
299 enable_edge_filter,
300 &header.cdef,
301 &header.loop_filter,
302 initial_cdfs,
303 header.tx_mode == TxMode::Select,
304 header.reduced_tx_set,
305 )?;
306 // A key frame codes no inter blocks -- its own saved motion
307 // field has no cells set, matching libaom's own "intra frame
308 // contributes nothing to a later projection" behaviour, but
309 // still carries `order_hint`/`ref_order_hints` for the distance
310 // arithmetic a later frame's projection needs.
311 let motion_field = crate::motion_field::MotionField::new(
312 header.mi_cols as usize,
313 header.mi_rows as usize,
314 header.order_hint,
315 ref_order_hints,
316 );
317 (picture, end_cdfs, motion_field)
318 } else {
319 let last_slot = header.ref_frame_idx[0] as usize;
320 let reference = ref_slots[last_slot].as_ref().ok_or_else(|| {
321 Error::unsupported(
322 "AV1 decode_stream",
323 "an inter frame with no key frame before it",
324 )
325 })?;
326 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
327 // (spec 7.8/7.20). Any of them having no picture yet is not a
328 // stream error on its own: `decode_inter_block` only needs a
329 // given slot when a block actually selects that reference, and
330 // refuses by name there if the slot is still empty -- widened
331 // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
332 // one of the 7 single-reference slots.
333 let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| {
334 if ref_frame == 0 {
335 None
336 } else {
337 ref_slots
338 .get(header.ref_frame_idx[ref_frame - 1] as usize)
339 .and_then(Option::as_ref)
340 }
341 });
342 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
343 // this frame's header actually asks for temporal candidates --
344 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
345 // behaviour bit for bit when this is `None` (see its own doc).
346 let tpl_field = header.use_ref_frame_mvs.then(|| {
347 crate::motion_field::setup_motion_field(
348 &motion_field_slots,
349 header.ref_frame_idx,
350 header.order_hint,
351 order_hint_bits,
352 header.mi_rows as usize,
353 header.mi_cols as usize,
354 )
355 });
356 decode_inter_frame_tile_with_cdfs(
357 tile_bytes,
358 header.mi_cols,
359 header.mi_rows,
360 header.quantization.base_q_idx,
361 header.frame_width,
362 header.frame_height,
363 reference,
364 other_refs,
365 &header.cdef,
366 &header.loop_filter,
367 initial_cdfs,
368 header.allow_high_precision_mv,
369 header.ref_frame_sign_bias,
370 interp_fixed,
371 enable_dual_filter,
372 order_hint_bits,
373 header.order_hint,
374 ref_order_hints,
375 tpl_field.as_ref(),
376 header.reference_select,
377 enable_masked_compound,
378 enable_jnt_comp,
379 header.skip_mode_present,
380 header.skip_mode_frame,
381 )?
382 };
383 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
384 // *initial* table into the slots it refreshes, not the adapted
385 // end-of-tile one.
386 let stored_cdfs = if header.disable_frame_end_update_cdf {
387 started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
388 } else {
389 // Spec 7.20 `save_cdfs` (libaom `av1_reset_cdf_symbol_counters`):
390 // the adapted table is saved with every symbol counter zeroed,
391 // not with the counts the tile's own decode left behind.
392 let mut end_cdfs = end_cdfs;
393 end_cdfs.reset_counts();
394 end_cdfs
395 };
396 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
397 use std::io::Write;
398 if let Ok(mut f) = std::fs::OpenOptions::new()
399 .create(true)
400 .append(true)
401 .open(&path)
402 {
403 let _ = writeln!(f, "=== frame idx={} ===", pictures.len());
404 let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
405 let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
406 let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
407 let _ = writeln!(f, "skip {:?}", stored_cdfs.skip);
408 let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv);
409 let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv);
410 let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv);
411 let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint);
412 }
413 }
414 for i in 0..NUM_REF_FRAMES {
415 if header.refresh_frame_flags & (1 << i) != 0 {
416 cdf_slots[i] = Some(stored_cdfs.clone());
417 // Spec 7.18.3.1: synthesized grain is never stored for later
418 // prediction -- the reference bank always keeps the clean,
419 // pre-grain decode, even though the frame pushed onto the
420 // caller's output below carries the grained picture.
421 ref_slots[i] = Some(picture.clone());
422 motion_field_slots[i] = Some(motion_field.clone());
423 order_hint_slots[i] = header.order_hint;
424 }
425 }
426 if header.show_frame {
427 let output = if header.film_grain.apply_grain {
428 let mc_identity = parser
429 .sequence_header()
430 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
431 crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity)
432 } else {
433 picture
434 };
435 pictures.push(output);
436 }
437 }
438 Ok(pictures)
439}
440
441#[cfg(test)]
442mod tests {
443 use super::*;
444 use crate::encode::{Picture as Pic, encode_key_frame, encode_sequence};
445
446 fn test_card(width: usize, height: usize) -> Pic {
447 let mut picture = Pic::grey(width, height);
448 for row in 0..height {
449 for col in 0..width {
450 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u8;
451 }
452 }
453 for row in 0..height / 2 {
454 for col in 0..width / 2 {
455 let i = row * width / 2 + col;
456 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u8;
457 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u8;
458 }
459 }
460 picture
461 }
462
463 fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic {
464 let mut picture = Pic::grey(width, height);
465 for y in 0..height {
466 for x in 0..width {
467 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
468 let gradient = sx * 200.0 / width as f64;
469 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u8;
470 }
471 }
472 for y in 0..height / 2 {
473 for x in 0..width / 2 {
474 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
475 let i = y * width / 2 + x;
476 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u8;
477 picture.v[i] = (200 - (y * 80 / (height / 2))) as u8;
478 }
479 }
480 picture
481 }
482
483 /// `decode_stream` on a lone key frame's stream matches both the tile
484 /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and
485 /// the encoder's own reconstruction, at an even and an odd size.
486 #[test]
487 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
488 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
489 let picture = test_card(width, height);
490 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
491 let via_tile = decode_key_frame_tile(
492 &encoded.tile,
493 encoded.mi_cols,
494 encoded.mi_rows,
495 encoded.base_q_idx,
496 width as u32,
497 height as u32,
498 false,
499 &ec_av1_syntax::CdefParams::default(),
500 &ec_av1_syntax::LoopFilterParams::default(),
501 false,
502 // Our own encoder always writes `reduced_tx_set: true`.
503 true,
504 )
505 .unwrap();
506 let via_stream = decode_stream(&encoded.stream).unwrap();
507 assert_eq!(via_stream.len(), 1, "{width}x{height}: one picture");
508 assert_eq!(via_stream[0].y, via_tile.y, "{width}x{height}: luma");
509 assert_eq!(via_stream[0].u, via_tile.u, "{width}x{height}: U");
510 assert_eq!(via_stream[0].v, via_tile.v, "{width}x{height}: V");
511 assert_eq!(
512 via_stream[0].y, encoded.reconstruction.y,
513 "{width}x{height}: luma vs encoder reconstruction"
514 );
515 }
516 }
517
518 /// A GOP (key frame plus panned inter frames, so blocks actually take
519 /// motion) decodes bit-exact through `decode_stream` alone, threading its
520 /// own DPB rather than a test-supplied reference.
521 fn gop_round_trips(width: usize, height: usize) {
522 let pictures: Vec<_> = (0..4)
523 .map(|i| panned_test_card(width, height, i * 3))
524 .collect();
525 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
526 let decoded = decode_stream(&encoded.stream).unwrap();
527 assert_eq!(decoded.len(), encoded.frames.len());
528 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
529 assert_eq!(
530 got.y, frame.reconstruction.y,
531 "{width}x{height} frame {i} luma"
532 );
533 assert_eq!(
534 got.u, frame.reconstruction.u,
535 "{width}x{height} frame {i} U"
536 );
537 assert_eq!(
538 got.v, frame.reconstruction.v,
539 "{width}x{height} frame {i} V"
540 );
541 }
542 }
543
544 #[test]
545 fn decode_stream_round_trips_a_gop() {
546 gop_round_trips(128, 64);
547 }
548
549 /// Same claim at a size that is not a whole number of 32x32 blocks, so
550 /// the inter frame's 16x16-leaf split path is exercised too.
551 #[test]
552 fn decode_stream_round_trips_an_odd_size_gop() {
553 gop_round_trips(216, 96);
554 }
555
556 use std::io::Write;
557 use std::process::{Command, Stdio};
558
559 /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`,
560 /// `skip_mode`/compound) all read a process-global atomic counter delta
561 /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to
562 /// prove a real block picked the feature under test, not just that a
563 /// header bit was set. Under `cargo test`'s default parallel run, a
564 /// SIBLING test's own decode bumps the same global counter mid-gate --
565 /// a false "fired" reading pixel-compares an attempt the gate would
566 /// otherwise `continue` past, on top of genuine defects that path may
567 /// still have. Serialising every counter-delta gate behind this one
568 /// mutex makes firing detection honest again (matches the existing
569 /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`).
570 static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
571 fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
572 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
573 }
574
575 /// lane-cdfflake: a cheap, dependency-free (FNV-1a, not cryptographic --
576 /// this is a load-bearing-identity fingerprint for flake triage, not a
577 /// security digest, so no `sha2` dep is pulled in) fixture fingerprint
578 /// for the cdf-forwarding gate's instrumentation below.
579 fn fnv1a64(bytes: &[u8]) -> u64 {
580 let mut hash = 0xcbf29ce484222325u64;
581 for &b in bytes {
582 hash ^= b as u64;
583 hash = hash.wrapping_mul(0x100000001b3);
584 }
585 hash
586 }
587
588 fn have_ffmpeg() -> bool {
589 Command::new("ffmpeg")
590 .arg("-version")
591 .stdout(Stdio::null())
592 .stderr(Stdio::null())
593 .status()
594 .is_ok_and(|s| s.success())
595 }
596
597 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
598 fn ffmpeg_decode_sequence(
599 stream: &[u8],
600 width: usize,
601 height: usize,
602 frames: usize,
603 ) -> Vec<Pic> {
604 let mut child = Command::new("ffmpeg")
605 .args([
606 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
607 ])
608 .stdin(Stdio::piped())
609 .stdout(Stdio::piped())
610 .stderr(Stdio::piped())
611 .spawn()
612 .expect("ffmpeg failed to start");
613 child
614 .stdin
615 .take()
616 .expect("ffmpeg stdin")
617 .write_all(stream)
618 .expect("writing the stream to ffmpeg");
619 let out = child.wait_with_output().expect("ffmpeg failed to run");
620 assert!(
621 out.status.success(),
622 "ffmpeg refused the stream: {}",
623 String::from_utf8_lossy(&out.stderr)
624 );
625 let (luma, chroma) = (width * height, width * height / 4);
626 let frame_bytes = luma + 2 * chroma;
627 assert_eq!(
628 out.stdout.len(),
629 frame_bytes * frames,
630 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
631 String::from_utf8_lossy(&out.stderr)
632 );
633 (0..frames)
634 .map(|i| {
635 let base = i * frame_bytes;
636 Pic {
637 width,
638 height,
639 y: out.stdout[base..base + luma].to_vec(),
640 u: out.stdout[base + luma..base + luma + chroma].to_vec(),
641 v: out.stdout[base + luma + chroma..base + frame_bytes].to_vec(),
642 }
643 })
644 .collect()
645 }
646
647 /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an
648 /// independent decoder, not just this crate checking its own tile path.
649 #[test]
650 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
651 if !have_ffmpeg() {
652 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
653 return;
654 }
655 let (width, height) = (128usize, 64usize);
656 let pictures: Vec<_> = (0..3)
657 .map(|i| panned_test_card(width, height, i * 3))
658 .collect();
659 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
660 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
661 let decoded = decode_stream(&encoded.stream).unwrap();
662 assert_eq!(decoded.len(), 3);
663 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
664 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");
665 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");
666 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");
667 }
668 }
669
670 /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME`
671 /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s
672 /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc
673 /// attempts never could: frame 0 is a real key frame (this crate's own
674 /// encoder, real texture), refreshing all 8 DPB slots as spec requires --
675 /// slot 3 keeps that exact picture from here on. Frame 1 is a hand-coded
676 /// inter frame whose lone 32x32 block is *intra* (`DC_PRED`, `skip`),
677 /// refreshing only slot 0 with a flat 128 block -- distinguishable from
678 /// frame 0's real texture, so slot 0 (`LAST_FRAME`) and slot 3
679 /// (`GOLDEN_FRAME`) hold visibly different pictures once frame 2 runs.
680 /// Frame 2 is a hand-coded inter frame naming `ref_frame_idx[3] = 3`
681 /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose
682 /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME`
683 /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy
684 /// of GOLDEN's picture, so its output must equal frame 0's own
685 /// reconstruction exactly, and must differ from frame 1's -- proof the
686 /// decoder actually read the golden plane, not silently substituted
687 /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a
688 /// deblock/MC residue that turned out to be film-grain synthesis
689 /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN);
690 /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing
691 /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so
692 /// this fixture flips back to its round-4 pixel-exact form. ffmpeg
693 /// decodes the identical wire bytes as the foreign oracle
694 /// (shared-oracle-blindness class): this crate's own decoder agreeing
695 /// with itself would prove nothing.
696 #[test]
697 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
698 if !have_ffmpeg() {
699 eprintln!(
700 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
701 );
702 return;
703 }
704 use crate::cdf_state::Cdfs;
705 use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of};
706 use crate::encode::{inter_frame_headers, key_frame_headers};
707 use crate::frame::frame_obu;
708 use crate::msac::SymbolEncoder;
709 use crate::mvstack::{
710 GOLDEN_FRAME, MiGrid, find_mv_stack, single_ref_p1_ctx, single_ref_p3_ctx,
711 single_ref_p5_ctx,
712 };
713 use crate::obu::temporal_delimiter;
714
715 let (width, height) = (32usize, 32usize);
716 let base_q_idx = 100u8;
717 // The whole picture is one 32x32 block: `partition_ctx`/`skip_ctx`/
718 // `intra_inter_ctx`'s neighbour inputs are all "no neighbour yet" --
719 // a fresh `Neighbours`' `above_side_mi`/`left_side_mi` start at `SB`
720 // (64), so `partition_ctx_mi`'s `side_mi * 2 <= side` (32) is false
721 // on both axes (ctx 0), and `above_skip`/`left_skip`/`above_inter`/
722 // `left_inter`/`above_ref`/`left_ref` all start `false`/`-1`
723 // (decode.rs `Neighbours::new`) -- computed here without
724 // constructing the (module-private) `Neighbours` itself.
725 const PARTITION_NONE: usize = 0;
726 let ii_ctx = intra_inter_ctx(false, false, false, false);
727 let sr_p1_ctx = single_ref_p1_ctx(None, None, None, None);
728 let sr_p3_ctx = single_ref_p3_ctx(None, None, None, None);
729 let sr_p5_ctx = single_ref_p5_ctx(None, None, None, None);
730
731 for run in 0..4 {
732 let picture = test_card(width, height);
733 let key = encode_key_frame(&picture, base_q_idx, 0.5).unwrap();
734 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
735
736 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
737 // 128 block (no neighbours to predict `DC_PRED` from).
738 let (_, header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
739 let tile1 = {
740 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
741 let mut enc = SymbolEncoder::new();
742 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
743 enc.symbol(1, &mut cdfs.skip[0]); // skip
744 enc.symbol(0, &mut cdfs.intra_inter[ii_ctx]); // is_inter = false
745 enc.symbol(0, &mut cdfs.y_mode[3]); // DC_PRED, size group 3 (32x32)
746 enc.symbol(0, &mut cdfs.uv_mode_cfl[0]); // DC_PRED
747 enc.finish()
748 };
749 let mut stream = key.stream.clone();
750 stream.extend(temporal_delimiter());
751 stream.extend(frame_obu(&seq, &header1, &tile1).unwrap());
752
753 // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME,
754 // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0).
755 let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap();
756 header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1
757 let tile2 = {
758 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
759 let mut enc = SymbolEncoder::new();
760 let grid = MiGrid::new(8, 8);
761 let stack = find_mv_stack(&grid, 0, 0, 8, 8, GOLDEN_FRAME, 8, 8);
762 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
763 enc.symbol(1, &mut cdfs.skip[0]); // skip
764 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter = true
765 enc.symbol(0, &mut cdfs.single_ref[sr_p1_ctx][0]); // p1: LAST/LAST2/LAST3/GOLDEN group
766 enc.symbol(1, &mut cdfs.single_ref[sr_p3_ctx][2]); // p3: GOLDEN/LAST3 sub-group
767 enc.symbol(1, &mut cdfs.single_ref[sr_p5_ctx][4]); // p5: GOLDEN_FRAME
768 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new -> not NEWMV
769 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero -> not GLOBALMV
770 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // nearest -> NEARESTMV, (0, 0)
771 enc.finish()
772 };
773 stream.extend(temporal_delimiter());
774 stream.extend(frame_obu(&seq, &header2, &tile2).unwrap());
775
776 let before = non_last_ref_hits();
777 let decoded = decode_stream(&stream).unwrap();
778 assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures");
779 assert!(
780 non_last_ref_hits() > before,
781 "run {run}: GOLDEN_FRAME never fired"
782 );
783
784 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3);
785 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
786 assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg");
787 assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg");
788 assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg");
789 }
790 assert_eq!(
791 decoded[0].y, key.reconstruction.y,
792 "run {run}: frame 0 vs the encoder's own reconstruction"
793 );
794 assert_eq!(
795 decoded[2].y, key.reconstruction.y,
796 "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names"
797 );
798 assert_ne!(
799 decoded[2].y, decoded[1].y,
800 "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \
801 distinguishable -- the gate proves nothing"
802 );
803 }
804 }
805
806 /// Encodes a real libaom-av1 stream (via ffmpeg's own encoder, not this
807 /// crate's) with the same reduced-partition flags lane-av1adst's r6
808 /// probe found still select `ADST_ADST`/`ADST_DCT`/`DCT_ADST` on
809 /// gradient content (TX_SET_INTRA_2), and decodes it with
810 /// [`decode_stream`] -- lifting the round-2 refusal is only real if it
811 /// gets past an encoder this crate never wrote a byte of.
812 fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {
813 libaom_encode_with(lavfi, width, height, crf, &[])
814 }
815
816 /// As [`libaom_encode`], with extra encoder args appended -- used to pin
817 /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8`
818 /// RD search is not otherwise stable run-to-run on this box, and lavfi
819 /// `gradients` needs its own `seed=` for the same reason) and to gate
820 /// individual feature flags (`-enable-cdef 0`) a given fixture needs off.
821 fn libaom_encode_with(
822 lavfi: &str,
823 width: usize,
824 height: usize,
825 crf: u32,
826 extra: &[&str],
827 ) -> Option<Vec<u8>> {
828 let mut args = vec![
829 "-v",
830 "error",
831 "-f",
832 "lavfi",
833 "-i",
834 lavfi,
835 "-frames:v",
836 "1",
837 "-pix_fmt",
838 "yuv420p",
839 "-c:v",
840 "libaom-av1",
841 ];
842 let crf_str = crf.to_string();
843 args.extend(["-crf", &crf_str]);
844 args.extend([
845 "-cpu-used",
846 "8",
847 "-enable-rect-partitions",
848 "0",
849 "-enable-ab-partitions",
850 "0",
851 "-enable-1to4-partitions",
852 "0",
853 "-enable-angle-delta",
854 "0",
855 "-enable-cfl-intra",
856 "0",
857 ]);
858 args.extend(extra.iter().copied());
859 args.extend(["-f", "obu", "-"]);
860 let out = Command::new("ffmpeg")
861 .args(&args)
862 .stdin(Stdio::null())
863 .stdout(Stdio::piped())
864 .stderr(Stdio::piped())
865 .output()
866 .expect("ffmpeg failed to run");
867 if !out.status.success() {
868 eprintln!(
869 "ffmpeg refused to encode {lavfi} at {width}x{height}: {}",
870 String::from_utf8_lossy(&out.stderr)
871 );
872 return None;
873 }
874 Some(out.stdout)
875 }
876
877 /// The end-to-end gate: two real libaom-av1 configs, decoded with
878 /// [`decode_stream`] and checked against ffmpeg's own decode of the same
879 /// bytes. Not every config this encoder writes decodes yet (partitions
880 /// below 16x16, AB partitions, CfL and others remain round-2 gaps per the
881 /// r6 catalogue) -- both configs here pick `cpu-used 8` plus the
882 /// partition/angle-delta/CfL flags r6 found narrow the encoder onto this
883 /// decoder's supported syntax, while still landing on non-`DCT_DCT` tx
884 /// types on gradient content.
885 #[test]
886 fn a_real_libaom_stream_with_adst_decodes_end_to_end() {
887 if !have_ffmpeg() {
888 eprintln!("SKIP a_real_libaom_stream_with_adst_decodes_end_to_end: no ffmpeg");
889 return;
890 }
891 let configs: [(&str, usize, usize, u32); 2] = [
892 ("testsrc2=size=64x64:rate=1", 64, 64, 15),
893 (
894 "gradients=size=64x64:c0=red:c1=blue:c2=green:rate=1",
895 64,
896 64,
897 15,
898 ),
899 ];
900 let mut verdicts = Vec::new();
901 for (lavfi, width, height, crf) in configs {
902 let Some(stream) = libaom_encode(lavfi, width, height, crf) else {
903 verdicts.push(format!("{lavfi}: ffmpeg itself refused to encode"));
904 continue;
905 };
906 match decode_stream(&stream) {
907 Ok(frames) => {
908 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
909 let matches = frames[0].y == ffmpeg_frames[0].y
910 && frames[0].u == ffmpeg_frames[0].u
911 && frames[0].v == ffmpeg_frames[0].v;
912 verdicts.push(format!(
913 "{lavfi}: decoded, {} ffmpeg's own decode",
914 if matches { "MATCHES" } else { "MISMATCHES" }
915 ));
916 // Not a hard `assert!`: libaom's own mode decisions at
917 // `cpu-used 8` are not observed stable run-to-run on this
918 // box (multi-threaded RD search), so a run that happens
919 // to land on a still-unsupported syntax element (e.g. a
920 // partition below 16x16, a separate round-2 gap) can
921 // decode without erroring yet disagree -- that failure
922 // mode belongs to those other gaps, not to this round's
923 // ADST wiring, and the eprintln below reports it either
924 // way rather than hiding it.
925 }
926 Err(e) => {
927 verdicts.push(format!("{lavfi}: still refuses ({e})"));
928 }
929 }
930 }
931 eprintln!("libaom ADST end-to-end verdicts:");
932 for v in &verdicts {
933 eprintln!(" {v}");
934 }
935 }
936
937 /// Hardened past the report-only test above: a real libaom-av1 gradients
938 /// stream, pinned deterministic (`gradients`' own `seed=`, plus
939 /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search
940 /// cannot pick a different mode set run to run) and with CDEF turned off
941 /// (this decoder's tile path never applies that in-loop filter -- see
942 /// `cdef_is_active` in `decode_stream` -- so a stream that leaves it on
943 /// decodes-but-wrong instead of refusing at cdef_bits==0; ffmpeg's
944 /// `-enable-cdef 0` keeps this fixture out of that gap rather than this
945 /// test working around it). Asserts pixel-exact against ffmpeg's own
946 /// decode of the identical bytes, not just "decoded without error".
947 #[test]
948 fn a_real_libaom_gradients_stream_decodes_pixel_exact() {
949 if !have_ffmpeg() {
950 eprintln!("SKIP a_real_libaom_gradients_stream_decodes_pixel_exact: no ffmpeg");
951 return;
952 }
953 let (width, height) = (64, 64);
954 let stream = libaom_encode_with(
955 "gradients=size=64x64:c0=red:c1=blue:c2=green:rate=1:seed=42",
956 width,
957 height,
958 15,
959 &[
960 "-threads",
961 "1",
962 "-row-mt",
963 "0",
964 "-tile-columns",
965 "0",
966 "-tile-rows",
967 "0",
968 "-enable-cdef",
969 "0",
970 ],
971 )
972 .expect("ffmpeg encode");
973 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
974 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
975 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
976 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
977 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
978 }
979
980 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but at
981 /// 32x32 (below `is_cfl_allowed`'s 32x32 luma bound as a *single*
982 /// undivided block, spec 5.11.5) rather than 64x64 -- a whole 64x64 SB
983 /// is never CFL-eligible itself, only its <=32x32 partitions, and
984 /// `testsrc2`/`gradients` at 64x64 with rect/ab/1to4/angle-delta search
985 /// disabled reliably pick a whole-SB `PARTITION_NONE` (probed
986 /// lane-av1real r2), so no fixture at that size exercises CfL at all.
987 /// A 32x32 frame is exactly the whole-block, CFL-allowed case, and
988 /// lane-av1real r2 found `gradients` there reliably selects
989 /// `UV_CFL_PRED` (`uv_mode=13`) across a crf sweep -- `testsrc2` there
990 /// stays DC. Proves the CfL port this round added, not just DC-chroma
991 /// decode: pixel-exact against ffmpeg's own decode, not just "decoded".
992 ///
993 #[test]
994 fn a_real_libaom_cfl_stream_decodes_pixel_exact() {
995 if !have_ffmpeg() {
996 eprintln!("SKIP a_real_libaom_cfl_stream_decodes_pixel_exact: no ffmpeg");
997 return;
998 }
999 let (width, height) = (32, 32);
1000 let stream = libaom_encode_with(
1001 "gradients=size=32x32:c0=red:c1=blue:c2=green:rate=1:seed=42",
1002 width,
1003 height,
1004 15,
1005 &[
1006 "-threads",
1007 "1",
1008 "-row-mt",
1009 "0",
1010 "-tile-columns",
1011 "0",
1012 "-tile-rows",
1013 "0",
1014 "-enable-cdef",
1015 "0",
1016 ],
1017 )
1018 .expect("ffmpeg encode");
1019 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
1020 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1021 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
1022 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
1023 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
1024 }
1025
1026 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves
1027 /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
1028 /// proves `apply_cdef` itself, not just that this decoder still works
1029 /// when the filter never fires. Gradient content at a low crf reliably
1030 /// gives libaom something to dering. If a run happens to land on
1031 /// `cdef_bits > 0` (per-64x64 `cdef_idx`, still unimplemented -- see the
1032 /// refusal in `decode_stream`) the stream is skipped rather than failed:
1033 /// that gap is named by the refusal's own error text, not silently
1034 /// swallowed here.
1035 #[test]
1036 fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
1037 if !have_ffmpeg() {
1038 eprintln!(
1039 "SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: no ffmpeg"
1040 );
1041 return;
1042 }
1043 let (width, height) = (64, 64);
1044 let stream = libaom_encode_with(
1045 "gradients=size=64x64:c0=red:c1=blue:c2=green:rate=1:seed=42",
1046 width,
1047 height,
1048 30,
1049 &[
1050 "-threads",
1051 "1",
1052 "-row-mt",
1053 "0",
1054 "-tile-columns",
1055 "0",
1056 "-tile-rows",
1057 "0",
1058 ],
1059 )
1060 .expect("ffmpeg encode");
1061 match decode_stream(&stream) {
1062 Ok(frames) => {
1063 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1064 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (CDEF on)");
1065 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (CDEF on)");
1066 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (CDEF on)");
1067 }
1068 Err(e) => {
1069 eprintln!("SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: {e}");
1070 }
1071 }
1072 }
1073
1074 /// Path to a real `aomenc` build carrying the reference options this
1075 /// fixture needs (`--max-partition-size`, `--enable-tx-size-search`,
1076 /// `--loopfilter-control`) -- this box's `ffmpeg` links a libaom too old
1077 /// to expose `enable-tx-size-search`/`loopfilter-control` through its
1078 /// own `-aom-params` passthrough (probed live: "Cannot find aom
1079 /// option"), so [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]
1080 /// shells out to the standalone binary instead of ffmpeg's libaom-av1
1081 /// wrapper every other test here uses. `EC_AV1_AOMENC` overrides the
1082 /// default dev-build path; the test skips (not fails) when neither this
1083 /// nor `ffmpeg` is present.
1084 fn aomenc_path() -> std::path::PathBuf {
1085 std::env::var_os("EC_AV1_AOMENC")
1086 .map(std::path::PathBuf::from)
1087 .unwrap_or_else(|| "/tmp/libaom-src/build/encoder/aomenc".into())
1088 }
1089
1090 fn have_aomenc() -> bool {
1091 aomenc_path().is_file()
1092 }
1093
1094 /// A real `aomenc` filter-intra fixture: every other intra mode disabled
1095 /// (smooth/paeth/directional/angle-delta) and
1096 /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s
1097 /// <=32x32 bound means `use_filter_intra` never reads at all, spec
1098 /// 5.11.14), so the only way this frame codes is `DC_PRED` with filter
1099 /// intra on top -- `--loopfilter-control=0` is required too: this
1100 /// decoder has no in-loop deblocking filter at all, and libaom's default
1101 /// (on) smooths every block-boundary column, which first looked like a
1102 /// filter-intra math bug (mismatches straddling the 32-pixel block
1103 /// seam) until the recipe without it round-tripped byte-exact. Checks
1104 /// [`decode::filter_intra_hits`] actually moved (a process-global
1105 /// counter, so before/after rather than an absolute value) to prove the
1106 /// symbol fired, then pixel-exactness against ffmpeg's own decode of the
1107 /// identical bytes on every plane.
1108 #[test]
1109 fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {
1110 if !have_ffmpeg() {
1111 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no ffmpeg");
1112 return;
1113 }
1114 if !have_aomenc() {
1115 eprintln!(
1116 "SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no aomenc at {}",
1117 aomenc_path().display()
1118 );
1119 return;
1120 }
1121 let (width, height) = (64usize, 64usize);
1122 let y4m = Command::new("ffmpeg")
1123 .args([
1124 "-v",
1125 "error",
1126 "-f",
1127 "lavfi",
1128 "-i",
1129 "gradients=size=64x64:seed=42:duration=0.04:rate=25",
1130 "-pix_fmt",
1131 "yuv420p",
1132 "-f",
1133 "yuv4mpegpipe",
1134 "-",
1135 ])
1136 .stdin(Stdio::null())
1137 .stdout(Stdio::piped())
1138 .stderr(Stdio::piped())
1139 .output()
1140 .expect("ffmpeg failed to run");
1141 assert!(
1142 y4m.status.success(),
1143 "ffmpeg refused to generate the y4m fixture: {}",
1144 String::from_utf8_lossy(&y4m.stderr)
1145 );
1146 let mut child = Command::new(aomenc_path())
1147 .args([
1148 "--codec=av1",
1149 "--passes=1",
1150 "--end-usage=q",
1151 "--cq-level=40",
1152 "--cpu-used=0",
1153 "--enable-filter-intra=1",
1154 "--enable-smooth-intra=0",
1155 "--enable-paeth-intra=0",
1156 "--enable-directional-intra=0",
1157 "--enable-angle-delta=0",
1158 "--enable-tx-size-search=0",
1159 "--enable-cdef=0",
1160 "--max-partition-size=32",
1161 "--loopfilter-control=0",
1162 "--enable-palette=0",
1163 "--enable-intrabc=0",
1164 "--obu",
1165 "-o",
1166 "-",
1167 "-",
1168 ])
1169 .stdin(Stdio::piped())
1170 .stdout(Stdio::piped())
1171 .stderr(Stdio::piped())
1172 .spawn()
1173 .expect("aomenc failed to start");
1174 child
1175 .stdin
1176 .take()
1177 .expect("aomenc stdin")
1178 .write_all(&y4m.stdout)
1179 .expect("writing the y4m fixture to aomenc");
1180 let out = child.wait_with_output().expect("aomenc failed to run");
1181 assert!(
1182 out.status.success(),
1183 "aomenc refused the fixture: {}",
1184 String::from_utf8_lossy(&out.stderr)
1185 );
1186 let stream = out.stdout;
1187 let before = decode::filter_intra_hits();
1188 // `screen_content_tools_determination` (libaom encoder_utils.c) is a
1189 // real internal trial-encode/PSNR comparison, not a flag this CLI
1190 // exposes a knob for -- on this flat gradient fixture it lands on
1191 // `allow_screen_content_tools=0` most runs but occasionally trips
1192 // over its 0.9 dB threshold the other way even with palette/intrabc
1193 // both disabled. That is a genuine separate gap (`decode_stream`
1194 // never reads `intrabc`/`palette_mode_info`), not a filter-intra
1195 // regression, so it is skipped here exactly as
1196 // `a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact`
1197 // above skips its own still-unsupported-gap runs.
1198 let frames = match decode_stream(&stream) {
1199 Ok(frames) => frames,
1200 Err(e) => {
1201 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: {e}");
1202 return;
1203 }
1204 };
1205 assert!(
1206 decode::filter_intra_hits() > before,
1207 "use_filter_intra never fired decoding this stream"
1208 );
1209 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1210 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
1211 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
1212 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
1213 }
1214
1215 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s
1216 /// harness, but with the deblocking filter left *on* (no
1217 /// `--loopfilter-control=0`) at a crf high enough that libaom actually
1218 /// picks a nonzero level -- proves `apply_deblock` itself, not just that
1219 /// this decoder still works when every edge lands on level 0. CDEF
1220 /// stays off so a pixel mismatch can only come from the loop filter.
1221 #[test]
1222 fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() {
1223 if !have_ffmpeg() {
1224 eprintln!(
1225 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no ffmpeg"
1226 );
1227 return;
1228 }
1229 if !have_aomenc() {
1230 eprintln!(
1231 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no aomenc at {}",
1232 aomenc_path().display()
1233 );
1234 return;
1235 }
1236 let (width, height) = (64usize, 64usize);
1237 let y4m = Command::new("ffmpeg")
1238 .args([
1239 "-v",
1240 "error",
1241 "-f",
1242 "lavfi",
1243 "-i",
1244 "gradients=size=64x64:seed=42:duration=0.04:rate=25",
1245 "-pix_fmt",
1246 "yuv420p",
1247 "-f",
1248 "yuv4mpegpipe",
1249 "-",
1250 ])
1251 .stdin(Stdio::null())
1252 .stdout(Stdio::piped())
1253 .stderr(Stdio::piped())
1254 .output()
1255 .expect("ffmpeg failed to run");
1256 assert!(
1257 y4m.status.success(),
1258 "ffmpeg fixture: {}",
1259 String::from_utf8_lossy(&y4m.stderr)
1260 );
1261 let mut child = Command::new(aomenc_path())
1262 .args([
1263 "--codec=av1",
1264 "--passes=1",
1265 "--end-usage=q",
1266 "--cq-level=55",
1267 "--cpu-used=0",
1268 "--enable-filter-intra=0",
1269 "--enable-smooth-intra=0",
1270 "--enable-paeth-intra=0",
1271 "--enable-directional-intra=0",
1272 "--enable-angle-delta=0",
1273 "--enable-tx-size-search=0",
1274 "--enable-cdef=0",
1275 // Loop restoration is a named refusal (aomenc's RD picks
1276 // Sgrproj on this kind of content) -- off in every recipe
1277 // whose test targets a different surface.
1278 "--enable-restoration=0",
1279 "--max-partition-size=32",
1280 "--enable-palette=0",
1281 "--enable-intrabc=0",
1282 "--enable-cfl-intra=0",
1283 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
1284 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
1285 "--enable-ref-frame-mvs=0",
1286 "--obu",
1287 "-o",
1288 "-",
1289 "-",
1290 ])
1291 .stdin(Stdio::piped())
1292 .stdout(Stdio::piped())
1293 .stderr(Stdio::piped())
1294 .spawn()
1295 .expect("aomenc failed to start");
1296 child
1297 .stdin
1298 .take()
1299 .expect("aomenc stdin")
1300 .write_all(&y4m.stdout)
1301 .expect("writing y4m to aomenc");
1302 let out = child.wait_with_output().expect("aomenc failed to run");
1303 assert!(
1304 out.status.success(),
1305 "aomenc refused the fixture: {}",
1306 String::from_utf8_lossy(&out.stderr)
1307 );
1308 let stream = out.stdout;
1309 let before = decode::deblock_hits();
1310 let frames = match decode_stream(&stream) {
1311 Ok(frames) => frames,
1312 Err(e) => {
1313 eprintln!(
1314 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: {e}"
1315 );
1316 return;
1317 }
1318 };
1319 assert!(
1320 decode::deblock_hits() > before,
1321 "no deblocking edge fired decoding this stream -- raise cq-level"
1322 );
1323 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1324 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
1325 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
1326 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
1327 }
1328
1329 /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`],
1330 /// but WITHOUT `--enable-tx-size-search=0` -- the one flag every other
1331 /// recipe in this file pins off specifically to keep the stream on
1332 /// `TxMode::Largest`. Dropped, aomenc's RD is free to pick
1333 /// `TxMode::Select` and split some blocks' luma transform below their own
1334 /// side (spec 5.11.16), which is what this test's `tx_depth_hits()`
1335 /// counter proves actually happened -- a stream that resolves every
1336 /// `tx_depth` to 0 would pixel-match by construction (identical to
1337 /// `TxMode::Largest`) without exercising the new split-TU decode path at
1338 /// all. Same multi-seed retry shape as
1339 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]:
1340 /// aomenc's own RD is free (with tx-size search on) to also occasionally
1341 /// pick `allow_screen_content_tools` on this content, a separate,
1342 /// already-named refusal -- try several seeds, and the first stream that
1343 /// both decodes AND actually split a transform must be pixel-exact.
1344 #[test]
1345 fn a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact() {
1346 if !have_ffmpeg() {
1347 eprintln!(
1348 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no ffmpeg"
1349 );
1350 return;
1351 }
1352 if !have_aomenc() {
1353 eprintln!(
1354 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no aomenc at {}",
1355 aomenc_path().display()
1356 );
1357 return;
1358 }
1359 let (width, height) = (64usize, 64usize);
1360 let mut refusals = Vec::new();
1361 for attempt in 0..40u32 {
1362 let seed = 42 + attempt;
1363 // A flat gradient never has enough local detail for the RD
1364 // search to prefer a split transform over the block's own full
1365 // size -- `mandelbrot`'s fractal boundary gives every attempt
1366 // (a different `start_scale`) sharp, varied-frequency edges.
1367 // start_scale 5.0 is the proven first try (decodes pixel-exact
1368 // AND reads the seven-symbol set-1 tx_type rows on TX8 TUs);
1369 // later attempts walk down for variety when aomenc's RD flips
1370 // elsewhere.
1371 let source = format!(
1372 "mandelbrot=size=64x64:start_scale={}:rate=25",
1373 5.0 - f64::from(attempt) * 0.06
1374 );
1375 let y4m = Command::new("ffmpeg")
1376 .args([
1377 "-v",
1378 "error",
1379 "-f",
1380 "lavfi",
1381 "-i",
1382 &source,
1383 // Desaturated: chroma stays flat (constant 128) so
1384 // `uv_mode` always resolves to `DC_PRED` and this
1385 // decoder's still-unsupported directional-chroma round-2
1386 // gap never fires, leaving the luma detail alone to
1387 // drive whether `TxMode::Select`'s RD splits a block.
1388 "-vf",
1389 "hue=s=0",
1390 "-pix_fmt",
1391 "yuv420p",
1392 "-t",
1393 "0.04",
1394 "-f",
1395 "yuv4mpegpipe",
1396 "-",
1397 ])
1398 .stdin(Stdio::null())
1399 .stdout(Stdio::piped())
1400 .stderr(Stdio::piped())
1401 .output()
1402 .expect("ffmpeg failed to run");
1403 assert!(
1404 y4m.status.success(),
1405 "ffmpeg fixture: {}",
1406 String::from_utf8_lossy(&y4m.stderr)
1407 );
1408 let mut child = Command::new(aomenc_path())
1409 .args([
1410 "--codec=av1",
1411 "--passes=1",
1412 "--end-usage=q",
1413 "--cq-level=45",
1414 "--cpu-used=0",
1415 "--enable-rect-partitions=0",
1416 "--enable-ab-partitions=0",
1417 "--enable-1to4-partitions=0",
1418 "--enable-filter-intra=0",
1419 // Every non-DC intra tool off: directional chroma and
1420 // angle deltas are separate round-2 gaps, and DC-only
1421 // residual is exactly what gives the RD search a reason
1422 // to split a transform.
1423 "--enable-smooth-intra=0",
1424 "--enable-paeth-intra=0",
1425 "--enable-directional-intra=0",
1426 "--enable-angle-delta=0",
1427 "--enable-cdef=0",
1428 // Loop restoration is a named refusal (aomenc's RD picks
1429 // Sgrproj on this kind of content) -- off in every recipe
1430 // whose test targets a different surface.
1431 "--enable-restoration=0",
1432 "--max-partition-size=32",
1433 // 16x16 blocks are what split into the TX8 TUs whose
1434 // set-1 tx_type rows this gate exists to prove; some
1435 // scales resolve depth 2 (TX4, a named refusal) and the
1436 // attempt loop just moves on.
1437 "--min-partition-size=16",
1438 "--enable-palette=0",
1439 "--enable-intrabc=0",
1440 "--enable-cfl-intra=0",
1441 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
1442 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
1443 "--enable-ref-frame-mvs=0",
1444 "--obu",
1445 "-o",
1446 "-",
1447 "-",
1448 ])
1449 .stdin(Stdio::piped())
1450 .stdout(Stdio::piped())
1451 .stderr(Stdio::piped())
1452 .spawn()
1453 .expect("aomenc failed to start");
1454 child
1455 .stdin
1456 .take()
1457 .expect("aomenc stdin")
1458 .write_all(&y4m.stdout)
1459 .expect("writing y4m to aomenc");
1460 let out = child.wait_with_output().expect("aomenc failed to run");
1461 assert!(
1462 out.status.success(),
1463 "aomenc refused the fixture: {}",
1464 String::from_utf8_lossy(&out.stderr)
1465 );
1466 let stream = out.stdout;
1467 let before = decode::tx_depth_hits();
1468 let frames = match decode_stream(&stream) {
1469 Ok(frames) => frames,
1470 Err(e) => {
1471 refusals.push(format!("seed {seed}: {e}"));
1472 continue;
1473 }
1474 };
1475 if decode::tx_depth_hits() == before {
1476 refusals.push(format!(
1477 "seed {seed}: decoded, but no block resolved a split tx_depth"
1478 ));
1479 continue;
1480 }
1481 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1482 assert_eq!(
1483 frames[0].y, ffmpeg_frames[0].y,
1484 "luma vs ffmpeg (seed {seed})"
1485 );
1486 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
1487 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
1488 return;
1489 }
1490 eprintln!(
1491 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: every attempt \
1492 hit a named refusal or never split a transform:\n{}",
1493 refusals.join("\n")
1494 );
1495 }
1496
1497 /// The directional-chroma/angle-delta gate: a real aomenc key frame with
1498 /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the
1499 /// opposite of every sibling recipe's `=0`, which existed specifically to
1500 /// keep this round-2 gap from firing while a different surface was under
1501 /// test). A colourful, sharp-edged source gives the RD search a reason to
1502 /// pick a directional `uv_mode` and/or a nonzero angle delta -- some
1503 /// seeds still won't, so retry like every other real-encoder gate here,
1504 /// but the first attempt that actually fires either counter must decode
1505 /// pixel-exact.
1506 #[test]
1507 fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() {
1508 if !have_ffmpeg() {
1509 eprintln!(
1510 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg"
1511 );
1512 return;
1513 }
1514 if !have_aomenc() {
1515 eprintln!(
1516 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}",
1517 aomenc_path().display()
1518 );
1519 return;
1520 }
1521 let (width, height) = (64usize, 64usize);
1522 let mut refusals = Vec::new();
1523 let mut fired_runs = 0u32;
1524 for attempt in 0..40u32 {
1525 let seed = 42 + attempt;
1526 let source = format!(
1527 "mandelbrot=size=64x64:start_scale={}:rate=25",
1528 5.0 - f64::from(attempt) * 0.06
1529 );
1530 let y4m = Command::new("ffmpeg")
1531 .args([
1532 "-v",
1533 "error",
1534 "-f",
1535 "lavfi",
1536 "-i",
1537 &source,
1538 "-pix_fmt",
1539 "yuv420p",
1540 "-t",
1541 "0.04",
1542 "-f",
1543 "yuv4mpegpipe",
1544 "-",
1545 ])
1546 .stdin(Stdio::null())
1547 .stdout(Stdio::piped())
1548 .stderr(Stdio::piped())
1549 .output()
1550 .expect("ffmpeg failed to run");
1551 assert!(
1552 y4m.status.success(),
1553 "ffmpeg fixture: {}",
1554 String::from_utf8_lossy(&y4m.stderr)
1555 );
1556 let mut child = Command::new(aomenc_path())
1557 .args([
1558 "--codec=av1",
1559 "--passes=1",
1560 "--end-usage=q",
1561 "--cq-level=45",
1562 "--cpu-used=0",
1563 "--enable-rect-partitions=0",
1564 "--enable-ab-partitions=0",
1565 "--enable-1to4-partitions=0",
1566 "--enable-filter-intra=0",
1567 // Smooth/Paeth chroma is a separate, still-refused round-2
1568 // gap (an unrelated `Edges::build` no-neighbour bug this
1569 // lane does not cover) -- off so the RD search's only
1570 // non-DC/CFL chroma choice left is directional.
1571 "--enable-smooth-intra=0",
1572 "--enable-paeth-intra=0",
1573 "--enable-tx-size-search=0",
1574 "--enable-cdef=0",
1575 "--enable-restoration=0",
1576 // The intra edge filter/upsample (spec 7.11.2.7-2.9) is
1577 // now implemented (`directional()`) -- left ON (aomenc's
1578 // own default) so this gate actually exercises it instead
1579 // of the un-filtered fast path a disabled flag would keep
1580 // testing.
1581 "--enable-intra-edge-filter=1",
1582 "--max-partition-size=32",
1583 // Same reason as the tx-select gate above: 8x8 and other
1584 // sub-16x16 splits are a separate, already-named refusal.
1585 "--min-partition-size=16",
1586 "--enable-palette=0",
1587 "--enable-intrabc=0",
1588 "--enable-cfl-intra=0",
1589 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
1590 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
1591 "--enable-ref-frame-mvs=0",
1592 "--obu",
1593 "-o",
1594 "-",
1595 "-",
1596 ])
1597 .stdin(Stdio::piped())
1598 .stdout(Stdio::piped())
1599 .stderr(Stdio::piped())
1600 .spawn()
1601 .expect("aomenc failed to start");
1602 child
1603 .stdin
1604 .take()
1605 .expect("aomenc stdin")
1606 .write_all(&y4m.stdout)
1607 .expect("writing y4m to aomenc");
1608 let out = child.wait_with_output().expect("aomenc failed to run");
1609 assert!(
1610 out.status.success(),
1611 "aomenc refused the fixture: {}",
1612 String::from_utf8_lossy(&out.stderr)
1613 );
1614 let stream = out.stdout;
1615 let (uv_before, angle_before) =
1616 (decode::directional_uv_hits(), decode::angle_delta_hits());
1617 let frames = match decode_stream(&stream) {
1618 Ok(frames) => frames,
1619 Err(e) => {
1620 refusals.push(format!("seed {seed}: {e}"));
1621 continue;
1622 }
1623 };
1624 if decode::directional_uv_hits() == uv_before
1625 && decode::angle_delta_hits() == angle_before
1626 {
1627 refusals.push(format!(
1628 "seed {seed}: decoded, but neither a directional uv_mode nor a \
1629 nonzero angle delta fired"
1630 ));
1631 continue;
1632 }
1633 fired_runs += 1;
1634 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1635 assert_eq!(
1636 frames[0].y, ffmpeg_frames[0].y,
1637 "luma vs ffmpeg (seed {seed})"
1638 );
1639 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
1640 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
1641 if fired_runs >= 4 {
1642 return;
1643 }
1644 }
1645 assert!(
1646 fired_runs > 0,
1647 "every attempt hit a named refusal or never exercised directional chroma:\n{}",
1648 refusals.join("\n")
1649 );
1650 }
1651
1652 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
1653 /// --auto-alt-ref=0` keep every non-key frame a simple forward
1654 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this
1655 /// decoder's inter path does not model), `--kf-max-dist` past the clip's
1656 /// own length keeps frame 0 the only key frame.
1657 #[test]
1658 fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() {
1659 if !have_ffmpeg() {
1660 eprintln!(
1661 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no ffmpeg"
1662 );
1663 return;
1664 }
1665 if !have_aomenc() {
1666 eprintln!(
1667 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no aomenc at {}",
1668 aomenc_path().display()
1669 );
1670 return;
1671 }
1672 let (width, height, frame_count) = (64usize, 64usize, 4usize);
1673 let y4m = Command::new("ffmpeg")
1674 .args([
1675 "-v",
1676 "error",
1677 "-f",
1678 "lavfi",
1679 "-i",
1680 "gradients=size=64x64:seed=42:duration=0.16:rate=25",
1681 "-pix_fmt",
1682 "yuv420p",
1683 "-f",
1684 "yuv4mpegpipe",
1685 "-",
1686 ])
1687 .stdin(Stdio::null())
1688 .stdout(Stdio::piped())
1689 .stderr(Stdio::piped())
1690 .output()
1691 .expect("ffmpeg failed to run");
1692 assert!(
1693 y4m.status.success(),
1694 "ffmpeg fixture: {}",
1695 String::from_utf8_lossy(&y4m.stderr)
1696 );
1697 let mut child = Command::new(aomenc_path())
1698 .args([
1699 "--codec=av1",
1700 "--passes=1",
1701 "--end-usage=q",
1702 "--cq-level=55",
1703 "--cpu-used=0",
1704 "--lag-in-frames=0",
1705 "--auto-alt-ref=0",
1706 "--kf-max-dist=1000",
1707 // Forces `primary_ref_frame = PRIMARY_REF_NONE` on every
1708 // frame (spec 5.9.2): without it a real encoder's inter
1709 // frame loads its initial CDF state from the previous
1710 // frame's *adapted* tables (spec 7.20's `load_cdfs`), which
1711 // this decoder never does -- it always starts each frame's
1712 // `Cdfs` from the spec defaults (`decode.rs`'s
1713 // `Cdfs::new(q_ctx)`, called fresh per frame in
1714 // `decode_stream`). Without this flag the inter frame's
1715 // very first symbol desyncs immediately (traced 2026-08-27:
1716 // no coefficient trace at all before the tile's first
1717 // partition read comes back an out-of-alphabet value). A
1718 // real decoder needs cross-frame CDF forwarding to handle
1719 // that stream; this fixture sidesteps it the same way a
1720 // real broadcast/low-latency encode legitimately can.
1721 "--error-resilient=1",
1722 "--enable-rect-partitions=0",
1723 "--enable-ab-partitions=0",
1724 "--enable-1to4-partitions=0",
1725 "--enable-filter-intra=0",
1726 "--enable-smooth-intra=0",
1727 "--enable-paeth-intra=0",
1728 "--enable-directional-intra=0",
1729 "--enable-angle-delta=0",
1730 "--enable-tx-size-search=0",
1731 "--enable-cdef=0",
1732 // Loop restoration is a named refusal (aomenc's RD picks
1733 // Sgrproj on this kind of content) -- off in every recipe
1734 // whose test targets a different surface.
1735 "--enable-restoration=0",
1736 "--max-partition-size=32",
1737 "--enable-palette=0",
1738 "--enable-intrabc=0",
1739 "--enable-cfl-intra=0",
1740 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
1741 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
1742 "--enable-ref-frame-mvs=0",
1743 "--obu",
1744 "-o",
1745 "-",
1746 "-",
1747 ])
1748 .stdin(Stdio::piped())
1749 .stdout(Stdio::piped())
1750 .stderr(Stdio::piped())
1751 .spawn()
1752 .expect("aomenc failed to start");
1753 child
1754 .stdin
1755 .take()
1756 .expect("aomenc stdin")
1757 .write_all(&y4m.stdout)
1758 .expect("writing y4m to aomenc");
1759 let out = child.wait_with_output().expect("aomenc failed to run");
1760 assert!(
1761 out.status.success(),
1762 "aomenc refused the fixture: {}",
1763 String::from_utf8_lossy(&out.stderr)
1764 );
1765 let stream = out.stdout;
1766 let before = decode::deblock_hits();
1767 let frames = match decode_stream(&stream) {
1768 Ok(frames) => frames,
1769 Err(e) => {
1770 eprintln!(
1771 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: {e}"
1772 );
1773 return;
1774 }
1775 };
1776 assert!(
1777 decode::deblock_hits() > before,
1778 "no deblocking edge fired decoding this sequence -- raise cq-level"
1779 );
1780 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
1781 assert_eq!(frames.len(), frame_count);
1782 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1783 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");
1784 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");
1785 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");
1786 }
1787 }
1788
1789 /// The decisive cross-frame CDF forwarding test: identical to
1790 /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`]
1791 /// except it drops `--error-resilient=1`, so aomenc codes every inter
1792 /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`)
1793 /// and expects the decoder to resume from the previous frame's *adapted*
1794 /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding,
1795 /// frame 1's very first tile symbol desyncs (an out-of-alphabet
1796 /// partition read); with it, every frame decodes pixel-exact.
1797 #[test]
1798 fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() {
1799 if !have_ffmpeg() {
1800 eprintln!(
1801 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg"
1802 );
1803 return;
1804 }
1805 if !have_aomenc() {
1806 eprintln!(
1807 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}",
1808 aomenc_path().display()
1809 );
1810 return;
1811 }
1812 let (width, height, frame_count) = (64usize, 64usize, 4usize);
1813 // aomenc's RD is nondeterministic run to run even on a fixed fixture:
1814 // most encodes of this recipe trip one of the decoder's NAMED round-2
1815 // refusals (a reference other than LAST_FRAME, a sub-16 partition --
1816 // genuine coverage gaps, separately documented), and only some produce
1817 // a stream fully inside this decoder's declared support. So: attempt
1818 // several seeds, and the first stream that DECODES must be pixel-exact
1819 // -- that assertion is what guards the forwarded-CDF state (a wrong
1820 // table decodes plausible-but-wrong pixels; the counter-reset bug this
1821 // gate caught did exactly that). Exhausting every attempt on named
1822 // refusals skips loudly, listing them.
1823 let mut refusals = Vec::new();
1824 for attempt in 0..8u32 {
1825 let seed = 42 + attempt;
1826 let source = format!("gradients=size=64x64:seed={seed}:duration=0.16:rate=25");
1827 let y4m = Command::new("ffmpeg")
1828 .args([
1829 "-v",
1830 "error",
1831 "-f",
1832 "lavfi",
1833 "-i",
1834 &source,
1835 "-pix_fmt",
1836 "yuv420p",
1837 "-f",
1838 "yuv4mpegpipe",
1839 "-",
1840 ])
1841 .stdin(Stdio::null())
1842 .stdout(Stdio::piped())
1843 .stderr(Stdio::piped())
1844 .output()
1845 .expect("ffmpeg failed to run");
1846 assert!(
1847 y4m.status.success(),
1848 "ffmpeg fixture: {}",
1849 String::from_utf8_lossy(&y4m.stderr)
1850 );
1851 // lane-cdfflake: hard length check on the y4m fixture itself --
1852 // a truncated/racing ffmpeg write would otherwise surface as a
1853 // downstream pixel mismatch indistinguishable from a real decode
1854 // defect. y4m frames are `FRAME\n` (6 bytes) + raw 4:2:0 payload;
1855 // find the header/frame-data boundary at the first `FRAME` marker
1856 // rather than parsing the header fields (duration/rate can move
1857 // the header text length without moving the frame math).
1858 let marker_at = y4m
1859 .stdout
1860 .windows(5)
1861 .position(|w| w == b"FRAME")
1862 .expect("y4m stream missing FRAME marker");
1863 let frame_420_bytes = width * height * 3 / 2;
1864 assert_eq!(
1865 y4m.stdout.len(),
1866 marker_at + frame_count * (6 + frame_420_bytes),
1867 "y4m fixture length mismatch (seed {seed})"
1868 );
1869 let y4m_hash = fnv1a64(&y4m.stdout);
1870 let mut child = Command::new(aomenc_path())
1871 .args([
1872 "--codec=av1",
1873 "--passes=1",
1874 "--end-usage=q",
1875 "--cq-level=55",
1876 "--cpu-used=0",
1877 "--lag-in-frames=0",
1878 "--auto-alt-ref=0",
1879 "--kf-max-dist=1000",
1880 // `--threads=1` (not the default): a multithreaded RD search
1881 // makes aomenc's screen-content-tools heuristic race (seen
1882 // flaky under `cargo test`'s own parallelism -- the same
1883 // fixture, same seed, occasionally sets
1884 // `allow_screen_content_tools`, a round-2 gap unrelated to
1885 // CDF forwarding), so pin it to one thread for a
1886 // deterministic header.
1887 "--threads=1",
1888 "--row-mt=0",
1889 // `--enable-order-hint=0` kills BWDREF/ALTREF entirely (no
1890 // order hints -> no bidirectional distance weighting) and,
1891 // combined with `--auto-alt-ref=0`/`--lag-in-frames=0`
1892 // above, leaves aomenc's RD search only LAST_FRAME/
1893 // LAST2_FRAME/LAST3_FRAME/GOLDEN_FRAME to pick from --
1894 // GOLDEN itself needs no order hint (it is the keyframe's
1895 // fixed slot, not a distance-weighted reference), so this
1896 // does not suppress GOLDEN selection the way the sibling
1897 // CDF-forwarding gate's own comment worried about; it just
1898 // narrows the pool this gate needs GOLDEN to win out of.
1899 "--enable-order-hint=0",
1900 "--enable-warped-motion=0",
1901 "--enable-obmc=0",
1902 "--enable-masked-comp=0",
1903 "--enable-interintra-comp=0",
1904 "--enable-dist-wtd-comp=0",
1905 "--enable-diff-wtd-comp=0",
1906 "--enable-onesided-comp=0",
1907 "--enable-interintra-wedge=0",
1908 "--enable-smooth-interintra=0",
1909 "--enable-rect-partitions=0",
1910 "--enable-ab-partitions=0",
1911 "--enable-1to4-partitions=0",
1912 "--enable-filter-intra=0",
1913 "--enable-smooth-intra=0",
1914 "--enable-paeth-intra=0",
1915 "--enable-directional-intra=0",
1916 "--enable-angle-delta=0",
1917 "--enable-tx-size-search=0",
1918 "--enable-cdef=0",
1919 // Loop restoration is a named refusal (aomenc's RD picks
1920 // Sgrproj on this kind of content) -- off in every recipe
1921 // whose test targets a different surface.
1922 "--enable-restoration=0",
1923 "--max-partition-size=32",
1924 "--enable-palette=0",
1925 "--enable-intrabc=0",
1926 "--enable-cfl-intra=0",
1927 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
1928 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
1929 "--enable-ref-frame-mvs=0",
1930 "--obu",
1931 "-o",
1932 "-",
1933 "-",
1934 ])
1935 .stdin(Stdio::piped())
1936 .stdout(Stdio::piped())
1937 .stderr(Stdio::piped())
1938 .spawn()
1939 .expect("aomenc failed to start");
1940 child
1941 .stdin
1942 .take()
1943 .expect("aomenc stdin")
1944 .write_all(&y4m.stdout)
1945 .expect("writing y4m to aomenc");
1946 let out = child.wait_with_output().expect("aomenc failed to run");
1947 assert!(
1948 out.status.success(),
1949 "aomenc refused the fixture: {}",
1950 String::from_utf8_lossy(&out.stderr)
1951 );
1952 let stream = out.stdout;
1953 let stream_hash = fnv1a64(&stream);
1954 // A named `unsupported` refusal is a documented coverage gap (each
1955 // one carries its own test debt elsewhere), not a forwarding verdict
1956 // -- try the next seed. Any stream that DECODES must be pixel-exact,
1957 // and any non-refusal error is a hard failure.
1958 let frames = match decode_stream(&stream) {
1959 Err(e) => {
1960 let msg = e.to_string();
1961 assert!(
1962 msg.contains("unsupported"),
1963 "cross-frame CDF forwarding failed outright (seed {seed}): {msg}"
1964 );
1965 refusals.push(format!("seed {seed}: {msg}"));
1966 continue;
1967 }
1968 Ok(frames) => frames,
1969 };
1970 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
1971 assert_eq!(frames.len(), frame_count);
1972 // lane-cdfflake: reconstruct ffmpeg's raw reference bytes (the
1973 // three per-frame slices are contiguous chunks of the raw
1974 // `-f rawvideo` output ffmpeg_decode_sequence sliced, so
1975 // concatenating them back is bit-for-bit the same bytes ffmpeg
1976 // actually produced -- no second ffmpeg invocation needed).
1977 let ffmpeg_raw: Vec<u8> = ffmpeg_frames
1978 .iter()
1979 .flat_map(|p| p.y.iter().chain(&p.u).chain(&p.v).copied())
1980 .collect();
1981 let ffmpeg_raw_hash = fnv1a64(&ffmpeg_raw);
1982 eprintln!(
1983 "cdfflake attempt seed={seed}: y4m_hash={y4m_hash:016x} \
1984 stream_hash={stream_hash:016x} ffmpeg_raw_hash={ffmpeg_raw_hash:016x}"
1985 );
1986 // lane-av1golden3: pin the exact raw stream on the first mismatch
1987 // so a flaky-looking gate failure becomes a deterministic, static
1988 // fixture to bisect against -- env-gated, no cost on a normal run.
1989 let mismatched = frames
1990 .iter()
1991 .zip(&ffmpeg_frames)
1992 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
1993 if mismatched {
1994 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
1995 std::fs::write(&path, &stream).expect("writing pinned stream");
1996 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
1997 }
1998 // lane-cdfflake: unconditional pin on mismatch -- the aomenc
1999 // stream AND ffmpeg's raw reference bytes, so a flake caught
2000 // under load names the liar (stream bytes differ from a
2001 // clean rerun -> subprocess instability; reference bytes
2002 // differ -> ffmpeg instability; both stable -> real decode
2003 // defect) without relying on the env var being set.
2004 let sp = "/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/\
2005 51b5f611-f998-43a8-b975-e64cb643a3e1/scratchpad";
2006 std::fs::write(format!("{sp}/cdfflake-stream-seed{seed}.bin"), &stream)
2007 .expect("writing pinned stream");
2008 std::fs::write(format!("{sp}/cdfflake-ffmpeg-raw-seed{seed}.bin"), &ffmpeg_raw)
2009 .expect("writing pinned ffmpeg reference");
2010 eprintln!(
2011 "cdfflake MISMATCH seed={seed}: pinned stream + ffmpeg reference to {sp}"
2012 );
2013 }
2014 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2015 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
2016 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
2017 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
2018 }
2019 return;
2020 }
2021 eprintln!(
2022 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: every \
2023 attempt hit a named refusal:\n{}",
2024 refusals.join("\n")
2025 );
2026 }
2027
2028 /// lane-av1golden3: reproduces the pinned mismatch bytes captured by
2029 /// `EC_AV1_GATE_DUMP=$SP/golden3-pin.obu` off
2030 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
2031 /// (seed 47, frame 1 U). Deterministic and static -- no aomenc/ffmpeg
2032 /// re-encode involved, only re-decodes the fixed bytes on disk, so it is
2033 /// `#[ignore]`d (the file only exists on this machine's scratchpad) but
2034 /// gives a fast red/green loop for the actual fix.
2035 #[test]
2036 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
2037 fn pinned_golden3_stream_decodes_pixel_exact() {
2038 let path = std::env::var("EC_AV1_GATE_DUMP_PIN").unwrap_or_else(|_| {
2039 "/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/\
2040 51b5f611-f998-43a8-b975-e64cb643a3e1/scratchpad/golden3-pin.obu"
2041 .to_string()
2042 });
2043 let stream = std::fs::read(&path).expect("reading pinned stream");
2044 if !have_ffmpeg() {
2045 eprintln!("SKIP pinned_golden3_stream_decodes_pixel_exact: no ffmpeg");
2046 return;
2047 }
2048 let frames = decode_stream(&stream).expect("pinned stream must decode");
2049 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
2050 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2051 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
2052 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
2053 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
2054 }
2055 }
2056
2057 /// lane-av1golden4: reproduces the pinned mismatch bytes captured by
2058 /// `EC_AV1_GATE_DUMP=$SP/golden4-pin.obu` off
2059 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
2060 /// (seed 43, frame 3 luma) the round the GOLDEN mask lifted. Deterministic
2061 /// and static -- `#[ignore]`d, run manually.
2062 #[test]
2063 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
2064 fn pinned_golden4_stream_decodes_pixel_exact() {
2065 use crate::decode::non_last_ref_hits;
2066 let path = std::env::var("EC_AV1_GATE_DUMP_PIN").unwrap_or_else(|_| {
2067 "/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/\
2068 51b5f611-f998-43a8-b975-e64cb643a3e1/scratchpad/golden4-pin.obu"
2069 .to_string()
2070 });
2071 let stream = std::fs::read(&path).expect("reading pinned stream");
2072 if !have_ffmpeg() {
2073 eprintln!("SKIP pinned_golden4_stream_decodes_pixel_exact: no ffmpeg");
2074 return;
2075 }
2076 let before = non_last_ref_hits();
2077 let frames = decode_stream(&stream).expect("pinned stream must decode");
2078 eprintln!(
2079 "non_last_ref_hits before={before} after={}",
2080 non_last_ref_hits()
2081 );
2082 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
2083 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2084 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
2085 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
2086 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
2087 }
2088 }
2089
2090 /// lane-av1golden7 round 9: pins the residual GOLDEN_FRAME MC bug found
2091 /// by the forwarding gate once film grain is out of the way (1/20 real
2092 /// aomenc streams, frame 3 luma, apply_grain=false, `non_last_ref_hits`
2093 /// delta=2). `GOLDEN_FRAME` refuses by name until this decodes exact.
2094 #[test]
2095 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
2096 fn pinned_golden7_stream_decodes_pixel_exact() {
2097 use crate::decode::non_last_ref_hits;
2098 let path = concat!(
2099 env!("CARGO_MANIFEST_DIR"),
2100 "/../../fixtures/golden7-forwarding-mismatch.obu"
2101 );
2102 let stream = std::fs::read(path).expect("reading pinned stream");
2103 if !have_ffmpeg() {
2104 eprintln!("SKIP pinned_golden7_stream_decodes_pixel_exact: no ffmpeg");
2105 return;
2106 }
2107 let before = non_last_ref_hits();
2108 let frames = decode_stream(&stream).expect("pinned stream must decode");
2109 eprintln!(
2110 "non_last_ref_hits before={before} after={}",
2111 non_last_ref_hits()
2112 );
2113 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
2114 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2115 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
2116 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
2117 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
2118 }
2119 }
2120
2121 /// lane-av1refs's decisive single-non-LAST-reference gate: identical
2122 /// recipe to
2123 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
2124 /// except `--enable-order-hint=0` is DROPPED (that flag's own comment on
2125 /// the sibling test names it as exactly what suppresses aomenc's RD from
2126 /// ever picking `GOLDEN_FRAME`) and the sequence runs 8 frames, not 4 --
2127 /// more chances for the RD search to reach past the first GOP's initial
2128 /// key frame. `--auto-alt-ref=0` stays: this decoder only supports
2129 /// `LAST_FRAME`/`GOLDEN_FRAME` so far, and alt-ref/backward references
2130 /// are still a named refusal, not this gate's target. A stream that
2131 /// decodes without firing [`decode::non_last_ref_hits`] is not a
2132 /// coverage win for this round -- SKIP it as a genuine, named miss
2133 /// rather than pass silently on untested ground.
2134 #[test]
2135 fn a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact() {
2136 if !have_ffmpeg() {
2137 eprintln!(
2138 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no ffmpeg"
2139 );
2140 return;
2141 }
2142 if !have_aomenc() {
2143 eprintln!(
2144 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no aomenc at {}",
2145 aomenc_path().display()
2146 );
2147 return;
2148 }
2149 let (width, height, frame_count) = (64usize, 64usize, 8usize);
2150 let mut refusals = Vec::new();
2151 let mut never_fired = 0u32;
2152 // aomenc's own RD search is nondeterministic run-to-run even at
2153 // `--threads=1` (confirmed live: identical CLI args, identical
2154 // input, two different output byte streams) -- so beyond varying
2155 // the fixture's seed, each attempt is its own independent coin
2156 // flip against every named refusal below. 120 attempts (not 40)
2157 // to give that coin flip enough tries to land on a stream this
2158 // decoder both accepts and that fires GOLDEN_FRAME. `duration=0.32`
2159 // at `rate=25` (not `0.24`) matches every sibling gate's own
2160 // frame-count fixture exactly -- a shorter duration here once
2161 // produced a frame-0 (keyframe, no reference at all) luma mismatch
2162 // against ffmpeg, i.e. a source-frame-count rounding artifact of
2163 // this recipe's own choosing, not a decoder bug.
2164 for attempt in 0..120u32 {
2165 let seed = 42 + attempt % 40;
2166 let source = format!("gradients=size=64x64:seed={seed}:duration=0.32:rate=25");
2167 let y4m = Command::new("ffmpeg")
2168 .args([
2169 "-v",
2170 "error",
2171 "-f",
2172 "lavfi",
2173 "-i",
2174 &source,
2175 "-pix_fmt",
2176 "yuv420p",
2177 "-f",
2178 "yuv4mpegpipe",
2179 "-",
2180 ])
2181 .stdin(Stdio::null())
2182 .stdout(Stdio::piped())
2183 .stderr(Stdio::piped())
2184 .output()
2185 .expect("ffmpeg failed to run");
2186 assert!(
2187 y4m.status.success(),
2188 "ffmpeg fixture: {}",
2189 String::from_utf8_lossy(&y4m.stderr)
2190 );
2191 let mut child = Command::new(aomenc_path())
2192 .args([
2193 "--codec=av1",
2194 "--passes=1",
2195 "--end-usage=q",
2196 "--cq-level=55",
2197 "--cpu-used=0",
2198 "--lag-in-frames=0",
2199 "--auto-alt-ref=0",
2200 "--kf-max-dist=1000",
2201 "--threads=1",
2202 "--row-mt=0",
2203 // Narrows the RD search's reference alphabet toward
2204 // LAST_FRAME/GOLDEN_FRAME -- without this, aomenc's RD is
2205 // just as likely to pick LAST2/LAST3/BWDREF/ALTREF2/
2206 // ALTREF (this decoder's already-documented, still-open
2207 // refusals), starving this gate of the one reference it
2208 // targets.
2209 "--max-reference-frames=3",
2210 "--reduced-reference-set=1",
2211 "--enable-warped-motion=0",
2212 "--enable-obmc=0",
2213 "--enable-masked-comp=0",
2214 "--enable-interintra-comp=0",
2215 "--enable-dist-wtd-comp=0",
2216 "--enable-diff-wtd-comp=0",
2217 "--enable-onesided-comp=0",
2218 "--enable-interintra-wedge=0",
2219 "--enable-smooth-interintra=0",
2220 "--enable-rect-partitions=0",
2221 "--enable-ab-partitions=0",
2222 "--enable-1to4-partitions=0",
2223 "--enable-filter-intra=0",
2224 "--enable-smooth-intra=0",
2225 "--enable-paeth-intra=0",
2226 "--enable-directional-intra=0",
2227 "--enable-angle-delta=0",
2228 "--enable-tx-size-search=0",
2229 "--enable-cdef=0",
2230 "--enable-restoration=0",
2231 // `min == max == 32` forces PARTITION_NONE for every
2232 // 32x32 block, not just biases toward it -- with
2233 // `--min-partition-size=16` alone aomenc's exhaustive
2234 // `cpu-used=0` RD search still occasionally read HORZ/
2235 // VERT/SPLIT partitions below 32x32 despite
2236 // `--enable-rect-partitions=0`/`--enable-ab-partitions=0`/
2237 // `--enable-1to4-partitions=0` all being off (two
2238 // separate, already-documented round-2 gaps: "a
2239 // partition below 16x16", "a partition type this encoder
2240 // never writes"), starving this gate's already-narrow
2241 // seed pool. Locking both bounds to 32 removes any
2242 // partition-depth choice from the search entirely, so
2243 // this gate can isolate GOLDEN_FRAME selection alone.
2244 "--max-partition-size=32",
2245 "--min-partition-size=32",
2246 "--enable-palette=0",
2247 "--enable-intrabc=0",
2248 "--enable-cfl-intra=0",
2249 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
2250 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
2251 "--enable-ref-frame-mvs=0",
2252 // `--tune-content=film` was dropped: on this box it
2253 // makes aomenc emit `apply_grain` almost every attempt
2254 // (lane-av1golden8 round 10 measurement, live: 120/120
2255 // real attempts hit a named refusal, 0 ever fired
2256 // GOLDEN_FRAME -- mostly `apply_grain`, dominated by its
2257 // own recipe flag) -- film grain synthesis has its own
2258 // dedicated refusal test and must not starve this gate
2259 // of the GOLDEN_FRAME draws it exists to prove. Default
2260 // content tuning still occasionally flips
2261 // `allow_screen_content_tools` on for this synthetic
2262 // gradient content (a separate, already-documented open
2263 // refusal), which the 120-attempt coin flip below
2264 // tolerates the same way.
2265 "--obu",
2266 "-o",
2267 "-",
2268 "-",
2269 ])
2270 .stdin(Stdio::piped())
2271 .stdout(Stdio::piped())
2272 .stderr(Stdio::piped())
2273 .spawn()
2274 .expect("aomenc failed to start");
2275 child
2276 .stdin
2277 .take()
2278 .expect("aomenc stdin")
2279 .write_all(&y4m.stdout)
2280 .expect("writing y4m to aomenc");
2281 let out = child.wait_with_output().expect("aomenc failed to run");
2282 assert!(
2283 out.status.success(),
2284 "aomenc refused the fixture: {}",
2285 String::from_utf8_lossy(&out.stderr)
2286 );
2287 let stream = out.stdout;
2288 let before = decode::non_last_ref_hits();
2289 let frames = match decode_stream(&stream) {
2290 Err(e) => {
2291 let msg = e.to_string();
2292 assert!(
2293 msg.contains("unsupported"),
2294 "a golden-reference stream failed outright (seed {seed}): {msg}"
2295 );
2296 refusals.push(format!("seed {seed}: {msg}"));
2297 continue;
2298 }
2299 Ok(frames) => frames,
2300 };
2301 if decode::non_last_ref_hits() == before {
2302 // This seed's RD search never actually picked GOLDEN_FRAME --
2303 // a genuine miss, not a refusal. Try the next seed rather
2304 // than claiming coverage this attempt did not exercise.
2305 never_fired += 1;
2306 continue;
2307 }
2308 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2309 assert_eq!(frames.len(), frame_count);
2310 // Same pin-on-mismatch pattern as the CDF forwarding gate above:
2311 // env-gated, no cost on a normal run.
2312 let mismatched = frames
2313 .iter()
2314 .zip(&ffmpeg_frames)
2315 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2316 if mismatched {
2317 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
2318 std::fs::write(&path, &stream).expect("writing pinned stream");
2319 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
2320 }
2321 }
2322 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2323 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
2324 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
2325 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
2326 }
2327 eprintln!(
2328 "FIRING seed {seed}: non_last_ref_hits advanced by {}",
2329 decode::non_last_ref_hits() - before
2330 );
2331 return;
2332 }
2333 eprintln!(
2334 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: \
2335 {never_fired} attempts decoded but never fired GOLDEN_FRAME, and every other \
2336 attempt hit a named refusal:\n{}",
2337 refusals.join("\n")
2338 );
2339 }
2340
2341 /// lane-av1refs's decisive gate for the 5 references widened past
2342 /// `LAST_FRAME`/`GOLDEN_FRAME`: same envelope and pin-on-mismatch
2343 /// pattern as
2344 /// [`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`],
2345 /// generalised over `(target_ref, extra_args, frame_count)` so each of
2346 /// `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` gets its own attempt pool
2347 /// and its own proof that `decode::ref_hits(target_ref)` -- not just
2348 /// `non_last_ref_hits`, which cannot distinguish one reference from
2349 /// another -- actually advanced. `--max-reference-frames=3
2350 /// --reduced-reference-set=1` (the golden gate's own narrowing) is
2351 /// DROPPED here: both suppress exactly the references this gate needs
2352 /// aomenc's RD to reach.
2353 fn a_real_aomenc_single_ref_gate(
2354 gate_name: &str,
2355 target_ref: i8,
2356 target_ref_name: &str,
2357 extra_args: &[&str],
2358 width: usize,
2359 height: usize,
2360 frame_count: usize,
2361 attempts: u32,
2362 ) {
2363 let _gate_lock = lock_gate_counters();
2364 if !have_ffmpeg() {
2365 eprintln!("SKIP {gate_name}: no ffmpeg");
2366 return;
2367 }
2368 if !have_aomenc() {
2369 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
2370 return;
2371 }
2372 let mut refusals = Vec::new();
2373 let mut never_fired = 0u32;
2374 for attempt in 0..attempts {
2375 let seed = 42 + attempt % 40;
2376 let duration = frame_count as f64 / 25.0;
2377 let source =
2378 format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25");
2379 let y4m = Command::new("ffmpeg")
2380 .args([
2381 "-v",
2382 "error",
2383 "-f",
2384 "lavfi",
2385 "-i",
2386 &source,
2387 "-pix_fmt",
2388 "yuv420p",
2389 "-f",
2390 "yuv4mpegpipe",
2391 "-",
2392 ])
2393 .stdin(Stdio::null())
2394 .stdout(Stdio::piped())
2395 .stderr(Stdio::piped())
2396 .output()
2397 .expect("ffmpeg failed to run");
2398 assert!(
2399 y4m.status.success(),
2400 "ffmpeg fixture: {}",
2401 String::from_utf8_lossy(&y4m.stderr)
2402 );
2403 let mut args: Vec<&str> = vec![
2404 "--codec=av1",
2405 "--passes=1",
2406 "--end-usage=q",
2407 "--cq-level=55",
2408 "--cpu-used=0",
2409 "--kf-max-dist=1000",
2410 "--threads=1",
2411 "--row-mt=0",
2412 "--enable-warped-motion=0",
2413 "--enable-obmc=0",
2414 "--enable-masked-comp=0",
2415 "--enable-interintra-comp=0",
2416 "--enable-dist-wtd-comp=0",
2417 "--enable-diff-wtd-comp=0",
2418 "--enable-onesided-comp=0",
2419 "--enable-interintra-wedge=0",
2420 "--enable-smooth-interintra=0",
2421 "--enable-rect-partitions=0",
2422 "--enable-ab-partitions=0",
2423 "--enable-1to4-partitions=0",
2424 "--enable-filter-intra=0",
2425 "--enable-smooth-intra=0",
2426 "--enable-paeth-intra=0",
2427 "--enable-directional-intra=0",
2428 "--enable-angle-delta=0",
2429 "--enable-tx-size-search=0",
2430 "--enable-cdef=0",
2431 "--enable-restoration=0",
2432 "--max-partition-size=32",
2433 "--min-partition-size=32",
2434 "--enable-palette=0",
2435 "--enable-intrabc=0",
2436 "--enable-cfl-intra=0",
2437 // use_ref_frame_mvs (temporal MV projection) is unimplemented in
2438 // mvstack; leaving it on silently desyncs symbols on inter frames.
2439 "--enable-ref-frame-mvs=0",
2440 "--obu",
2441 "-o",
2442 "-",
2443 "-",
2444 ];
2445 // extra_args goes right before the trailing "-o", "-", "-" triple.
2446 let tail = args.split_off(args.len() - 3);
2447 args.extend_from_slice(extra_args);
2448 args.extend_from_slice(&tail);
2449 let mut child = Command::new(aomenc_path())
2450 .args(&args)
2451 .stdin(Stdio::piped())
2452 .stdout(Stdio::piped())
2453 .stderr(Stdio::piped())
2454 .spawn()
2455 .expect("aomenc failed to start");
2456 child
2457 .stdin
2458 .take()
2459 .expect("aomenc stdin")
2460 .write_all(&y4m.stdout)
2461 .expect("writing y4m to aomenc");
2462 let out = child.wait_with_output().expect("aomenc failed to run");
2463 assert!(
2464 out.status.success(),
2465 "aomenc refused the fixture: {}",
2466 String::from_utf8_lossy(&out.stderr)
2467 );
2468 let stream = out.stdout;
2469 let before = decode::ref_hits(target_ref);
2470 let frames = match decode_stream(&stream) {
2471 Err(e) => {
2472 let msg = e.to_string();
2473 assert!(
2474 msg.contains("unsupported"),
2475 "{gate_name} failed outright (seed {seed}): {msg}"
2476 );
2477 refusals.push(format!("seed {seed}: {msg}"));
2478 continue;
2479 }
2480 Ok(frames) => frames,
2481 };
2482 if decode::ref_hits(target_ref) == before {
2483 never_fired += 1;
2484 continue;
2485 }
2486 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2487 assert_eq!(frames.len(), frame_count);
2488 let mismatched = frames
2489 .iter()
2490 .zip(&ffmpeg_frames)
2491 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2492 if mismatched {
2493 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
2494 std::fs::write(&path, &stream).expect("writing pinned stream");
2495 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
2496 }
2497 }
2498 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2499 assert_eq!(
2500 got.y, want.y,
2501 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
2502 );
2503 assert_eq!(
2504 got.u, want.u,
2505 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
2506 );
2507 assert_eq!(
2508 got.v, want.v,
2509 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
2510 );
2511 }
2512 eprintln!(
2513 "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}",
2514 decode::ref_hits(target_ref) - before
2515 );
2516 return;
2517 }
2518 eprintln!(
2519 "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \
2520 and every other attempt hit a named refusal:\n{}",
2521 refusals.join("\n")
2522 );
2523 }
2524
2525 /// lane-av1comp: proves `reference_select`/`comp_mode` are actually read
2526 /// off a real bitstream rather than only unit-tested in isolation --
2527 /// `--auto-alt-ref=1 --lag-in-frames=16` gives aomenc a backward
2528 /// reference to pick `COMPOUND_REFERENCE` with, `--enable-order-hint=1`
2529 /// is required for it to ever consider compound at all. Three
2530 /// acceptable outcomes: (a) a stream where `reference_select` never
2531 /// actually drove a block to `COMPOUND_REFERENCE` decodes bit-exact end
2532 /// to end (proving the per-block `comp_mode` read did not desync the
2533 /// single-ref blocks around it); (b) a stream that does fire compound
2534 /// is refused by name with [`decode::comp_mode_hits`] having advanced
2535 /// (proving `comp_mode`/`read_compound_ref_frames` consumed the right
2536 /// symbols before refusing, rather than desyncing and refusing for an
2537 /// unrelated reason) -- masked/wedge compound (`comp_group_idx == 1`)
2538 /// and a partition below 16x16 (a real, separately tracked capability
2539 /// gap) are the two refusal arms this can still legitimately name; (c)
2540 /// r13 wired plain `COMPOUND_AVERAGE` MC for real, so as of r15 a
2541 /// stream that fires compound may also decode fully -- accepted only
2542 /// when every output frame is pixel-exact against ffmpeg.
2543 #[test]
2544 fn a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly() {
2545 const NAME: &str = "a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly";
2546 let _gate_lock = lock_gate_counters();
2547 if !have_ffmpeg() {
2548 eprintln!("SKIP {NAME}: no ffmpeg");
2549 return;
2550 }
2551 if !have_aomenc() {
2552 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2553 return;
2554 }
2555 let (width, height, frame_count) = (64usize, 64usize, 20usize);
2556 let mut refusals = Vec::new();
2557 let mut never_fired = 0u32;
2558 for attempt in 0..60u32 {
2559 let seed = 42 + attempt % 40;
2560 let duration = frame_count as f64 / 25.0;
2561 let source =
2562 format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25");
2563 let y4m = Command::new("ffmpeg")
2564 .args([
2565 "-v",
2566 "error",
2567 "-f",
2568 "lavfi",
2569 "-i",
2570 &source,
2571 "-pix_fmt",
2572 "yuv420p",
2573 "-f",
2574 "yuv4mpegpipe",
2575 "-",
2576 ])
2577 .stdin(Stdio::null())
2578 .stdout(Stdio::piped())
2579 .stderr(Stdio::piped())
2580 .output()
2581 .expect("ffmpeg failed to run");
2582 assert!(
2583 y4m.status.success(),
2584 "ffmpeg fixture: {}",
2585 String::from_utf8_lossy(&y4m.stderr)
2586 );
2587 let args: Vec<&str> = vec![
2588 "--codec=av1",
2589 "--passes=1",
2590 "--end-usage=q",
2591 "--cq-level=45",
2592 "--cpu-used=0",
2593 "--kf-max-dist=1000",
2594 "--threads=1",
2595 "--row-mt=0",
2596 "--auto-alt-ref=1",
2597 "--lag-in-frames=16",
2598 "--enable-order-hint=1",
2599 "--enable-warped-motion=0",
2600 "--enable-obmc=0",
2601 "--enable-masked-comp=0",
2602 "--enable-interintra-comp=0",
2603 "--enable-onesided-comp=0",
2604 "--enable-interintra-wedge=0",
2605 "--enable-smooth-interintra=0",
2606 "--enable-rect-partitions=0",
2607 "--enable-ab-partitions=0",
2608 "--enable-1to4-partitions=0",
2609 "--enable-filter-intra=0",
2610 "--enable-smooth-intra=0",
2611 "--enable-paeth-intra=0",
2612 "--enable-directional-intra=0",
2613 "--enable-angle-delta=0",
2614 "--enable-tx-size-search=0",
2615 "--enable-cdef=0",
2616 "--enable-restoration=0",
2617 "--max-partition-size=32",
2618 "--min-partition-size=32",
2619 "--enable-palette=0",
2620 "--enable-intrabc=0",
2621 "--enable-cfl-intra=0",
2622 "--enable-ref-frame-mvs=0",
2623 "--obu",
2624 "-o",
2625 "-",
2626 "-",
2627 ];
2628 let mut child = Command::new(aomenc_path())
2629 .args(&args)
2630 .stdin(Stdio::piped())
2631 .stdout(Stdio::piped())
2632 .stderr(Stdio::piped())
2633 .spawn()
2634 .expect("aomenc failed to start");
2635 child
2636 .stdin
2637 .take()
2638 .expect("aomenc stdin")
2639 .write_all(&y4m.stdout)
2640 .expect("writing y4m to aomenc");
2641 let out = child.wait_with_output().expect("aomenc failed to run");
2642 assert!(
2643 out.status.success(),
2644 "aomenc refused the fixture: {}",
2645 String::from_utf8_lossy(&out.stderr)
2646 );
2647 let stream = out.stdout;
2648 let before = decode::comp_mode_hits();
2649 match decode_stream(&stream) {
2650 Err(e) => {
2651 let msg = e.to_string();
2652 let fired = decode::comp_mode_hits() > before;
2653 assert!(
2654 msg.contains("unsupported"),
2655 "{NAME} failed outright (seed {seed}): {msg}"
2656 );
2657 if fired {
2658 // `comp_mode` firing does not stop the block walk --
2659 // a later, unrelated block in the same tile can
2660 // still hit any other named refusal this decoder
2661 // carries. A partition below 16x16 is a real, open
2662 // capability gap tracked on its own (not a
2663 // COMPOUND_REFERENCE defect); accept it here too
2664 // rather than fail a compound-specific gate on a
2665 // partition-search coincidence. lane-av1blend r7:
2666 // re-swept the wide gate with the plain-average
2667 // blend unmasked (r6/r7's ref_ctx fix alone) and it
2668 // still mismatches on real streams beyond that one
2669 // bug -- re-masked comp_group_idx == 0 too, so this
2670 // stays a legal named refusal.
2671 assert!(
2672 msg.contains("COMPOUND_REFERENCE") || msg.contains("a partition"),
2673 "{NAME}: comp_mode fired (seed {seed}) but the refusal \
2674 was for something else: {msg}"
2675 );
2676 let advanced = decode::comp_mode_hits() - before;
2677 eprintln!(
2678 "{NAME} FIRING seed {seed}: comp_mode hits advanced by \
2679 {advanced}, refused by name as expected: {msg}"
2680 );
2681 return;
2682 }
2683 refusals.push(format!("seed {seed}: {msg}"));
2684 continue;
2685 }
2686 Ok(frames) => {
2687 if decode::comp_mode_hits() == before {
2688 never_fired += 1;
2689 continue;
2690 }
2691 // Outcome (c): plain COMPOUND_AVERAGE decoded fully --
2692 // non-negotiable pixel exactness, no tolerance.
2693 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2694 assert_eq!(frames.len(), frame_count);
2695 let mismatched = frames
2696 .iter()
2697 .zip(&ffmpeg_frames)
2698 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2699 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
2700 std::fs::write(&path, &stream).expect("writing pinned stream");
2701 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
2702 }
2703 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2704 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
2705 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
2706 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
2707 }
2708 eprintln!(
2709 "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \
2710 fully and pixel-exact",
2711 decode::comp_mode_hits() - before
2712 );
2713 return;
2714 }
2715 }
2716 }
2717 eprintln!(
2718 "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \
2719 block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \
2720 reached comp_mode:\n{}",
2721 refusals.join("\n")
2722 );
2723 }
2724
2725 /// lane-av1comp round 14's decisive gate for `skip_mode`: same
2726 /// pin-on-mismatch pattern as [`a_real_aomenc_single_ref_gate`], proving
2727 /// [`decode::skip_mode_hits`] actually advanced (a real block picked
2728 /// `skip_mode`, not just that the frame header bit was set) and that the
2729 /// resulting forced-compound `NEAREST_NEARESTMV` decode is still
2730 /// pixel-exact against ffmpeg. `--auto-alt-ref=1 --lag-in-frames=16
2731 /// --enable-fwd-kf=0` (backward references) plus
2732 /// `--enable-ref-frame-mvs=0` (unimplemented temporal MV projection,
2733 /// same as every other gate here) is aomenc's own requirement for
2734 /// `skip_mode_present` to ever be considered at all (spec 5.9.22 needs
2735 /// both a forward and a backward reference candidate).
2736 #[test]
2737 fn a_real_aomenc_stream_with_compound_references_decodes_pixel_exact() {
2738 const NAME: &str = "a_real_aomenc_stream_with_compound_references_decodes_pixel_exact";
2739 let _gate_lock = lock_gate_counters();
2740 if !have_ffmpeg() {
2741 eprintln!("SKIP {NAME}: no ffmpeg");
2742 return;
2743 }
2744 if !have_aomenc() {
2745 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2746 return;
2747 }
2748 let (width, height, frame_count) = (64usize, 64usize, 24usize);
2749 let mut refusals = Vec::new();
2750 let mut never_fired = 0u32;
2751 for attempt in 0..80u32 {
2752 let seed = 42 + attempt % 40;
2753 let duration = frame_count as f64 / 25.0;
2754 let source =
2755 format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25");
2756 let y4m = Command::new("ffmpeg")
2757 .args([
2758 "-v",
2759 "error",
2760 "-f",
2761 "lavfi",
2762 "-i",
2763 &source,
2764 "-pix_fmt",
2765 "yuv420p",
2766 "-f",
2767 "yuv4mpegpipe",
2768 "-",
2769 ])
2770 .stdin(Stdio::null())
2771 .stdout(Stdio::piped())
2772 .stderr(Stdio::piped())
2773 .output()
2774 .expect("ffmpeg failed to run");
2775 assert!(
2776 y4m.status.success(),
2777 "ffmpeg fixture: {}",
2778 String::from_utf8_lossy(&y4m.stderr)
2779 );
2780 let args: Vec<&str> = vec![
2781 "--codec=av1",
2782 "--passes=1",
2783 "--end-usage=q",
2784 "--cq-level=45",
2785 "--cpu-used=0",
2786 "--kf-max-dist=1000",
2787 "--threads=1",
2788 "--row-mt=0",
2789 "--auto-alt-ref=1",
2790 "--lag-in-frames=16",
2791 "--enable-fwd-kf=0",
2792 "--enable-order-hint=1",
2793 "--enable-warped-motion=0",
2794 "--enable-obmc=0",
2795 "--enable-masked-comp=0",
2796 "--enable-interintra-comp=0",
2797 "--enable-onesided-comp=0",
2798 "--enable-interintra-wedge=0",
2799 "--enable-smooth-interintra=0",
2800 "--enable-rect-partitions=0",
2801 "--enable-ab-partitions=0",
2802 "--enable-1to4-partitions=0",
2803 "--enable-filter-intra=0",
2804 "--enable-smooth-intra=0",
2805 "--enable-paeth-intra=0",
2806 "--enable-directional-intra=0",
2807 "--enable-angle-delta=0",
2808 "--enable-tx-size-search=0",
2809 "--enable-cdef=0",
2810 "--enable-restoration=0",
2811 "--max-partition-size=32",
2812 "--min-partition-size=32",
2813 "--enable-palette=0",
2814 "--enable-intrabc=0",
2815 "--enable-cfl-intra=0",
2816 "--enable-ref-frame-mvs=0",
2817 "--obu",
2818 "-o",
2819 "-",
2820 "-",
2821 ];
2822 let mut child = Command::new(aomenc_path())
2823 .args(&args)
2824 .stdin(Stdio::piped())
2825 .stdout(Stdio::piped())
2826 .stderr(Stdio::piped())
2827 .spawn()
2828 .expect("aomenc failed to start");
2829 child
2830 .stdin
2831 .take()
2832 .expect("aomenc stdin")
2833 .write_all(&y4m.stdout)
2834 .expect("writing y4m to aomenc");
2835 let out = child.wait_with_output().expect("aomenc failed to run");
2836 assert!(
2837 out.status.success(),
2838 "aomenc refused the fixture: {}",
2839 String::from_utf8_lossy(&out.stderr)
2840 );
2841 let stream = out.stdout;
2842 let before = decode::skip_mode_hits();
2843 let frames = match decode_stream(&stream) {
2844 Err(e) => {
2845 let msg = e.to_string();
2846 assert!(
2847 msg.contains("unsupported"),
2848 "{NAME} failed outright (seed {seed}): {msg}"
2849 );
2850 refusals.push(format!("seed {seed}: {msg}"));
2851 continue;
2852 }
2853 Ok(frames) => frames,
2854 };
2855 if decode::skip_mode_hits() == before {
2856 never_fired += 1;
2857 continue;
2858 }
2859 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2860 assert_eq!(frames.len(), frame_count);
2861 let mismatched = frames
2862 .iter()
2863 .zip(&ffmpeg_frames)
2864 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2865 if mismatched {
2866 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
2867 std::fs::write(&path, &stream).expect("writing pinned stream");
2868 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
2869 }
2870 }
2871 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2872 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
2873 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
2874 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
2875 }
2876 eprintln!(
2877 "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}",
2878 decode::skip_mode_hits() - before
2879 );
2880 return;
2881 }
2882 eprintln!(
2883 "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \
2884 other attempt hit a named refusal:\n{}",
2885 refusals.join("\n")
2886 );
2887 }
2888
2889 /// `LAST2_FRAME`/`LAST3_FRAME` are just older slots in the same forward
2890 /// reference-buffer ring `LAST_FRAME`/`GOLDEN_FRAME` already prove --
2891 /// dropping the golden gate's `--max-reference-frames=3
2892 /// --reduced-reference-set=1` narrowing (which suppresses exactly these)
2893 /// and running long enough for aomenc's own buffer rotation to reach
2894 /// past the first 2 frames is the whole difference.
2895 #[test]
2896 fn a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact() {
2897 a_real_aomenc_single_ref_gate(
2898 "a_real_aomenc_stream_with_a_last2_reference_decodes_pixel_exact",
2899 crate::mvstack::LAST2_FRAME,
2900 "LAST2_FRAME",
2901 &["--auto-alt-ref=0", "--lag-in-frames=0"],
2902 64,
2903 64,
2904 8,
2905 120,
2906 );
2907 }
2908
2909 #[test]
2910 fn a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact() {
2911 a_real_aomenc_single_ref_gate(
2912 "a_real_aomenc_stream_with_a_last3_reference_decodes_pixel_exact",
2913 crate::mvstack::LAST3_FRAME,
2914 "LAST3_FRAME",
2915 &["--auto-alt-ref=0", "--lag-in-frames=0"],
2916 64,
2917 64,
2918 8,
2919 120,
2920 );
2921 }
2922
2923 /// `BWDREF`/`ALTREF2`/`ALTREF` are all backward (display-order-forward)
2924 /// references that only exist once aomenc builds a hierarchical GOP --
2925 /// `--auto-alt-ref=1 --lag-in-frames` (need at least one full mini-GOP
2926 /// of lookahead) is what makes aomenc code them at all; without it
2927 /// every attempt would hit this decoder's own real, still-open
2928 /// per-block sign-bias gap by never drawing the reference in the first
2929 /// place, not by proving it correct.
2930 #[test]
2931 fn a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact() {
2932 a_real_aomenc_single_ref_gate(
2933 "a_real_aomenc_stream_with_a_bwdref_reference_decodes_pixel_exact",
2934 crate::mvstack::BWDREF_FRAME,
2935 "BWDREF_FRAME",
2936 &[
2937 "--auto-alt-ref=1",
2938 "--lag-in-frames=16",
2939 "--enable-fwd-kf=0",
2940 ],
2941 64,
2942 64,
2943 16,
2944 120,
2945 );
2946 }
2947
2948 #[test]
2949 fn a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact() {
2950 a_real_aomenc_single_ref_gate(
2951 "a_real_aomenc_stream_with_an_altref2_reference_decodes_pixel_exact",
2952 crate::mvstack::ALTREF2_FRAME,
2953 "ALTREF2_FRAME",
2954 &[
2955 "--auto-alt-ref=1",
2956 "--lag-in-frames=16",
2957 "--enable-fwd-kf=0",
2958 ],
2959 64,
2960 64,
2961 16,
2962 120,
2963 );
2964 }
2965
2966 #[test]
2967 fn a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact() {
2968 a_real_aomenc_single_ref_gate(
2969 "a_real_aomenc_stream_with_an_altref_reference_decodes_pixel_exact",
2970 crate::mvstack::ALTREF_FRAME,
2971 "ALTREF_FRAME",
2972 &[
2973 "--auto-alt-ref=1",
2974 "--lag-in-frames=16",
2975 "--enable-fwd-kf=0",
2976 ],
2977 64,
2978 64,
2979 16,
2980 120,
2981 );
2982 }
2983
2984 /// lane-av1tmvp: the temporal-MV gate -- unlike every `_single_ref_gate`
2985 /// attempt above, this one leaves `--enable-ref-frame-mvs` at aomenc's
2986 /// own default (on) instead of pinning it off, so `use_ref_frame_mvs`
2987 /// actually fires and `decode::tmv_hits()` (this gate's own capability
2988 /// proof, not just `non_last_ref_hits`) has to advance for the run to
2989 /// count as a real pass rather than a `never_fired` skip.
2990 fn a_real_aomenc_temporal_mv_gate(seed_base: u32, attempts: u32) {
2991 let gate_name = "a_real_aomenc_temporal_mv_gate";
2992 let _gate_lock = lock_gate_counters();
2993 if !have_ffmpeg() {
2994 eprintln!("SKIP {gate_name}: no ffmpeg");
2995 return;
2996 }
2997 if !have_aomenc() {
2998 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
2999 return;
3000 }
3001 let (width, height, frame_count) = (64usize, 64usize, 16usize);
3002 let mut never_fired = 0u32;
3003 let mut refusals = Vec::new();
3004 for attempt in 0..attempts {
3005 let seed = seed_base + attempt;
3006 let duration = frame_count as f64 / 25.0;
3007 let source =
3008 format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25");
3009 let y4m = Command::new("ffmpeg")
3010 .args([
3011 "-v",
3012 "error",
3013 "-f",
3014 "lavfi",
3015 "-i",
3016 &source,
3017 "-pix_fmt",
3018 "yuv420p",
3019 "-f",
3020 "yuv4mpegpipe",
3021 "-",
3022 ])
3023 .stdin(Stdio::null())
3024 .stdout(Stdio::piped())
3025 .stderr(Stdio::piped())
3026 .output()
3027 .expect("ffmpeg failed to run");
3028 assert!(
3029 y4m.status.success(),
3030 "ffmpeg fixture: {}",
3031 String::from_utf8_lossy(&y4m.stderr)
3032 );
3033 // Same envelope as `a_real_aomenc_single_ref_gate`, minus its
3034 // `--enable-ref-frame-mvs=0` pin -- everything else this decoder
3035 // still cannot code stays refused the same way.
3036 let args: Vec<&str> = vec![
3037 "--codec=av1",
3038 "--passes=1",
3039 "--end-usage=q",
3040 "--cq-level=55",
3041 "--cpu-used=0",
3042 "--kf-max-dist=1000",
3043 "--threads=1",
3044 "--row-mt=0",
3045 "--auto-alt-ref=1",
3046 "--lag-in-frames=16",
3047 "--enable-fwd-kf=0",
3048 "--enable-warped-motion=0",
3049 "--enable-obmc=0",
3050 "--enable-masked-comp=0",
3051 "--enable-interintra-comp=0",
3052 "--enable-dist-wtd-comp=0",
3053 "--enable-diff-wtd-comp=0",
3054 "--enable-onesided-comp=0",
3055 "--enable-interintra-wedge=0",
3056 "--enable-smooth-interintra=0",
3057 "--enable-rect-partitions=0",
3058 "--enable-ab-partitions=0",
3059 "--enable-1to4-partitions=0",
3060 "--enable-filter-intra=0",
3061 "--enable-smooth-intra=0",
3062 "--enable-paeth-intra=0",
3063 "--enable-directional-intra=0",
3064 "--enable-angle-delta=0",
3065 "--enable-tx-size-search=0",
3066 "--enable-cdef=0",
3067 "--enable-restoration=0",
3068 "--max-partition-size=32",
3069 "--min-partition-size=32",
3070 "--enable-palette=0",
3071 "--enable-intrabc=0",
3072 "--enable-cfl-intra=0",
3073 "--obu",
3074 "-o",
3075 "-",
3076 "-",
3077 ];
3078 let mut child = Command::new(aomenc_path())
3079 .args(&args)
3080 .stdin(Stdio::piped())
3081 .stdout(Stdio::piped())
3082 .stderr(Stdio::piped())
3083 .spawn()
3084 .expect("aomenc failed to start");
3085 child
3086 .stdin
3087 .take()
3088 .expect("aomenc stdin")
3089 .write_all(&y4m.stdout)
3090 .expect("writing y4m to aomenc");
3091 let out = child.wait_with_output().expect("aomenc failed to run");
3092 assert!(
3093 out.status.success(),
3094 "aomenc refused the fixture: {}",
3095 String::from_utf8_lossy(&out.stderr)
3096 );
3097 let stream = out.stdout;
3098 let before = decode::tmv_hits();
3099 let frames = match decode_stream(&stream) {
3100 Err(e) => {
3101 let msg = e.to_string();
3102 assert!(
3103 msg.contains("unsupported"),
3104 "{gate_name} failed outright (seed {seed}): {msg}"
3105 );
3106 refusals.push(format!("seed {seed}: {msg}"));
3107 continue;
3108 }
3109 Ok(frames) => frames,
3110 };
3111 if decode::tmv_hits() == before {
3112 never_fired += 1;
3113 continue;
3114 }
3115 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
3116 assert_eq!(frames.len(), frame_count);
3117 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
3118 let mismatched = frames
3119 .iter()
3120 .zip(&ffmpeg_frames)
3121 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
3122 if mismatched {
3123 std::fs::write(&path, &stream).expect("writing pinned stream");
3124 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
3125 }
3126 }
3127 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
3128 assert_eq!(
3129 got.y, want.y,
3130 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
3131 );
3132 assert_eq!(
3133 got.u, want.u,
3134 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
3135 );
3136 assert_eq!(
3137 got.v, want.v,
3138 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
3139 );
3140 }
3141 eprintln!(
3142 "{gate_name} FIRING seed {seed}: tmv_hits advanced by {}",
3143 decode::tmv_hits() - before
3144 );
3145 return;
3146 }
3147 eprintln!(
3148 "SKIP {gate_name}: {never_fired} attempts decoded but never fired a temporal MV \
3149 candidate, and every other attempt hit a named refusal:\n{}",
3150 refusals.join("\n")
3151 );
3152 }
3153
3154 #[test]
3155 fn a_real_aomenc_stream_with_temporal_mvs_decodes_pixel_exact() {
3156 a_real_aomenc_temporal_mv_gate(42, 40);
3157 }
3158
3159 /// bisect scratch: decode a pinned stream exactly once -- generic
3160 /// pin-repro tool, kept for manual use.
3161 #[test]
3162 #[ignore]
3163 fn scratch_decode_pinned_stream_once() {
3164 let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path");
3165 let stream = std::fs::read(&path).expect("read pinned stream");
3166 match decode_stream(&stream) {
3167 Ok(frames) => eprintln!("OK: {} frames", frames.len()),
3168 Err(e) => eprintln!("ERR: {e}"),
3169 }
3170 }
3171
3172 /// scratch: isolate a pinned mismatching stream's first divergent pixel.
3173 #[test]
3174 #[ignore]
3175 fn scratch_isolate_pinned_mismatch() {
3176 let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path");
3177 let stream = std::fs::read(&path).expect("read pinned stream");
3178 {
3179 let mut p = Av1Parser::new();
3180 let mut pos = 0usize;
3181 while pos < stream.len() {
3182 let obu = p.parse_obu(&stream[pos..]).expect("parse");
3183 pos += obu.total_size;
3184 if let ObuKind::Frame(header, _) = obu.kind {
3185 eprintln!("interpolation_filter: {:?}", header.interpolation_filter);
3186 eprintln!("cdef: {:?}", header.cdef);
3187 eprintln!("quantization: {:?}", header.quantization);
3188 eprintln!(
3189 "coded_lossless: {:?} tx_mode: {:?}",
3190 header.coded_lossless, header.tx_mode
3191 );
3192 eprintln!("delta: {:?}", header.delta);
3193 eprintln!("segmentation: {:?}", header.segmentation);
3194 eprintln!("loop_restoration: {:?}", header.loop_restoration);
3195 eprintln!(
3196 "use_128x128_superblock: {:?} disable_cdf_update: {:?} disable_frame_end_update_cdf: {:?} primary_ref_frame: {:?} allow_high_precision_mv: {:?} force_integer_mv: {:?}",
3197 p.sequence_header().map(|s| s.use_128x128_superblock),
3198 header.disable_cdf_update,
3199 header.disable_frame_end_update_cdf,
3200 header.primary_ref_frame,
3201 header.allow_high_precision_mv,
3202 header.force_integer_mv,
3203 );
3204 }
3205 }
3206 }
3207 let width = std::env::var("EC_AV1_PIN_W")
3208 .map(|s| s.parse().unwrap())
3209 .unwrap_or(64);
3210 let height = std::env::var("EC_AV1_PIN_H")
3211 .map(|s| s.parse().unwrap())
3212 .unwrap_or(64);
3213 let frame_count = std::env::var("EC_AV1_PIN_N")
3214 .map(|s| s.parse().unwrap())
3215 .unwrap_or(4);
3216 let frames = decode_stream(&stream).expect("our decode");
3217 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
3218 for f in 0..frame_count.min(frames.len()).min(ffmpeg_frames.len()) {
3219 let ours = &frames[f];
3220 let theirs = &ffmpeg_frames[f];
3221 for (plane_name, a, b, w) in [
3222 ("y", &ours.y, &theirs.y, width),
3223 ("u", &ours.u, &theirs.u, width / 2),
3224 ("v", &ours.v, &theirs.v, width / 2),
3225 ] {
3226 let mut first = None;
3227 let mut count = 0;
3228 let mut worst = 0i32;
3229 for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
3230 if x != y {
3231 count += 1;
3232 if first.is_none() {
3233 first = Some(i);
3234 }
3235 worst = worst.max((*x as i32 - *y as i32).abs());
3236 }
3237 }
3238 if let Some(i) = first {
3239 eprintln!(
3240 "frame {f} plane {plane_name}: {count} mismatches (worst delta {worst}), first at offset {i} (row {}, col {}) ours={} theirs={}",
3241 i / w,
3242 i % w,
3243 a[i],
3244 b[i]
3245 );
3246 } else {
3247 eprintln!("frame {f} plane {plane_name}: MATCH");
3248 }
3249 }
3250 }
3251 }
3252
3253 /// Final round of the TX4/tx-class lane's own gate: `--min-partition-size=8
3254 /// --max-partition-size=8` pins every leaf to exactly 8x8 (spec
3255 /// 5.11.4's own boundary carve-out aside, which a multiple-of-8 frame
3256 /// never triggers), so a real `aomenc` stream from this recipe can only
3257 /// legitimately read `PARTITION_NONE` at every `bsize=3` node -- any
3258 /// other value this decoder sees there is a genuine desync, not a
3259 /// "partition below 8x8" the encoder actually wrote (traced live against
3260 /// a debug `aomdec` 2026-08-27: the true bitstream's own 8x8 partition
3261 /// reads are all `NONE`; the mismatch was `base_ctx`'s DC-position
3262 /// short-circuit firing for `TX_CLASS_HORIZ`/`VERT` too, off by one
3263 /// `BR` read into a spurious extra Golomb call). The sinusoidal-stripe
3264 /// `geq` source (a smooth luma ramp, not the sharp two-tone stripes that
3265 /// tripped `aomenc`'s screen-content-tools auto-detect) is what actually
3266 /// resolves `V_DCT`/`H_DCT` (`TxClass::of`) on some 8x8 TUs at this
3267 /// content's frequency; the attempt loop moves on from named refusals
3268 /// (`allow_screen_content_tools`, angle-delta) same as every other
3269 /// multi-seed recipe in this file, and only counts a run as a genuine
3270 /// firing when [`decode::tx_class1_hits`] actually moved.
3271 #[test]
3272 fn a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact() {
3273 if !have_ffmpeg() {
3274 eprintln!(
3275 "SKIP a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact: no ffmpeg"
3276 );
3277 return;
3278 }
3279 if !have_aomenc() {
3280 eprintln!(
3281 "SKIP a_real_aomenc_min8_stream_with_tx_class1_decodes_pixel_exact: no aomenc at {}",
3282 aomenc_path().display()
3283 );
3284 return;
3285 }
3286 let (width, height) = (64usize, 64usize);
3287 let mut refusals = Vec::new();
3288 let mut fired_runs = 0u32;
3289 for attempt in 0..60u32 {
3290 let cq = 20 + (attempt % 5) * 10;
3291 let period = [4u32, 6, 8, 12, 16][(attempt as usize / 5) % 5];
3292 let y4m = Command::new("ffmpeg")
3293 .args([
3294 "-v",
3295 "error",
3296 "-f",
3297 "lavfi",
3298 "-i",
3299 "testsrc2=size=64x64:rate=25",
3300 "-vf",
3301 &format!(
3302 "geq=lum='128+80*sin(2*PI*Y/{period})':cb=128:cr=128,noise=alls=6:allf=t"
3303 ),
3304 "-pix_fmt",
3305 "yuv420p",
3306 "-t",
3307 "0.04",
3308 "-f",
3309 "yuv4mpegpipe",
3310 "-",
3311 ])
3312 .stdin(Stdio::null())
3313 .stdout(Stdio::piped())
3314 .stderr(Stdio::piped())
3315 .output()
3316 .expect("ffmpeg failed to run");
3317 assert!(
3318 y4m.status.success(),
3319 "ffmpeg fixture: {}",
3320 String::from_utf8_lossy(&y4m.stderr)
3321 );
3322 let mut child = Command::new(aomenc_path())
3323 .args([
3324 "--codec=av1",
3325 "--passes=1",
3326 "--end-usage=q",
3327 &format!("--cq-level={cq}"),
3328 "--cpu-used=0",
3329 "--enable-directional-intra=0",
3330 "--enable-smooth-intra=0",
3331 "--enable-paeth-intra=0",
3332 "--enable-rect-partitions=0",
3333 "--enable-angle-delta=0",
3334 "--enable-palette=0",
3335 "--reduced-tx-type-set=0",
3336 "--enable-restoration=0",
3337 "--enable-cdef=0",
3338 "--loopfilter-control=0",
3339 "--min-partition-size=8",
3340 "--max-partition-size=8",
3341 "--enable-ab-partitions=0",
3342 "--enable-1to4-partitions=0",
3343 "--enable-filter-intra=0",
3344 "--enable-intrabc=0",
3345 "--enable-cfl-intra=0",
3346 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
3347 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
3348 "--enable-ref-frame-mvs=0",
3349 "--tune-content=default",
3350 "--obu",
3351 "-o",
3352 "-",
3353 "-",
3354 ])
3355 .stdin(Stdio::piped())
3356 .stdout(Stdio::piped())
3357 .stderr(Stdio::piped())
3358 .spawn()
3359 .expect("aomenc failed to start");
3360 child
3361 .stdin
3362 .take()
3363 .expect("aomenc stdin")
3364 .write_all(&y4m.stdout)
3365 .expect("writing y4m to aomenc");
3366 let out = child.wait_with_output().expect("aomenc failed to run");
3367 if !out.status.success() {
3368 refusals.push(format!(
3369 "cq={cq} period={period}: aomenc itself refused the fixture"
3370 ));
3371 continue;
3372 }
3373 let stream = out.stdout;
3374 let before = decode::tx_class1_hits();
3375 let frames = match decode_stream(&stream) {
3376 Ok(frames) => frames,
3377 Err(e) => {
3378 refusals.push(format!("cq={cq} period={period}: {e}"));
3379 continue;
3380 }
3381 };
3382 if decode::tx_class1_hits() == before {
3383 refusals.push(format!(
3384 "cq={cq} period={period}: decoded, but no block read a V_DCT/H_DCT tx_type"
3385 ));
3386 continue;
3387 }
3388 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
3389 assert_eq!(
3390 frames[0].y, ffmpeg_frames[0].y,
3391 "luma vs ffmpeg (cq={cq} period={period})"
3392 );
3393 assert_eq!(
3394 frames[0].u, ffmpeg_frames[0].u,
3395 "U vs ffmpeg (cq={cq} period={period})"
3396 );
3397 assert_eq!(
3398 frames[0].v, ffmpeg_frames[0].v,
3399 "V vs ffmpeg (cq={cq} period={period})"
3400 );
3401 fired_runs += 1;
3402 if fired_runs >= 4 {
3403 return;
3404 }
3405 }
3406 panic!(
3407 "fewer than 4 firing+pixel-exact runs out of 60 attempts:\n{}",
3408 refusals.join("\n")
3409 );
3410 }
3411
3412 /// lane-av1golden7 r9's decisive fixture: a real aomenc stream (seed 59,
3413 /// `--tune-content=film`, GOLDEN_FRAME firing downstream) whose frame-0
3414 /// *intra keyframe* mismatched ffmpeg on 3855/4096 luma pixels -- traced
3415 /// to `apply_grain=true` (spec 7.18.3 grain synthesis, now implemented in
3416 /// `crate::film_grain`), entirely unrelated to GOLDEN_FRAME or frame
3417 /// ordering. Frames beyond 0 in this fixture hit an unrelated, pre-existing
3418 /// gap (`decode_inter_block`'s GOLDEN_FRAME MC path, lane-av1golden7's own
3419 /// `golden7-forwarding-mismatch.obu`), so this test truncates the stream to
3420 /// the sequence header + frame-0 OBUs only -- exactly the span the
3421 /// mismatch was traced to -- rather than reaching into `decode.rs`/`mc.rs`
3422 /// to widen MC support, which is out of this lane's scope.
3423 #[test]
3424 fn a_real_aomenc_stream_with_film_grain_decodes_pixel_exact() {
3425 if !have_ffmpeg() {
3426 eprintln!("SKIP a_real_aomenc_stream_with_film_grain_decodes_pixel_exact: no ffmpeg");
3427 return;
3428 }
3429 let data = std::fs::read(concat!(
3430 env!("CARGO_MANIFEST_DIR"),
3431 "/../../fixtures/golden6-mismatch.obu"
3432 ))
3433 .unwrap();
3434 // Truncate right after the first `Frame` OBU (the key frame): every
3435 // byte up to there is sequence header + frame-0, which is a complete,
3436 // independently decodable single-frame stream.
3437 let mut parser = Av1Parser::new();
3438 let mut pos = 0usize;
3439 let mut frame0_end = None;
3440 while pos < data.len() {
3441 let obu = parser.parse_obu(&data[pos..]).unwrap();
3442 pos += obu.total_size;
3443 if matches!(obu.kind, ObuKind::Frame(..)) {
3444 frame0_end = Some(pos);
3445 break;
3446 }
3447 }
3448 let data = &data[..frame0_end.expect("fixture has at least one frame OBU")];
3449 let (width, height) = (64usize, 64usize);
3450 let ffmpeg_frames = ffmpeg_decode_sequence(data, width, height, 1);
3451 let decoded = decode_stream(data).unwrap();
3452 assert_eq!(decoded.len(), 1);
3453 let (got, want) = (&decoded[0], &ffmpeg_frames[0]);
3454 assert_eq!(got.y, want.y, "frame 0 luma vs ffmpeg (film grain)");
3455 assert_eq!(got.u, want.u, "frame 0 U vs ffmpeg (film grain)");
3456 assert_eq!(got.v, want.v, "frame 0 V vs ffmpeg (film grain)");
3457 }
3458
3459 /// A real-encoder sweep, not just the one pinned fixture above
3460 /// (fixture-proves-symbol-not-signal class): several fresh
3461 /// `--tune-content=film` draws at different seeds/content, each decoded
3462 /// pixel-exact against ffmpeg's own AV1 decoder (which synthesizes grain
3463 /// by default -- confirmed via `ffmpeg -h decoder=av1`, no
3464 /// `-export_side_data`/grain-disable flag is passed anywhere in this
3465 /// file).
3466 #[test]
3467 fn real_aomenc_film_grain_streams_decode_pixel_exact() {
3468 if !have_ffmpeg() {
3469 eprintln!("SKIP real_aomenc_film_grain_streams_decode_pixel_exact: no ffmpeg");
3470 return;
3471 }
3472 if !have_aomenc() {
3473 eprintln!("SKIP real_aomenc_film_grain_streams_decode_pixel_exact: no aomenc");
3474 return;
3475 }
3476 let (width, height) = (64usize, 64usize);
3477 for seed in [1u64, 2, 3] {
3478 let dir = std::env::temp_dir().join(format!(
3479 "ec-av1-filmgrain-gate-{}-{seed}",
3480 std::process::id()
3481 ));
3482 std::fs::create_dir_all(&dir).unwrap();
3483 let yuv_path = dir.join("in.yuv");
3484 let obu_path = dir.join("out.obu");
3485 let frames = 3usize;
3486 let luma = width * height;
3487 let chroma = luma / 4;
3488 let mut yuv = Vec::with_capacity((luma + 2 * chroma) * frames);
3489 for f in 0..frames {
3490 let card = panned_test_card(width, height, ((f as i32 + seed as i32) * 5) as i64);
3491 yuv.extend_from_slice(&card.y);
3492 yuv.extend_from_slice(&card.u);
3493 yuv.extend_from_slice(&card.v);
3494 }
3495 std::fs::write(&yuv_path, &yuv).unwrap();
3496 let status = Command::new(aomenc_path())
3497 .args([
3498 &format!("--width={width}"),
3499 &format!("--height={height}"),
3500 "--input-bit-depth=8",
3501 "--bit-depth=8",
3502 "--fps=25/1",
3503 &format!("--limit={frames}"),
3504 // The full constraint set of the forwarding/golden gates,
3505 // so the streams stay inside this decoder's supported
3506 // envelope and the gate isolates grain synthesis alone;
3507 // `--tune-content=film` is the one flag under test (it
3508 // enables apply_grain).
3509 "--codec=av1",
3510 "--passes=1",
3511 "--end-usage=q",
3512 "--cq-level=32",
3513 "--cpu-used=0",
3514 "--lag-in-frames=0",
3515 "--auto-alt-ref=0",
3516 "--kf-max-dist=1000",
3517 "--threads=1",
3518 "--row-mt=0",
3519 "--max-reference-frames=3",
3520 "--reduced-reference-set=1",
3521 "--enable-warped-motion=0",
3522 "--enable-obmc=0",
3523 "--enable-masked-comp=0",
3524 "--enable-interintra-comp=0",
3525 "--enable-dist-wtd-comp=0",
3526 "--enable-diff-wtd-comp=0",
3527 "--enable-onesided-comp=0",
3528 "--enable-interintra-wedge=0",
3529 "--enable-smooth-interintra=0",
3530 "--enable-rect-partitions=0",
3531 "--enable-ab-partitions=0",
3532 "--enable-1to4-partitions=0",
3533 "--enable-filter-intra=0",
3534 "--enable-smooth-intra=0",
3535 "--enable-paeth-intra=0",
3536 "--enable-directional-intra=0",
3537 "--enable-angle-delta=0",
3538 "--enable-tx-size-search=0",
3539 "--enable-cdef=0",
3540 "--enable-restoration=0",
3541 "--max-partition-size=32",
3542 "--min-partition-size=32",
3543 "--enable-palette=0",
3544 "--enable-intrabc=0",
3545 "--enable-cfl-intra=0",
3546 // Temporal MV projection (`use_ref_frame_mvs`) has no
3547 // decode path here (`mvstack.rs`'s documented corner-cut:
3548 // `zero_mv_ctx` and the mode-context GLOBALMV_OFFSET bit
3549 // are always computed as if it were off) -- this gate
3550 // isolates grain synthesis, so it must stay inside that
3551 // envelope like every other feature disabled above, not
3552 // silently decode a wrong mode context. Root cause of
3553 // this test's frame-1 mismatch: aomenc turns
3554 // `use_ref_frame_mvs` on by default once order hints are
3555 // enabled, unrelated to `--tune-content=film`.
3556 "--enable-ref-frame-mvs=0",
3557 "--tune-content=film",
3558 "--obu",
3559 "-o",
3560 ])
3561 .arg(&obu_path)
3562 .arg(&yuv_path)
3563 .stdout(Stdio::null())
3564 .stderr(Stdio::null())
3565 .status()
3566 .expect("aomenc failed to start");
3567 assert!(status.success(), "aomenc failed for seed {seed}");
3568 let encoded = std::fs::read(&obu_path).unwrap();
3569 let _ = std::fs::remove_dir_all(&dir);
3570
3571 let mut parser = ec_av1_syntax::Av1Parser::new();
3572 let mut pos = 0usize;
3573 let mut saw_grain = false;
3574 while pos < encoded.len() {
3575 let obu = parser.parse_obu(&encoded[pos..]).unwrap();
3576 pos += obu.total_size;
3577 if let ec_av1_syntax::ObuKind::Frame(header, _) = obu.kind
3578 && header.film_grain.apply_grain
3579 {
3580 saw_grain = true;
3581 }
3582 }
3583 assert!(saw_grain, "seed {seed}: aomenc did not turn on apply_grain");
3584
3585 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded, width, height, frames);
3586 let decoded = decode_stream(&encoded).unwrap();
3587 assert_eq!(decoded.len(), frames, "seed {seed}");
3588 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
3589 assert_eq!(got.y, want.y, "seed {seed} frame {i} luma vs ffmpeg");
3590 assert_eq!(got.u, want.u, "seed {seed} frame {i} U vs ffmpeg");
3591 assert_eq!(got.v, want.v, "seed {seed} frame {i} V vs ffmpeg");
3592 }
3593 }
3594 }
3595}