forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

stream.rs21311 lines, 1.7 MiBHistoryRawDownload
1//! The stream-level entry point a real decoder needs: walk a raw AV1 OBU
2//! stream (`Encoded::stream`, or any low-overhead-format bitstream this
3//! crate's own writers produce) via [`ec_av1_syntax::Av1Parser`] and dispatch
4//! each frame's tile payload to [`crate::decode::decode_key_frame_tile_with_cdfs`] /
5//! [`crate::decode::decode_inter_frame_tile_with_cdfs`], threading a
6//! single-slot picture DPB exactly as [`crate::encode::encode_sequence`] does
7//! on the write side, plus the full 8-slot *CDF* reference bank spec 7.20
8//! (`load_cdfs`) and 7.4 (the reference frame update) describe: a frame whose
9//! header names `primary_ref_frame != PRIMARY_REF_NONE` resumes from the
10//! adapted table a previous frame's `refresh_frame_flags` left in that slot,
11//! rather than the spec 8.4 defaults.
12//!
13//! This is the only reachable path for a caller that does not have the
14//! encoder's own `Encoded::tile`/`mi_cols`/`mi_rows`/`base_q_idx` fields (they
15//! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is
16//! an implementation detail of how this crate happens to build it).
17
18use ec_av1_syntax::{
19 Av1Parser, FrameHeader, FrameType, MAX_SEGMENTS, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE,
20 SEG_LVL_GLOBALMV, SEG_LVL_REF_FRAME, SEG_LVL_SKIP, Tile, TxMode,
21};
22// Census-only: read outside `mod tests` only in comments; the non-test lib
23// target never touches them, so they ride in behind cfg(test) (via the test
24// module's `use super::*`).
25#[cfg(test)]
26use ec_av1_syntax::{SEG_LVL_ALT_Q, SEG_LVL_MAX};
27use ec_core::{Error, Result};
28
29use crate::cdf_state::Cdfs;
30use crate::decode;
31use crate::decode::{
32 decode_inter_frame_tile_with_cdfs, decode_key_frame_tile_with_cdfs,
33 q_ctx_of,
34};
35#[cfg(test)]
36use crate::decode::decode_key_frame_tile_lr;
37use crate::encode::Picture;
38
39/// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a
40/// mid-film mismatch splits into "reconstruction" (compare against
41/// `ffmpeg -c:v libdav1d -filmgrain 0`) and "grain synthesis" in one run.
42fn no_grain() -> bool {
43 std::env::var_os("EC_AV1_NO_GRAIN").is_some()
44}
45
46// lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the
47// current thread, overriding the environment variable. Every ffmpeg/aomdec
48// pixel gate in this repo compares SHOWN frames only (class
49// gate-blind-to-hidden-frames), so the hidden alt-ref frames a real aomenc
50// stream carries were never compared at all; the gate that does compare
51// them needs a dump path that cannot race a sibling test's decode on
52// another thread, which a process-global env var cannot give.
53thread_local! {
54 static FINAL_DUMP_PREFIX: std::cell::RefCell<Option<String>> =
55 const { std::cell::RefCell::new(None) };
56}
57
58/// Sets (or with `None` clears) this thread's `EC_AV1_FINAL_DUMP` prefix.
59#[allow(dead_code)]
60pub(crate) fn set_final_dump_prefix(prefix: Option<String>) {
61 FINAL_DUMP_PREFIX.with(|c| *c.borrow_mut() = prefix);
62}
63
64fn final_dump_prefix() -> Option<String> {
65 FINAL_DUMP_PREFIX
66 .with(|c| c.borrow().clone())
67 .or_else(|| std::env::var("EC_AV1_FINAL_DUMP").ok())
68}
69
70/// 32x32-level 1:4 strip counters, for `decode_probe`'s fixture search:
71/// (HORZ_4 strips, VERT_4 strips, strips that read coefficients).
72/// lane-inter4 r1: the INTER-frame partition counters this lane's gates
73/// assert -- `(32x8, 8x32, 64x32, 32x64, 64x16, 16x64)` strips decoded.
74pub fn inter_rect_counters() -> (usize, usize, usize, usize, usize, usize) {
75 (
76 crate::decode::rect4_32_horz_inter_hits(),
77 crate::decode::rect4_32_vert_inter_hits(),
78 crate::decode::inter_sb_horz_hits(),
79 crate::decode::inter_sb_vert_hits(),
80 crate::decode::inter_sb_horz4_hits(),
81 crate::decode::inter_sb_vert4_hits(),
82 )
83}
84
85/// lane-r14 r2: luma transform units of an inter strip with a 64-px axis,
86/// coded as the truncated low-32 coefficient corner.
87pub fn rect64_inter_tu_hits() -> usize {
88 crate::decode::rect64_inter_tu_hits()
89}
90
91/// lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
92/// inter strip (`TX_32X8`/`TX_8X32`), `[32x8, 8x32]`.
93pub fn rect32x8_inter_tu_hits() -> [usize; 2] {
94 crate::decode::rect32x8_inter_tu_hits()
95}
96
97/// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherited a
98/// `tx_type` different from the group's FIRST sub-block, i.e. groups that can
99/// only decode right under `av1_get_tx_type`'s chroma-reference rule.
100pub fn sub8_chroma_tx_from_ref_hits() -> usize {
101 crate::decode::sub8_chroma_tx_from_ref_hits()
102}
103
104/// lane-intra16x4: `(16x4, 4x16, chroma-reference)` INTRA strips decoded inside
105/// an inter 16x16-level 1:4 partition.
106pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
107 crate::decode::intra16x4_in_inter_hits()
108}
109
110/// lane-sub8intra: INTRA 8x4/4x8 leaves inside an inter frame's sub-8x8
111/// HORZ/VERT partition, `(8x4, 4x8, chroma-reference, mixed groups, split
112/// 4x4 leaves)`.
113pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
114 crate::decode::sub8_intra_rect_hits()
115}
116
117/// lane-r14 r3: RECTANGULAR var-tx leaf transform units, `[32x16, 16x32]` --
118/// the leaves `sub_tx_size_map` produces when a 1:4 strip with a 64-px axis
119/// splits its transform (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`).
120pub fn vartx_rect_leaf_hits() -> [usize; 2] {
121 crate::decode::vartx_rect_leaf_hits()
122}
123
124/// How many rect intra strips read the `use_intrabc` symbol on the last decode.
125pub fn rect_intrabc_reads() -> usize {
126 crate::decode::rect_intrabc_reads()
127}
128
129/// `(y, uv)` palette blocks RECONSTRUCTED inside an inter frame (lane-t900
130/// r22) -- the counter a screen-content witness gate reads to prove it
131/// exercises the inter-frame palette path, not the key frame's.
132pub fn intra_in_inter_palette_hits() -> (usize, usize) {
133 crate::decode::intra_in_inter_palette_hits()
134}
135
136/// `(y, uv)` palette blocks reconstructed on an 8x8 LEAF inside an inter
137/// frame (lane-t900 r23) -- the site-specific half of
138/// [`intra_in_inter_palette_hits`], which a >=16 block also moves.
139pub fn inter8_palette_hits() -> (usize, usize) {
140 crate::decode::inter8_palette_hits()
141}
142
143/// lane-rect64port r1: coded 64-level HORZ/VERT intra strips whose luma
144/// transform unit is the un-split TX_64X32 (orient 0) / TX_32X64 (orient 1).
145pub fn rect64_corner_tu_hits(orient: usize) -> usize {
146 crate::decode::rect64_corner_tu_hits(orient)
147}
148
149/// lane-inter16ab r4: RECTANGULAR var-tx leaves with a 4-px axis, `[8x4, 4x8]`
150/// -- what `sub_tx_size_map[TX_16X4] == TX_8X4` produces when a 16x16-level
151/// 1:4 inter strip splits its transform.
152pub fn vartx_rect_leaf4_hits() -> [usize; 2] {
153 crate::decode::vartx_rect_leaf4_hits()
154}
155
156/// lane-inter16ab r5: COMPOUND_WEDGE / wedge-INTERINTRA blocks that used a
157/// RECTANGULAR wedge codebook row, per shape (`RECT_WEDGE_SHAPES` order:
158/// 8x16, 16x8, 16x32, 32x16, 8x32, 32x8).
159pub fn rect_wedge_hits() -> [usize; 6] {
160 crate::decode::rect_wedge_hits()
161}
162
163/// lane-inter16ab r5: the wedge-interintra half of [`rect_wedge_hits`].
164pub fn rect_wii_hits() -> [usize; 6] {
165 crate::decode::rect_wii_hits()
166}
167
168/// lane-sb128c r7: the 128 root's rect arms -- (gathered edge HORZ, gathered
169/// edge VERT, inter 128x64 blocks, inter 64x128 blocks).
170pub fn sb128_rect_counters() -> (usize, usize, usize, usize) {
171 (
172 crate::decode::part128_edge_horz_hits(),
173 crate::decode::part128_edge_vert_hits(),
174 crate::decode::inter_sb128_horz_hits(),
175 crate::decode::inter_sb128_vert_hits(),
176 )
177}
178
179/// lane-av1-ibcrect: the 128 root's interior partition arms plus the key-frame
180/// intra 128-axis blocks -- (split, none, horz, vert, ab[4], intra_horz,
181/// intra_vert). Non-zero horz/vert mean a stream carried real PARTITION_HORZ/
182/// VERT at the 128 root, so an intrabc-rect hunt can tell "the partition was
183/// never chosen" from "chosen and decoded intra (or refused)".
184pub fn part128_census() -> (usize, usize, usize, usize, [usize; 4], usize, usize) {
185 (
186 crate::decode::part128_split_hits(),
187 crate::decode::part128_none_hits(),
188 crate::decode::part128_horz_hits(),
189 crate::decode::part128_vert_hits(),
190 crate::decode::part128_ab_hits(),
191 crate::decode::intra_sb128_hits().0,
192 crate::decode::intra_sb128_hits().1,
193 )
194}
195
196/// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip whose
197/// reconstruction ([`crate::decode::decode_intrabc_128rect`]) ran -- the
198/// engagement counter the sb128 intrabc-rect gate asserts on.
199pub fn intrabc_128rect_hits() -> usize {
200 crate::decode::intrabc_128rect_hits()
201}
202
203/// Blocks reconstructed with intra block copy at an 8x8 LEAF specifically
204/// (lane-kf900 r7's shape); [`crate::decode::intrabc_hits`] counts every shape.
205pub fn leaf8_intrabc_hits() -> usize {
206 crate::decode::leaf8_intrabc_hits()
207}
208
209/// Blocks whose `use_intrabc` symbol came out 1 and took the DV path, at ANY
210/// shape -- the engagement counter the intrabc gates assert on. It counts
211/// "read a `use_intrabc` DV", not "reconstructed": a block the rect-strip
212/// reader REFUSES for an unported shape bumps it too (the symbol and the DV
213/// are parsed before the refusal). [`leaf8_intrabc_hits`] is its 8x8-leaf
214/// subset.
215pub fn intrabc_hits() -> usize {
216 crate::decode::intrabc_hits()
217}
218
219/// lane-av1txbands: sub-8x8 group chroma-reference leaves that USED intrabc and
220/// were SKIPPED -- the route that armed [`crate::decode::intrabc_hits`]'s chroma
221/// transform slot and then read no chroma coefficient. A non-zero value is what
222/// makes the disarm at that route load-bearing on a real stream.
223pub fn skipped_intrabc_chroma_arm_hits() -> usize {
224 crate::decode::skipped_intrabc_chroma_arm_hits()
225}
226
227/// lane-sb128c r8: the 128 root's INTRA (key-frame) rect arm -- (128x64
228/// blocks, 64x128 blocks, blocks per resolved intra `tx_depth` 0/1/2).
229pub fn intra_sb128_counters() -> (usize, usize, [usize; 3]) {
230 crate::decode::intra_sb128_hits()
231}
232
233/// lane-inter128intra r1: the 128 root's HORZ/VERT half coded INTRA inside an
234/// INTER frame -- (128x64 blocks, 64x128 blocks).
235pub fn intra128_in_inter_counters() -> [usize; 2] {
236 crate::decode::intra128_in_inter_hits()
237}
238
239/// lane-lossless128: intra 128-axis blocks decoded on a LOSSLESS frame, where
240/// every plane is a TX_4X4 unit. The engagement counter for
241/// `a_lossless_sb128_rect_intra_block_decodes_sample_exact`.
242pub fn intra128_lossless_counters() -> usize {
243 crate::decode::intra128_lossless_hits()
244}
245
246/// lane-sb128c r9: the four AB shapes at the 128 root, in `PARTITION_HORZ_A`,
247/// `_HORZ_B`, `_VERT_A`, `_VERT_B` order (key and inter tile paths share the
248/// counter -- it is bumped where the root symbol resolves).
249pub fn sb128_ab_counters() -> [usize; 4] {
250 crate::decode::part128_ab_hits()
251}
252
253/// lane-obmcrec r1: OBMC neighbours taken from the second half of a 1:4-strip
254/// chroma pair -- the shape whose filter record the r1 fix re-sourced.
255pub fn obmc_pair_filter_hits() -> usize {
256 crate::decode::obmc_pair_filter_hits()
257}
258
259/// Gate counters for the 4x32/32x4 rectangular strips: `(horz, vert, coeff)` hits.
260pub fn rect4_32_counters() -> (usize, usize, usize) {
261 (
262 crate::decode::rect4_32_horz_hits(),
263 crate::decode::rect4_32_vert_hits(),
264 crate::decode::rect4_coeff_hits(),
265 )
266}
267
268/// lane-inter4 r4: rectangular inter transform units coded whole, rect
269/// var-tx trees that split, and OBMC blends run on a 16x8/8x16 leaf -- the
270/// three counters a recipe sweep needs to see from outside the crate.
271pub fn rect_inter_tu_counters() -> (usize, usize, usize) {
272 (
273 crate::decode::rect_inter_tu_hits(),
274 crate::decode::rect_inter_txsplit_hits(),
275 crate::decode::obmc_rect_leaf_hits(),
276 )
277}
278
279/// Decode every frame in a raw AV1 OBU stream, in coding order.
280///
281/// A key frame becomes the reference for the inter frames that follow it,
282/// until the next key frame resets the DPB — the same single-slot chain
283/// [`crate::encode::encode_sequence`] threads on the write side. Only a
284/// `Frame` OBU (an uncompressed header and its tile group in one OBU, which
285/// is all this crate's encoder ever writes) carries a tile payload; sequence
286/// headers and temporal delimiters are consumed for the state they carry (or
287/// skipped) and produce no picture.
288///
289/// # Errors
290/// Returns an error when the stream is truncated or malformed (as
291/// [`Av1Parser`] reports it), when a frame header names anything this
292/// crate's tile decoders do not reconstruct (see their own docs), or when an
293/// inter frame appears before any key frame has supplied a reference.
294pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
295 let mut pictures = Vec::new();
296 decode_stream_with(data, |picture, _decode_idx, shown| {
297 if shown {
298 pictures.push(picture.clone());
299 }
300 Ok(())
301 })?;
302 Ok(pictures)
303}
304
305/// Streaming form of [`decode_stream`]: hand every completed picture to
306/// `sink` the moment it exists and drop it right after, so peak memory is one
307/// output picture plus the 8-slot DPB instead of the whole decoded stream --
308/// a 4K long-GOP segment costs the same as a short one. `decode_stream`
309/// itself is this function collecting into a `Vec`.
310///
311/// `sink` is called with the picture, the decode-order index of the coded
312/// frame it came from, and whether it is output: a hidden reference frame
313/// (`show_frame == 0`) is reported with `shown == false` and is NOT part of
314/// `decode_stream`'s output, a `show_existing_frame` output with `true`.
315/// The grain-synthesised picture is what a shown frame's sink sees; the
316/// reference bank keeps the clean one (spec 7.18.3.1). An `Err` the sink
317/// returns aborts the decode and is returned unchanged.
318///
319/// # Errors
320/// As [`decode_stream`], plus whatever `sink` returns.
321pub fn decode_stream_with(
322 data: &[u8],
323 sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
324) -> Result<()> {
325 decode_stream_with_threads(data, decode_threads(), sink)
326}
327
328/// lane-thread2: how many threads [`decode_stream_with`] decodes with --
329/// `EC_AV1_THREADS`, default 1. One is not "threading with a pool of one":
330/// it is the single-threaded decoder unchanged, which is what keeps every
331/// gate that reads this crate's per-thread counters meaningful.
332fn decode_threads() -> usize {
333 static N: std::sync::LazyLock<usize> = std::sync::LazyLock::new(|| {
334 crate::envflags::var("EC_AV1_THREADS")
335 .ok()
336 .and_then(|v| v.parse::<usize>().ok())
337 .filter(|&n| n > 0)
338 .unwrap_or(1)
339 });
340 *N
341}
342
343/// lane-thread2: output-order queue. A leaf frame decoded on a worker
344/// finishes whenever it finishes; `sink` must still see every picture in the
345/// order the stream codes them, so each sink call gets an `emit_seq` when the
346/// main thread reaches its frame header and is held here until every earlier
347/// one has been emitted. (The decode index the sink is TOLD is unchanged, and
348/// is deliberately not unique: a `show_existing_frame` re-output reports the
349/// count of frames decoded before it, per this function's contract.)
350#[derive(Default)]
351struct Reorder {
352 next: usize,
353 // lane-pool1: the picture is shared, not owned -- a decoded frame that
354 // refreshes a reference slot is already behind an `Arc` for the slot, and
355 // handing the output an owned `Picture` meant copying every plane of it
356 // (24 MB per 4K 10-bit frame) purely to put it in this queue.
357 pending: std::collections::BTreeMap<usize, (std::sync::Arc<Picture>, usize, bool)>,
358}
359
360impl Reorder {
361 fn push(&mut self, seq: usize, picture: std::sync::Arc<Picture>, decode_idx: usize, shown: bool) {
362 self.pending.insert(seq, (picture, decode_idx, shown));
363 }
364
365 /// Emits every queued picture whose turn has come. An `Err` from `sink`
366 /// aborts the decode, unchanged, exactly as the serial path did.
367 fn drain(
368 &mut self,
369 sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>,
370 ) -> Result<()> {
371 while let Some((picture, decode_idx, shown)) = self.pending.remove(&self.next) {
372 self.next += 1;
373 sink(&picture, decode_idx, shown)?;
374 crate::timeline::output(decode_idx);
375 }
376 Ok(())
377 }
378}
379
380/// lane-thread2/3: how many coded frames this PROCESS has dispatched to a
381/// worker thread (see [`decode_stream_with_threads`]). Process-global and
382/// atomic on purpose: it is the only counter here a caller can read after a
383/// threaded decode, and it is what keeps a "decodes identically with 4
384/// threads" gate from silently proving nothing because every frame ran
385/// inline. (lane-thread2 counted only LEAF frames, the only ones it could
386/// dispatch; lane-thread3 dispatches every non-key, non-`show_existing_frame`
387/// frame, hence the rename.)
388static FRAMES_DISPATCHED: std::sync::atomic::AtomicUsize =
389 std::sync::atomic::AtomicUsize::new(0);
390
391/// Reads [`FRAMES_DISPATCHED`].
392pub fn frames_dispatched() -> usize {
393 FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed)
394}
395
396/// lane-thread3: what one decoded frame stores into every reference slot its
397/// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated
398/// object -- so a slot costs an `Arc` clone instead of a picture copy.
399struct SlotValue {
400 /// lane-twostage: this frame's FILTERED pixels, still being produced
401 /// when the rest of this value is published.
402 pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>>,
403 /// The size those pixels will have, known from the tile decode.
404 width: usize,
405 height: usize,
406 cdfs: Cdfs,
407 motion_field: crate::motion_field::MotionField,
408 seg_map: Vec<u8>,
409 order_hint: u32,
410}
411
412/// lane-thread3: a reference slot's contents as a FUTURE. At `threads > 1`
413/// the 8-slot bank holds these instead of values: a slot refreshed by a frame
414/// that is still decoding on a worker holds the promise from the moment the
415/// parsing thread DISPATCHES that frame, so the next frame can be dispatched
416/// straight away and waits, on its own worker, for exactly the slots it
417/// reads. This is what makes a pyramid stream (aomenc's default, where nearly
418/// every coded frame refreshes a slot, so lane-thread2's leaf rule dispatched
419/// almost nothing) decode in parallel.
420///
421/// DEADLOCK ARGUMENT. A promise is installed into a slot on the parsing
422/// thread, in decode order, when its producer is dispatched; a consumer
423/// captures the promises of the slots it reads at ITS dispatch, which is
424/// strictly later in decode order. Every wait therefore points from a later
425/// coded frame to an earlier one -- the wait graph is the reference DAG, and
426/// is acyclic. The parsing thread waits only for a `show_existing_frame`
427/// output (again an earlier frame) and at the in-flight bound, where it waits
428/// for ANY worker to answer: the earliest in-flight frame has no earlier
429/// in-flight producer, so it is always runnable and the bound always clears.
430/// Each dispatched frame gets its own thread, so a blocked waiter never holds
431/// a resource its producer needs. A producer that errors or panics marks its
432/// promise `Failed`, so no consumer can wait for a value that never comes.
433struct SlotPromise<T = std::sync::Arc<SlotValue>> {
434 state: std::sync::Mutex<PromiseState<T>>,
435 ready: std::sync::Condvar,
436}
437
438enum PromiseState<T> {
439 Pending,
440 Ready(T),
441 Failed,
442}
443
444impl<T: Clone> SlotPromise<T> {
445 fn pending() -> std::sync::Arc<Self> {
446 std::sync::Arc::new(Self {
447 state: std::sync::Mutex::new(PromiseState::Pending),
448 ready: std::sync::Condvar::new(),
449 })
450 }
451
452 /// A slot filled by a frame the parsing thread decoded itself.
453 fn ready(value: T) -> std::sync::Arc<Self> {
454 std::sync::Arc::new(Self {
455 state: std::sync::Mutex::new(PromiseState::Ready(value)),
456 ready: std::sync::Condvar::new(),
457 })
458 }
459
460 fn fulfil(&self, value: T) {
461 *self.state.lock().expect("slot promise") = PromiseState::Ready(value);
462 self.ready.notify_all();
463 }
464
465 /// lane-twostage: fulfils only a promise the stage-1 sink did not
466 /// already fill (a superres frame, or a key frame, whose meta is
467 /// published here as it always was).
468 fn fulfil_if_pending(&self, value: impl FnOnce() -> T) {
469 let mut state = self.state.lock().expect("slot promise");
470 if matches!(*state, PromiseState::Pending) {
471 *state = PromiseState::Ready(value());
472 }
473 self.ready.notify_all();
474 }
475
476 fn fail(&self) {
477 let mut state = self.state.lock().expect("slot promise");
478 if matches!(*state, PromiseState::Pending) {
479 *state = PromiseState::Failed;
480 }
481 self.ready.notify_all();
482 }
483
484 /// Blocks until the producing frame has published this slot.
485 fn wait(&self) -> Result<T> {
486 let mut state = self.state.lock().expect("slot promise");
487 loop {
488 match &*state {
489 PromiseState::Ready(value) => return Ok(value.clone()),
490 PromiseState::Failed => {
491 return Err(Error::corrupt(
492 "AV1 decode_stream: a reference frame this frame depends on failed to decode",
493 ));
494 }
495 PromiseState::Pending => {
496 state = self.ready.wait(state).expect("slot promise");
497 }
498 }
499 }
500 }
501}
502
503/// One finished frame from a worker: its output position, whether the job was
504/// a frame DECODE (as opposed to a `show_existing_frame` output, which only
505/// waits for a slot and synthesises grain -- lane-thread3 counts the two
506/// against separate in-flight bounds, since a waiting output job costs no
507/// CPU), and either the (grain-synthesised) picture with the decode index to
508/// report or the error that aborts the stream.
509type LeafResult = (usize, bool, Result<(std::sync::Arc<Picture>, usize, bool)>);
510
511/// Waits for one in-flight job and emits whatever that unblocks.
512fn collect_one(
513 rx: &std::sync::mpsc::Receiver<LeafResult>,
514 decodes: &mut usize,
515 shows: &mut usize,
516 reorder: &mut Reorder,
517 sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>,
518) -> Result<()> {
519 // Every dispatched worker answers exactly once, panic included (it is
520 // caught and turned into an error below), so the sender count cannot
521 // reach zero while `in_flight > 0`.
522 let (seq, decode_job, result) = rx
523 .recv()
524 .map_err(|_| Error::corrupt("AV1 decode_stream: a worker thread vanished"))?;
525 if decode_job {
526 *decodes -= 1;
527 } else {
528 *shows -= 1;
529 }
530 let (picture, decode_idx, shown) = result?;
531 reorder.push(seq, picture, decode_idx, shown);
532 reorder.drain(sink)
533}
534
535/// [`decode_stream_with`] with an explicit worker count (lane-thread2).
536///
537/// `threads == 1` is the serial decoder. Above that, frames that no later
538/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags`
539/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads
540/// while the main thread keeps parsing headers and decoding the frames that
541/// DO feed the reference banks; `sink` still sees every picture in coded
542/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot
543/// of the banks taken before dispatch, so no decode state is shared.
544///
545/// The per-decode counters this crate's gates read are thread-local, so at
546/// `threads > 1` a leaf frame's counts land on the worker and are invisible
547/// to the caller; that is why the default is 1.
548///
549/// # Errors
550/// As [`decode_stream_with`]; a worker's error aborts the stream.
551pub fn decode_stream_with_threads(
552 data: &[u8],
553 threads: usize,
554 mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
555) -> Result<()> {
556 // lane-pool1: this replaced a `std::thread::scope` -- frame workers now
557 // come from a persistent pool (one per submitting thread, workers reused
558 // across frames, so their `thread_local!` decode scratch survives the
559 // frame). `jobs` is declared here and dropped at the end of the function,
560 // including on `?`, so no job outlives the data it borrows.
561 let jobs = crate::par::Batch::new("ec-av1-frame");
562 // lane-thread1: this stream's per-frame decode state (was 38 thread_local
563 // statics in decode.rs) -- one object, threaded down the decode call graph.
564 let fctx = &crate::decode::FrameCtx::new();
565 let final_dump = final_dump_prefix();
566 let mut parser = Av1Parser::new();
567 let mut pictures_shown: usize = 0;
568 let mut pictures_decoded: usize = 0;
569 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
570 // previous frame's `refresh_frame_flags` stored into it, exactly like the
571 // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,
572 // not simply "the previous frame decoded"; a frame whose own predecessor
573 // didn't refresh that slot (an altref/hidden frame, or any GOP with more
574 // than one live reference) must keep predicting from whatever picture is
575 // still sitting there. Round 7's cdffwd hunt: a global `reference`
576 // overwritten every frame silently always used "the most recent decode"
577 // instead, producing a bit-exact motion vector into the WRONG picture --
578 // luma-only (chroma coincidentally shares this fixture's flat regions)
579 // and small-magnitude (the two pictures mostly agree), which is exactly
580 // what made it look like a rounding bug rather than a wrong reference.
581 // lane-pool1: shared, not owned -- a frame refreshing k slots used to copy
582 // its whole picture k times, and its output a (k+1)-th time.
583 let mut ref_slots: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] =
584 std::array::from_fn(|_| None);
585 // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion
586 // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom
587 // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was
588 // decoded with -- `Picture` itself carries neither, so both ride
589 // alongside `ref_slots` on the exact same `refresh_frame_flags` update.
590 let mut motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES] =
591 std::array::from_fn(|_| None);
592 let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES];
593 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
594 // previous frame's `refresh_frame_flags` stored into it -- the frame's
595 // own end-of-tile adapted table, or (when the frame set
596 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
597 let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
598 // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also
599 // remembers the segment map the frame stored there decoded, which is what
600 // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds`
601 // (spec `load_previous_segment_ids`) for temporal segment-id prediction
602 // and for a `segmentation_update_map == 0` frame's inherited map.
603 let mut seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
604
605 // lane-thread2: output plumbing (inert at `threads == 1`, where nothing
606 // is ever dispatched and `reorder` emits each picture the moment it is
607 // pushed).
608 let mut emit_seq = 0usize;
609 let mut reorder = Reorder::default();
610 // lane-thread3: frame decodes and `show_existing_frame` outputs are
611 // bounded separately -- an output job is a promise wait plus a memcpy, so
612 // letting it eat a decode's budget just idles a core (measured: sharing
613 // one bound cost 4K 18.7 s at 244% CPU against 17.7 s at 287%).
614 let mut in_flight_decodes = 0usize;
615 let mut in_flight_shows = 0usize;
616 let in_flight_cap = threads + 2;
617 let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();
618 // lane-thread3: at `threads > 1` THIS is the reference bank -- one
619 // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled
620 // itself and pending for one an in-flight frame will fill. The owned
621 // arrays above are then untouched (and the single-threaded path never
622 // creates a promise: it stays exactly the decoder it was, which is what
623 // keeps every counter-reading gate meaningful).
624 let mut slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
625 std::array::from_fn(|_| None);
626 // lane-timeline: which decoded frame installed each slot's promise, so
627 // the timeline records a dependency EDGE (frame -> producing frame) and
628 // not just a slot number. `usize::MAX` = nobody yet.
629 let mut slot_owner = [usize::MAX; NUM_REF_FRAMES];
630
631 let mut pos = 0usize;
632 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec
633 // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone
634 // `OBU_FRAME_HEADER` first, with `show_existing_frame == false` and no
635 // tile payload of its own -- `OBU_FRAME` (the `ObuKind::Frame` arm below)
636 // only ever folds ONE tile group into the header's own OBU. Stash the
637 // header here and accumulate tiles from each `OBU_TILE_GROUP` that
638 // follows until every tile of the frame has arrived.
639 let mut pending_header: Option<Box<FrameHeader>> = None;
640 let mut pending_tiles: Vec<Tile> = Vec::new();
641 while pos < data.len() {
642 let obu = parser.parse_obu(&data[pos..])?;
643 let obu_offset = pos;
644 pos += obu.total_size;
645
646 if let ObuKind::FrameHeader(header) = &obu.kind {
647 if !header.show_existing_frame {
648 // Before this fix, this branch fired unconditionally for
649 // EVERY `FrameHeader` OBU (including this one), so a
650 // standalone header always fell into the `show_existing_frame`
651 // slot lookup below and misreported "a show_existing_frame
652 // header naming an empty reference slot" for a frame that was
653 // never a show_existing_frame header at all.
654 pending_header = Some(header.clone());
655 pending_tiles = Vec::new();
656 continue;
657 }
658 // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this
659 // OBU only names a DPB slot to output again -- the coded-frame
660 // count and the shown-picture count are different things (a
661 // hidden altref's own `Frame` OBU below is never pushed to
662 // `pictures` on its own; it is only pushed here, later, when a
663 // `show_existing_frame` header names its slot). Before r15 this
664 // arm didn't exist at all: every `ObuKind::Frame` was pushed
665 // unconditionally regardless of `show_frame`, so a hidden altref
666 // was emitted (wrongly, in decode order) and its real
667 // `show_existing_frame` output was silently dropped.
668 let slot = header.frame_to_show_map_idx as usize;
669 // lane-hdrlossless: libaom errors on the same stream
670 // (`decodeframe.c:4651`: `if (frame_to_show == NULL)
671 // aom_internal_error(... AOM_CODEC_UNSUP_BITSTREAM, "Buffer does
672 // not contain a decoded frame")`) -- a spec-conformant guard.
673 let empty_slot = || {
674 Error::unsupported(
675 "AV1 decode_stream",
676 "a show_existing_frame header naming an empty reference slot",
677 )
678 };
679 if threads > 1 {
680 // lane-thread3: the named slot may still be decoding on a
681 // worker, and the copy into the slots this header refreshes
682 // is then just the promise -- no value needed. The OUTPUT
683 // does need the picture, so it is produced on a worker too:
684 // waiting for it here would stall the parsing thread, and a
685 // stalled parser dispatches nothing (measured before this
686 // arm existed: 7.9 s of an 8.8 s 1080p decode, 18.9 s of
687 // 23.3 s at 4K, spent in this one wait). The wait still
688 // points at an earlier coded frame, so the argument in
689 // [`SlotPromise`] is unchanged.
690 let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?;
691 for i in 0..NUM_REF_FRAMES {
692 if header.refresh_frame_flags & (1 << i) != 0 {
693 slot_promises[i] = Some(promise.clone());
694 slot_owner[i] = slot_owner[slot];
695 }
696 }
697 let cap_t0 = crate::timeline::now();
698 let capped = in_flight_shows >= in_flight_cap;
699 while in_flight_shows >= in_flight_cap {
700 collect_one(
701 &rx,
702 &mut in_flight_decodes,
703 &mut in_flight_shows,
704 &mut reorder,
705 &mut sink,
706 )?;
707 }
708 if capped {
709 crate::timeline::cap_wait("show", cap_t0, crate::timeline::now());
710 }
711 let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
712 emit_seq += 1;
713 pictures_shown += 1;
714 let grain = header.film_grain;
715 let seq = SeqFlags::read(&parser);
716 let tx = tx.clone();
717 jobs.submit(move || {
718 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
719 let value = promise.wait()?;
720 let shown_picture = value.pixels.wait()?;
721 let output = if grain.apply_grain && !no_grain() {
722 std::sync::Arc::new(crate::film_grain::apply_grain(
723 &shown_picture,
724 &grain,
725 seq.mc_identity,
726 u32::from(seq.bit_depth),
727 &crate::decode::FrameCtx::new(),
728 ))
729 } else {
730 std::sync::Arc::clone(&shown_picture)
731 };
732 Ok((output, decode_idx, true))
733 }))
734 .unwrap_or_else(|_| {
735 Err(Error::corrupt(
736 "AV1 decode_stream: a worker thread panicked on a show_existing_frame output",
737 ))
738 });
739 let _ = tx.send((job_seq, false, reply));
740 });
741 in_flight_shows += 1;
742 while let Ok((seq, decode_job, result)) = rx.try_recv() {
743 if decode_job {
744 in_flight_decodes -= 1;
745 } else {
746 in_flight_shows -= 1;
747 }
748 let (picture, decode_idx, shown) = result?;
749 reorder.push(seq, picture, decode_idx, shown);
750 reorder.drain(&mut sink)?;
751 }
752 continue;
753 }
754 let picture = {
755 let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?;
756 for i in 0..NUM_REF_FRAMES {
757 if header.refresh_frame_flags & (1 << i) != 0 {
758 cdf_slots[i] = cdf_slots[slot].clone();
759 ref_slots[i] = Some(picture.clone());
760 motion_field_slots[i] = motion_field_slots[slot].clone();
761 seg_map_slots[i] = seg_map_slots[slot].clone();
762 order_hint_slots[i] = order_hint_slots[slot];
763 }
764 }
765 picture
766 };
767 let output = if header.film_grain.apply_grain && !no_grain() {
768 // lane-hbd10 r1: grain synthesis is bit-depth generic
769 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
770 let bit_depth = parser
771 .sequence_header()
772 .map_or(8, |seq| seq.color_config.bit_depth);
773 let mc_identity = parser
774 .sequence_header()
775 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
776 std::sync::Arc::new(crate::film_grain::apply_grain(
777 &picture,
778 &header.film_grain,
779 mc_identity,
780 bit_depth as u32, fctx,
781 ))
782 } else {
783 picture
784 };
785 reorder.push(emit_seq, output, pictures_decoded, true);
786 emit_seq += 1;
787 reorder.drain(&mut sink)?;
788 pictures_shown += 1;
789 continue;
790 }
791 // `tiles_base_offset` is added to every `Tile::offset` below to reach
792 // an absolute position in `data`. `OBU_FRAME`'s tiles are relative to
793 // this OBU's own `obu_offset`; an accumulated run of `OBU_TILE_GROUP`s
794 // may span several different OBUs (each at a different offset in
795 // `data`), so those tiles are normalised to an absolute offset the
796 // moment they are appended to `pending_tiles`, and `tiles_base_offset`
797 // is 0 for that case.
798 let (header, tiles, tiles_base_offset): (Box<FrameHeader>, Vec<Tile>, usize) =
799 match obu.kind {
800 ObuKind::Frame(header, tiles) => (header, tiles, obu_offset),
801 ObuKind::TileGroup(new_tiles) => {
802 let header = pending_header.clone().ok_or_else(|| {
803 Error::corrupt(
804 "AV1 decode_stream: a tile group OBU with no preceding frame header",
805 )
806 })?;
807 let expected = header.tile_info.cols * header.tile_info.rows;
808 pending_tiles.extend(new_tiles.into_iter().map(|mut t| {
809 t.offset += obu_offset;
810 t
811 }));
812 if (pending_tiles.len() as u32) < expected {
813 continue;
814 }
815 pending_header = None;
816 (header, std::mem::take(&mut pending_tiles), 0)
817 }
818 _ => continue,
819 };
820 // Every tile is decoded below through `tile_bufs`; this only rejects a
821 // frame OBU that carries no tile group at all.
822 if tiles.is_empty() {
823 return Err(Error::unsupported(
824 "AV1 decode_stream",
825 "a frame OBU with no tile group",
826 ));
827 }
828 // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
829 // block of each 64x64) only reads a literal `cdef_idx` when
830 // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a
831 // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is
832 // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into
833 // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so
834 // a `cdef_bits > 0` stream no longer needs this refusal.
835 // Both frame types now read their transform size under
836 // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads
837 // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's
838 // `decode_inter_block`/`decode_inter_block8` read the recursive
839 // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the
840 // blanket inter-frame refusal that used to stand here is gone. What
841 // remains refused is named at its own site in `read_block_tx_size`.
842 // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`,
843 // libaom decodemv.c): three more per-block/per-SB symbols this crate
844 // never reads at all, each gated by a header field this decoder
845 // otherwise accepts uncomplaining -- the same silent-desync shape
846 // `use_filter_intra` was. `allow_screen_content_tools` gates both
847 // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/
848 // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel`
849 // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse
850 // before desyncing rather than silently miscode, the same pattern as
851 // the CDEF/TxMode::Select refusals above.
852 // lane-screen r2: key frames consume (not reconstruct) palette/
853 // intrabc syntax via read_intra_mode, and decode_inter_block/
854 // decode_inter_block8's own intra-sub-block branches now consume
855 // palette the same way (libaom's read_intra_block_mode_info has no
856 // intrabc call at all -- that symbol is intra-frame-only). A
857 // genuine palette/intrabc use still refuses by name deeper in the
858 // block readers, so no whole-frame refusal is needed here anymore.
859 // lane-realworld r5: both delta_q (maybe_read_delta_q, CURRENT_Q_IDX)
860 // and delta_lf (maybe_read_delta_lf, CURRENT_DELTA_LF ->
861 // Neighbours::delta_lf_grid -> lf_level) are now read and applied;
862 // no whole-frame refusal needed here anymore.
863 //
864 // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an
865 // earlier round), `BIT_DEPTH` is wired from this frame's own sequence
866 // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10`
867 // stream decodes pixel-exact against ffmpeg's own decode of the same
868 // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The
869 // blanket refusal that used to be here is gone; `film_grain.rs` and
870 // `superres.rs` still refuse narrowly by name (their own hardcoded
871 // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes
872 // will show up as a real pixel mismatch, not a silent truncation --
873 // the whole reason the widen (and this wiring) happened.
874 // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9,
875 // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the
876 // per-segment quantizer (spec 7.12.2) and loop-filter level
877 // (spec 7.14.4). The three features that instead REWRITE a block's
878 // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the
879 // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress
880 // symbols `decode_inter_block` unconditionally reads) -- have no
881 // reader on the inter path, so they still refuse by name rather than
882 // desyncing. aomenc's `--aq-mode` segmentation only ever sets
883 // `SEG_LVL_ALT_Q` (census gate
884 // `a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`:
885 // 1-pass, alt-ref-lag and two-pass arms, every frame header parsed).
886 let tile_bufs: Vec<&[u8]> = tiles
887 .iter()
888 .map(|t| {
889 data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size)
890 .ok_or(Error::NeedMore)
891 })
892 .collect::<Result<_>>()?;
893 let seq = SeqFlags::read(&parser);
894 // lane-thread3: at `threads > 1` every coded frame that is not a key
895 // frame is decoded on a worker -- frames that refresh reference slots
896 // included, which on a pyramid stream is nearly all of them. Its
897 // inputs are taken as promises and its output is published as one,
898 // installed into the slots it refreshes HERE, on the parsing thread,
899 // in decode order, so the next frame's dependencies are known without
900 // waiting for this one to finish (see [`SlotPromise`] for the
901 // deadlock argument). A key frame stays inline: it resets the whole
902 // bank and reads nothing, so there is nothing to gain.
903 if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame {
904 let cap_t0 = crate::timeline::now();
905 let capped = in_flight_decodes >= in_flight_cap;
906 while in_flight_decodes >= in_flight_cap {
907 collect_one(
908 &rx,
909 &mut in_flight_decodes,
910 &mut in_flight_shows,
911 &mut reorder,
912 &mut sink,
913 )?;
914 }
915 if capped {
916 crate::timeline::cap_wait("decode", cap_t0, crate::timeline::now());
917 }
918 // Exactly the slots this frame reads: `ref_frame_idx` names its
919 // references, and its `primary_ref_frame` CDFs/segment map, its
920 // reference order hints and every field `setup_motion_field`
921 // projects all come from those same slots. Nothing else is
922 // waited on.
923 let mut deps: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
924 std::array::from_fn(|_| None);
925 for i in 0..7 {
926 let slot = header.ref_frame_idx[i] as usize;
927 deps[slot] = slot_promises[slot].clone();
928 }
929 let dep_owner = slot_owner;
930 let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending);
931 if let Some(promise) = &produces {
932 for i in 0..NUM_REF_FRAMES {
933 if header.refresh_frame_flags & (1 << i) != 0 {
934 slot_promises[i] = Some(promise.clone());
935 slot_owner[i] = pictures_decoded;
936 }
937 }
938 }
939 let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);
940 emit_seq += 1;
941 pictures_decoded += 1;
942 let shown = header.show_frame;
943 if shown {
944 pictures_shown += 1;
945 }
946 let tx = tx.clone();
947 let dump = final_dump.clone();
948 crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown);
949 jobs.submit(move || {
950 let promise = produces;
951 // lane-twostage: stage 2 -- this frame's filtered pixels. Its
952 // consumers hold this promise from the moment stage 1 (CDFs,
953 // segment map, motion field, size) is published at the tile
954 // boundary, and wait on it at their first prediction.
955 let pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>> =
956 SlotPromise::pending();
957 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
958 crate::timeline::start(decode_idx);
959 // The wait happens HERE, off the parsing thread, and only
960 // for this frame's own references.
961 let mut resolved: [Option<std::sync::Arc<SlotValue>>; NUM_REF_FRAMES] =
962 std::array::from_fn(|_| None);
963 for (slot, dep) in deps.iter().enumerate() {
964 if let Some(dep) = dep {
965 let t0 = crate::timeline::now();
966 resolved[slot] = Some(dep.wait()?);
967 crate::timeline::ref_wait(
968 decode_idx,
969 slot,
970 dep_owner[slot],
971 crate::timeline::now().saturating_sub(t0),
972 );
973 }
974 }
975 crate::timeline::refs_ready();
976 // Fresh per-thread state: every field this path reads is
977 // written from this frame's own header before it is read.
978 let fctx = crate::decode::FrameCtx::new();
979 // lane-twostage: the pictures behind this frame's own
980 // references, waited for at the first `ref_planes` call
981 // inside the tile decode rather than here.
982 let ref_metas: [Option<std::sync::Arc<SlotValue>>; 8] =
983 std::array::from_fn(|i| {
984 if i == 0 {
985 None
986 } else {
987 resolved
988 .get(header.ref_frame_idx[i - 1] as usize)
989 .cloned()
990 .flatten()
991 }
992 });
993 let pix_cell: std::sync::OnceLock<
994 [Option<std::sync::Arc<Picture>>; 8],
995 > = std::sync::OnceLock::new();
996 let wait_pixels = || -> Result<[Option<&Picture>; 8]> {
997 if pix_cell.get().is_none() {
998 let mut pics: [Option<std::sync::Arc<Picture>>; 8] =
999 Default::default();
1000 for (i, meta) in ref_metas.iter().enumerate() {
1001 if let Some(meta) = meta {
1002 let slot = header.ref_frame_idx[i - 1] as usize;
1003 let t0 = crate::timeline::now();
1004 pics[i] = Some(meta.pixels.wait()?);
1005 crate::timeline::ref_wait(
1006 decode_idx,
1007 slot,
1008 dep_owner[slot],
1009 crate::timeline::now().saturating_sub(t0),
1010 );
1011 }
1012 }
1013 let _ = pix_cell.set(pics);
1014 }
1015 let pics = pix_cell.get().expect("the pictures were just set");
1016 Ok(std::array::from_fn(|i| pics[i].as_deref()))
1017 };
1018 let refpix = decode::RefPix::lazy(
1019 std::array::from_fn(|i| {
1020 ref_metas[i].as_ref().map(|m| (m.width, m.height))
1021 }),
1022 &wait_pixels,
1023 );
1024 // Stage 1: published at this frame's tile boundary, before
1025 // its filters run (`take_segment_ids` copies the map, so
1026 // the filters that read it are unaffected).
1027 let stage1 = |cdfs: Cdfs,
1028 motion_field: crate::motion_field::MotionField,
1029 width: usize,
1030 height: usize| {
1031 if let Some(promise) = &promise {
1032 promise.fulfil(std::sync::Arc::new(SlotValue {
1033 pixels: pixels.clone(),
1034 width,
1035 height,
1036 cdfs,
1037 motion_field,
1038 seg_map: decode::take_segment_ids(&fctx),
1039 order_hint: header.order_hint,
1040 }));
1041 crate::timeline::slot_fulfil();
1042 }
1043 };
1044 // spec 7.9's `av1_setup_motion_field` runs inside
1045 // `RefSnapshot::take`, i.e. here, after those waits --
1046 // it reads the referenced slots' saved motion fields.
1047 let motion_fields =
1048 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.motion_field));
1049 let snap = RefSnapshot::take(
1050 &header,
1051 seq,
1052 &refpix,
1053 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)),
1054 std::array::from_fn(|i| {
1055 resolved[i].as_ref().map(|v| v.seg_map.as_slice())
1056 }),
1057 &motion_fields,
1058 std::array::from_fn(|i| resolved[i].as_ref().map_or(0, |v| v.order_hint)),
1059 );
1060 let out = decode_frame(
1061 &fctx,
1062 &header,
1063 &tile_bufs,
1064 seq,
1065 snap,
1066 decode_idx,
1067 shown_idx,
1068 dump.as_deref(),
1069 // lane-twostage publishes a frame's meta at its tile
1070 // boundary instead of after its filters, so a consumer
1071 // parses over its producer's filter tail. It is ON by
1072 // default since lane-sub8group: with every reference
1073 // pixel read deferred to the recon workers, the
1074 // consumer parses its WHOLE tile before it needs a
1075 // pixel, and the 4K critical chain shortens by 11-14%
1076 // in three interleaved pairs (14450/10594/14407 ms off
1077 // vs 12790/9207/12463 ms on) where it moved 3-7%
1078 // before. `EC_AV1_TWO_STAGE=0` turns it back off.
1079 (crate::envflags::var("EC_AV1_TWO_STAGE").as_deref() != Ok("0"))
1080 .then_some(&stage1 as &dyn Fn(_, _, _, _)),
1081 )?;
1082 // Publish before grain synthesis: every frame waiting on
1083 // this slot can start the moment the clean picture exists
1084 // (spec 7.18.3.1 -- the bank never stores grain).
1085 let picture = std::sync::Arc::new(out.picture);
1086 pixels.fulfil(picture.clone());
1087 if let Some(promise) = &promise {
1088 // Only a frame whose stage-1 sink never fired (a
1089 // superres frame) still has meta to publish here.
1090 promise.fulfil_if_pending(|| {
1091 std::sync::Arc::new(SlotValue {
1092 pixels: pixels.clone(),
1093 width: picture.width,
1094 height: picture.height,
1095 cdfs: out.stored_cdfs,
1096 motion_field: out.motion_field.expect(
1097 "a frame that published no stage 1 carries its motion field back",
1098 ),
1099 seg_map: out.seg_map,
1100 order_hint: header.order_hint,
1101 })
1102 });
1103 crate::timeline::slot_fulfil();
1104 }
1105 // Grain is synthesised for OUTPUT only: a hidden frame is
1106 // reported to the sink clean, exactly as the inline path
1107 // below reports it (spec 7.18.3.1).
1108 let output = if shown && header.film_grain.apply_grain && !no_grain() {
1109 std::sync::Arc::new(crate::film_grain::apply_grain(
1110 &picture,
1111 &header.film_grain,
1112 seq.mc_identity,
1113 u32::from(seq.bit_depth),
1114 &fctx,
1115 ))
1116 } else {
1117 picture
1118 };
1119 crate::timeline::grain_done();
1120 Ok((output, decode_idx, shown))
1121 }))
1122 .unwrap_or_else(|_| {
1123 Err(Error::corrupt(
1124 "AV1 decode_stream: a worker thread panicked decoding a frame",
1125 ))
1126 });
1127 // A frame nobody can decode must not leave its consumers
1128 // waiting for a slot that will never be filled.
1129 if reply.is_err() {
1130 // Neither stage may leave a consumer waiting for a value
1131 // that will never come.
1132 if let Some(promise) = &promise {
1133 promise.fail();
1134 }
1135 pixels.fail();
1136 }
1137 let _ = tx.send((job_seq, true, reply));
1138 });
1139 in_flight_decodes += 1;
1140 FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1141 // Anything that finished while this frame was being set up.
1142 while let Ok((seq, decode_job, result)) = rx.try_recv() {
1143 if decode_job {
1144 in_flight_decodes -= 1;
1145 } else {
1146 in_flight_shows -= 1;
1147 }
1148 let (picture, decode_idx, shown) = result?;
1149 reorder.push(seq, picture, decode_idx, shown);
1150 reorder.drain(&mut sink)?;
1151 }
1152 continue;
1153 }
1154 // lane-twostage: the inline path's references are decoded already,
1155 // so its handle never waits.
1156 let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| {
1157 if i == 0 {
1158 None
1159 } else {
1160 ref_slots
1161 .get(header.ref_frame_idx[i - 1] as usize)
1162 .and_then(|p| p.as_deref())
1163 }
1164 }));
1165 let snap = RefSnapshot::take(
1166 &header,
1167 seq,
1168 &inline_refpix,
1169 std::array::from_fn(|i| cdf_slots[i].as_ref()),
1170 std::array::from_fn(|i| seg_map_slots[i].as_deref()),
1171 &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
1172 order_hint_slots,
1173 );
1174 let bit_depth = seq.bit_depth;
1175 let FrameOutput {
1176 picture,
1177 stored_cdfs,
1178 motion_field,
1179 seg_map: decoded_seg_map,
1180 } = decode_frame(
1181 fctx,
1182 &header,
1183 &tile_bufs,
1184 seq,
1185 snap,
1186 pictures_decoded,
1187 pictures_shown,
1188 final_dump.as_deref(),
1189 None,
1190 )?;
1191 let motion_field =
1192 motion_field.expect("the inline path passes no stage-1 sink");
1193 pictures_decoded += 1;
1194 // lane-pool1: one allocation, then every slot store and the output
1195 // itself are refcount bumps instead of plane copies.
1196 let picture = std::sync::Arc::new(picture);
1197 if threads > 1 {
1198 // lane-thread3: only a key frame reaches this inline path at
1199 // `threads > 1`, and the bank it fills is the promise array --
1200 // already resolved, since the picture exists right here.
1201 if header.refresh_frame_flags != 0 {
1202 let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {
1203 pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)),
1204 width: picture.width,
1205 height: picture.height,
1206 cdfs: stored_cdfs,
1207 motion_field,
1208 seg_map: decoded_seg_map,
1209 order_hint: header.order_hint,
1210 }));
1211 for i in 0..NUM_REF_FRAMES {
1212 if header.refresh_frame_flags & (1 << i) != 0 {
1213 slot_promises[i] = Some(promise.clone());
1214 slot_owner[i] = pictures_decoded - 1;
1215 }
1216 }
1217 }
1218 } else {
1219 for i in 0..NUM_REF_FRAMES {
1220 if header.refresh_frame_flags & (1 << i) != 0 {
1221 cdf_slots[i] = Some(stored_cdfs.clone());
1222 // Spec 7.18.3.1: synthesized grain is never stored for
1223 // later prediction -- the reference bank always keeps the
1224 // clean, pre-grain decode, even though the frame pushed
1225 // onto the caller's output below carries the grained
1226 // picture.
1227 ref_slots[i] = Some(std::sync::Arc::clone(&picture));
1228 motion_field_slots[i] = Some(motion_field.clone());
1229 seg_map_slots[i] = Some(decoded_seg_map.clone());
1230 order_hint_slots[i] = header.order_hint;
1231 }
1232 }
1233 }
1234 // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a
1235 // KEY frame coded with `show_frame == 0`, output later by a
1236 // `show_existing_frame` header -- counted only once its tiles have
1237 // decoded, so the gate's assert covers decoded-and-compared frames.
1238 if header.frame_type == FrameType::Key && !header.show_frame {
1239 decode::note_fwd_kf();
1240 }
1241 if header.show_frame {
1242 let output = if header.film_grain.apply_grain && !no_grain() {
1243 let mc_identity = seq.mc_identity;
1244 std::sync::Arc::new(crate::film_grain::apply_grain(
1245 &picture,
1246 &header.film_grain,
1247 mc_identity,
1248 bit_depth as u32, fctx,
1249 ))
1250 } else {
1251 picture
1252 };
1253 reorder.push(emit_seq, output, pictures_decoded - 1, true);
1254 emit_seq += 1;
1255 reorder.drain(&mut sink)?;
1256 pictures_shown += 1;
1257 } else {
1258 // Hidden (alt-ref/forward-key) frames never reach
1259 // `decode_stream`'s output, but a decode-order consumer -- the
1260 // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs
1261 // them, so they are reported too, with `shown == false`.
1262 reorder.push(emit_seq, picture, pictures_decoded - 1, false);
1263 emit_seq += 1;
1264 reorder.drain(&mut sink)?;
1265 }
1266 }
1267 while in_flight_decodes + in_flight_shows > 0 {
1268 collect_one(
1269 &rx,
1270 &mut in_flight_decodes,
1271 &mut in_flight_shows,
1272 &mut reorder,
1273 &mut sink,
1274 )?;
1275 }
1276 debug_assert!(reorder.pending.is_empty(), "a frame was never emitted");
1277 crate::timeline::dump();
1278 Ok(())
1279}
1280
1281
1282
1283/// lane-thread2: the sequence-header bits a single frame's decode needs,
1284/// read once on the parsing thread so that [`decode_frame`] never touches the
1285/// [`Av1Parser`] (a worker thread has no access to it).
1286#[derive(Clone, Copy)]
1287pub(crate) struct SeqFlags {
1288 pub(crate) enable_filter_intra: bool,
1289 pub(crate) enable_dual_filter: bool,
1290 pub(crate) enable_edge_filter: bool,
1291 pub(crate) enable_masked_compound: bool,
1292 pub(crate) enable_jnt_comp: bool,
1293 pub(crate) enable_interintra_compound: bool,
1294 pub(crate) use_sb128: bool,
1295 pub(crate) bit_depth: u8,
1296 /// lane-av1mono: `color_config.mono_chrome` (spec 5.5.2):
1297 /// `NumPlanes == 1`, no chroma is coded or reconstructed.
1298 pub(crate) mono_chrome: bool,
1299 pub(crate) order_hint_bits: u32,
1300 pub(crate) mc_identity: bool,
1301 /// lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2). The decoder
1302 /// itself hardcodes 4:2:0 everywhere, so these exist only for the
1303 /// sequence-level refusal in [`decode_stream_with`] -- nothing downstream
1304 /// reads them. A monochrome header parses as 1,1, so `!(1,1)` singles out
1305 /// 4:4:4 (profile 1 / sRGB) and 4:2:2 (profile 2 below 12-bit).
1306 pub(crate) subsampling_x: u8,
1307 pub(crate) subsampling_y: u8,
1308}
1309
1310impl SeqFlags {
1311 fn read(parser: &Av1Parser) -> Self {
1312 let seq = parser.sequence_header();
1313 Self {
1314 enable_filter_intra: seq.is_some_and(|s| s.enable_filter_intra),
1315 enable_dual_filter: seq.is_some_and(|s| s.enable_dual_filter),
1316 enable_edge_filter: seq.is_some_and(|s| s.enable_intra_edge_filter),
1317 enable_masked_compound: seq.is_some_and(|s| s.enable_masked_compound),
1318 enable_jnt_comp: seq.is_some_and(|s| s.enable_jnt_comp),
1319 enable_interintra_compound: seq.is_some_and(|s| s.enable_interintra_compound),
1320 use_sb128: seq.is_some_and(|s| s.use_128x128_superblock),
1321 bit_depth: seq.map_or(8, |s| s.color_config.bit_depth),
1322 mono_chrome: seq.is_some_and(|s| s.color_config.mono_chrome),
1323 order_hint_bits: seq.map_or(0, |s| s.order_hint_bits),
1324 mc_identity: seq.is_some_and(|s| s.color_config.matrix_coefficients == 0),
1325 subsampling_x: seq.map_or(1, |s| s.color_config.subsampling_x),
1326 subsampling_y: seq.map_or(1, |s| s.color_config.subsampling_y),
1327 }
1328 }
1329}
1330
1331/// lane-thread2: everything one frame's decode reads out of the cross-frame
1332/// banks `decode_stream_with` owns -- taken on the parsing thread, before any
1333/// later frame can overwrite a slot, so a frame can be decoded anywhere.
1334pub(crate) struct RefSnapshot<'a> {
1335 /// lane-twostage: this frame's references, indexed by `ref_frame`
1336 /// (`LAST_FRAME` = 1) -- sizes now, pixels at the first prediction.
1337 pub(crate) refpix: &'a decode::RefPix<'a>,
1338 /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame
1339 /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the
1340 /// second case is the refusal [`decode_frame`] raises where it always
1341 /// did, so the error order over a malformed stream is unchanged).
1342 pub(crate) primary_cdfs: Option<Cdfs>,
1343 /// Spec `load_previous_segment_ids`, from the same slot.
1344 pub(crate) prev_seg_map: Option<Vec<u8>>,
1345 /// Spec 7.9's projection, already run against `motion_field_slots`.
1346 pub(crate) tpl_field: Option<crate::motion_field::TplField>,
1347 /// `order_hint_slots[ref_frame_idx[i]]` for `LAST_FRAME + i`.
1348 pub(crate) ref_order_hints: [u32; 7],
1349}
1350
1351impl<'a> RefSnapshot<'a> {
1352 /// Reads the banks for `header`. Every slot is passed in by reference so
1353 /// that the single-threaded path can borrow the DPB in place while a
1354 /// worker borrows the resolved [`SlotPromise`] values it waited on --
1355 /// spec 7.9's `setup_motion_field` therefore runs on the DECODING thread
1356 /// (lane-thread3), after those waits.
1357 fn take(
1358 header: &FrameHeader,
1359 seq: SeqFlags,
1360 refpix: &'a decode::RefPix<'a>,
1361 cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],
1362 seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],
1363 motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],
1364 order_hint_slots: [u32; NUM_REF_FRAMES],
1365 ) -> Self {
1366 let primary = (header.primary_ref_frame != PRIMARY_REF_NONE)
1367 .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize);
1368 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
1369 // this frame's header asks for it, and never for a key frame (which
1370 // codes no inter block at all).
1371 let tpl_field = (header.frame_type != FrameType::Key && header.use_ref_frame_mvs).then(
1372 || {
1373 crate::motion_field::setup_motion_field(
1374 motion_field_slots,
1375 header.ref_frame_idx,
1376 header.order_hint,
1377 seq.order_hint_bits,
1378 header.mi_rows as usize,
1379 header.mi_cols as usize,
1380 )
1381 },
1382 );
1383 if std::env::var_os("EC_TPL").is_some() {
1384 eprintln!(
1385 "EC_TPL order_hint={} use_ref_frame_mvs={} cells={}",
1386 header.order_hint,
1387 header.use_ref_frame_mvs,
1388 tpl_field
1389 .as_ref()
1390 .map_or(0, crate::motion_field::TplField::filled_cells)
1391 );
1392 }
1393 Self {
1394 refpix,
1395 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),
1396 prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)),
1397 tpl_field,
1398 ref_order_hints: std::array::from_fn(|i| {
1399 order_hint_slots[header.ref_frame_idx[i] as usize]
1400 }),
1401 }
1402 }
1403}
1404
1405/// lane-thread2: what one decoded frame contributes back to the stream --
1406/// its picture (clean, pre-grain: spec 7.18.3.1) plus the three pieces a
1407/// `refresh_frame_flags` bit stores into a reference slot.
1408pub(crate) struct FrameOutput {
1409 pub(crate) picture: Picture,
1410 pub(crate) stored_cdfs: Cdfs,
1411 /// lane-twostage: `None` when this frame handed its motion field to the
1412 /// stage-1 sink at its tile boundary instead of carrying it back here.
1413 pub(crate) motion_field: Option<crate::motion_field::MotionField>,
1414 pub(crate) seg_map: Vec<u8>,
1415}
1416
1417/// Spec 7.20's own `save_cdfs`: what a frame's `refresh_frame_flags` slots
1418/// keep -- the frame's INITIAL table when `disable_frame_end_update_cdf`,
1419/// otherwise the adapted end-of-tile table with every symbol counter zeroed
1420/// (libaom `av1_reset_cdf_symbol_counters`). lane-twostage: shared with the
1421/// stage-1 publish, which hands a consumer the same table it always got.
1422fn stored_cdfs_for(header: &FrameHeader, end_cdfs: Cdfs, started_from: Option<Cdfs>) -> Cdfs {
1423 if header.disable_frame_end_update_cdf {
1424 started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
1425 } else {
1426 let mut end_cdfs = end_cdfs;
1427 end_cdfs.reset_counts();
1428 end_cdfs
1429 }
1430}
1431
1432/// lane-thread2: one coded frame, decoded from its header, its tile payload
1433/// and a snapshot of the reference banks -- and from nothing else. Lifted
1434/// verbatim out of [`decode_stream_with`]'s loop so that the same code can
1435/// run on the parsing thread (a frame that refreshes a reference slot) or on
1436/// a worker (a leaf frame, see `decode_stream_with_threads`).
1437///
1438/// `fctx` is the DECODING thread's context: a worker uses a fresh one, which
1439/// is sound because every field this path reads is written by this function
1440/// (or by the tile decoders it calls) before it is read -- see the
1441/// `a_worker_context_starts_where_the_stream_context_would` gate.
1442///
1443/// # Errors
1444/// As [`decode_stream_with`], for this one frame.
1445#[allow(clippy::too_many_arguments)]
1446fn decode_frame(
1447 fctx: &crate::decode::FrameCtx,
1448 header: &FrameHeader,
1449 tile_bufs: &[&[u8]],
1450 seq: SeqFlags,
1451 snap: RefSnapshot<'_>,
1452 decode_idx: usize,
1453 shown_idx: usize,
1454 final_dump: Option<&str>,
1455 // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`.
1456 stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,
1457) -> Result<FrameOutput> {
1458 crate::census::frame_start(header, tile_bufs.iter().map(|t| t.len()).sum(), decode_idx);
1459 if header.segmentation.enabled {
1460 // lane-hdrlossless: libaom IMPLEMENTS these three -- they rewrite a
1461 // block's reference / skip / mode BEFORE the symbols are read
1462 // (`decodemv.c:431` SEG_LVL_SKIP, `:437` SEG_LVL_REF_FRAME /
1463 // SEG_LVL_GLOBALMV, `:1071` in `read_ref_frames`, `:1350` in
1464 // `read_is_inter_block`), so a conformant stream CAN carry them and
1465 // this is a capability gap, not a spec-conformant guard. Reachability
1466 // from `aomenc` is nil, for three independent reasons (lane-av1seglvl
1467 // census): the AQ modules clear the table then set `SEG_LVL_ALT_Q`
1468 // only (`aq_variance.c:61` clear + `:89` enable, `aq_complexity.c:74`
1469 // + `:118`, `aq_cyclicrefresh.c:616` + `:630`); the one other setter,
1470 // `configure_static_seg_features` (`encoder_utils.c:315`, which would
1471 // set ALT_LF/REF_FRAME/SKIP around alt-ref groups), is gated on
1472 // `hl_sf.static_segmentation` -- a speed feature libaom's own
1473 // `speed_features.h` documents as "Always set to 0" -- AND on the
1474 // second pass of a two-pass encode (`encoder_utils.c:738`); and
1475 // ROI/active-map maps are control-API only (`av1_apply_roi_map`,
1476 // `av1_apply_active_map`: the CLI exposes no flag for either). Kept as
1477 // a named gap: the lift is an INTER-block-path change (ref/skip/mode
1478 // selection) outside this lane's region. See `lanes/av1hdr.report.md`
1479 // §4.1 and `lanes/av1seglvl.report.md`.
1480 for segment in 0..MAX_SEGMENTS {
1481 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
1482 if header.segmentation.feature_enabled[segment][feature] {
1483 return Err(Error::unsupported(
1484 "AV1 decode_stream",
1485 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",
1486 ));
1487 }
1488 }
1489 }
1490 }
1491 // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the
1492 // primary reference frame's slot, and is all-zero without one.
1493 decode::set_segmentation(
1494 header.segmentation,
1495 header.mi_rows as usize,
1496 header.mi_cols as usize,
1497 snap.prev_seg_map.as_deref(), fctx,
1498 );
1499 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
1500 // symbol (spec 7.16's upscaling is a pixel-domain post-process
1501 // libaom's `decodeframe.c` runs between CDEF and loop restoration,
1502 // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile
1503 // reads stay bit-exact in sync and `crate::superres::upscale_picture`
1504 // (below, after decode) makes its `Picture` the spec-correct
1505 // `upscaled_width` instead of silently staying at `frame_width`.
1506 // lane-superres r10: an INTER frame under `use_superres` no longer
1507 // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3)
1508 // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/
1509 // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes
1510 // at the downscaled `frame_width` and upscales its own output the
1511 // same way the key-frame branch above does (see the inter branch
1512 // below). The combinations `predict_scaled` does not cover
1513 // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8
1514 // leaf) still refuse by name, deep in `decode.rs`, rather than
1515 // silently mispredicting -- see `refusal_inventory.rs`.
1516 // Loop restoration carries per-restoration-unit symbols in the tile
1517 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
1518 // superblock walk) -- lane-lr r2 ported the reader
1519 // (`crate::restoration`), r3 moved this refusal check to AFTER the
1520 // tile decode call below (was here, before it, in r2 -- meaning
1521 // `read_lr` was NEVER actually reached through `decode_stream`, the
1522 // gap the r3 gate caught live: 40/40 attempts hit this refusal with
1523 // zero `read_lr_unit` hits). Checking post-decode instead proves the
1524 // superblock walk actually survived `read_lr` (no desync) before
1525 // refusing on the true remaining gap: decoded Wiener/SGR filters are
1526 // stored per unit but never applied to pixels.
1527 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
1528 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
1529 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
1530 // zero vector only under `GmType == IDENTITY` -- any other warp
1531 // model needs the full affine/translation MV derivation this
1532 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
1533 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
1534 // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
1535 // to every one of the 7 single-reference slots `decode_inter_block`
1536 // can now select.
1537 //
1538 // lane-gm r2 STEP-8 ATTEMPT (reverted): removing this refusal
1539 // exposed a real pixel mismatch --
1540 // a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact
1541 // seed 43, frame 1 luma, with EC_WEDGE_GATE_ATTEMPTS=20
1542 // EC_AV1_REQUIRE_AOMENC=1 -- so the single-ref/compound MV wiring
1543 // is not yet provably correct end to end; keeping the refusal
1544 // until that seed is captured (EC_AV1_GATE_DUMP), self-pinned, and
1545 // root-caused rather than shipping a wrong decode.
1546 //
1547 // lane-gm r3 ROOT CAUSE (pinned, range-ladder-confirmed, still not
1548 // fixed): the mismatch is NOT an mv/mvstack/entropy bug -- msac
1549 // RANGE at the first divergent block (mi=(8,0), frame 1) matches
1550 // aomdec's own `EC_PART` trace bit-for-bit (rng=38664 both sides),
1551 // and this decoder's own `gm_get_motion_vector` for that block
1552 // (ROTZOOM, seed 43's own header) computes the spec-correct
1553 // mv=(-8,8) (hand-verified against mv.h's `block_center_x`/`_y`,
1554 // which found and fixed a real `- 1` omission in `warp.rs` --
1555 // harmless for THIS block's rounding but a genuine spec bug fixed
1556 // regardless). The actual gap: `reconinter.c`'s `allow_warp` has a
1557 // `global_warp_allowed` branch (`warp_types.global_warp_allowed =
1558 // is_global_mv_block(...)`, `reconinter_enc.c:281`) that predicts
1559 // an `is_global_mv_block` block (ROTZOOM/AFFINE GLOBALMV, >=8x8)
1560 // with the FULL per-pixel affine global-motion warp, independent
1561 // of `motion_mode` -- this decoder only ever builds a warp
1562 // prediction for local `WARPED_CAUSAL` motion mode and falls back
1563 // to plain translational MC with the block-centre mv for every
1564 // other GLOBALMV block, which is only a centre-point approximation
1565 // of the true per-pixel warp. That is the entire remaining gap.
1566 // lane-gm r4: `decode.rs` now feeds `global_motion[ref]` into
1567 // `crate::warp::global_warp_params` for every single-ref
1568 // `is_global_mv_block` (ROTZOOM/AFFINE), matching `allow_warp`'s
1569 // `global_warp_allowed` branch -- ROTZOOM is pin-verified
1570 // (`gm-seed43.obu`, frame 1 luma MATCH) and TRANSLATION already
1571 // worked (`gm_get_motion_vector`'s translation-only mv, no warp
1572 // needed). AFFINE is untested this round (no aomenc fixture in the
1573 // wedge gate reached a 6-parameter model) -- keep refusing it by
1574 // name rather than shipping an unverified decode.
1575 // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom
1576 // can never write a 6-parameter model -- its encoder-side search is
1577 // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`,
1578 // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) --
1579 // which is why four rounds of `--enable-global-motion=1` recipes
1580 // never reached the case. `scripts/build-aom-affine-oracle.sh` widens
1581 // exactly that search range in a side build, and
1582 // `a_real_affine_global_motion_stream_decodes_pixel_exact` below
1583 // decodes its output pixel-exact against ffmpeg with
1584 // `affine_gm_hits() > 0`, i.e. real blocks predicted through the
1585 // 6-parameter warp. Nothing in the decoder needed changing: the
1586 // header reader already reads params 4/5 with their own subexp refs
1587 // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s
1588 // shear-validity check + `warp_affine` are model-agnostic.
1589 // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two
1590 // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and
1591 // refused the shape by name rather than guess-fix it. r5 localized
1592 // the mismatch to an ordinary NEWMV/GOLDEN block, not the new
1593 // global-warp branch at all -- proving "two active slots" was a
1594 // correlated symptom, not the cause. r6 range-laddered that block
1595 // against aomdec's `EC_TRACE_MODE` (identical `rng` before/after
1596 // mode info -- symbol consumption bit-exact) and found the real
1597 // defect in `mvstack.rs`'s single-reference predictor fallback:
1598 // libaom's `setup_ref_mv_list` fills any `mv_ref_list` slot the real
1599 // neighbour scan left short with this block's OWN global motion
1600 // vector for its ref (`gm_get_motion_vector`), not zero -- invisible
1601 // whenever the live ref's global motion is itself
1602 // identity/translation, wrong the moment it's a real ROTZOOM/AFFINE
1603 // and the querying block's own stack comes up short (frame 14's
1604 // mi=(0,0), the very first block decoded, has no neighbours at
1605 // all). Fixed at the predictor fallback; the refusal above (single
1606 // untested shape: AFFINE on a single-ref frame) stays, but the
1607 // *multi-slot* refusal this comment used to guard is lifted -- the
1608 // r5/r6 pin (seed-43 wedge-gate mismatch) now decodes all 24 frames
1609 // byte-exact with it gone.
1610 // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
1611 // `comp_mode` per block whenever this frame's own `reference_select`
1612 // header bit is set (spec 5.11.25), and refuse by name the blocks
1613 // that pick `COMPOUND_REFERENCE` -- two-reference motion
1614 // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
1615 // is wired at the block level too (forced NEAREST_NEARESTMV compound
1616 // of `skip_mode_frame`, plain average blend), so the old blanket
1617 // `skip_mode_present` refusal is gone.
1618 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
1619 // which tile's end-of-tile adapted CDFs become the frame's own.
1620 // lane-tiles r8: this comment used to claim a `!= 0` refusal existed
1621 // "further down" -- it did not (`decode.rs` reads
1622 // `tile_info.context_update_tile_id` generically at both the
1623 // key-frame and inter-frame tile loops' `result_cdfs = cdfs` sites,
1624 // never hardcoded to tile 0); stale documentation, not a real gap.
1625 // `a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact`
1626 // hard-asserts a live aomenc stream naming tile 1/2/3 decodes
1627 // pixel-exact, so the capability is now proven as well as described
1628 // correctly.
1629 //
1630 // lane-tiles r4/r6/r7/r8: the multi-tile refusal itself is scoped,
1631 // not blanket. `decode_key_frame_tile_with_cdfs` and (r6)
1632 // `decode_inter_frame_tile_with_cdfs` both genuinely loop every
1633 // tile, `mvstack.rs`'s `MiGrid` is bounded per tile
1634 // (`MiGrid::set_tile_bounds`), and `PlaneBuf`'s `tile_x0/y0/x1/y1`
1635 // origin receives real values at every call site (r6's
1636 // `set_tile_origin` sweep). r7 proved the two remaining
1637 // tile-*column* gaps closed (inter frames, >2 columns with loop
1638 // filtering on). r8 proved tile *rows* the same way: the per-tile
1639 // loop's row math (`tile_num / tile_info.cols`,
1640 // `mi_row_starts`/`set_tile_origin`'s `y0`/`y1`) is exactly
1641 // symmetric with the column path already proven, and
1642 // `a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact`
1643 // (bypass gate, loop filter ON) confirmed it: 20/20 pixel-exact.
1644 // `a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_
1645 // stream` below re-proves it through this entry point. Tile columns
1646 // and tile rows (any count, loop filter on) are no longer capped.
1647 // `Tile::offset` is relative to the buffer `parse_obu` was handed
1648 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
1649 // to `obu_offset`, not to `data` as a whole.
1650 let enable_filter_intra = seq.enable_filter_intra;
1651 let enable_dual_filter = seq.enable_dual_filter;
1652 let enable_edge_filter = seq.enable_edge_filter;
1653 // Inter frames' intra blocks read this through a thread-local that only
1654 // the key-frame tile path used to set; without this call a stream whose
1655 // inter frames are decoded on a thread that previously decoded a
1656 // different sequence would inherit that sequence's bit.
1657 crate::decode::set_enable_edge_filter(enable_edge_filter, fctx);
1658 // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the
1659 // key-frame and the inter tile path read the 128 partition root and
1660 // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and
1661 // libaom's quadrant visit order into the inter loop too). A frame at
1662 // most 64x64 decodes identically either way (its 128 root reads no
1663 // symbol -- neither half is in frame, so SPLIT is inferred), so the
1664 // flag is only armed for frames bigger than one 64x64 superblock.
1665 let use_sb128 = seq.use_sb128;
1666 let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);
1667 crate::decode::set_sb128(sb128_active, fctx);
1668 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
1669 // which every dequant/inverse-transform clamp reads -- set per frame,
1670 // not once per process, for the same cross-sequence-on-one-thread
1671 // reason as `set_enable_edge_filter` above. Defaults to 8 when no
1672 // sequence header has been seen yet, matching every existing fixture.
1673 let bit_depth = seq.bit_depth;
1674 // lane-av112bit: the blanket 12-bit refusal is LIFTED for the paths the
1675 // lane's witnesses prove byte-exact against ffmpeg on real `aomenc
1676 // --bit-depth=12` streams (key frame and inter sequence, CDEF and loop
1677 // restoration ON, grain off -- gates
1678 // `a_real_aomenc_12bit_stream_decodes_pixel_exact` and
1679 // `a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact`). The
1680 // rounding sites that move at 12 bits are parameterised from libaom's
1681 // own rule (`mc.rs`'s `round_pair` -- convolve.h:81..86's `intbufrange`
1682 // delta: round_0 += bd-10, non-compound round_1 -= bd-10; the Wiener
1683 // pair via `get_conv_params_wiener`; the compound post-rounds absorb
1684 // the CONV_BUF gain), and CDEF/deblock/quant tables/SGR/palette reads/
1685 // superres upscale were already bit-depth generic (10-bit-proven).
1686 // Everything no 12-bit witness reached stays refused BY NAME at its own
1687 // site: warp (decode.rs, warp's reduce bits inherit the 12-bit round_0)
1688 // and any per-feature gap the witnesses' counters prove unreached -- see
1689 // the 12-bit refusals in decode.rs and `refusal_inventory.rs`.
1690 // lane-av112bitg: film grain joined the witnessed set (`grain_refusal`
1691 // deleted; the two-arm witness is
1692 // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
1693 // lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2) are parsed by
1694 // `ec-av1-syntax` -- profile 1 forces 4:4:4, profile 2 below 12-bit forces
1695 // 4:2:2, and the sRGB identity description forces full-range 4:4:4 -- but
1696 // the decoder reads them NOWHERE: every chroma extent is hardcoded 4:2:0
1697 // (`let (chroma_w, chroma_h) = (bw / 2, bh / 2)` at every rect site,
1698 // `chroma_side = side / 2` in `decode_block`) and the probe emits 4:2:0
1699 // planes only. Measured consequence: EVERY 4:4:4 stream desyncs at the
1700 // first chroma transform (a444-cu6 block (0,0): aomdec reads
1701 // `EC_COEFF plane=1 tx=TX_8X16` at rng 39857 where ours reads a 4-wide,
1702 // 8-high 4:2:0 chroma block at the same rng) and then decodes pixels that
1703 // are silently wrong. Refuse by name rather than return garbage. A
1704 // `num_planes == 1` (monochrome) header keeps its parsed 1,1 and is
1705 // unaffected. Gates: `a_non_420_subsampled_sequence_header_is_refused_by_
1706 // name` below (hand-built profile 1/2 headers plus a real aomenc 4:4:4
1707 // stream).
1708 // lane-av1-444: 4:4:4 (ss 0,0) is decoded. 4:2:2 (ss_x != ss_y) is not.
1709 if seq.subsampling_x != seq.subsampling_y {
1710 return Err(Error::unsupported(
1711 "AV1 decode_stream",
1712 "a chroma format of 4:2:2 (subsampling_x != subsampling_y): this decoder decodes 4:2:0 and 4:4:4; 4:2:2 is not ported",
1713 ));
1714 }
1715 // lane-av1-qmatrix: `quantization_params.using_qmatrix` + `qm_y`/`qm_u`/
1716 // `qm_v` (spec 5.9.12) select per-plane INVERSE QUANTISATION MATRICES --
1717 // spec 7.12.3's per-position `dqv` scale, libaom `get_dqv` over
1718 // `iwt_matrix_ref`. The parsed 4-bit values ARE the table levels
1719 // (libaom `quant_params->qmatrix_level_y/u/v`); 15 is libaom's flat
1720 // NULL-table sentinel, and a `using_qmatrix == 0` frame keeps all three
1721 // parked there, selecting no matrix. Frame-constant: recorded here (the
1722 // spot where this decoder refused such frames until this lane), read by
1723 // every dequantisation call site through [`crate::decode::block_iqmatrix`].
1724 // A real `aomenc --enable-qm=1` stream (`using_qmatrix = 1`, levels 5)
1725 // decodes byte-exact vs ffmpeg; the witness is
1726 // `a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact` below.
1727 let q = &header.quantization;
1728 // When the bit is UNSET the parsed 4-bit fields read 0 but mean nothing
1729 // (spec: they are not even coded): libaom parks the level at
1730 // `NUM_QM_LEVELS - 1`, its flat NULL-table sentinel
1731 // (`setup_segmentation_dequant`: `use_qmatrix ? qmatrix_level_y : 15`),
1732 // so a matrix-free frame selects no matrix.
1733 let flat = crate::qm::NUM_QM_LEVELS as u8 - 1;
1734 let levels = if q.using_qmatrix {
1735 [q.qm_y, q.qm_u, q.qm_v]
1736 } else {
1737 [flat; 3]
1738 };
1739 crate::decode::set_qm_levels(levels, fctx);
1740 // lane-av112bit: the frame-level half of the 12-bit gate -- screen
1741 // content tools. Neither palette nor intrabc has a 12-bit witness (the
1742 // 12-bit gates are natural content), and both hang off this header bit:
1743 // `allow_screen_content_tools` is what lets a block code a palette or
1744 // read a `use_intrabc` symbol. Refusing the FRAME by name keeps every
1745 // palette/intrabc code path 12-bit-unreachable rather than unwitnessed
1746 // and trusted. Gate:
1747 // `a_12bit_screen_content_stream_is_refused_by_name`.
1748 if bit_depth == 12 && header.allow_screen_content_tools {
1749 return Err(Error::unsupported(
1750 "AV1 decode_stream",
1751 "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)",
1752 ));
1753 }
1754 // lane-dpm1: a LOSSLESS frame (`qindex == 0` with zero deltas, spec 5.9.12)
1755 // is a different tile syntax, and this decoder has none of it: libaom
1756 // forces TX_4X4 with the WALSH-HADAMARD transform over every block (so no
1757 // `tx_depth` symbol is coded at all), and `is_cfl_allowed` narrows to
1758 // `plane_bsize == BLOCK_4X4` instead of the 32x32 rule, which changes the
1759 // `uv_mode` ALPHABET. Measured on his own screen-capture row at libaom
1760 // `-crf 5` (base_q_idx 0): the very first block, mi(0,0) BLOCK_32X32,
1761 // reads `uv_mode` off the CfL alphabet where libaom reads the plain one
1762 // (ours 12 = UV_CFL_PRED, aomdec 1 = V_PRED) and the tile desyncs at
1763 // symbol four of the frame. Refuse by name rather than return a picture
1764 // that is silently wrong from luma sample 0 (class `refusal-hides-a-defect`
1765 // read the other way: a silent wrong decode is worse than a named gap).
1766 // lane-lossless: `CodedLossless` (spec 5.9.12) -- every segment at
1767 // `qindex == 0` with zero plane deltas. The tile reader then forces TX_4X4
1768 // with the Walsh-Hadamard transform on every plane, codes no `tx_type`
1769 // symbol and narrows `is_cfl_allowed` to `plane_bsize == BLOCK_4X4`
1770 // (libaom `read_tx_size`/`read_tx_type`/`is_cfl_allowed`).
1771 //
1772 // lane-av1mixloss: PER-SEGMENT lossless (libaom `decodeframe.c:5205`) --
1773 // the header parser computes `lossless[segment_id]` for all 8 segments
1774 // (`qindex == 0` with zero plane deltas, `segment_qindex` applying that
1775 // segment's own `SEG_LVL_ALT_Q`) and `coded_lossless` = every segment
1776 // lossless. Everything FRAME-level already keys on the header's fields,
1777 // exactly as libaom gates them on `features->coded_lossless`/
1778 // `all_lossless`: `tx_mode` is `Only4x4` only when EVERY segment is
1779 // lossless, CDEF and the loop-filter levels are forced to 0 only then,
1780 // and loop restoration only on `all_lossless`. What this decoder lacked
1781 // was the BLOCK level: every block-decoder rule -- `read_tx_size`'s TX_4X4
1782 // early return, the suppressed `tx_type`, the Walsh-Hadamard,
1783 // `is_cfl_allowed`'s narrowing, the 4x4 chroma rasters -- indexes
1784 // `xd->lossless[segment_id]`, so a frame whose segments DISAGREE codes
1785 // lossless blocks inside a lossy frame. aomenc WRITES one:
1786 // `--end-usage=q --cq-level=0 --aq-mode=1` (variance AQ over a lossless
1787 // base) gives a high-variance segment a positive `SEG_LVL_ALT_Q` while a
1788 // flat one stays at `qindex == 0`. The table goes in whole and
1789 // [`decode::lossless`] resolves it per block through the block's own
1790 // `segment_id` (set by the spec-order `segment_id` read that precedes
1791 // every mode/transform symbol). Witness:
1792 // `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact`.
1793 crate::decode::set_lossless_per_seg(header.lossless, fctx);
1794 crate::decode::set_bit_depth(bit_depth, fctx);
1795 // lane-av1mono: the sequence header's `mono_chrome`, set per frame like
1796 // the bit depth so a mono frame decoded on a thread that last saw a
1797 // 4:2:0 one never inherits the wrong plane count.
1798 crate::decode::set_mono(seq.mono_chrome, fctx);
1799 crate::decode::set_subsampling(seq.subsampling_x, seq.subsampling_y, fctx);
1800 // lane-av1txr: spec 5.9.2 `disable_cdf_update` -- a frame that sets it
1801 // codes every tile symbol against the CDFs it started with, so the tile
1802 // readers must not adapt (libaom `decodeframe.c:2909`:
1803 // `allow_update_cdf = allow_update_cdf && !cm->features.disable_cdf_update`).
1804 crate::decode::set_disable_cdf_update(header.disable_cdf_update, fctx);
1805 // spec 7.16: this frame's superres state, for the filter chain --
1806 // `decode.rs` upscales between CDEF and loop restoration and sizes
1807 // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an
1808 // unscaled frame so a later frame never inherits it.
1809 crate::decode::set_superres(
1810 if header.use_superres { header.upscaled_width } else { 0 },
1811 u32::from(header.superres_denom), fctx,
1812 );
1813 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
1814 let enable_masked_compound = seq.enable_masked_compound;
1815 let enable_jnt_comp = seq.enable_jnt_comp;
1816 // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's
1817 // read site doc.
1818 let enable_interintra_compound = seq.enable_interintra_compound;
1819 let interp_fixed = match header.interpolation_filter {
1820 ec_av1_syntax::InterpolationFilter::Switchable => None,
1821 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
1822 };
1823 // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
1824 // from that reference slot's saved CDF state instead of the spec 8.4
1825 // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
1826 // builds.
1827 // lane-hdrlossless: libaom errors on the same stream (`decodeframe.c:5075`:
1828 // `if (features->primary_ref_frame != PRIMARY_REF_NONE &&
1829 // get_primary_ref_frame_buf(cm) == NULL) aom_internal_error(...,
1830 // AOM_CODEC_CORRUPT_FRAME, "Reference frame containing this frame's
1831 // initial frame context is unavailable.")`) -- a spec-conformant guard.
1832 let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
1833 None
1834 } else {
1835 Some(snap.primary_cdfs.clone().ok_or_else(|| {
1836 Error::unsupported(
1837 "AV1 decode_stream",
1838 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
1839 )
1840 })?)
1841 };
1842 let started_from = initial_cdfs.clone();
1843 // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame.
1844 decode::set_coeff_trace_frame(decode_idx);
1845 // lane-t900 r9: one line per DECODE-order frame naming the header
1846 // fields a desync cliff is usually keyed on (frame type, base q,
1847 // primary_ref, the 7 ref slots, refresh mask, order hints).
1848 if std::env::var_os("EC_PROBE_HDR").is_some() {
1849 eprintln!(
1850 "EC_HDR decode_idx={decode_idx} type={:?} show={} show_existing={} base_q={} primary_ref={} ref_idx={:?} refresh=0x{:02x} order_hint={} tiles={}x{} txmode={:?} interp={:?} reduced_tx={} allow_warp={} switchable_mo={} ref_mvs={} skip_mode={} cdef={:?} lr={:?}",
1851 header.frame_type,
1852 header.show_frame,
1853 header.show_existing_frame,
1854 header.quantization.base_q_idx,
1855 header.primary_ref_frame,
1856 header.ref_frame_idx,
1857 header.refresh_frame_flags,
1858 header.order_hint,
1859 header.tile_info.cols,
1860 header.tile_info.rows,
1861 header.tx_mode,
1862 header.interpolation_filter,
1863 header.reduced_tx_set,
1864 header.allow_warped_motion,
1865 header.is_motion_mode_switchable,
1866 header.use_ref_frame_mvs,
1867 header.skip_mode_present,
1868 header.cdef.bits,
1869 header.loop_restoration.frame_restoration_type,
1870 );
1871 }
1872
1873 let order_hint_bits = seq.order_hint_bits;
1874 // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
1875 // of the picture sitting in each of its 7 single references' DPB
1876 // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
1877 // (a later frame projects from it) whether or not this frame itself
1878 // reads temporal candidates.
1879 let ref_order_hints = snap.ref_order_hints;
1880
1881 crate::timeline::bind(
1882 decode_idx,
1883 if header.frame_type == FrameType::Key {
1884 'K'
1885 } else if header.show_frame {
1886 'P'
1887 } else {
1888 'A'
1889 },
1890 header.show_frame,
1891 );
1892 crate::timeline::hdr_done();
1893 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
1894 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
1895 &tile_bufs,
1896 &header.tile_info,
1897 header.mi_cols,
1898 header.mi_rows,
1899 header.quantization.base_q_idx,
1900 crate::quant::QuantDeltas {
1901 y_dc: i32::from(header.quantization.delta_q_y_dc),
1902 u_dc: i32::from(header.quantization.delta_q_u_dc),
1903 u_ac: i32::from(header.quantization.delta_q_u_ac),
1904 v_dc: i32::from(header.quantization.delta_q_v_dc),
1905 v_ac: i32::from(header.quantization.delta_q_v_ac),
1906 },
1907 header.frame_width,
1908 header.frame_height,
1909 enable_filter_intra,
1910 enable_edge_filter,
1911 &header.cdef,
1912 &header.loop_filter,
1913 &header.loop_restoration,
1914 initial_cdfs,
1915 header.tx_mode == TxMode::Select,
1916 header.reduced_tx_set,
1917 header.allow_screen_content_tools,
1918 header.allow_intrabc,
1919 header.delta, fctx,
1920 )?;
1921 // A key frame codes no inter blocks -- its own saved motion
1922 // field has no cells set, matching libaom's own "intra frame
1923 // contributes nothing to a later projection" behaviour, but
1924 // still carries `order_hint`/`ref_order_hints` for the distance
1925 // arithmetic a later frame's projection needs.
1926 let motion_field = crate::motion_field::MotionField::new(
1927 header.mi_cols as usize,
1928 header.mi_rows as usize,
1929 header.order_hint,
1930 ref_order_hints,
1931 // `frame_type` for the DPB slot: a key (or intra-only) frame is
1932 // never a projection source, and never spends a `ref_stamp`.
1933 true,
1934 );
1935 (picture, end_cdfs, Some(motion_field))
1936 } else {
1937 let last_slot = header.ref_frame_idx[0] as usize;
1938 let _ = last_slot;
1939 // lane-hdrlossless: libaom errors on the same stream -- a stream may
1940 // OPEN on an intra-only frame, but a reference resolving to a slot
1941 // that is still NULL is `AOM_CODEC_CORRUPT_FRAME "Inter frame
1942 // requests nonexistent reference"` (`decodeframe.c:5008-5031`) -- a
1943 // spec-conformant guard.
1944 if snap.refpix.dims(1).is_none() {
1945 return Err(Error::unsupported(
1946 "AV1 decode_stream",
1947 "an inter frame with no key frame before it",
1948 ));
1949 }
1950 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
1951 // (spec 7.8/7.20). Any of them having no picture yet is not a
1952 // stream error on its own: `decode_inter_block` only needs a
1953 // given slot when a block actually selects that reference, and
1954 // refuses by name there if the slot is still empty -- widened
1955 // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
1956 // one of the 7 single-reference slots.
1957 // lane-fimv r1: record the header state the fimv gate asserts on
1958 // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause).
1959 if header.force_integer_mv {
1960 decode::note_force_integer_mv_frame();
1961 }
1962 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
1963 // this frame's header actually asks for temporal candidates --
1964 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
1965 // behaviour bit for bit when this is `None` (see its own doc).
1966 // lane-twostage: the stage-1 sink is handed the table a consumer
1967 // would have read out of the slot, not the raw end-of-tile one.
1968 let started_from_stage1 = started_from.clone();
1969 let stage1_adapter = stage1.map(|sink| {
1970 move |end_cdfs: Cdfs,
1971 motion_field: crate::motion_field::MotionField,
1972 width: usize,
1973 height: usize| {
1974 sink(
1975 stored_cdfs_for(header, end_cdfs, started_from_stage1.clone()),
1976 motion_field,
1977 width,
1978 height,
1979 )
1980 }
1981 });
1982 let tpl_field = &snap.tpl_field;
1983 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
1984 &tile_bufs,
1985 &header.tile_info,
1986 header.mi_cols,
1987 header.mi_rows,
1988 header.quantization.base_q_idx,
1989 crate::quant::QuantDeltas {
1990 y_dc: i32::from(header.quantization.delta_q_y_dc),
1991 u_dc: i32::from(header.quantization.delta_q_u_dc),
1992 u_ac: i32::from(header.quantization.delta_q_u_ac),
1993 v_dc: i32::from(header.quantization.delta_q_v_dc),
1994 v_ac: i32::from(header.quantization.delta_q_v_ac),
1995 },
1996 header.frame_width,
1997 header.frame_height,
1998 snap.refpix,
1999 &header.cdef,
2000 &header.loop_filter,
2001 &header.loop_restoration,
2002 initial_cdfs,
2003 header.allow_high_precision_mv,
2004 header.force_integer_mv,
2005 header.ref_frame_sign_bias,
2006 header.global_motion,
2007 interp_fixed,
2008 enable_dual_filter,
2009 order_hint_bits,
2010 header.order_hint,
2011 ref_order_hints,
2012 tpl_field.as_ref(),
2013 header.reference_select,
2014 enable_masked_compound,
2015 enable_jnt_comp,
2016 enable_interintra_compound,
2017 header.skip_mode_present,
2018 header.skip_mode_frame,
2019 header.reduced_tx_set,
2020 header.tx_mode == TxMode::Select,
2021 header.is_motion_mode_switchable,
2022 header.allow_warped_motion,
2023 header.allow_screen_content_tools,
2024 header.delta,
2025 enable_filter_intra,
2026 stage1_adapter
2027 .as_ref()
2028 .map(|f| f as &dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)),
2029 fctx,
2030 )?;
2031 (picture, end_cdfs, motion_field)
2032 };
2033 // lane-lr r4: the Wiener/self-guided pixel filters are wired
2034 // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
2035 // `uses_lr` frames now decode all the way to pixels.
2036 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
2037 // *initial* table into the slots it refreshes, not the adapted
2038 // end-of-tile one.
2039 let stored_cdfs = stored_cdfs_for(header, end_cdfs, started_from);
2040 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
2041 use std::io::Write;
2042 if let Ok(mut f) = std::fs::OpenOptions::new()
2043 .create(true)
2044 .append(true)
2045 .open(&path)
2046 {
2047 let _ = writeln!(f, "=== frame idx={} ===", shown_idx);
2048 let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
2049 let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
2050 let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
2051 let _ = writeln!(f, "skip {:?}", stored_cdfs.skip);
2052 let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv);
2053 let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv);
2054 let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv);
2055 let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint);
2056 }
2057 }
2058 // lane-comppin r3: decode-order (not display-order) dump of every
2059 // frame's own post-deblock buffer -- the pre-existing pixel diff
2060 // (`scratch_isolate_pinned_mismatch`) only ever compares *shown*
2061 // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a
2062 // later shown frame is otherwise invisible; diff this byte-for-byte
2063 // against `EC_AV1_POSTFILT_DUMP.fN` from the instrumented aomdec
2064 // build to isolate whether the defect is in a hidden frame's own
2065 // reconstruction or downstream of it.
2066 if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") {
2067 use std::io::Write;
2068 let idx = decode_idx;
2069 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
2070 // lane-hbd r4: debug dump narrows to u8 -- this diagnostic
2071 // predates 10-bit support and is an 8-bit-oracle comparison
2072 // only (aomdec's own dump is 8-bit here too).
2073 let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
2074 let _ = f.write_all(&narrow(&picture.y));
2075 let _ = f.write_all(&narrow(&picture.u));
2076 let _ = f.write_all(&narrow(&picture.v));
2077 }
2078 }
2079 // lane-hidden r1: the frame exactly as it is about to be stored into
2080 // the reference slots -- after deblock/CDEF/LR/superres, in DECODE
2081 // order, hidden (`show_frame == 0`) alt-ref frames included, and
2082 // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the
2083 // u8-narrowing diagnostic dumps above. Matches the instrumented
2084 // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte
2085 // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a
2086 // hidden frame's pixels comparable at all.
2087 if let Some(prefix) = final_dump {
2088 use std::io::Write;
2089 if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{decode_idx}")) {
2090 let mut buf = Vec::new();
2091 for plane in [&picture.y, &picture.u, &picture.v] {
2092 if bit_depth == 8 {
2093 buf.extend(plane.iter().map(|&s| s as u8));
2094 } else {
2095 for &s in plane {
2096 buf.extend_from_slice(&s.to_le_bytes());
2097 }
2098 }
2099 }
2100 let _ = f.write_all(&buf);
2101 }
2102 }
2103 Ok(FrameOutput {
2104 picture,
2105 stored_cdfs,
2106 motion_field,
2107 seg_map: decode::take_segment_ids(fctx),
2108 })
2109}
2110
2111/// lane-intra14 r1: INTRA-coded 1:4 strips decoded on the INTER block path
2112/// (64x16, 16x64, 32x8, 8x32) -- the counters a recipe sweep needs from
2113/// outside the crate.
2114pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) {
2115 (
2116 crate::decode::intra_rect4_strip_in_inter_hits(0),
2117 crate::decode::intra_rect4_strip_in_inter_hits(1),
2118 crate::decode::intra_rect4_strip_in_inter_hits(2),
2119 crate::decode::intra_rect4_strip_in_inter_hits(3),
2120 )
2121}
2122
2123#[cfg(test)]
2124pub(crate) mod tests {
2125 use super::*;
2126 use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
2127
2128 fn test_card(width: usize, height: usize) -> Pic {
2129 let mut picture = Pic::grey(width, height);
2130 for row in 0..height {
2131 for col in 0..width {
2132 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
2133 }
2134 }
2135 for row in 0..height / 2 {
2136 for col in 0..width / 2 {
2137 let i = row * width / 2 + col;
2138 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
2139 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
2140 }
2141 }
2142 picture
2143 }
2144
2145 fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic {
2146 let mut picture = Pic::grey(width, height);
2147 for y in 0..height {
2148 for x in 0..width {
2149 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
2150 let gradient = sx * 200.0 / width as f64;
2151 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
2152 }
2153 }
2154 for y in 0..height / 2 {
2155 for x in 0..width / 2 {
2156 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
2157 let i = y * width / 2 + x;
2158 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
2159 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
2160 }
2161 }
2162 picture
2163 }
2164
2165 /// lane-av1txr: a sequence header describing any chroma shape but 4:2:0 is
2166 /// refused by name, because the decoder reconstructs every chroma extent
2167 /// at hardcoded 4:2:0 (`bw / 2, bh / 2` at every rect site) and the probe
2168 /// emits 4:2:0 planes only -- a 4:4:4 stream "decodes" into silently wrong
2169 /// pixels (measured: a444-cu6's first chroma transform reads a 4x2-wide/
2170 /// 8-high 4:2:0 chroma at aomdec's `TX_8X16` entry rng 39857, then
2171 /// desyncs; every 4:4:4 fixture measured byte-differs from ffmpeg).
2172 ///
2173 /// Reachability, not a pixel claim: the header is written at the two
2174 /// profiles that force a non-4:2:0 shape (spec 5.5.2 -- profile 1 forces
2175 /// 4:4:4 with no coded bit; profile 2 below 12-bit forces 4:2:2) and the
2176 /// tile is never reached. The 4:2:0 CONTROL below proves the refusal is
2177 /// about the shape, not about this construction.
2178 #[test]
2179 fn a_non_420_subsampled_sequence_header_is_refused_by_name() {
2180 const NAME: &str = "a_non_420_subsampled_sequence_header_is_refused_by_name";
2181 const REFUSAL: &str = "a chroma format of 4:2:2";
2182 let fctx = &crate::decode::FrameCtx::new();
2183 let picture = test_card(64, 64);
2184 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2185 for (profile, label, sx, sy) in [(2u8, "4:2:2", 1u8, 0u8)] {
2186 let color = ec_av1_syntax::ColorConfig {
2187 num_planes: 3,
2188 subsampling_x: sx,
2189 subsampling_y: sy,
2190 ..Default::default()
2191 };
2192 let (mut seq, header) =
2193 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
2194 seq.seq_profile = profile;
2195 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2196 stream.extend_from_slice(
2197 &crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap(),
2198 );
2199 let err = decode_stream(&stream).unwrap_err().to_string();
2200 assert!(
2201 err.contains(REFUSAL),
2202 "{NAME}: expected the non-4:2:0 refusal for the {label} header, got: {err}"
2203 );
2204 }
2205 // CONTROL: the same construction at profile 0 (4:2:0) still decodes.
2206 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2207 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2208 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap());
2209 let frames = decode_stream(&stream).expect("the 4:2:0 control must decode");
2210 assert_eq!(frames.len(), 1, "{NAME}: the 4:2:0 control decoded no frame");
2211 }
2212
2213 /// lane-av1-qmatrix: WITNESS for the lifted `using_qmatrix` refusal (the
2214 /// old gate `a_frame_using_quantisation_matrices_is_refused_by_name` is
2215 /// its mirror image -- its own panic said "flip this gate to a witness"
2216 /// the moment the dequant landed).
2217 ///
2218 /// A REAL `aomenc --enable-qm=1` stream (same source and recipe as the
2219 /// refusal's gate, plus its `--enable-qm=0` control) now DECODES, and
2220 /// every frame of both arms is pixel-exact against ffmpeg's own decode
2221 /// of the same OBU. The census proves the feature non-vacuously both
2222 /// ways (class `gate-blind-to-feature`): the parsed frame headers really
2223 /// carry `using_qmatrix = 1`, the dequantiser really SCALED transform
2224 /// units through a matrix on the qm-on arm (`qm_scaled_units() > 0`),
2225 /// and the qm-off control really scaled none (`== 0`).
2226 #[test]
2227 fn a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact() {
2228 const NAME: &str = "a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact";
2229 if !have_ffmpeg() || !have_aomenc() {
2230 eprintln!(
2231 "SKIP {NAME}: needs ffmpeg + an aomenc oracle at {}",
2232 aomenc_path().display()
2233 );
2234 return;
2235 }
2236 const W: usize = 128;
2237 const H: usize = 96;
2238 const FRAMES: usize = 3;
2239 // Every frame header's (using_qmatrix, qm_y, qm_u, qm_v), parsed
2240 // straight off the encoded bytes.
2241 let qm_headers = |stream: &[u8]| -> Vec<(bool, u8, u8, u8)> {
2242 let mut parser = Av1Parser::new();
2243 let mut pos = 0usize;
2244 let mut out = Vec::new();
2245 while pos < stream.len() {
2246 let obu = parser.parse_obu(&stream[pos..]).unwrap();
2247 pos += obu.total_size;
2248 if let ObuKind::Frame(header, _) = obu.kind {
2249 let q = &header.quantization;
2250 out.push((q.using_qmatrix, q.qm_y, q.qm_u, q.qm_v));
2251 }
2252 }
2253 out
2254 };
2255 // `census_attempt` hands back only the stream LENGTH; this witness
2256 // needs the BYTES to hand ffmpeg, so the same recipe (its base args
2257 // verbatim, `testsrc2` 128x96 @ 25fps, 3 frames) runs inline.
2258 let encode = |extra: &[&str]| -> Vec<u8> {
2259 let y4m = Command::new("ffmpeg")
2260 .args([
2261 "-v",
2262 "error",
2263 "-f",
2264 "lavfi",
2265 "-i",
2266 &format!("testsrc2=size={W}x{H}:rate=25"),
2267 "-t",
2268 "0.12",
2269 "-pix_fmt",
2270 "yuv420p",
2271 "-strict",
2272 "-1",
2273 "-f",
2274 "yuv4mpegpipe",
2275 "-",
2276 ])
2277 .stdin(Stdio::null())
2278 .stdout(Stdio::piped())
2279 .stderr(Stdio::piped())
2280 .output()
2281 .expect("ffmpeg failed to run");
2282 assert!(y4m.status.success(), "ffmpeg refused the {W}x{H} fixture");
2283 let mut args: Vec<String> = [
2284 "--codec=av1",
2285 "--passes=1",
2286 "--end-usage=q",
2287 "--threads=1",
2288 "--row-mt=0",
2289 "--kf-max-dist=9999",
2290 "--lag-in-frames=0",
2291 ]
2292 .iter()
2293 .map(|s| (*s).to_owned())
2294 .collect();
2295 args.push(format!("--limit={FRAMES}"));
2296 args.extend(extra.iter().map(|s| (*s).to_owned()));
2297 args.extend(["--obu".to_owned(), "-o".to_owned(), "-".to_owned(), "-".to_owned()]);
2298 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2299 assert!(
2300 out.status.success(),
2301 "aomenc refused {args:?}: {}",
2302 String::from_utf8_lossy(&out.stderr)
2303 );
2304 out.stdout
2305 };
2306 // Pixel-exact every decoded frame of `stream` against ffmpeg, plane
2307 // by plane, first differing sample named.
2308 let compare = |stream: &[u8], frames: usize, label: &str| {
2309 let want = ffmpeg_decode_sequence(stream, W, H, frames);
2310 let got =
2311 decode_stream(stream).unwrap_or_else(|e| panic!("{NAME}: {label} decode: {e}"));
2312 assert_eq!(got.len(), want.len(), "{NAME}: {label} frame count");
2313 for (i, (g, w)) in got.iter().zip(want.iter()).enumerate() {
2314 for (plane, (gp, wp)) in
2315 [(&g.y, &w.y), (&g.u, &w.u), (&g.v, &w.v)].into_iter().enumerate()
2316 {
2317 assert_eq!(gp, wp,
2318 "{NAME}: {label} frame {i} plane {plane} differs from ffmpeg (first mismatching sample: got {}, want {})",
2319 gp.iter().zip(wp.iter()).find(|(a, b)| a != b).map_or(0, |(a, _)| *a),
2320 gp.iter().zip(wp.iter()).find(|(a, b)| a != b).map_or(0, |(_, b)| *b));
2321 }
2322 }
2323 };
2324
2325 // CONTROL: the same source and recipe with quantisation matrices OFF
2326 // -- unchanged by this lane, and it must not scale a single unit
2327 // through a matrix.
2328 crate::quant::reset_qm_scaled_units();
2329 let control_stream = encode(&["--enable-qm=0"]);
2330 let control_frames = decode_stream(&control_stream)
2331 .unwrap_or_else(|e| panic!("{NAME}: the --enable-qm=0 control must decode, got: {e}"))
2332 .len();
2333 assert!(
2334 control_frames >= 1,
2335 "{NAME}: the qm-off control decoded no frame"
2336 );
2337 for (using, y, u, v) in qm_headers(&control_stream) {
2338 assert!(!using, "{NAME}: the control's frame header set using_qmatrix");
2339 assert_eq!(
2340 (y, u, v),
2341 (0, 0, 0),
2342 "{NAME}: the control's frame header carried qm levels {y}/{u}/{v}"
2343 );
2344 }
2345 compare(&control_stream, control_frames, "qm-off control");
2346 assert_eq!(
2347 crate::quant::qm_scaled_units(),
2348 0,
2349 "{NAME}: the qm-off control scaled units through a matrix"
2350 );
2351
2352 // The qm-on stream: decodes now, pixel-exact, levels 5 per plane as
2353 // aomenc writes them.
2354 crate::quant::reset_qm_scaled_units();
2355 let qm_stream = encode(&["--enable-qm=1"]);
2356 let qm_frames = decode_stream(&qm_stream)
2357 .unwrap_or_else(|e| panic!("{NAME}: the --enable-qm=1 stream must decode, got: {e}"))
2358 .len();
2359 assert!(qm_frames >= 1, "{NAME}: the qm-on stream decoded no frame");
2360 let headers = qm_headers(&qm_stream);
2361 assert!(
2362 !headers.is_empty() && headers.iter().all(|h| h.0),
2363 "{NAME}: not every qm-on frame header set using_qmatrix: {headers:?}"
2364 );
2365 assert!(
2366 headers.iter().all(|h| (h.1, h.2, h.3) == (5, 5, 5)),
2367 "{NAME}: expected aomenc's qm levels 5/5/5, got {headers:?}"
2368 );
2369 compare(&qm_stream, qm_frames, "qm-on");
2370 let scaled = crate::quant::qm_scaled_units();
2371 assert!(
2372 scaled > 0,
2373 "{NAME}: the --enable-qm=1 stream dequantized every unit flat -- \
2374 the matrices were never applied (class gate-blind-to-feature)"
2375 );
2376 eprintln!(
2377 "{NAME}: qm-off control {control_frames} frames exact (0 matrix-scaled units), \
2378 qm-on {qm_frames} frames exact ({scaled} matrix-scaled units, levels 5/5/5)"
2379 );
2380 }
2381
2382 /// lane-av1mono: the INVERSE of the pilot's
2383 /// `a_real_libaom_monochrome_key_frame_is_refused_by_name`, which the
2384 /// pilot's merge `d71084ae` landed on `main` (after this lane's base
2385 /// `7f4e8301`): the very same recipe now decodes, and its luma is
2386 /// byte-exact against ffmpeg's own decode of the same OBU. A merge of this
2387 /// lane into `main` must therefore resolve that pinning gate by adopting
2388 /// this witness in its place.
2389 ///
2390 /// `ffmpeg -pix_fmt gray -c:v libaom-av1` sets `color_config.mono_chrome`,
2391 /// so libaom codes NO chroma symbol anywhere in the sequence -- not the
2392 /// mode syntax, not a coefficient. That reaches all three classes this lane
2393 /// had to close: chroma SYMBOL reads (`uv_mode`/cfl/angle/palette), chroma
2394 /// COEFFICIENT reads on the rect-strip paths that call `read_coeffs_rect`
2395 /// DIRECTLY instead of through `read_plane`'s own plane gate, and the
2396 /// palette-mode neighbour band a mono sub-8x8 leaf must still clear before
2397 /// it returns (an uncleared band made the next block read `palette_y_mode`
2398 /// off the wrong CDF row and silently desynced the rest of the tile --
2399 /// measured at decode-order frame 33 of this very recipe).
2400 ///
2401 /// The 4:2:0 twin of the same source and settings is the control: it proves
2402 /// the recipe is decodable, so a failure here is about the plane count and
2403 /// not about the source or the encoder settings.
2404 #[test]
2405 fn a_real_libaom_monochrome_key_frame_decodes_pixel_exact() {
2406 const NAME: &str = "a_real_libaom_monochrome_key_frame_decodes_pixel_exact";
2407 if !have_ffmpeg() {
2408 eprintln!("SKIP {NAME}: no ffmpeg");
2409 return;
2410 }
2411 let emit = |pix: &str| -> Vec<u8> {
2412 let out = Command::new("ffmpeg")
2413 .args([
2414 "-v",
2415 "error",
2416 "-f",
2417 "lavfi",
2418 "-i",
2419 "testsrc2=size=320x240:rate=30:duration=2",
2420 "-pix_fmt",
2421 pix,
2422 "-c:v",
2423 "libaom-av1",
2424 "-cpu-used",
2425 "8",
2426 "-b:v",
2427 "300k",
2428 "-f",
2429 "obu",
2430 "-",
2431 ])
2432 .stdin(Stdio::null())
2433 .stdout(Stdio::piped())
2434 .stderr(Stdio::piped())
2435 .output()
2436 .expect("ffmpeg failed to run");
2437 assert!(
2438 out.status.success(),
2439 "{NAME}: ffmpeg ({pix}) failed: {}",
2440 String::from_utf8_lossy(&out.stderr)
2441 );
2442 out.stdout
2443 };
2444 // CONTROL: the identical recipe at 4:2:0 still decodes.
2445 let twin = decode_stream(&emit("yuv420p")).expect("the 4:2:0 twin must decode");
2446 assert!(!twin.is_empty(), "{NAME}: the 4:2:0 twin decoded no frames");
2447 // THE WITNESS: the monochrome stream decodes and every luma sample
2448 // equals ffmpeg's own decode of the same OBU.
2449 let gray = emit("gray");
2450 let ours = decode_stream(&gray)
2451 .unwrap_or_else(|e| panic!("{NAME}: the monochrome stream is REFUSED again: {e}"));
2452 let (width, height) = (320usize, 240usize);
2453 const FRAMES: usize = 60;
2454 assert_eq!(ours.len(), FRAMES, "{NAME}: expected {FRAMES} mono frames");
2455 let reference = ffmpeg_decode_gray_sequence(&gray, width, height, FRAMES);
2456 for (i, plane) in reference.chunks_exact(width * height).enumerate() {
2457 assert_eq!(ours[i].width, width, "{NAME}: frame {i} width");
2458 assert_eq!(ours[i].height, height, "{NAME}: frame {i} height");
2459 assert_eq!(
2460 ours[i].y.len(),
2461 width * height,
2462 "{NAME}: frame {i} luma length"
2463 );
2464 for (j, (got, want)) in plane.iter().zip(ours[i].y.iter()).enumerate() {
2465 assert_eq!(
2466 *want,
2467 u16::from(*got),
2468 "{NAME}: frame {i} luma sample {j} (row {}, col {}) is {want}, ffmpeg says {got}",
2469 j / width,
2470 j % width
2471 );
2472 }
2473 }
2474 eprintln!(
2475 "{NAME}: 4:2:0 twin {} frames, monochrome {} frames byte-exact vs ffmpeg",
2476 twin.len(),
2477 ours.len()
2478 );
2479 }
2480
2481 /// lane-t900 r25: the refusal "a frame OBU with no tile group" names a
2482 /// shape the parser cannot hand [`decode_stream`].
2483 ///
2484 /// `tiles` reaches that check from exactly two places -- `ObuKind::Frame`'s
2485 /// own vector and the `ObuKind::TileGroup` accumulation -- and both are
2486 /// filled by `ec_av1_syntax`'s `parse_tile_group`, whose only success path
2487 /// pushes one `Tile` per `tile_num` of the INCLUSIVE range
2488 /// `tg_start..=tg_end`. That range is never empty: the single-tile-group
2489 /// case takes `(0, num_tiles - 1)` saturating at 0, and the multi-group
2490 /// case rejects `end < start` as corrupt. So an `OBU_FRAME` either fails to
2491 /// parse or carries at least one tile, however short its payload is --
2492 /// including the empty payload the charter for this round asked to build,
2493 /// which parses into ONE zero-byte tile rather than none.
2494 ///
2495 /// Sweeping a real frame OBU's tile payload from empty upwards asserts both
2496 /// halves: every `Frame` OBU that parses has a tile, and `decode_stream`
2497 /// never reports this refusal for any of them.
2498 #[test]
2499 fn a_frame_obu_that_parses_always_carries_at_least_one_tile() {
2500 let fctx = &crate::decode::FrameCtx::new();
2501 const REFUSAL: &str = "a frame OBU with no tile group";
2502 let picture = test_card(64, 64);
2503 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2504 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2505 let mut frame_obus_parsed = 0;
2506 for len in 0..=encoded.tile.len().min(24) {
2507 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2508 stream.extend_from_slice(
2509 &crate::frame::frame_obu(&seq, &header, &encoded.tile[..len]).unwrap(),
2510 );
2511 let mut parser = Av1Parser::new();
2512 let mut pos = 0usize;
2513 while pos < stream.len() {
2514 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
2515 break;
2516 };
2517 pos += obu.total_size;
2518 if let ObuKind::Frame(_, tiles) = &obu.kind {
2519 frame_obus_parsed += 1;
2520 assert!(
2521 !tiles.is_empty(),
2522 "a {len}-byte tile payload parsed into a frame OBU with no tile group -- \
2523 the refusal {REFUSAL:?} is reachable after all"
2524 );
2525 }
2526 }
2527 if let Err(e) = decode_stream(&stream) {
2528 let e = e.to_string();
2529 assert!(
2530 !e.contains(REFUSAL),
2531 "a {len}-byte tile payload reached {REFUSAL:?}: {e}"
2532 );
2533 }
2534 }
2535 assert!(
2536 frame_obus_parsed >= 2,
2537 "the sweep parsed {frame_obus_parsed} frame OBUs -- it proves nothing about the \
2538 refusal's reachability"
2539 );
2540 }
2541
2542 /// lane-t900 r27, negative gate: a frame whose segmentation enables one of
2543 /// the three MODE-OVERRIDING features -- `SEG_LVL_REF_FRAME` (forces a
2544 /// block's reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both
2545 /// suppress symbols `decode_inter_block` reads unconditionally) -- is
2546 /// refused BY NAME and outputs no picture, rather than desyncing on the
2547 /// first block that would have obeyed the override.
2548 ///
2549 /// Written, not hand-built: `write_segmentation_params` (spec 5.9.14)
2550 /// codes `feature_enabled`/`feature_data` for every segment, so a real
2551 /// key frame carrying the flag is a two-line change to the header the
2552 /// encoder already produced. Swept over all three features and over the
2553 /// first, a middle and the last segment id.
2554 #[test]
2555 fn a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name() {
2556 let fctx = &crate::decode::FrameCtx::new();
2557 const REFUSAL: &str =
2558 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
2559 let picture = test_card(64, 64);
2560 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2561 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2562 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
2563 for segment in [0usize, 3, 7] {
2564 let mut header = key.clone();
2565 header.segmentation.enabled = true;
2566 header.segmentation.update_map = true;
2567 header.segmentation.update_data = true;
2568 header.segmentation.feature_enabled[segment][feature] = true;
2569 header.segmentation.feature_data[segment][feature] = 1;
2570 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2571 stream.extend_from_slice(
2572 &crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap(),
2573 );
2574 let mut shown = 0;
2575 let err = decode_stream_with(&stream, |_, _, _| {
2576 shown += 1;
2577 Ok(())
2578 })
2579 .unwrap_err()
2580 .to_string();
2581 assert!(
2582 err.contains(REFUSAL),
2583 "feature {feature} segment {segment}: expected {REFUSAL:?}, got: {err}"
2584 );
2585 assert_eq!(
2586 shown, 0,
2587 "feature {feature} segment {segment}: a refused frame produced a picture"
2588 );
2589 }
2590 }
2591 }
2592
2593 /// One census attempt: encode `frames` frames of `source` with real
2594 /// aomenc plus `extra` args, decode with THIS decoder, and return the
2595 /// stream's byte length with either the picture count or the refusal (any
2596 /// decode error) it produced. A census is about what the encoder emits,
2597 /// so a refusal is data here, not a failure.
2598 fn census_attempt(
2599 source: &str,
2600 width: usize,
2601 height: usize,
2602 frames: usize,
2603 extra: &[&str],
2604 ) -> (usize, std::result::Result<usize, String>) {
2605 let duration = format!("{}", frames as f64 / 25.0);
2606 let src = format!("{source}=size={width}x{height}:rate=25");
2607 let y4m = Command::new("ffmpeg")
2608 .args([
2609 "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt", "yuv420p",
2610 "-strict", "-1", "-f", "yuv4mpegpipe", "-",
2611 ])
2612 .stdin(Stdio::null())
2613 .stdout(Stdio::piped())
2614 .stderr(Stdio::piped())
2615 .output()
2616 .expect("ffmpeg failed to run");
2617 assert!(y4m.status.success(), "ffmpeg refused the {width}x{height} fixture");
2618 let limit = format!("--limit={frames}");
2619 let mut args: Vec<String> = [
2620 "--codec=av1",
2621 "--passes=1",
2622 "--end-usage=q",
2623 "--threads=1",
2624 "--row-mt=0",
2625 "--kf-max-dist=9999",
2626 "--lag-in-frames=0",
2627 ]
2628 .iter()
2629 .map(|s| (*s).to_owned())
2630 .collect();
2631 args.push(limit);
2632 args.extend(extra.iter().map(|s| (*s).to_owned()));
2633 args.extend(["--obu".to_owned(), "-o".to_owned(), "-".to_owned(), "-".to_owned()]);
2634 let out = run_with_stdin(Command::new(aomenc_path())
2635 .args(&args), &y4m.stdout);
2636 assert!(out.status.success(), "aomenc refused {args:?}: {}", String::from_utf8_lossy(&out.stderr));
2637 let stream = out.stdout;
2638 let result = match decode_stream(&stream) {
2639 Ok(pictures) => Ok(pictures.len()),
2640 Err(e) => Err(e.to_string()),
2641 };
2642 (stream.len(), result)
2643 }
2644
2645 /// lane-av1seglvl: encode `frames` frames of `source` with real aomenc
2646 /// plus `extra` args and return the raw `.obu` bytes -- the census's
2647 /// half-sibling of [`census_attempt`] that keeps the STREAM instead of
2648 /// only its decode verdict, so the caller can parse the frame headers'
2649 /// segmentation tables themselves.
2650 fn encode_aomenc_stream(
2651 source: &str,
2652 width: usize,
2653 height: usize,
2654 frames: usize,
2655 extra: &[&str],
2656 ) -> Vec<u8> {
2657 let duration = format!("{}", frames as f64 / 25.0);
2658 let src = format!("{source}=size={width}x{height}:rate=25");
2659 let y4m = Command::new("ffmpeg")
2660 .args([
2661 "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt", "yuv420p",
2662 "-strict", "-1", "-f", "yuv4mpegpipe", "-",
2663 ])
2664 .stdin(Stdio::null())
2665 .stdout(Stdio::piped())
2666 .stderr(Stdio::piped())
2667 .output()
2668 .expect("ffmpeg failed to run");
2669 assert!(y4m.status.success(), "ffmpeg refused the {width}x{height} fixture");
2670 let limit = format!("--limit={frames}");
2671 let mut args: Vec<String> = [
2672 "--codec=av1",
2673 "--passes=1",
2674 "--end-usage=q",
2675 "--threads=1",
2676 "--row-mt=0",
2677 "--kf-max-dist=9999",
2678 "--lag-in-frames=0",
2679 ]
2680 .iter()
2681 .map(|s| (*s).to_owned())
2682 .collect();
2683 args.push(limit);
2684 args.extend(extra.iter().map(|s| (*s).to_owned()));
2685 args.extend(["--obu".to_owned(), "-o".to_owned(), "-".to_owned(), "-".to_owned()]);
2686 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2687 assert!(out.status.success(), "aomenc refused {args:?}: {}", String::from_utf8_lossy(&out.stderr));
2688 out.stdout
2689 }
2690
2691 /// lane-av1seglvl: encode `frames` frames with a real TWO-PASS aomenc
2692 /// (pass 1 writes the stats file into the session temp dir, pass 2
2693 /// consumes it) and return the `.obu` bytes. This is the only shape that
2694 /// reaches libaom's `is_stat_consumption_stage_twopass` segmentation
2695 /// setup (`configure_static_seg_features`), so the census is not proven
2696 /// over the encoder's whole reachable surface without it.
2697 fn encode_aomenc_stream_twopass(
2698 source: &str,
2699 width: usize,
2700 height: usize,
2701 frames: usize,
2702 extra: &[&str],
2703 ) -> Vec<u8> {
2704 let duration = format!("{}", frames as f64 / 25.0);
2705 let src = format!("{source}=size={width}x{height}:rate=25");
2706 let y4m = Command::new("ffmpeg")
2707 .args([
2708 "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt", "yuv420p",
2709 "-strict", "-1", "-f", "yuv4mpegpipe", "-",
2710 ])
2711 .stdin(Stdio::null())
2712 .stdout(Stdio::piped())
2713 .stderr(Stdio::piped())
2714 .output()
2715 .expect("ffmpeg failed to run");
2716 assert!(y4m.status.success(), "ffmpeg refused the {width}x{height} fixture");
2717 let limit = format!("--limit={frames}");
2718 let fpf = std::env::temp_dir().join(format!("ec-av1-segldapass-{}.fpf", std::process::id()));
2719 let mut base: Vec<String> = [
2720 "--codec=av1",
2721 "--passes=2",
2722 "--end-usage=q",
2723 "--threads=1",
2724 "--row-mt=0",
2725 "--kf-max-dist=9999",
2726 "--lag-in-frames=0",
2727 ]
2728 .iter()
2729 .map(|s| (*s).to_owned())
2730 .collect();
2731 base.push(limit);
2732 base.extend(extra.iter().map(|s| (*s).to_owned()));
2733 let mut pass1 = base.clone();
2734 pass1.extend(["--pass=1".to_owned(), format!("--fpf={}", fpf.display())]);
2735 pass1.extend(["--obu".to_owned(), "-o".to_owned(), "/dev/null".to_owned(), "-".to_owned()]);
2736 let out1 = run_with_stdin(Command::new(aomenc_path()).args(&pass1), &y4m.stdout);
2737 assert!(out1.status.success(), "aomenc pass 1 refused {pass1:?}: {}", String::from_utf8_lossy(&out1.stderr));
2738 let mut pass2 = base;
2739 pass2.extend(["--pass=2".to_owned(), format!("--fpf={}", fpf.display())]);
2740 pass2.extend(["--obu".to_owned(), "-o".to_owned(), "-".to_owned(), "-".to_owned()]);
2741 let out2 = run_with_stdin(Command::new(aomenc_path()).args(&pass2), &y4m.stdout);
2742 let _ = std::fs::remove_file(&fpf);
2743 assert!(out2.status.success(), "aomenc pass 2 refused {pass2:?}: {}", String::from_utf8_lossy(&out2.stderr));
2744 out2.stdout
2745 }
2746
2747 /// lane-av1seglvl: walk every frame OBU of `stream` and tally which
2748 /// `SEG_LVL` features the frame headers actually ENABLE, plus the shape
2749 /// counters a census premise is asserted against: frames with
2750 /// segmentation on, of which `update_map == 1` (the map is coded) and
2751 /// `update_map == 0` (every block's id is INHERITED), and frames whose
2752 /// table carries a real `SEG_LVL_ALT_Q` delta.
2753 /// The last vector counts per SEGMENT-FEATURE INSTANCE (a frame with
2754 /// ALT_Q on all 8 segments contributes 8), which is all the verdict
2755 /// needs: only index `SEG_LVL_ALT_Q` may be non-zero.
2756 /// Returns `(enabled_frames, update_map_frames, inherited_frames,
2757 /// alt_q_frames, feature_instances: [usize; SEG_LVL_MAX])`.
2758 #[allow(clippy::type_complexity)]
2759 fn segmentation_feature_census(
2760 stream: &[u8],
2761 ) -> (usize, usize, usize, usize, [usize; SEG_LVL_MAX]) {
2762 let mut parser = Av1Parser::new();
2763 let obus = parser
2764 .parse_temporal_unit(stream)
2765 .unwrap_or_else(|e| panic!("the census stream does not even parse: {e}"));
2766 let mut enabled = 0usize;
2767 let mut update_map = 0usize;
2768 let mut inherited = 0usize;
2769 let mut alt_q = 0usize;
2770 let mut feature_frames = [0usize; SEG_LVL_MAX];
2771 for obu in &obus {
2772 if let ObuKind::Frame(header, _) = &obu.kind {
2773 let seg = &header.segmentation;
2774 if !seg.enabled {
2775 continue;
2776 }
2777 enabled += 1;
2778 if seg.update_map {
2779 update_map += 1;
2780 } else {
2781 inherited += 1;
2782 }
2783 let mut any_q = false;
2784 for segment in 0..MAX_SEGMENTS {
2785 for feature in 0..SEG_LVL_MAX {
2786 if seg.feature_enabled[segment][feature] {
2787 feature_frames[feature] += 1;
2788 if feature == SEG_LVL_ALT_Q {
2789 any_q = true;
2790 }
2791 }
2792 }
2793 }
2794 if any_q {
2795 alt_q += 1;
2796 }
2797 }
2798 }
2799 (enabled, update_map, inherited, alt_q, feature_frames)
2800 }
2801
2802 /// lane-hdrlossless WITNESS → lane-av1mixloss LIFT. `--end-usage=q
2803 /// --cq-level=0 --aq-mode=1` (variance AQ over a lossless base) gives a
2804 /// high-variance segment a positive `SEG_LVL_ALT_Q` while a flat segment
2805 /// stays at `qindex == 0` (`aq_variance.c` sets `SEG_LVL_ALT_Q` per
2806 /// segment and only clamps when `base_qindex != 0`, so a lossless base is
2807 /// exactly where the mixed case comes from): a frame MIXING lossless and
2808 /// lossy segments, which this decoder refused by name until the
2809 /// per-segment lossless table (libaom `decodeframe.c:5205`,
2810 /// `xd->lossless[segment_id]`; `read_tx_size` returns TX_4X4 before it
2811 /// reads a symbol, `decodeframe.c:1170`) landed. Non-vacuity, three ways:
2812 /// (1) the header census proves the arms REALLY carry a mixed frame
2813 /// (class `gate-blind-to-feature` -- variance AQ over a lossless base is
2814 /// the whole point, not the flag spelling), (2) the WHT-unit counter
2815 /// proves the per-segment lossless reconstruction really ran, and (3)
2816 /// every decoded plane is compared SAMPLE-EXACT against ffmpeg's libaom,
2817 /// which accepts the same stream -- so the old refusal named a capability
2818 /// gap, and this gate now proves the gap closed on a real encoder output.
2819 #[test]
2820 fn a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact() {
2821 const NAME: &str = "a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact";
2822 if !have_ffmpeg() {
2823 eprintln!("SKIP {NAME}: no ffmpeg");
2824 return;
2825 }
2826 if !have_aomenc() {
2827 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2828 return;
2829 }
2830 const FRAMES: usize = 4;
2831 const WIDTH: usize = 256;
2832 const HEIGHT: usize = 192;
2833 // (source, per-arm overrides). `--end-usage=q --cq-level=0` is the
2834 // lossless base; `--aq-mode=1` is variance AQ, the only aomenc path
2835 // that sets `SEG_LVL_ALT_Q` with no clamp at base 0 (`aq_variance.c`).
2836 // Several arms because the segment split depends on the encoder's own
2837 // variance decisions (class knob-never-reached-the-tool: require at
2838 // least one arm to actually mix, and fail if none does).
2839 let arms: [(&str, &[&str]); 3] = [
2840 (
2841 "testsrc2=size=256x192:rate=25",
2842 &["--end-usage=q", "--cq-level=0", "--aq-mode=1", "--good", "--cpu-used=3", "--sb-size=64"],
2843 ),
2844 (
2845 "testsrc2=size=256x192:rate=25",
2846 &["--end-usage=q", "--cq-level=0", "--aq-mode=1", "--good", "--cpu-used=5", "--sb-size=64"],
2847 ),
2848 (
2849 "gradients=size=256x192:rate=25",
2850 &["--end-usage=q", "--cq-level=0", "--aq-mode=1", "--good", "--cpu-used=6", "--sb-size=64"],
2851 ),
2852 ];
2853 let mut mixed_arms = 0usize;
2854 // The WHT-unit delta below is a process-wide counter: serialize the
2855 // arms against the other counter-reading gates.
2856 let _gate_lock = lock_gate_counters();
2857 for (src, extra) in &arms {
2858 let y4m = Command::new("ffmpeg")
2859 .args([
2860 "-v", "error", "-f", "lavfi", "-i", *src, "-t", "0.16", "-pix_fmt",
2861 "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-",
2862 ])
2863 .stdin(Stdio::null())
2864 .stdout(Stdio::piped())
2865 .stderr(Stdio::piped())
2866 .output()
2867 .expect("ffmpeg failed to run");
2868 assert!(y4m.status.success(), "{NAME}: ffmpeg failed for {src}");
2869 let limit = format!("--limit={FRAMES}");
2870 let mut args: Vec<String> = ["--codec=av1", "--passes=1", "--threads=1", "--obu", "-o", "-", "-"]
2871 .iter()
2872 .map(|s| (*s).to_owned())
2873 .collect();
2874 args.insert(1, limit);
2875 args.extend(extra.iter().map(|s| (*s).to_owned()));
2876 let out = run_with_stdin(Command::new(aomenc_path())
2877 .args(&args), &y4m.stdout);
2878 assert!(
2879 out.status.success(),
2880 "{NAME}: aomenc refused {args:?}: {}",
2881 String::from_utf8_lossy(&out.stderr)
2882 );
2883 let stream = out.stdout;
2884 // (2) the stream really carries a frame the old refusal named.
2885 let mut parser = Av1Parser::new();
2886 let (mut pos, mut mixed) = (0usize, 0usize);
2887 while pos < stream.len() {
2888 let obu = parser.parse_obu(&stream[pos..]).expect("aomenc OBU parses");
2889 pos += obu.total_size.max(1);
2890 let header = match &obu.kind {
2891 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
2892 _ => continue,
2893 };
2894 if header.lossless.iter().any(|&l| l) && !header.lossless.iter().all(|&l| l) {
2895 mixed += 1;
2896 }
2897 }
2898 if mixed == 0 {
2899 eprintln!("{NAME}: arm {extra:?} coded no mixed frame -- trying the next");
2900 continue;
2901 }
2902 // (3) ours DECODES it, sample-exact against ffmpeg's libaom (the
2903 // reference decode doubles as the libaom-accepts proof). The
2904 // WHT-unit delta proves the per-segment lossless reconstruction
2905 // really ran inside a frame that is NOT `CodedLossless`.
2906 let before = crate::decode::lossless_wht_units();
2907 let ours = decode_stream(&stream)
2908 .unwrap_or_else(|e| panic!("{NAME}: a mixed-lossless frame decodes after the per-segment lift: {e}"));
2909 let wht_units = crate::decode::lossless_wht_units() - before;
2910 let refs = ffmpeg_decode_sequence(&stream, WIDTH, HEIGHT, FRAMES);
2911 assert_eq!(ours.len(), FRAMES, "{NAME}: frame count");
2912 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
2913 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
2914 .iter()
2915 .enumerate()
2916 {
2917 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
2918 assert_eq!(bad, 0, "{NAME}: arm {extra:?} frame {i} plane {plane}: {bad} samples differ");
2919 }
2920 }
2921 assert!(wht_units > 0, "{NAME}: arm {extra:?} reconstructed no Walsh-Hadamard unit -- the mixed census is lying or the lossless path never ran");
2922 mixed_arms += 1;
2923 eprintln!(
2924 "{NAME}: arm {extra:?}: {mixed} mixed frame(s), {FRAMES} frames sample-exact vs ffmpeg, {wht_units} WHT units"
2925 );
2926 }
2927 assert!(
2928 mixed_arms > 0,
2929 "{NAME}: no arm produced a mixed lossless/lossy frame -- the witness is vacuous \
2930 (re-measure the aomenc recipe)"
2931 );
2932 }
2933
2934 /// lane-t900 r27 CENSUS behind the negative gate above: does a real
2935 /// aomenc ever ENABLE one of the three mode-overriding segmentation
2936 /// features? Measured over the recipes that turn segmentation on --
2937 /// `--aq-mode=1/2/3` (variance, complexity and cyclic-refresh AQ) and
2938 /// `--deltaq-mode=1` -- with the refusal as the instrument: if one of
2939 /// those features appeared, the decode would stop by name.
2940 ///
2941 /// lane-av1seglvl re-scope: r27's arms were all `--passes=1
2942 /// --lag-in-frames=0`, so they never coded an alt-ref frame or ran an
2943 /// encoder second pass -- the only shapes where libaom's OTHER seg
2944 /// feature setup (`configure_static_seg_features`) could ever run. The
2945 /// re-scoped half below adds alt-ref-group arms and a real two-pass arm,
2946 /// and upgrades the instrument from the refusal (blind to a pure-ALT_LF
2947 /// stream) to a direct parse of every frame header's `feature_enabled`
2948 /// table: over all of it, aomenc enables `SEG_LVL_ALT_Q` and nothing
2949 /// else.
2950 #[test]
2951 fn a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature() {
2952 if !have_aomenc() {
2953 eprintln!("SKIP a_segmentation_census_over_real_aq_streams: no aomenc");
2954 return;
2955 }
2956 const REFUSAL: &str =
2957 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
2958 let recipes: [(&str, Vec<&str>); 6] = [
2959 ("baseline", vec!["--cpu-used=4", "--cq-level=40"]),
2960 ("aq-mode=1", vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=40"]),
2961 ("aq-mode=2", vec!["--cpu-used=4", "--aq-mode=2", "--cq-level=40"]),
2962 ("aq-mode=3", vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=40"]),
2963 ("aq-mode=3 cq10", vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=10"]),
2964 ("deltaq-mode=1", vec!["--cpu-used=4", "--deltaq-mode=1", "--cq-level=40"]),
2965 ];
2966 // Arrival, not intent (class knob-never-reached-the-tool): a recipe
2967 // whose stream is byte-for-byte the baseline's changed nothing, and a
2968 // census over such arms would be vacuous. Measured r27: only
2969 // `--aq-mode=3` (cyclic refresh) does -- aq-mode 1/2 and deltaq-mode=1
2970 // all reproduce the baseline's 7147 B at this recipe.
2971 let mut baseline_bytes = 0usize;
2972 let mut segment_symbols = 0usize;
2973 let mut refused = 0usize;
2974 let mut decoded = 0usize;
2975 for (name, extra) in &recipes {
2976 let before = crate::decode::segment_id_hits();
2977 let (bytes, result) = census_attempt("mandelbrot", 192, 128, 8, extra);
2978 match result {
2979 Ok(pictures) => {
2980 decoded += 1;
2981 let symbols = crate::decode::segment_id_hits() - before;
2982 segment_symbols += symbols;
2983 if *name == "baseline" {
2984 baseline_bytes = bytes;
2985 }
2986 eprintln!(
2987 "SEGCENSUS {name}: {bytes} B{}, {pictures} pictures, segment_id symbols {symbols}",
2988 if bytes == baseline_bytes && *name != "baseline" {
2989 " (== baseline: the flag changed nothing)"
2990 } else {
2991 ""
2992 }
2993 );
2994 }
2995 Err(e) => {
2996 eprintln!("SEGCENSUS {name}: {bytes} B, refused: {e}");
2997 assert!(
2998 !e.contains(REFUSAL),
2999 "{name}: a real aomenc stream DOES enable a mode-overriding \
3000 segmentation feature -- the refusal is a capability gap, not a \
3001 claim about the encoder: {e}"
3002 );
3003 refused += 1;
3004 }
3005 }
3006 }
3007 eprintln!(
3008 "SEGCENSUS: {} recipes, {decoded} decoded, {refused} refused for other reasons",
3009 recipes.len()
3010 );
3011 assert_eq!(decoded, recipes.len(), "every recipe must decode; {refused} refused");
3012 assert!(
3013 segment_symbols > 0,
3014 "no recipe coded a single segment_id symbol -- segmentation never arrived, so \
3015 this census measures nothing about the three mode-overriding features"
3016 );
3017
3018 // lane-av1seglvl re-scope: the r27 arms above are all `--passes=1
3019 // --lag-in-frames=0`, which never codes an alt-ref frame -- the one
3020 // frame type whose segmentation libaom sets up differently
3021 // (`configure_static_seg_features`, encoder_utils.c:738, is further
3022 // gated on the second pass AND on `hl_sf.static_segmentation`, which
3023 // speed_features.h itself documents as "Always set to 0"). The arms
3024 // below cover that whole remaining surface: alt-ref groups under
3025 // `--aq-mode`, a high-cq arm (the branch's own `high_q` gate is
3026 // `avg_q > 48`), and a genuine two-pass encode. The instrument is no
3027 // longer the refusal -- the refusal only fires on
3028 // REF_FRAME/SKIP/GLOBALMV, so an ALT_LF-only stream would decode
3029 // silently past it -- but a direct parse of every frame header's
3030 // `feature_enabled` table.
3031 let lag_recipes: [(&str, &str, usize, usize, Vec<&str>); 3] = [
3032 (
3033 "aq-mode=1 lag16 mandelbrot",
3034 "mandelbrot",
3035 192,
3036 128,
3037 vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=45", "--lag-in-frames=16", "--auto-alt-ref=1"],
3038 ),
3039 (
3040 "aq-mode=1 lag16 screen",
3041 "testsrc2",
3042 256,
3043 192,
3044 vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=45", "--lag-in-frames=16", "--auto-alt-ref=1"],
3045 ),
3046 (
3047 "aq-mode=1 lag16 cq63 high_q",
3048 "mandelbrot",
3049 192,
3050 128,
3051 vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=63", "--lag-in-frames=16", "--auto-alt-ref=1"],
3052 ),
3053 // `--aq-mode=2 lag16` (complexity AQ over an alt-ref group) was
3054 // measured 2026-09-24: it encodes and decodes cleanly but codes
3055 // ZERO segmentation-enabled frames -- complexity AQ never reaches
3056 // the seg table at this recipe -- so as a census arm it measures
3057 // nothing (class gate-blind-to-feature) and was dropped; the
3058 // 1-pass `aq-mode=2` r27 arm above stays.
3059 ];
3060 let mut total_enabled = 0usize;
3061 let mut total_inherited = 0usize;
3062 let mut total_alt_q = 0usize;
3063 let mut feature_frames = [0usize; SEG_LVL_MAX];
3064 for (name, source, w, h, extra) in &lag_recipes {
3065 let stream = encode_aomenc_stream(source, *w, *h, 40, extra);
3066 let (enabled, umap, inherited, alt_q, frames_per_feature) =
3067 segmentation_feature_census(&stream);
3068 eprintln!(
3069 "SEGCENSUS {name}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}"
3070 );
3071 total_enabled += enabled;
3072 total_inherited += inherited;
3073 total_alt_q += alt_q;
3074 for (f, n) in frames_per_feature.iter().enumerate() {
3075 feature_frames[f] += n;
3076 }
3077 }
3078 // The two-pass arm: `configure_static_seg_features` runs ONLY at
3079 // `is_stat_consumption_stage_twopass`, so this is the arm that would
3080 // catch its ALT_LF/REF_FRAME/SKIP tables if the dead speed feature
3081 // were ever revived.
3082 {
3083 let stream = encode_aomenc_stream_twopass(
3084 "mandelbrot",
3085 192,
3086 128,
3087 40,
3088 &["--cpu-used=4", "--aq-mode=1", "--cq-level=45", "--lag-in-frames=16", "--auto-alt-ref=1"],
3089 );
3090 let (enabled, umap, inherited, alt_q, frames_per_feature) =
3091 segmentation_feature_census(&stream);
3092 eprintln!(
3093 "SEGCENSUS twopass aq-mode=1 lag16: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}"
3094 );
3095 total_enabled += enabled;
3096 total_inherited += inherited;
3097 total_alt_q += alt_q;
3098 for (f, n) in frames_per_feature.iter().enumerate() {
3099 feature_frames[f] += n;
3100 }
3101 }
3102 // Premise (class gate-blind-to-feature): the arms must actually reach
3103 // the shapes the census speaks about -- segmentation-carrying frames,
3104 // frames whose map is INHERITED (update_map == 0), and frames with a
3105 // real ALT_Q table -- or the "only ALT_Q" verdict below measures
3106 // nothing.
3107 assert!(
3108 total_enabled > 0 && total_alt_q > 0,
3109 "no lag/two-pass arm carried a segmentation-enabled frame -- the census premise \
3110 never arrived"
3111 );
3112 assert!(
3113 total_inherited > 0,
3114 "no arm carried an update_map == 0 frame -- the map-inheritance path the decoder \
3115 reads segment ids through is unmeasured"
3116 );
3117 // The census verdict, over every frame of every arm: segmentation on
3118 // aomenc's CLI carries SEG_LVL_ALT_Q and NOTHING else. The three
3119 // mode-overriding features and the four ALT_LF deltas have no encoder
3120 // path: `configure_static_seg_features` (the only setter of ALT_LF/
3121 // REF_FRAME/SKIP in the tree) is gated on `hl_sf.static_segmentation`,
3122 // documented "Always set to 0" (speed_features.h), and ROI/active-map
3123 // are control-API only (aomenc.c has no flag for either).
3124 for (feature, frames) in feature_frames.iter().enumerate() {
3125 if feature == SEG_LVL_ALT_Q {
3126 continue;
3127 }
3128 assert_eq!(
3129 *frames, 0,
3130 "feature index {feature} appeared on {frames} frames of real aomenc output -- \
3131 the refusal's encoder-never-writes claim is FALSE and the mode path needs \
3132 porting before this census can stay green"
3133 );
3134 }
3135 eprintln!(
3136 "SEGCENSUS lag/twopass: {total_enabled} seg-enabled frames over 4 arms, {total_inherited} inherited-map frames, {total_alt_q} with ALT_Q, all other SEG_LVL features: 0 frames"
3137 );
3138 }
3139
3140 /// lane-av1seglvl WITNESS: the reaching stream. `--aq-mode=1` turns
3141 /// segmentation on for every frame; `--lag-in-frames=16 --auto-alt-ref=1`
3142 /// adds real alt-ref groups, so the stream mixes map-CODING frames
3143 /// (`update_map == 1`: the key frame and each group's arf) with dozens of
3144 /// map-INHERITING frames (`update_map == 0`), and an inheriting block's
3145 /// id is the MIN of the previous map over its own footprint while the
3146 /// saved map itself inherits that footprint VERBATIM
3147 /// (`copy_segment_id`, decodemv.c:342) -- heterogeneous footprints are
3148 /// exactly what a 1:4-split arf leaves behind. Stamping the minified id
3149 /// (the pre-lane defect) flattened those footprints and mis-dequantized
3150 /// scattered blocks frames later: 2 luma bytes of mandelbrot frame 35
3151 /// differed from the oracle, everything else exact.
3152 ///
3153 /// Both arms decode EVERY frame in decode order -- hidden arfs included
3154 /// -- byte-exact against the instrumented oracle, and every SHOWN frame
3155 /// pixel-exact against ffmpeg; the census counters prove the premise
3156 /// (segmentation symbols read, a wider-than-zero quantizer span from
3157 /// `SEG_LVL_ALT_Q`, and an inheritance-heavy shape).
3158 #[test]
3159 fn a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact() {
3160 const NAME: &str = "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact";
3161 if !have_aomenc() {
3162 eprintln!("SKIP {NAME}: no aomenc");
3163 return;
3164 }
3165 if !have_ffmpeg() {
3166 eprintln!("SKIP {NAME}: no ffmpeg");
3167 return;
3168 }
3169 let extra = [
3170 "--cpu-used=4",
3171 "--aq-mode=1",
3172 "--cq-level=45",
3173 "--lag-in-frames=16",
3174 "--auto-alt-ref=1",
3175 ];
3176 let arms: [(&str, &str, usize, usize); 2] = [
3177 ("screen testsrc2", "testsrc2", 256, 192),
3178 ("film mandelbrot", "mandelbrot", 192, 128),
3179 ];
3180 for (arm, source, width, height) in &arms {
3181 let stream = encode_aomenc_stream(source, *width, *height, 40, &extra);
3182 // Premise: the shape under test really arrived -- segmentation on
3183 // every frame, the map both coded and inherited, and real ALT_Q
3184 // tables. An aomenc drift that dropped any of these would make
3185 // the decode below prove nothing (class gate-blind-to-feature).
3186 let (enabled, umap, inherited, alt_q, _) = segmentation_feature_census(&stream);
3187 eprintln!(
3188 "{NAME} {arm}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q-carrying {alt_q}"
3189 );
3190 assert!(
3191 enabled > 0 && umap > 0,
3192 "{arm}: no segmentation-carrying/map-coding frame -- the premise is gone"
3193 );
3194 assert!(
3195 inherited > 0,
3196 "{arm}: no update_map == 0 frame -- the map-inheritance path under test never runs"
3197 );
3198 assert!(
3199 alt_q > 0,
3200 "{arm}: no frame carries a SEG_LVL_ALT_Q table -- the feature under test never fires"
3201 );
3202 // Every frame in decode order -- hidden arfs included (each one
3203 // re-surfaces via show-existing in this recipe, so `hidden == 0`
3204 // is possible while `frames` still covers the whole coded set) --
3205 // byte-exact against the oracle.
3206 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, arm);
3207 assert!(frames > 0, "{arm}: decoded nothing");
3208 assert_eq!(
3209 frames, enabled,
3210 "{arm}: decode-order frame count != segmentation-enabled frame count -- the \
3211 parse and the decode disagree about the stream"
3212 );
3213 let _ = hidden;
3214 // And every shown frame pixel-exact against ffmpeg.
3215 crate::decode::reset_segment_hits();
3216 let pictures = decode_stream(&stream)
3217 .unwrap_or_else(|e| panic!("{NAME} {arm}: decode refused: {e}"));
3218 assert!(
3219 crate::decode::segment_id_hits() > 0,
3220 "{arm}: zero segment_id symbols read -- the decode proved nothing about \
3221 segmentation"
3222 );
3223 let (lo, hi) = crate::decode::block_q_span();
3224 assert!(
3225 hi > lo,
3226 "{arm}: every block dequantized at the same qindex ({lo}) -- SEG_LVL_ALT_Q \
3227 never changed any block's quantizer"
3228 );
3229 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, *width, *height, pictures.len());
3230 for (i, (ours, theirs)) in pictures.iter().zip(&ffmpeg_frames).enumerate() {
3231 assert_eq!(ours.y, theirs.y, "{NAME} {arm}: frame {i} luma vs ffmpeg");
3232 assert_eq!(ours.u, theirs.u, "{NAME} {arm}: frame {i} U vs ffmpeg");
3233 assert_eq!(ours.v, theirs.v, "{NAME} {arm}: frame {i} V vs ffmpeg");
3234 }
3235 eprintln!(
3236 "{NAME} {arm}: {frames} frames decode-order exact vs oracle ({hidden} hidden), {} shown frames exact vs ffmpeg, q span {lo}..{hi}, segment_id symbols {}",
3237 pictures.len(),
3238 crate::decode::segment_id_hits()
3239 );
3240 }
3241 }
3242
3243 /// lane-t900 r27, WITNESS half of the proof for "an OBMC neighbour whose
3244 /// switchable interp filter was never recorded" (the structural half is
3245 /// `decode::tests::every_inter_record_publishes_an_obmc_readable_filter`,
3246 /// which shows no INTER cell is ever stamped with the `[3, 3]`
3247 /// sentinel): real OBMC streams whose frames use a SWITCHABLE (and dual)
3248 /// interp filter decode with the refusal firing 0 times while OBMC blends
3249 /// really read the neighbour band -- a decode that never read one would
3250 /// pass just as well and prove nothing (class gate-blind-to-feature).
3251 #[test]
3252 fn a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour() {
3253 if !have_aomenc() {
3254 eprintln!("SKIP a_real_obmc_stream_reads_a_recorded_switchable_filter: no aomenc");
3255 return;
3256 }
3257 // `--cpu-used=0` is load-bearing: at speed 4 aomenc settles on a
3258 // FRAME-level fixed interp filter, every neighbour then legitimately
3259 // carries the sentinel, and the band is never read at all (measured
3260 // r27: 0 reads over two speed-4 streams).
3261 let base = vec![
3262 "--cpu-used=0",
3263 "--enable-obmc=1",
3264 "--enable-dual-filter=1",
3265 "--min-partition-size=8",
3266 "--max-partition-size=16",
3267 "--enable-palette=0",
3268 "--enable-intrabc=0",
3269 ];
3270 let recipes: [(&str, usize, usize, Vec<&str>); 2] = [
3271 ("obmc dual cq40", 192, 128, [vec!["--cq-level=40"], base.clone()].concat()),
3272 ("obmc dual cq20", 192, 128, [vec!["--cq-level=20"], base.clone()].concat()),
3273 ];
3274 let mut reads = 0usize;
3275 let mut decoded = 0usize;
3276 for (name, w, h, extra) in &recipes {
3277 let before = crate::decode::obmc_filter_band_reads();
3278 let obmc_before = crate::decode::obmc_hits();
3279 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 8, extra);
3280 match result {
3281 Ok(pictures) => {
3282 decoded += 1;
3283 let got = crate::decode::obmc_filter_band_reads() - before;
3284 reads += got;
3285 eprintln!(
3286 "OBMCFILT {name}: {bytes} B, {pictures} pictures, {got} band reads, \
3287 {} OBMC blocks",
3288 crate::decode::obmc_hits() - obmc_before
3289 );
3290 }
3291 Err(e) => {
3292 assert!(
3293 !e.contains("an OBMC neighbour whose switchable interp filter was never recorded"),
3294 "{name}: a real OBMC stream reached the unrecorded-filter refusal -- \
3295 a publication site is missing: {e}"
3296 );
3297 eprintln!("OBMCFILT {name}: {bytes} B, refused for another reason: {e}");
3298 }
3299 }
3300 }
3301 assert!(decoded > 0, "no OBMC recipe decoded -- the witness is vacuous");
3302 assert!(
3303 reads > 0,
3304 "every OBMC blend took the fixed-filter path: the band was never read, so this \
3305 proves nothing about the refusal"
3306 );
3307 }
3308
3309 /// lane-t900 r27 CENSUS for the three SUPERRES refusals -- "warp
3310 /// prediction with a scaled reference", "a sub-8x8 inter block under a
3311 /// scaled reference" and "an 8x8 partition leaf under a scaled reference".
3312 /// Six real `--superres-mode` encodes (fixed denominators and the auto
3313 /// mode, warped motion and OBMC on), decoded by this decoder: the table it
3314 /// prints is which of the three a real encoder actually reaches.
3315 ///
3316 /// Every one of them is a REAL capability gap (unlike the enumerated
3317 /// refusals elsewhere in the inventory), so this gate asserts the measured
3318 /// shape rather than "no refusal": at least one recipe must decode (else
3319 /// the census says nothing), and any refusal must be one of the three
3320 /// named superres ones -- a fourth string would be a new gap this round
3321 /// did not measure.
3322 #[test]
3323 fn a_superres_census_over_six_real_streams_records_which_scaled_refusals_fire() {
3324 if !have_aomenc() {
3325 eprintln!("SKIP a_superres_census_over_six_real_streams: no aomenc");
3326 return;
3327 }
3328 const WARP: &str = "warp prediction with a scaled reference";
3329 const SUB8: &str = "a sub-8x8 inter block under a scaled reference";
3330 const LEAF8: &str = "an 8x8 partition leaf under a scaled reference";
3331 let common = [
3332 "--enable-warped-motion=1",
3333 "--enable-obmc=1",
3334 "--enable-palette=0",
3335 "--enable-intrabc=0",
3336 ];
3337 let recipes: [(&str, usize, usize, Vec<&str>); 6] = [
3338 ("denom12 320x180 cq32", 320, 180, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=12", "--cq-level=32"]),
3339 ("denom12 320x180 cq50", 320, 180, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=12", "--cq-level=50"]),
3340 ("denom16 320x180 cq32", 320, 180, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=16", "--cq-level=32"]),
3341 ("denom10 192x128 cq32", 192, 128, vec!["--cpu-used=4", "--superres-mode=1", "--superres-denominator=10", "--cq-level=32"]),
3342 ("auto 320x180 cq50", 320, 180, vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"]),
3343 ("auto 192x128 cq50", 192, 128, vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"]),
3344 ];
3345 let (mut decoded, mut warp, mut sub8, mut leaf8) = (0, 0, 0, 0);
3346 // lane-t900 r36 (class [[gate-blind-to-feature]]): unknown refusal
3347 // strings used to `other += 1` and panic on the spot, so the census
3348 // summary below -- the whole point of the gate -- never printed when
3349 // one fired. They are collected instead, reported in the summary, and
3350 // asserted after it.
3351 let mut other: Vec<String> = Vec::new();
3352 for (name, w, h, extra) in &recipes {
3353 let mut args = extra.clone();
3354 args.extend_from_slice(&common);
3355 let before = crate::mc::predict_scaled_hits();
3356 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 10, &args);
3357 match result {
3358 Ok(pictures) => {
3359 decoded += 1;
3360 eprintln!(
3361 "SUPERRES {name}: {bytes} B, {pictures} pictures, scaled MC blocks {}",
3362 crate::mc::predict_scaled_hits() - before
3363 );
3364 }
3365 Err(e) => {
3366 eprintln!("SUPERRES {name}: {bytes} B, refused: {e}");
3367 if e.contains(WARP) {
3368 warp += 1;
3369 } else if e.contains(SUB8) {
3370 sub8 += 1;
3371 } else if e.contains(LEAF8) {
3372 leaf8 += 1;
3373 } else {
3374 other.push(format!("{name}: {e}"));
3375 }
3376 }
3377 }
3378 }
3379 eprintln!(
3380 "SUPERRES CENSUS: 6 streams, {decoded} decoded, warp {warp}x, sub8 {sub8}x, leaf8 {leaf8}x, other {}x",
3381 other.len()
3382 );
3383 assert!(
3384 other.is_empty(),
3385 "{} superres stream(s) stopped on a string this census does not know: {other:?}",
3386 other.len()
3387 );
3388 // Measured r27: the four FIXED-denominator recipes all stop at the
3389 // 8x8-leaf refusal, and the two `--superres-mode=3` (auto) streams
3390 // decode with ZERO scaled MC blocks -- auto picked denominator 8, so
3391 // those two arms carry no scaling at all and prove nothing. The warp
3392 // and sub-8x8 refusals never fire because the 8x8-leaf one sits in
3393 // front of them: whichever partition path a scaled frame takes, the
3394 // leaf guard is reached first. Lifting the leaf gap is what makes the
3395 // other two measurable, so this gate pins the ORDER, not just a count.
3396 assert!(decoded > 0, "no superres recipe decoded -- the census is vacuous");
3397 // lane-t900 r28: all three scaled refusals are LIFTED, so the census
3398 // now pins the opposite shape -- every fixed-denominator recipe must
3399 // DECODE, and none of the three strings may come back.
3400 assert_eq!(
3401 (warp, sub8, leaf8),
3402 (0, 0, 0),
3403 "a scaled-reference refusal came back (warp {warp}, sub8 {sub8}, leaf8 {leaf8})"
3404 );
3405 assert!(decoded > 0, "no superres recipe decoded -- the census is vacuous");
3406 }
3407
3408 /// lane-t900 r25, negative gate: a `show_existing_frame` header naming a
3409 /// slot no frame has refreshed is refused BY NAME, and outputs no picture.
3410 ///
3411 /// The OBU is hand-built because [`crate::frame::write_frame_header`]
3412 /// refuses to write one (it writes shown key and inter frames only): spec
3413 /// 5.9.2's whole header for this case is `show_existing_frame` (1) plus
3414 /// `frame_to_show_map_idx` (3), the sequence carrying neither a decoder
3415 /// model nor frame ids.
3416 ///
3417 /// Deviation from the round's charter, which asked for a key frame first
3418 /// with the named slot's `refresh_frame_flags` bit clear: a SHOWN key frame
3419 /// refreshes every slot (spec 5.9.2 forces `refresh_frame_flags` to
3420 /// `all_frames` and does not code it, which is also what
3421 /// `write_frame_header` does), so the only reachable empty-slot stream is
3422 /// one where no frame has refreshed that slot yet. The stream below is a
3423 /// valid sequence header followed by the header OBU, and every one of the
3424 /// eight slots is tried.
3425 #[test]
3426 fn a_show_existing_frame_header_naming_an_empty_slot_is_refused_by_name() {
3427 const REFUSAL: &str = "a show_existing_frame header naming an empty reference slot";
3428 let (seq, _) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
3429 for slot in 0..NUM_REF_FRAMES as u32 {
3430 let mut w = ec_core::BitWriter::new();
3431 w.write_bit(true); // show_existing_frame
3432 w.write_bits(slot, 3); // frame_to_show_map_idx
3433 crate::bits::write_byte_alignment(&mut w);
3434 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
3435 stream.extend_from_slice(&crate::obu::wrap_obu(
3436 &ec_av1_syntax::obu::ObuHeader {
3437 obu_type: ec_av1_syntax::obu::ObuType::FrameHeader,
3438 extension_flag: false,
3439 has_size_field: true,
3440 temporal_id: 0,
3441 spatial_id: 0,
3442 },
3443 &w.into_bytes(),
3444 ));
3445
3446 let mut shown = 0;
3447 let err = decode_stream_with(&stream, |_, _, _| {
3448 shown += 1;
3449 Ok(())
3450 })
3451 .unwrap_err()
3452 .to_string();
3453 assert!(
3454 err.contains(REFUSAL),
3455 "slot {slot}: expected {REFUSAL:?}, got: {err}"
3456 );
3457 assert_eq!(shown, 0, "slot {slot}: an empty slot was output as a picture");
3458 }
3459 }
3460
3461 /// lane-t900 r25, negative gate: an inter frame whose `ref_frame_idx[0]`
3462 /// slot holds no picture -- a stream that opens on an inter frame -- is
3463 /// refused BY NAME rather than predicting from nothing.
3464 ///
3465 /// Deviation from the round's charter, which asked for a real aomenc
3466 /// two-frame stream with the key frame's OBUs stripped: this crate's own
3467 /// `write_frame_header` writes a shown INTER frame (short reference
3468 /// signalling and non-identity global motion are the parts it refuses), so
3469 /// the fixture is built from the writers, needs neither ffmpeg nor aomenc,
3470 /// and is byte-identical on every run. The tile payload is a real key
3471 /// frame's; the refusal fires on the header's reference lookup, before any
3472 /// tile is decoded.
3473 #[test]
3474 fn an_inter_frame_opening_a_stream_is_refused_by_name() {
3475 let fctx = &crate::decode::FrameCtx::new();
3476 const REFUSAL: &str = "an inter frame with no key frame before it";
3477 let picture = test_card(64, 64);
3478 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3479 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
3480 let inter = FrameHeader {
3481 frame_type: FrameType::Inter,
3482 frame_is_intra: false,
3483 // Keeps `primary_ref_frame`, `frame_size_with_refs` and
3484 // `use_ref_frame_mvs` out of the written header (spec 5.9.2).
3485 error_resilient_mode: true,
3486 primary_ref_frame: PRIMARY_REF_NONE,
3487 refresh_frame_flags: 0x02,
3488 order_hint: 1,
3489 ..key
3490 };
3491 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
3492 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
3493
3494 let mut shown = 0;
3495 let err = decode_stream_with(&stream, |_, _, _| {
3496 shown += 1;
3497 Ok(())
3498 })
3499 .unwrap_err()
3500 .to_string();
3501 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
3502 assert_eq!(shown, 0, "an inter frame with no reference produced a picture");
3503 }
3504
3505 /// lane-t900 r26, negative gate: an inter frame whose own coded size is
3506 /// SHORTER than the reference it predicts from is refused BY NAME, and
3507 /// outputs no picture beyond the key frame that preceded it.
3508 ///
3509 /// The height mismatch is the one size difference this decoder cannot
3510 /// absorb: `mc::predict_scaled` scales horizontally (a `use_superres`
3511 /// reference), and nothing on this path scales vertically. The fixture is
3512 /// written, not hand-built: a shown key frame at 64x64 (which refreshes
3513 /// every slot), then a shown inter frame carrying
3514 /// `frame_size_override_flag` with `error_resilient_mode` set -- the one
3515 /// combination [`crate::frame::write_frame_header`] writes, since
3516 /// `frame_size_with_refs` (spec 5.9.7) is only read when error resilience
3517 /// is OFF. The inter frame's tile payload is the key frame's; the refusal
3518 /// fires on the reference's dimensions before a tile symbol is read.
3519 #[test]
3520 fn an_inter_frame_shorter_than_its_reference_is_refused_by_name() {
3521 let fctx = &crate::decode::FrameCtx::new();
3522 const REFUSAL: &str =
3523 "a reference picture whose height does not match this frame's own true size";
3524 let picture = test_card(64, 64);
3525 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3526 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
3527 let inter = FrameHeader {
3528 frame_type: FrameType::Inter,
3529 frame_is_intra: false,
3530 error_resilient_mode: true,
3531 primary_ref_frame: PRIMARY_REF_NONE,
3532 refresh_frame_flags: 0x02,
3533 order_hint: 1,
3534 frame_size_override_flag: true,
3535 frame_height: 32,
3536 render_height: 32,
3537 ..key.clone()
3538 };
3539 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
3540 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &key, &encoded.tile).unwrap());
3541 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
3542
3543 let mut shown = 0;
3544 let err = decode_stream_with(&stream, |_, _, _| {
3545 shown += 1;
3546 Ok(())
3547 })
3548 .unwrap_err()
3549 .to_string();
3550 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
3551 assert_eq!(shown, 1, "expected the key frame alone, got {shown} pictures");
3552 }
3553
3554 /// lane-t900 r26, negative gate: an inter frame naming a
3555 /// `primary_ref_frame` whose reference slot has never been refreshed is
3556 /// refused BY NAME rather than decoded from the spec 8.4 default tables.
3557 ///
3558 /// Enumeration first, because the refusal's premise is an invariant: the
3559 /// picture slots and the CDF slots are written by exactly two loops in
3560 /// [`decode_stream`] (the `show_existing_frame` arm's copy and the
3561 /// end-of-frame store), and both walk the SAME `refresh_frame_flags` mask
3562 /// writing `ref_slots[i]` and `cdf_slots[i]` together -- so no slot can
3563 /// hold a picture without CDFs, and the reachable case is a slot nothing
3564 /// has refreshed at all. That is what this builds: a stream that OPENS on
3565 /// a non-error-resilient inter frame (the only header shape that codes
3566 /// `primary_ref_frame` at all, spec 5.9.2), tried at all eight slots.
3567 ///
3568 /// This refusal, not "an inter frame with no key frame before it", is the
3569 /// one such a stream reaches: the CDF load happens in the header path,
3570 /// before the reference pictures are looked up.
3571 #[test]
3572 fn an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name() {
3573 let fctx = &crate::decode::FrameCtx::new();
3574 const REFUSAL: &str =
3575 "a frame naming primary_ref_frame at a reference slot with no saved CDF state";
3576 // The invariant above, read off the source: every line that stores a
3577 // picture into a slot sits in a block that stores that slot's CDFs too.
3578 let src = include_str!("stream.rs");
3579 let stores: Vec<usize> = src
3580 .lines()
3581 .enumerate()
3582 .filter(|(_, l)| l.trim().starts_with("ref_slots[i] = "))
3583 .map(|(i, _)| i)
3584 .collect();
3585 assert_eq!(
3586 stores.len(),
3587 2,
3588 "the picture slots gained a writer -- check it stores cdf_slots too"
3589 );
3590 let lines: Vec<&str> = src.lines().collect();
3591 for &i in &stores {
3592 let window = lines[i.saturating_sub(6)..(i + 6).min(lines.len())].join("\n");
3593 assert!(
3594 window.contains("cdf_slots[i] = "),
3595 "line {} stores a reference picture with no cdf_slots store beside it: a slot \
3596 can then hold a picture with no saved CDF state",
3597 i + 1
3598 );
3599 }
3600
3601 let picture = test_card(64, 64);
3602 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3603 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
3604 for slot in 0..NUM_REF_FRAMES as u8 {
3605 let inter = FrameHeader {
3606 frame_type: FrameType::Inter,
3607 frame_is_intra: false,
3608 // `primary_ref_frame` is coded only when error resilience is
3609 // off (spec 5.9.2); `frame_size_override_flag` stays clear so
3610 // the header writes a plain `frame_size()`.
3611 error_resilient_mode: false,
3612 primary_ref_frame: 0,
3613 ref_frame_idx: [slot; ec_av1_syntax::REFS_PER_FRAME],
3614 refresh_frame_flags: 0x02,
3615 order_hint: 1,
3616 ..key.clone()
3617 };
3618 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
3619 stream
3620 .extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
3621
3622 let mut shown = 0;
3623 let err = decode_stream_with(&stream, |_, _, _| {
3624 shown += 1;
3625 Ok(())
3626 })
3627 .unwrap_err()
3628 .to_string();
3629 assert!(err.contains(REFUSAL), "slot {slot}: expected {REFUSAL:?}, got: {err}");
3630 assert_eq!(shown, 0, "slot {slot}: a frame with no CDF state produced a picture");
3631 }
3632 }
3633
3634 /// lane-t900 r26, enumeration: no frame header a stream can carry derives
3635 /// an empty mode-info grid, so "a frame with no mode-info grid" names a
3636 /// case outside the coded domain.
3637 ///
3638 /// `compute_image_size` (spec 5.9.9) is `mi_cols = 2 * ((frame_width + 7)
3639 /// >> 3)`, which is 0 only for `frame_width == 0`, and a frame width is
3640 /// never 0 on any of the three paths that set one:
3641 ///
3642 /// * `frame_size()` (5.9.5) reads `frame_width_minus_1` and adds one, or
3643 /// takes the sequence's `max_frame_width` (itself `+ 1`-coded);
3644 /// * `superres_params()` (5.9.8) divides by a denominator of 9..=16 with
3645 /// rounding, whose minimum over the whole 16-bit upscaled-width domain
3646 /// is enumerated below and is 1, not 0;
3647 /// * `show_existing_frame` and `frame_size_with_refs()` copy a slot's own
3648 /// dimensions, which came from one of the above.
3649 ///
3650 /// The sweep drives the REAL header reader (write a header, parse it back)
3651 /// over every width and every height a 16-bit `frame_size()` can code,
3652 /// per axis -- the derivation is independent per axis -- rather than
3653 /// re-deriving the formula here.
3654 #[test]
3655 fn every_frame_size_a_header_can_code_has_a_mode_info_grid() {
3656 let mut sizes: Vec<u32> = (1..=1024).collect();
3657 sizes.extend([2048, 4095, 4096, 8192, 16384, 32768, 65535, 65536]);
3658 // `mi_cols` is nondecreasing in `frame_width`, so an empty grid can
3659 // only appear at the SMALL end -- which is why a size this crate's
3660 // tile-info writer cannot express (its tile log2 range runs out well
3661 // before 65536) is skipped rather than worked around, while every
3662 // size up to 1024 must be covered.
3663 let mut skipped: Vec<u32> = Vec::new();
3664 for n in sizes {
3665 for (w, h) in [(n, 16), (16, n)] {
3666 let Ok((seq, header)) =
3667 crate::encode::key_frame_headers(w as usize, h as usize, 100)
3668 else {
3669 skipped.push(n);
3670 continue;
3671 };
3672 let Ok(stream) = crate::frame::frame_obu(&seq, &header, &[]) else {
3673 skipped.push(n);
3674 continue;
3675 };
3676 let mut parser = Av1Parser::new();
3677 parser.parse_obu(&crate::sequence::sequence_header_obu(&seq).unwrap()).unwrap();
3678 let obu = parser.parse_obu(&stream).unwrap();
3679 let ObuKind::Frame(parsed, _) = &obu.kind else {
3680 panic!("{w}x{h}: the written frame OBU did not parse as one");
3681 };
3682 assert!(
3683 parsed.mi_cols >= 2 && parsed.mi_rows >= 2,
3684 "{w}x{h} parsed to a {}x{} mode-info grid",
3685 parsed.mi_cols,
3686 parsed.mi_rows
3687 );
3688 }
3689 }
3690 assert!(
3691 skipped.iter().all(|&n| n > 1024),
3692 "the writer could not express these small frame sizes, so the small end of the \
3693 sweep is incomplete: {skipped:?}"
3694 );
3695 // The superres arm, which no writer here can express: spec 5.9.8's
3696 // `(upscaled_width * 8 + denom / 2) / denom` over its whole domain.
3697 for denom in 9u32..=16 {
3698 for upscaled in [1u32, 2, 3, 7, 8, 9, 255, 4096, 65535, 65536] {
3699 let width = (upscaled * 8 + denom / 2) / denom;
3700 assert!(
3701 width >= 1,
3702 "superres denom {denom} maps an upscaled width of {upscaled} to {width}, \
3703 which would derive an empty mode-info grid"
3704 );
3705 }
3706 }
3707 }
3708
3709 /// lane-interedge r1: one attempt of the inter frame-edge half-strip gate --
3710 /// encode `width x height` with real aomenc (rect partitions ON, every other
3711 /// lane's open tool pinned off), decode it, and return
3712 /// `(inter_edge_strip hits, frames whose LUMA differs, frames whose CHROMA
3713 /// differs)` against ffmpeg. A refusal or a decode error is a hard failure:
3714 /// this recipe reached every size without one (measured r1).
3715 fn inter_edge_strip_attempt(
3716 name: &str,
3717 width: usize,
3718 height: usize,
3719 bit_depth: u32,
3720 cq: u32,
3721 frames: usize,
3722 ) -> ([usize; 6], usize, usize) {
3723 let duration = format!("{}", frames as f64 / 25.0);
3724 let source = format!("mandelbrot=size={width}x{height}:rate=25");
3725 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
3726 let y4m = Command::new("ffmpeg")
3727 .args([
3728 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration, "-pix_fmt",
3729 pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
3730 ])
3731 .stdin(Stdio::null())
3732 .stdout(Stdio::piped())
3733 .stderr(Stdio::piped())
3734 .output()
3735 .expect("ffmpeg failed to run");
3736 assert!(
3737 y4m.status.success(),
3738 "{name}: ffmpeg refused the {width}x{height} {bit_depth}-bit fixture: {}",
3739 String::from_utf8_lossy(&y4m.stderr)
3740 );
3741 let depth_arg = format!("--bit-depth={bit_depth}");
3742 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
3743 let cq_arg = format!("--cq-level={cq}");
3744 let limit_arg = format!("--limit={frames}");
3745 let out = run_with_stdin(Command::new(aomenc_path())
3746 .args([
3747 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg,
3748 // cpu-used >= 1 keeps libaom on 64x64 superblocks at these
3749 // sizes (`av1_select_sb_size`).
3750 "--cpu-used=4", "--threads=1", "--row-mt=0", "--kf-max-dist=9999",
3751 &limit_arg,
3752 // decode order == display order, so the compare below covers
3753 // every frame the stream carries (class gate-blind-to-hidden-frames).
3754 "--lag-in-frames=0", &depth_arg, &input_depth_arg,
3755 // Rect partitions stay ON: the frame-edge strip is a FORCED
3756 // (gathered) HORZ/VERT, but with rect coding off the encoder
3757 // answers that gathered symbol SPLIT every time and no edge
3758 // strip ever fires (lane-oddh r2's finding, re-measured r1).
3759 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
3760 "--enable-1to4-partitions=0", "--min-partition-size=8",
3761 "--max-partition-size=64",
3762 // Other lanes' open gaps this recipe must not trip.
3763 "--enable-palette=0", "--enable-intrabc=0", "--enable-warped-motion=0",
3764 "--enable-obmc=0", "--enable-masked-comp=0", "--enable-interintra-comp=0",
3765 "--enable-onesided-comp=0", "--enable-interintra-wedge=0",
3766 "--enable-smooth-interintra=0", "--enable-ref-frame-mvs=0",
3767 "--enable-angle-delta=0", "--enable-cfl-intra=0",
3768 "--enable-directional-intra=0", "--enable-smooth-intra=0",
3769 "--enable-paeth-intra=0", "--enable-filter-intra=0",
3770 "--enable-tx-size-search=0",
3771 "--obu", "-o", "-", "-",
3772 ]), &y4m.stdout);
3773 assert!(
3774 out.status.success(),
3775 "aomenc refused: {}",
3776 String::from_utf8_lossy(&out.stderr)
3777 );
3778 let stream = out.stdout;
3779
3780 // Reset, never a delta: a refused attempt's hits must not leak into the
3781 // next one (class counter-from-refused-stream).
3782 crate::decode::reset_inter_edge_strip_hits();
3783 let decoded = decode_stream(&stream).unwrap_or_else(|e| {
3784 panic!("{name}: {width}x{height} {bit_depth}-bit cq {cq} did not decode: {e}")
3785 });
3786 let hits = crate::decode::inter_edge_strip_hits();
3787 let reference = if bit_depth == 10 {
3788 ffmpeg_decode_sequence_10bit(&stream, width, height, frames)
3789 } else {
3790 ffmpeg_decode_sequence(&stream, width, height, frames)
3791 };
3792 assert_eq!(
3793 decoded.len(),
3794 reference.len(),
3795 "{name}: {width}x{height} {bit_depth}-bit cq {cq} frame count"
3796 );
3797 assert!(
3798 decoded.len() >= frames,
3799 "{name}: {width}x{height} {bit_depth}-bit cq {cq} decoded only {} frames",
3800 decoded.len()
3801 );
3802 let (mut luma_bad, mut chroma_bad) = (0usize, 0usize);
3803 for (ours, theirs) in decoded.iter().zip(&reference) {
3804 if ours.y != theirs.y {
3805 luma_bad += 1;
3806 }
3807 if ours.u != theirs.u || ours.v != theirs.v {
3808 chroma_bad += 1;
3809 }
3810 }
3811 (hits, luma_bad, chroma_bad)
3812 }
3813
3814 /// lane-interedge r1 GATE (was lane-oddh r2's `#[ignore]`d twin): the INTER
3815 /// frame-edge half strips -- a `PARTITION_HORZ`/`PARTITION_VERT` forced by
3816 /// the gathered edge symbol at the 64, 32 or 16 level whose second half lies
3817 /// outside the true frame. Both of the user's films are height mod 16 == 8
3818 /// (1920x792, 3840x1608), so every inter frame crosses these nodes.
3819 ///
3820 /// r1 root cause: the inter tile's 32-level `PARTITION_HORZ`/`PARTITION_VERT`
3821 /// decoded the SECOND strip unconditionally, while libaom `decode_partition`
3822 /// (decodeframe.c, PARTITION_HORZ) guards it with `has_rows`/`has_cols` --
3823 /// so at the edge we read symbols the encoder never wrote. With that guard
3824 /// removed this gate's 72x192 cq 32 arm refuses outright and its 104x192 arm
3825 /// decodes luma rows 127..191 of frame 5 wrong (measured r1).
3826 ///
3827 /// The compare is LUMA-exact per frame plus a CONTROL size with no edge node
3828 /// at all: chroma is excluded because a chroma-only inter residue that has
3829 /// nothing to do with the frame edge is open on main (lanes/tiny-r3,
3830 /// lanes/gmaffine-r4, lanes/palette2-r8) and the control below reproduces it
3831 /// with `inter_edge_strip_hits` all zero.
3832 #[test]
3833 fn a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact() {
3834 const NAME: &str = "a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact";
3835 let _gate_lock = lock_gate_counters();
3836 if !have_ffmpeg() || !have_aomenc() {
3837 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
3838 return;
3839 }
3840 let frames = 6usize;
3841 // h mod 16 == 8 (bottom edge) and w mod 16 == 8 (right edge).
3842 let sizes: &[(usize, usize)] = &[(192, 72), (192, 88), (72, 192), (88, 192), (104, 192)];
3843 let mut totals = [0usize; 6];
3844 let mut compared = 0u32;
3845 let mut chroma_frames = 0usize;
3846 for &(width, height) in sizes {
3847 for bit_depth in [8u32, 10] {
3848 for cq in [20u32, 32, 45] {
3849 let (hits, luma_bad, chroma_bad) =
3850 inter_edge_strip_attempt(NAME, width, height, bit_depth, cq, frames);
3851 assert_eq!(
3852 luma_bad, 0,
3853 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {luma_bad} of {frames} \
3854 frames differ from ffmpeg in LUMA (edge hits {hits:?})"
3855 );
3856 // merge J, after lane-rectchroma2: the chroma residue this
3857 // gate used to tolerate WAS this decoder's -- the per-axis
3858 // narrow-block MC kernel decision read side x side instead
3859 // of the block's true dims. Full-plane now.
3860 assert_eq!(
3861 chroma_bad, 0,
3862 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {chroma_bad} of \
3863 {frames} frames differ from ffmpeg in CHROMA (edge hits {hits:?})"
3864 );
3865 for (t, h) in totals.iter_mut().zip(hits) {
3866 *t += h;
3867 }
3868 chroma_frames += chroma_bad;
3869 compared += 1;
3870 }
3871 }
3872 }
3873 // Every level x axis this recipe reaches must have fired on a COMPARED
3874 // attempt. h32 (a bottom-edge HORZ at the 32 level) is not asserted: no
3875 // recipe found in r1 makes libaom answer that gathered symbol HORZ
3876 // (sweep ~/.cache/interedge-tmp/h32.sh, 3 sizes x 6 cq, all SPLIT); it
3877 // is the transposed twin of v32, which this gate does fire.
3878 assert!(
3879 totals[0] > 0 && totals[1] > 0 && totals[3] > 0 && totals[4] > 0 && totals[5] > 0,
3880 "{NAME}: {compared} attempts luma-exact but the edge strips did not all fire \
3881 (h64,v64,h32,v32,h16,v16 = {totals:?}) -- the recipe no longer reaches the arms \
3882 this gate exists for"
3883 );
3884 // CONTROL: a size with no frame-edge node anywhere (192x128, both axes
3885 // 0 mod 64). It must be luma-exact with ZERO edge hits -- that is what
3886 // makes the chroma exclusion above a statement about a foreign defect
3887 // rather than about this lane's code.
3888 let (chits, cluma, cchroma) = inter_edge_strip_attempt(NAME, 192, 128, 8, 32, frames);
3889 assert_eq!(
3890 (chits, cluma, cchroma),
3891 ([0usize; 6], 0usize, 0usize),
3892 "{NAME}: control 192x128 (no frame-edge node) must be pixel-exact with no edge hits"
3893 );
3894 eprintln!(
3895 "{NAME}: {compared} attempts luma-exact over {} sizes, edge hits \
3896 (h64,v64,h32,v32,h16,v16)={totals:?}, 0 refusals; chroma-only frames {chroma_frames} \
3897 (control 192x128: hits {chits:?}, chroma-only frames {cchroma} -- foreign defect)",
3898 sizes.len()
3899 );
3900 }
3901
3902 /// lane-sb128 r4 GATE (was lane-oddh r2's refusal gate): the SAME real
3903 /// aomenc 64x72 `--cpu-used=0 --sb-size=128` stream that once desynced at
3904 /// the very first symbol now decodes PIXEL-EXACT against aomdec. mi_rows
3905 /// = 18 > 16, so the BLOCK_128X128 root reads a real gathered partition
3906 /// symbol (2 symbols: has_cols false, has_rows true) -- exactly the case
3907 /// r1 mis-read as a 10-symbol BLOCK_64X64 partition.
3908 ///
3909 /// The `use_128x128_superblock` assert is the "knob reached the tool"
3910 /// half: without it an aomenc that ignored `--sb-size=128` would leave
3911 /// the gate proving nothing about 128 superblocks.
3912 #[test]
3913 fn a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact() {
3914 if !have_ffmpeg() || !have_aomenc() {
3915 eprintln!("SKIP: no ffmpeg/aomenc");
3916 return;
3917 }
3918 let (width, height) = (64usize, 72usize);
3919 let y4m = Command::new("ffmpeg")
3920 .args([
3921 "-v", "error", "-f", "lavfi", "-i",
3922 "mandelbrot=size=64x72:rate=25:start_x=-0.6:start_y=-0.4", "-t", "0.04",
3923 "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-",
3924 ])
3925 .stdin(Stdio::null())
3926 .stdout(Stdio::piped())
3927 .stderr(Stdio::piped())
3928 .output()
3929 .expect("ffmpeg failed to run");
3930 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
3931 let out = run_with_stdin(Command::new(aomenc_path())
3932 .args([
3933 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32",
3934 "--cpu-used=0", "--sb-size=128", "--min-partition-size=16",
3935 "--kf-max-dist=0", "--limit=1",
3936 "--threads=1", "--row-mt=0", "--obu", "-o", "-", "-",
3937 ]), &y4m.stdout);
3938 assert!(out.status.success(), "aomenc refused: {}", String::from_utf8_lossy(&out.stderr));
3939 let stream = out.stdout;
3940
3941 // The knob actually arrived: this stream's sequence header codes
3942 // `use_128x128_superblock = 1`.
3943 let mut parser = Av1Parser::new();
3944 let mut pos = 0usize;
3945 let mut sb128 = false;
3946 while pos < stream.len() {
3947 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
3948 break;
3949 };
3950 pos += obu.total_size.max(1);
3951 if let Some(seq) = parser.sequence_header() {
3952 sb128 = seq.use_128x128_superblock;
3953 break;
3954 }
3955 }
3956 assert!(sb128, "aomenc ignored --sb-size=128: this stream is 64x64-superblock");
3957
3958 let _guard = lock_gate_counters();
3959 let before = crate::decode::part128_symbols()
3960 + crate::decode::part128_gathered_symbols();
3961 let (frames, hidden) =
3962 decode_all_frames_vs_oracle(&stream, "sb128-oddh-64x72");
3963 assert!(frames > 0, "no frames decoded for {width}x{height}");
3964 // The 128 root actually READ a partition symbol here: at mi_rows=18
3965 // `has_rows` is true, so BLOCK_128X128 is not a forced split.
3966 let part128 = crate::decode::part128_symbols()
3967 + crate::decode::part128_gathered_symbols()
3968 - before;
3969 assert!(
3970 part128 > 0,
3971 "{width}x{height} decoded without reading a single BLOCK_128X128 \
3972 partition symbol -- the gate proves nothing about the 128 root"
3973 );
3974 eprintln!(
3975 "a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact: \
3976 {frames} frames pixel-exact ({hidden} hidden) at {width}x{height}, \
3977 part128_symbols={part128}"
3978 );
3979 }
3980
3981 /// `decode_stream` on a lone key frame's stream matches both the tile
3982 /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and
3983 /// the encoder's own reconstruction, at an even and an odd size.
3984 #[test]
3985 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
3986 // lane-b128m: the ENCODER writes at this process's superblock size, so
3987 // its own trial decode -- and the raw tile decode below -- must be given
3988 // that size too (class: stale header in the test harness).
3989 let fctx = &crate::decode::FrameCtx::for_encoder();
3990 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
3991 let picture = test_card(width, height);
3992 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3993 let via_tile = decode_key_frame_tile_lr(
3994 &encoded.tile,
3995 encoded.mi_cols,
3996 encoded.mi_rows,
3997 encoded.base_q_idx,
3998 width as u32,
3999 height as u32,
4000 // lane-fintra: the sequence bit the encoder wrote this tile under
4001 // (stale-header class -- a hard-coded `false` here reads one symbol
4002 // short at the first DC_PRED block once the search offers filter intra).
4003 crate::encode::filter_intra_on(),
4004 &encoded.cdef,
4005 &encoded.loop_filter,
4006 encoded.tx_select,
4007 // lane-intertx: the frame's own `reduced_tx_set` -- a screen
4008 // key frame at preset 0 codes the wider intra alphabets, so
4009 // the old hardcoded `true` (ours "always" wrote true) is a
4010 // stale-header bug waiting for the first screen fixture.
4011 encoded.reduced_tx_set,
4012 // `allow_screen_content_tools` off the frame the encoder
4013 // actually wrote: a screen-content picture codes two palette
4014 // symbols per intra block, and a raw tile decode that guessed
4015 // `false` desyncs at the first one (class: test asserts
4016 // against a stale header).
4017 encoded.screen,
4018 // ... and its own `allow_intrabc` (stale-header class).
4019 encoded.allow_intrabc,
4020 &encoded.loop_restoration, fctx,
4021 )
4022 .unwrap();
4023 let via_stream = decode_stream(&encoded.stream).unwrap();
4024 assert_eq!(via_stream.len(), 1, "{width}x{height}: one picture");
4025 assert_eq!(via_stream[0].y, via_tile.y, "{width}x{height}: luma");
4026 assert_eq!(via_stream[0].u, via_tile.u, "{width}x{height}: U");
4027 assert_eq!(via_stream[0].v, via_tile.v, "{width}x{height}: V");
4028 assert_eq!(
4029 via_stream[0].y, encoded.reconstruction.y,
4030 "{width}x{height}: luma vs encoder reconstruction"
4031 );
4032 }
4033 }
4034
4035 /// A GOP (key frame plus panned inter frames, so blocks actually take
4036 /// motion) decodes bit-exact through `decode_stream` alone, threading its
4037 /// own DPB rather than a test-supplied reference.
4038 fn gop_round_trips(width: usize, height: usize, fctx: &crate::decode::FrameCtx) {
4039 let pictures: Vec<_> = (0..4)
4040 .map(|i| panned_test_card(width, height, i * 3))
4041 .collect();
4042 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
4043 let decoded = decode_stream(&encoded.stream).unwrap();
4044 assert_eq!(decoded.len(), encoded.frames.len());
4045 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
4046 assert_eq!(
4047 got.y, frame.reconstruction.y,
4048 "{width}x{height} frame {i} luma"
4049 );
4050 assert_eq!(
4051 got.u, frame.reconstruction.u,
4052 "{width}x{height} frame {i} U"
4053 );
4054 assert_eq!(
4055 got.v, frame.reconstruction.v,
4056 "{width}x{height} frame {i} V"
4057 );
4058 }
4059 }
4060
4061 #[test]
4062 fn decode_stream_round_trips_a_gop() {
4063 let fctx = &crate::decode::FrameCtx::for_encoder();
4064 gop_round_trips(128, 64, fctx);
4065 }
4066
4067 /// Same claim at a size that is not a whole number of 32x32 blocks, so
4068 /// the inter frame's 16x16-leaf split path is exercised too.
4069 #[test]
4070 fn decode_stream_round_trips_an_odd_size_gop() {
4071 let fctx = &crate::decode::FrameCtx::for_encoder();
4072 gop_round_trips(216, 96, fctx);
4073 }
4074
4075 /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures
4076 /// `decode_stream` collects, in the same order -- the streaming path is
4077 /// the decoder now (`decode_stream` is a collecting wrapper), so an
4078 /// equivalence check here is what keeps every gate's Vec-shaped assert
4079 /// meaningful. Also pins the sink contract: one call per shown picture,
4080 /// decode indices non-decreasing, and an `Err` from the sink aborting.
4081 #[test]
4082 fn streaming_decode_matches_the_collecting_one() {
4083 let fctx = &crate::decode::FrameCtx::for_encoder();
4084 let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect();
4085 let stream = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap().stream;
4086 let collected = decode_stream(&stream).unwrap();
4087
4088 let mut shown = Vec::new();
4089 let mut idxs = Vec::new();
4090 let mut live = 0usize;
4091 decode_stream_with(&stream, |p, idx, is_shown| {
4092 live += 1;
4093 if is_shown {
4094 idxs.push(idx);
4095 shown.push(p.clone());
4096 }
4097 Ok(())
4098 })
4099 .unwrap();
4100 assert_eq!(shown.len(), collected.len(), "callback count vs shown frames");
4101 assert!(live >= shown.len(), "every shown picture is also a callback");
4102 assert!(
4103 idxs.windows(2).all(|w| w[0] <= w[1]),
4104 "decode indices out of order: {idxs:?}"
4105 );
4106 for (i, (got, want)) in shown.iter().zip(&collected).enumerate() {
4107 assert_eq!(got.y, want.y, "frame {i} luma");
4108 assert_eq!(got.u, want.u, "frame {i} U");
4109 assert_eq!(got.v, want.v, "frame {i} V");
4110 }
4111
4112 // A sink error stops the decode and comes back unchanged.
4113 let mut seen = 0usize;
4114 let err = decode_stream_with(&stream, |_, _, _| {
4115 seen += 1;
4116 Err(Error::corrupt("sink says stop"))
4117 })
4118 .unwrap_err();
4119 assert_eq!(seen, 1, "decode continued past a failing sink");
4120 assert!(format!("{err}").contains("sink says stop"), "{err}");
4121 }
4122
4123 use crate::probe::run_with_stdin;
4124 use std::process::{Command, Stdio};
4125
4126 /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`,
4127 /// `skip_mode`/compound) all read a process-global atomic counter delta
4128 /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to
4129 /// prove a real block picked the feature under test, not just that a
4130 /// header bit was set. Under `cargo test`'s default parallel run, a
4131 /// SIBLING test's own decode bumps the same global counter mid-gate --
4132 /// a false "fired" reading pixel-compares an attempt the gate would
4133 /// otherwise `continue` past, on top of genuine defects that path may
4134 /// still have. Serialising every counter-delta gate behind this one
4135 /// mutex makes firing detection honest again (matches the existing
4136 /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`).
4137 static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
4138 /// Three-bucket gate summary (class [[gate-skips-on-its-own-failure]]):
4139 /// every attempt lands in exactly one bucket -- decoded pixel-exact WITH
4140 /// the feature counter moving, decoded pixel-exact WITHOUT it, or a named
4141 /// refusal -- and the three sum to the attempts made.
4142 fn gate_buckets(name: &str, counted_exact: u32, uncounted_exact: u32, named_refusals: usize) {
4143 eprintln!(
4144 "{name}: buckets counted-exact={counted_exact} uncounted-exact={uncounted_exact} \
4145 named-refusals={named_refusals} (attempts {})",
4146 counted_exact as usize + uncounted_exact as usize + named_refusals
4147 );
4148 }
4149
4150 pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
4151 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
4152 }
4153
4154 /// lane-cdfflake: a cheap, dependency-free (FNV-1a, not cryptographic --
4155 /// this is a load-bearing-identity fingerprint for flake triage, not a
4156 /// security digest, so no `sha2` dep is pulled in) fixture fingerprint
4157 /// for the cdf-forwarding gate's instrumentation below.
4158 fn fnv1a64(bytes: &[u8]) -> u64 {
4159 let mut hash = 0xcbf29ce484222325u64;
4160 for &b in bytes {
4161 hash ^= b as u64;
4162 hash = hash.wrapping_mul(0x100000001b3);
4163 }
4164 hash
4165 }
4166
4167 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
4168 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
4169 /// aomenc gate decodes its stream through ffmpeg and is meaningless
4170 /// without it -- turns it into a hard failure. Without this the require
4171 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
4172 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
4173 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
4174 fn have_ffmpeg() -> bool {
4175 let present = Command::new("ffmpeg")
4176 .arg("-version")
4177 .stdout(Stdio::null())
4178 .stderr(Stdio::null())
4179 .status()
4180 .is_ok_and(|s| s.success());
4181 assert!(
4182 present
4183 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
4184 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
4185 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
4186 );
4187 present
4188 }
4189
4190 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
4191 fn ffmpeg_decode_sequence(
4192 stream: &[u8],
4193 width: usize,
4194 height: usize,
4195 frames: usize,
4196 ) -> Vec<Pic> {
4197 let out = run_with_stdin(
4198 Command::new("ffmpeg").args([
4199 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
4200 ]),
4201 stream,
4202 );
4203 assert!(
4204 out.status.success(),
4205 "ffmpeg refused the stream: {}",
4206 String::from_utf8_lossy(&out.stderr)
4207 );
4208 let (luma, chroma) = (width * height, width * height / 4);
4209 let frame_bytes = luma + 2 * chroma;
4210 assert_eq!(
4211 out.stdout.len(),
4212 frame_bytes * frames,
4213 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
4214 String::from_utf8_lossy(&out.stderr)
4215 );
4216 (0..frames)
4217 .map(|i| {
4218 let base = i * frame_bytes;
4219 Pic {
4220 width,
4221 height,
4222 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
4223 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
4224 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
4225 }
4226 })
4227 .collect()
4228 }
4229
4230 /// As [`ffmpeg_decode_sequence`], for a MONOCHROME stream: one 8-bit luma
4231 /// plane per frame, exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes
4232 /// (lane-av1mono). Fed through [`run_with_stdin`] for the reason its doc
4233 /// records.
4234 fn ffmpeg_decode_gray_sequence(
4235 stream: &[u8],
4236 width: usize,
4237 height: usize,
4238 frames: usize,
4239 ) -> Vec<u8> {
4240 let out = run_with_stdin(
4241 Command::new("ffmpeg").args([
4242 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "gray", "-",
4243 ]),
4244 stream,
4245 );
4246 assert!(
4247 out.status.success(),
4248 "ffmpeg refused the monochrome stream: {}",
4249 String::from_utf8_lossy(&out.stderr)
4250 );
4251 assert_eq!(
4252 out.stdout.len(),
4253 width * height * frames,
4254 "expected {frames} monochrome frames, ffmpeg said: {}",
4255 String::from_utf8_lossy(&out.stderr)
4256 );
4257 out.stdout
4258 }
4259
4260 /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples
4261 /// are 2-byte little-endian, one full 16-bit range regardless of the
4262 /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the
4263 /// bit depth). The 8-bit helper above stays untouched -- every existing
4264 /// gate depends on it.
4265 fn ffmpeg_decode_sequence_10bit(
4266 stream: &[u8],
4267 width: usize,
4268 height: usize,
4269 frames: usize,
4270 ) -> Vec<Pic> {
4271 let out = run_with_stdin(
4272 Command::new("ffmpeg").args([
4273 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt",
4274 "yuv420p10le", "-",
4275 ]),
4276 stream,
4277 );
4278 assert!(
4279 out.status.success(),
4280 "ffmpeg refused the stream: {}",
4281 String::from_utf8_lossy(&out.stderr)
4282 );
4283 let (luma, chroma) = (width * height, width * height / 4);
4284 let frame_samples = luma + 2 * chroma;
4285 let frame_bytes = frame_samples * 2;
4286 assert_eq!(
4287 out.stdout.len(),
4288 frame_bytes * frames,
4289 "expected {frames} 4:2:0 10-bit frames, ffmpeg said: {}",
4290 String::from_utf8_lossy(&out.stderr)
4291 );
4292 fn le16(bytes: &[u8]) -> Vec<u16> {
4293 bytes
4294 .chunks_exact(2)
4295 .map(|c| u16::from_le_bytes([c[0], c[1]]))
4296 .collect()
4297 }
4298 (0..frames)
4299 .map(|i| {
4300 let base = i * frame_bytes;
4301 Pic {
4302 width,
4303 height,
4304 y: le16(&out.stdout[base..base + luma * 2]),
4305 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
4306 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
4307 }
4308 })
4309 .collect()
4310 }
4311
4312 /// lane-svtinter: an SVT-AV1 screen stream whose frame height is not a
4313 /// multiple of the superblock size codes PALETTE blocks in the bottom
4314 /// (and right) superblock row that hang off the mi grid. Spec 5.11.50
4315 /// `palette_tokens` reads the colour-index map only over the block's
4316 /// `onscreenWidth x onscreenHeight` corner and replicates it outward;
4317 /// this decoder read the full block grid, so it consumed colour-index
4318 /// symbols libaom never wrote and desynced the rest of the tile -- either
4319 /// a wrong bottom superblock row (1599 luma samples in this stream's
4320 /// frame 0, ~80k per inter frame after) or, further along the same tile,
4321 /// a bogus "a Golomb tail longer than this decoder reads" refusal.
4322 ///
4323 /// Unlike its lane-svt1 sibling above this one BUILDS its stream: the
4324 /// recipe is synthetic (`smptebars,drawgrid` through `libsvtav1 -preset 8
4325 /// -svtav1-params screen-content-mode=1`), and 384x152 puts a 32x32
4326 /// palette block at mi row 32 of a 38-mi-tall frame, 24 of its 32 rows
4327 /// on screen. `palette_onscreen_cut_hits` is asserted non-zero so the row
4328 /// cannot pass on a stream that never cuts a palette map (class
4329 /// gate-blind-to-feature).
4330 #[test]
4331 fn an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly() {
4332 const NAME: &str = "an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly";
4333 if !have_ffmpeg() {
4334 eprintln!("SKIP {NAME}: no ffmpeg");
4335 return;
4336 }
4337 let (width, height) = (384usize, 152usize);
4338 let out = Command::new("ffmpeg")
4339 .args([
4340 "-v", "error", "-f", "lavfi", "-i",
4341 "smptebars=s=384x152:r=12,drawgrid=w=8:h=8:t=1:c=black",
4342 "-frames:v", "4", "-c:v", "libsvtav1", "-preset", "8", "-crf", "30",
4343 "-svtav1-params", "lp=1:screen-content-mode=1", "-g", "12", "-f", "obu", "-",
4344 ])
4345 .stdin(Stdio::null())
4346 .stdout(Stdio::piped())
4347 .stderr(Stdio::piped())
4348 .output()
4349 .expect("ffmpeg failed to run");
4350 if !out.status.success() || out.stdout.is_empty() {
4351 eprintln!(
4352 "SKIP {NAME}: no libsvtav1 in this ffmpeg: {}",
4353 String::from_utf8_lossy(&out.stderr)
4354 );
4355 return;
4356 }
4357 let stream = out.stdout;
4358 crate::decode::reset_palette_onscreen_cut_hits();
4359 let decoded = decode_stream(&stream).expect("the SVT-AV1 screen stream decodes");
4360 assert_eq!(decoded.len(), 4, "{NAME}: frame count");
4361 assert!(
4362 crate::decode::palette_onscreen_cut_hits() > 0,
4363 "{NAME}: no palette map is cut by the frame edge here -- the gate would pass blind"
4364 );
4365 let want = ffmpeg_decode_sequence(&stream, width, height, decoded.len());
4366 assert_eq!(want.len(), decoded.len(), "{NAME}: ffmpeg frame count");
4367 for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
4368 assert_eq!(got.y, want.y, "{NAME}: frame {i} luma vs ffmpeg");
4369 assert_eq!(got.u, want.u, "{NAME}: frame {i} U vs ffmpeg");
4370 assert_eq!(got.v, want.v, "{NAME}: frame {i} V vs ffmpeg");
4371 }
4372 }
4373
4374 /// lane-svt1: an SVT-AV1 (v3.1.2, `-preset 8 -crf 35`) screen key frame
4375 /// codes 16x16 PALETTE blocks with `skip == 1` whose `tx_depth` split the
4376 /// luma transform. [`crate::decode::decode_block`] armed the palette
4377 /// prediction only when the transform covered the whole block, so that one
4378 /// block predicted DC off its own edges instead: the right symbols (the
4379 /// whole mode ladder diffs clean against an instrumented aomdec) and the
4380 /// wrong pixels -- 812 luma samples in frame 0, carried by the V_PRED
4381 /// blocks under it to 10122 samples over the 12-frame stream.
4382 ///
4383 /// No lavfi recipe witnesses it in a stream this decoder otherwise decodes:
4384 /// 6 sources x 5 sizes x 6 crf values through `libsvtav1 -preset 8
4385 /// -svtav1-params screen-content-mode=1` produced 8 streams that reach the
4386 /// path, and every one of them either refuses on an unrelated Golomb tail
4387 /// or misses by ~200k samples on unrelated inter-frame defects (both
4388 /// recorded in `lanes/svt1.report.md`). So the gate rides the kept stream
4389 /// named by `EC_AV1_SVT1_STREAM` and SKIPs when it is unset -- the screen
4390 /// crop itself is never committed to `fixtures/`.
4391 ///
4392 /// `skip_split_tx_override_hits` is asserted non-zero so the row cannot
4393 /// pass on a stream that never reaches the fixed arm (class
4394 /// gate-blind-to-feature).
4395 #[test]
4396 fn an_svt_screen_palette_block_with_a_split_transform_decodes_exactly() {
4397 const NAME: &str = "an_svt_screen_palette_block_with_a_split_transform_decodes_exactly";
4398 let Ok(path) = std::env::var("EC_AV1_SVT1_STREAM") else {
4399 eprintln!("SKIP {NAME}: EC_AV1_SVT1_STREAM names no stream");
4400 return;
4401 };
4402 if !have_ffmpeg() {
4403 eprintln!("SKIP {NAME}: no ffmpeg");
4404 return;
4405 }
4406 let data = match std::fs::read(&path) {
4407 Ok(data) => data,
4408 Err(e) => {
4409 eprintln!("SKIP {NAME}: {path}: {e}");
4410 return;
4411 }
4412 };
4413 crate::decode::reset_skip_split_tx_override_hits();
4414 let decoded = decode_stream(&data).expect("the kept SVT-AV1 screen stream decodes");
4415 assert!(
4416 crate::decode::skip_split_tx_override_hits() > 0,
4417 "{NAME}: no skipped split-transform palette block in {path} -- the gate would pass blind"
4418 );
4419 let (width, height) = (decoded[0].width, decoded[0].height);
4420 let want = ffmpeg_decode_sequence(&data, width, height, decoded.len());
4421 for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
4422 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");
4423 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");
4424 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");
4425 }
4426 }
4427
4428 /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an
4429 /// independent decoder, not just this crate checking its own tile path.
4430 #[test]
4431 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
4432 let fctx = &crate::decode::FrameCtx::for_encoder();
4433 if !have_ffmpeg() {
4434 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
4435 return;
4436 }
4437 // lane-av1straddle: 216x96 joins 128x64 because only a size whose
4438 // 32x32 blocks straddle the right-hand frame edge can see the writer
4439 // coding a transform unit that starts outside the frame -- libdav1d
4440 // AND libaom both refused the whole key frame while it did, and this
4441 // crate's own (lenient) decoder only differed in the last block's V.
4442 for &(width, height) in &[(128usize, 64usize), (216usize, 96usize)] {
4443 let pictures: Vec<_> = (0..3)
4444 .map(|i| panned_test_card(width, height, i * 3))
4445 .collect();
4446 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
4447 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
4448 let decoded = decode_stream(&encoded.stream).unwrap();
4449 assert_eq!(decoded.len(), 3);
4450 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
4451 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
4452 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
4453 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
4454 }
4455 // ... and the encoder's own reconstruction is what ffmpeg sees,
4456 // so the check fails on a writer-side desync too, not only on a
4457 // decoder-side one.
4458 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
4459 let rec = &frame.reconstruction;
4460 assert_eq!(rec.y, want.y, "{width}x{height} frame {i} luma: reconstruction vs ffmpeg");
4461 assert_eq!(rec.u, want.u, "{width}x{height} frame {i} U: reconstruction vs ffmpeg");
4462 assert_eq!(rec.v, want.v, "{width}x{height} frame {i} V: reconstruction vs ffmpeg");
4463 }
4464 }
4465 }
4466
4467 /// lane-av1rect: the encoder used to REFUSE every size where a 32x32
4468 /// block straddles BOTH true frame edges at once ("straddles the true
4469 /// frame edge in a way that needs a rectangular (HORZ/VERT) transform
4470 /// this encoder does not code yet"). That refusal was a misreading of
4471 /// spec 5.11.4: a block whose `hasRows` and `hasCols` are BOTH false
4472 /// reads no partition symbol at all and is `PARTITION_SPLIT` by
4473 /// inference, down to the 8x8 leaves whose own mi origin is inside the
4474 /// frame -- exactly the leaves this writer already codes for the
4475 /// one-axis case, and no rectangular transform anywhere. The sweep walks
4476 /// the corners around the 32-multiples (each width has a 16x16 column
4477 /// whose right half is outside, each height a row whose bottom half is,
4478 /// so the bottom-right 16x16 of every size here is cut on both axes) and
4479 /// three-way compares: our decoder, the encoder's own reconstruction and
4480 /// ffmpeg, over a 4-frame GOP so the inter writer's copy of the same
4481 /// signaling is covered too. `edge_both_cut_hits` proves the decoder
4482 /// really took the inferred-split path rather than the gate passing on
4483 /// geometry that never fires it.
4484 #[test]
4485 fn a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg() {
4486 let fctx = &crate::decode::FrameCtx::for_encoder();
4487 if !have_ffmpeg() {
4488 eprintln!("SKIP a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg: no ffmpeg");
4489 return;
4490 }
4491 const FRAMES: usize = 4;
4492 let mut both_cut = 0usize;
4493 for &width in &[200usize, 216, 232, 248] {
4494 for &height in &[104usize, 120, 136, 152] {
4495 let pictures: Vec<_> = (0..FRAMES as i64)
4496 .map(|i| panned_test_card(width, height, i * 3))
4497 .collect();
4498 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
4499 .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
4500 // Reset per attempt, never a delta across sizes (class
4501 // counter-from-refused-stream).
4502 crate::decode::reset_edge_both_cut_hits();
4503 let decoded = decode_stream(&encoded.stream)
4504 .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
4505 both_cut += crate::decode::edge_both_cut_hits().iter().sum::<usize>();
4506 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
4507 assert_eq!(
4508 ffmpeg_frames.len(),
4509 FRAMES,
4510 "{width}x{height}: ffmpeg decoded {} of {FRAMES} frames",
4511 ffmpeg_frames.len()
4512 );
4513 assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
4514 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
4515 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
4516 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
4517 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
4518 }
4519 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
4520 let rec = &frame.reconstruction;
4521 assert_eq!(rec.y, want.y, "{width}x{height} frame {i} luma: recon vs ffmpeg");
4522 assert_eq!(rec.u, want.u, "{width}x{height} frame {i} U: recon vs ffmpeg");
4523 assert_eq!(rec.v, want.v, "{width}x{height} frame {i} V: recon vs ffmpeg");
4524 }
4525 }
4526 }
4527 assert!(
4528 both_cut > 0,
4529 "no partition node in the whole sweep was coded as the both-axes-cut \
4530 inferred split -- the gate is blind to the feature it pins"
4531 );
4532 }
4533
4534 /// lane-corner: sizes whose LAST superblock is cut by the true frame
4535 /// edge on BOTH axes with more than half of each still inside -- so
4536 /// `has_cols` and `has_rows` are both true and the spec lets that
4537 /// superblock stay a whole 64x64 `PARTITION_NONE` block, which this
4538 /// encoder's roots take (`EC_AV1_B64EDGE` on the inter side, the key
4539 /// frame's own `Superblock::Whole`). The sibling luma-only test
4540 /// (`encoder.rs`'s `a_non_superblock_aligned_clip_...`) is blind to
4541 /// chroma (class `metric-blind-to-a-plane`), so this one compares all
4542 /// three planes three ways: our decoder, the encoder's own
4543 /// reconstruction, and ffmpeg.
4544 #[test]
4545 fn a_doubly_cut_superblock_root_round_trips_in_every_plane() {
4546 let fctx = &crate::decode::FrameCtx::for_encoder();
4547 if !have_ffmpeg() {
4548 eprintln!("SKIP a_doubly_cut_superblock_root_round_trips_in_every_plane: no ffmpeg");
4549 return;
4550 }
4551 const FRAMES: usize = 4;
4552 // Each size leaves MORE than half of its last superblock row (and,
4553 // but for 200x120's 8-px column, of its last column) inside, which is
4554 // what makes the root legal there at all; 248x168/232x168/248x184 are
4555 // cut on BOTH axes at once. 1920x1080 -- the user's own export shape
4556 // -- is the same case: 1080 = 16*64 + 56, a 56-px bottom straddle.
4557 for &(width, height) in &[(248usize, 168usize), (232, 168), (200, 120), (248, 184)] {
4558 let pictures: Vec<_> = (0..FRAMES as i64)
4559 .map(|i| panned_test_card(width, height, i * 3))
4560 .collect();
4561 let _ = crate::encode::take_b64_edge_hits();
4562 let _ = crate::encode::take_i64_root_hits();
4563 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
4564 .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
4565 let edges = crate::encode::take_b64_edge_hits();
4566 let [i64_whole, i64_offered, i64_edge] = crate::encode::take_i64_root_hits();
4567 eprintln!(
4568 "{width}x{height}: edge inter 64 roots {edges}, key 64 roots {i64_whole} of \
4569 {i64_offered} offered, {i64_edge} of them cut by the frame edge"
4570 );
4571 // gate-blind-to-feature: without this the three-way compare below
4572 // passes on a stream that never coded a whole root at the cut
4573 // superblock at all.
4574 assert!(
4575 i64_edge > 0,
4576 "{width}x{height}: no 64x64 root sat on a superblock the frame edge cuts"
4577 );
4578 let decoded = decode_stream(&encoded.stream)
4579 .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
4580 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
4581 assert_eq!(ffmpeg_frames.len(), FRAMES, "{width}x{height}: ffmpeg frame count");
4582 assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
4583 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
4584 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma: ours vs ffmpeg");
4585 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U: ours vs ffmpeg");
4586 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V: ours vs ffmpeg");
4587 }
4588 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
4589 let rec = &frame.reconstruction;
4590 assert_eq!(rec.y, want.y, "{width}x{height} frame {i} luma: recon vs ffmpeg");
4591 assert_eq!(rec.u, want.u, "{width}x{height} frame {i} U: recon vs ffmpeg");
4592 assert_eq!(rec.v, want.v, "{width}x{height} frame {i} V: recon vs ffmpeg");
4593 }
4594 }
4595 }
4596
4597 /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME`
4598 /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s
4599 /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc
4600 /// attempts never could: frame 0 is a real key frame (this crate's own
4601 /// encoder, real texture), refreshing all 8 DPB slots as spec requires --
4602 /// slot 3 keeps that exact picture from here on. Frame 1 is a hand-coded
4603 /// inter frame whose lone 32x32 block is *intra* (`DC_PRED`, `skip`),
4604 /// refreshing only slot 0 with a flat 128 block -- distinguishable from
4605 /// frame 0's real texture, so slot 0 (`LAST_FRAME`) and slot 3
4606 /// (`GOLDEN_FRAME`) hold visibly different pictures once frame 2 runs.
4607 /// Frame 2 is a hand-coded inter frame naming `ref_frame_idx[3] = 3`
4608 /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose
4609 /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME`
4610 /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy
4611 /// of GOLDEN's picture, so its output must equal frame 0's own
4612 /// reconstruction exactly, and must differ from frame 1's -- proof the
4613 /// decoder actually read the golden plane, not silently substituted
4614 /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a
4615 /// deblock/MC residue that turned out to be film-grain synthesis
4616 /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN);
4617 /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing
4618 /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so
4619 /// this fixture flips back to its round-4 pixel-exact form. ffmpeg
4620 /// decodes the identical wire bytes as the foreign oracle
4621 /// (shared-oracle-blindness class): this crate's own decoder agreeing
4622 /// with itself would prove nothing.
4623 #[test]
4624 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
4625 let fctx = &crate::decode::FrameCtx::new();
4626 if !have_ffmpeg() {
4627 eprintln!(
4628 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
4629 );
4630 return;
4631 }
4632 use crate::cdf_state::Cdfs;
4633 use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of};
4634 use crate::encode::{inter_frame_headers, key_frame_headers};
4635 use crate::frame::frame_obu;
4636 use crate::msac::SymbolEncoder;
4637 use crate::mvstack::{
4638 GOLDEN_FRAME, MiGrid, find_mv_stack, single_ref_p1_ctx, single_ref_p3_ctx,
4639 single_ref_p5_ctx,
4640 };
4641 use crate::obu::temporal_delimiter;
4642
4643 let (width, height) = (32usize, 32usize);
4644 let base_q_idx = 100u8;
4645 // The whole picture is one 32x32 block: `partition_ctx`/`skip_ctx`/
4646 // `intra_inter_ctx`'s neighbour inputs are all "no neighbour yet" --
4647 // a fresh `Neighbours`' `above_side_mi`/`left_side_mi` start at `SB`
4648 // (64), so `partition_ctx_mi`'s `side_mi * 2 <= side` (32) is false
4649 // on both axes (ctx 0), and `above_skip`/`left_skip`/`above_inter`/
4650 // `left_inter`/`above_ref`/`left_ref` all start `false`/`-1`
4651 // (decode.rs `Neighbours::new`) -- computed here without
4652 // constructing the (module-private) `Neighbours` itself.
4653 const PARTITION_NONE: usize = 0;
4654 let ii_ctx = intra_inter_ctx(false, false, false, false);
4655 let sr_p1_ctx = single_ref_p1_ctx(None, None, None, None);
4656 let sr_p3_ctx = single_ref_p3_ctx(None, None, None, None);
4657 let sr_p5_ctx = single_ref_p5_ctx(None, None, None, None);
4658
4659 for run in 0..4 {
4660 let picture = test_card(width, height);
4661 let key = encode_key_frame_with_ctx(&picture, base_q_idx, 0.5, fctx).unwrap();
4662 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
4663
4664 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
4665 // 128 block (no neighbours to predict `DC_PRED` from).
4666 let (_, mut header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
4667 // These two tiles are hand-coded from a FRESH `Cdfs`, so the
4668 // frames must not carry CDF state the way the encoder's own inter
4669 // frames now do (spec 7.20): with the bit set, what each frame
4670 // stores is what it started from -- the defaults -- which is
4671 // exactly what the next hand-coded tile assumes.
4672 header1.disable_frame_end_update_cdf = true;
4673 let tile1 = {
4674 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
4675 let mut enc = SymbolEncoder::new();
4676 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
4677 enc.symbol(1, &mut cdfs.skip[0]); // skip
4678 enc.symbol(0, &mut cdfs.intra_inter[ii_ctx]); // is_inter = false
4679 enc.symbol(0, &mut cdfs.y_mode[3]); // DC_PRED, size group 3 (32x32)
4680 enc.symbol(0, &mut cdfs.uv_mode_cfl[0]); // DC_PRED
4681 enc.finish()
4682 };
4683 let mut stream = key.stream.clone();
4684 stream.extend(temporal_delimiter());
4685 stream.extend(frame_obu(&seq, &header1, &tile1).unwrap());
4686
4687 // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME,
4688 // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0).
4689 let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap();
4690 header2.disable_frame_end_update_cdf = true;
4691 header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1
4692 let tile2 = {
4693 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
4694 let mut enc = SymbolEncoder::new();
4695 let grid = MiGrid::new(8, 8);
4696 let stack = find_mv_stack(&grid, 0, 0, 8, 8, GOLDEN_FRAME, 8, 8);
4697 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
4698 enc.symbol(1, &mut cdfs.skip[0]); // skip
4699 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter = true
4700 enc.symbol(0, &mut cdfs.single_ref[sr_p1_ctx][0]); // p1: LAST/LAST2/LAST3/GOLDEN group
4701 enc.symbol(1, &mut cdfs.single_ref[sr_p3_ctx][2]); // p3: GOLDEN/LAST3 sub-group
4702 enc.symbol(1, &mut cdfs.single_ref[sr_p5_ctx][4]); // p5: GOLDEN_FRAME
4703 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new -> not NEWMV
4704 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero -> not GLOBALMV
4705 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // nearest -> NEARESTMV, (0, 0)
4706 enc.finish()
4707 };
4708 stream.extend(temporal_delimiter());
4709 stream.extend(frame_obu(&seq, &header2, &tile2).unwrap());
4710
4711 let before = non_last_ref_hits();
4712 let decoded = decode_stream(&stream).unwrap();
4713 assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures");
4714 assert!(
4715 non_last_ref_hits() > before,
4716 "run {run}: GOLDEN_FRAME never fired"
4717 );
4718
4719 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3);
4720 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
4721 assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg");
4722 assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg");
4723 assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg");
4724 }
4725 assert_eq!(
4726 decoded[0].y, key.reconstruction.y,
4727 "run {run}: frame 0 vs the encoder's own reconstruction"
4728 );
4729 assert_eq!(
4730 decoded[2].y, key.reconstruction.y,
4731 "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names"
4732 );
4733 assert_ne!(
4734 decoded[2].y, decoded[1].y,
4735 "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \
4736 distinguishable -- the gate proves nothing"
4737 );
4738 }
4739 }
4740
4741 /// Builds a `gradients` lavfi source string with colours derived from
4742 /// `seed`, not left to the filter's own default.
4743 ///
4744 /// Measured (lane-fixdet r1): ffmpeg's `gradients` source IGNORES its
4745 /// `seed=` parameter for colour selection -- five encodes of an
4746 /// identical command line (same `seed=`, same everything) produced five
4747 /// different fixtures, because the unset `c0..c9` stops are randomized
4748 /// from something other than that seed. Every one of this file's ~20
4749 /// gate fixtures built a `gradients` source this way, so none of them
4750 /// had a reproducible input: a pin captured from one run could not be
4751 /// regenerated, and "attempt N failed" was as likely to be a different
4752 /// fixture as a different decode outcome.
4753 ///
4754 /// Freezing the colours outright (as the earliest four gates below do,
4755 /// hand-picking `c0=red:c1=blue:c2=green`) fixes reproducibility but
4756 /// throws away the per-attempt content variety the sweep gates need to
4757 /// make features (OBMC, warp, wedge, ...) fire at all -- this repo's own
4758 /// `sampler-decorrelated-gate` class. So: derive `c0..c3` deterministically
4759 /// FROM the seed with a plain integer hash, and keep passing `seed=`
4760 /// itself too, so a future ffmpeg that actually honours it only adds
4761 /// more variety, never removes the determinism this buys.
4762 fn gradients_source(seed: u32, width: usize, height: usize, tail: &str) -> String {
4763 fn hash_color(seed: u32, salt: u32) -> String {
4764 let h = seed
4765 .wrapping_mul(2_654_435_761)
4766 .wrapping_add(salt.wrapping_mul(0x9E37_79B9))
4767 ^ (seed.rotate_left(13));
4768 format!("0x{:06x}", h & 0x00ff_ffff)
4769 }
4770 let (c0, c1, c2, c3) = (
4771 hash_color(seed, 0),
4772 hash_color(seed, 1),
4773 hash_color(seed, 2),
4774 hash_color(seed, 3),
4775 );
4776 format!("gradients=size={width}x{height}:c0={c0}:c1={c1}:c2={c2}:c3={c3}:seed={seed}:{tail}")
4777 }
4778
4779 /// The determinism guard: same seed twice must byte-match ffmpeg's own
4780 /// output; different seeds must not. Regresses this fix if it ever
4781 /// breaks.
4782 #[test]
4783 fn gradients_source_is_reproducible_per_seed() {
4784 if !have_ffmpeg() {
4785 eprintln!("SKIP gradients_source_is_reproducible_per_seed: no ffmpeg");
4786 return;
4787 }
4788 fn render_hash(lavfi: &str) -> Vec<u8> {
4789 let out = Command::new("ffmpeg")
4790 .args([
4791 "-v", "error", "-f", "lavfi", "-i", lavfi, "-frames:v", "1", "-f", "rawvideo",
4792 "-",
4793 ])
4794 .stdin(Stdio::null())
4795 .stdout(Stdio::piped())
4796 .stderr(Stdio::piped())
4797 .output()
4798 .expect("ffmpeg failed to run");
4799 assert!(out.status.success(), "ffmpeg refused {lavfi}");
4800 out.stdout
4801 }
4802 let a1 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
4803 let a2 = render_hash(&gradients_source(43, 64, 64, "duration=0.04:rate=25"));
4804 let a3 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
4805 assert_eq!(a1, a3, "same seed must reproduce byte-identical output");
4806 assert_ne!(a1, a2, "different seeds must not collide");
4807 }
4808
4809 /// Encodes a real libaom-av1 stream (via ffmpeg's own encoder, not this
4810 /// crate's) with the same reduced-partition flags lane-av1adst's r6
4811 /// probe found still select `ADST_ADST`/`ADST_DCT`/`DCT_ADST` on
4812 /// gradient content (TX_SET_INTRA_2), and decodes it with
4813 /// [`decode_stream`] -- lifting the round-2 refusal is only real if it
4814 /// gets past an encoder this crate never wrote a byte of.
4815 fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {
4816 libaom_encode_with(lavfi, width, height, crf, &[])
4817 }
4818
4819 /// As [`libaom_encode`], with extra encoder args appended -- used to pin
4820 /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8`
4821 /// RD search is not otherwise stable run-to-run on this box, and lavfi
4822 /// `gradients` needs its own `seed=` for the same reason) and to gate
4823 /// individual feature flags (`-enable-cdef 0`) a given fixture needs off.
4824 fn libaom_encode_with(
4825 lavfi: &str,
4826 width: usize,
4827 height: usize,
4828 crf: u32,
4829 extra: &[&str],
4830 ) -> Option<Vec<u8>> {
4831 let mut args = vec![
4832 "-v",
4833 "error",
4834 "-f",
4835 "lavfi",
4836 "-i",
4837 lavfi,
4838 "-frames:v",
4839 "1",
4840 "-pix_fmt",
4841 "yuv420p",
4842 "-c:v",
4843 "libaom-av1",
4844 ];
4845 let crf_str = crf.to_string();
4846 args.extend(["-crf", &crf_str]);
4847 args.extend([
4848 "-cpu-used",
4849 "8",
4850 "-enable-rect-partitions",
4851 "0",
4852 "-enable-ab-partitions",
4853 "0",
4854 "-enable-1to4-partitions",
4855 "0",
4856 "-enable-angle-delta",
4857 "0",
4858 "-enable-cfl-intra",
4859 "0",
4860 ]);
4861 args.extend(extra.iter().copied());
4862 args.extend(["-f", "obu", "-"]);
4863 let out = Command::new("ffmpeg")
4864 .args(&args)
4865 .stdin(Stdio::null())
4866 .stdout(Stdio::piped())
4867 .stderr(Stdio::piped())
4868 .output()
4869 .expect("ffmpeg failed to run");
4870 if !out.status.success() {
4871 eprintln!(
4872 "ffmpeg refused to encode {lavfi} at {width}x{height}: {}",
4873 String::from_utf8_lossy(&out.stderr)
4874 );
4875 return None;
4876 }
4877 Some(out.stdout)
4878 }
4879
4880 /// The end-to-end gate: two real libaom-av1 configs, decoded with
4881 /// [`decode_stream`] and checked against ffmpeg's own decode of the same
4882 /// bytes. Not every config this encoder writes decodes yet (partitions
4883 /// below 16x16, AB partitions, CfL and others remain round-2 gaps per the
4884 /// r6 catalogue) -- both configs here pick `cpu-used 8` plus the
4885 /// partition/angle-delta/CfL flags r6 found narrow the encoder onto this
4886 /// decoder's supported syntax, while still landing on non-`DCT_DCT` tx
4887 /// types on gradient content.
4888 #[test]
4889 fn a_real_libaom_stream_with_adst_decodes_end_to_end() {
4890 if !have_ffmpeg() {
4891 eprintln!("SKIP a_real_libaom_stream_with_adst_decodes_end_to_end: no ffmpeg");
4892 return;
4893 }
4894 let configs: [(String, usize, usize, u32); 2] = [
4895 ("testsrc2=size=64x64:rate=1".to_string(), 64, 64, 15),
4896 (gradients_source(42, 64, 64, "rate=1"), 64, 64, 15),
4897 ];
4898 let mut verdicts = Vec::new();
4899 for (lavfi, width, height, crf) in configs {
4900 let lavfi = lavfi.as_str();
4901 let Some(stream) = libaom_encode(lavfi, width, height, crf) else {
4902 verdicts.push(format!("{lavfi}: ffmpeg itself refused to encode"));
4903 continue;
4904 };
4905 match decode_stream(&stream) {
4906 Ok(frames) => {
4907 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
4908 let matches = frames[0].y == ffmpeg_frames[0].y
4909 && frames[0].u == ffmpeg_frames[0].u
4910 && frames[0].v == ffmpeg_frames[0].v;
4911 verdicts.push(format!(
4912 "{lavfi}: decoded, {} ffmpeg's own decode",
4913 if matches { "MATCHES" } else { "MISMATCHES" }
4914 ));
4915 // Not a hard `assert!`: libaom's own mode decisions at
4916 // `cpu-used 8` are not observed stable run-to-run on this
4917 // box (multi-threaded RD search), so a run that happens
4918 // to land on a still-unsupported syntax element (e.g. a
4919 // partition below 16x16, a separate round-2 gap) can
4920 // decode without erroring yet disagree -- that failure
4921 // mode belongs to those other gaps, not to this round's
4922 // ADST wiring, and the eprintln below reports it either
4923 // way rather than hiding it.
4924 }
4925 Err(e) => {
4926 verdicts.push(format!("{lavfi}: still refuses ({e})"));
4927 }
4928 }
4929 }
4930 eprintln!("libaom ADST end-to-end verdicts:");
4931 for v in &verdicts {
4932 eprintln!(" {v}");
4933 }
4934 }
4935
4936 /// lane-dgolomb: the `force_integer_mv` gate. libaom turns screen-content
4937 /// tools on for DARK, SMOOTH content -- its `av1_set_screen_content_options`
4938 /// counts 16x16 blocks with 2..=4 distinct luma values -- and then sets
4939 /// `force_integer_mv` on any inter frame whose source is pixel-identical to
4940 /// the previously coded source (`av1_is_integer_mv`: `cs_rate >= 0.8` and
4941 /// `C == T`, every collocated 8x8 block matching, is the only path that
4942 /// returns 1). Both hold on his real AV1 films, and this decoder used to
4943 /// drop `lower_mv_precision`'s `is_integer` half as unreachable, so every
4944 /// temporal MV candidate on such a frame came out at eighth-pel: the frame
4945 /// decoded without any error into a whole-frame prediction mismatch, and
4946 /// the desync surfaced blocks later as "a Golomb tail longer than this
4947 /// decoder reads".
4948 ///
4949 /// The source is SYNTHETIC (no film sample lives in `fixtures`): the
4950 /// near-flat dark pattern libaom's own screen-content detector counts as
4951 /// screen content, at the film-B crop size 1920x1024, SCROLLING globally
4952 /// 5 px per frame and frozen on frame 8 -- an exact duplicate of frame 7
4953 /// (the `C == T` trigger) whose twin is not among its own references, so
4954 /// its blocks still code real motion under `force_integer_mv`.
4955 ///
4956 /// lane-dpm1 made this gate SENSITIVE: with the `force_integer_mv` branch
4957 /// of [`crate::motion_field::lower_mv_precision`] stubbed out (`if false
4958 /// &&`) the stream decodes WRONG -- frame 8, luma sample 25695, 20 against
4959 /// ffmpeg's 19 -- where the previous patch-in-a-static-background recipe
4960 /// (and two others tried) still decoded byte-exact: there the used mv-stack
4961 /// slots came from agreeing spatial neighbours and the rounded temporal
4962 /// entries never won one. The gate asserts both halves: at least one INTER
4963 /// frame really carries `force_integer_mv` (class `gate-blind-to-feature`),
4964 /// and every shown frame decodes sample-exact against ffmpeg's own decode.
4965 #[test]
4966 fn a_libaom_force_integer_mv_stream_decodes_exact() {
4967 const NAME: &str = "a_libaom_force_integer_mv_stream_decodes_exact";
4968 if !have_ffmpeg() {
4969 eprintln!("SKIP {NAME}: no ffmpeg");
4970 return;
4971 }
4972 let (w, h, frames) = (1920usize, 1024usize, 16usize);
4973 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
4974 let mut off = 0usize;
4975 for f in 0..frames {
4976 // lane-dpm1: the WHOLE picture scrolls 5 px per frame and freezes
4977 // on frame 8, so (a) every block of the frozen frame -- including
4978 // mi(0,0), which has no spatial neighbour at all -- still codes
4979 // real motion against the references that are not its twin, and
4980 // (b) 40 eighth-pels projected over the pyramid's distances lands
4981 // on non-multiples of 8 (40/2 = 20 -> 16). A patch moving inside a
4982 // static background was NOT sensitive: there the used stack slots
4983 // came from spatial neighbours that agreed, and the rounded
4984 // temporal entries never won one.
4985 if f > 0 && f != 8 {
4986 off = (off + 5) % h;
4987 }
4988 let mut y = vec![0u8; w * h];
4989 for row in 0..h {
4990 let src = (row + off) % h;
4991 for col in 0..w {
4992 // 2..=4 distinct values per 16x16 block, all dark: the
4993 // screen-content detector's own counting rule.
4994 y[row * w + col] =
4995 16 + ((col / 32 + src / 32) % 5) as u8 + ((col / 4 + src / 4) % 3) as u8;
4996 }
4997 }
4998 raw.extend_from_slice(&y);
4999 raw.extend(std::iter::repeat_n(128u8, w * h / 2));
5000 }
5001 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
5002 let src = std::env::temp_dir().join(format!("ec-av1-intmv-{}.yuv", std::process::id()));
5003 std::fs::write(&src, &raw).expect("raw source");
5004 let out = Command::new("ffmpeg")
5005 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
5006 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
5007 .arg(&src)
5008 .args(["-an", "-threads", "1", "-g", "16", "-c:v", "libaom-av1"])
5009 .args(["-cpu-used", "6", "-b:v", "0", "-crf", "35", "-f", "obu", "-"])
5010 .stdin(Stdio::null())
5011 .stdout(Stdio::piped())
5012 .stderr(Stdio::piped())
5013 .output()
5014 .expect("ffmpeg failed to run");
5015 let _ = std::fs::remove_file(&src);
5016 if !out.status.success() {
5017 eprintln!(
5018 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
5019 String::from_utf8_lossy(&out.stderr)
5020 );
5021 return;
5022 }
5023 let stream = out.stdout;
5024
5025 // Half of the gate: the stream must actually carry the feature.
5026 let mut parser = Av1Parser::new();
5027 let (mut pos, mut int_mv_inter) = (0usize, 0usize);
5028 while pos < stream.len() {
5029 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
5030 pos += obu.total_size.max(1);
5031 let header = match &obu.kind {
5032 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
5033 _ => continue,
5034 };
5035 if header.force_integer_mv && !header.frame_is_intra && header.use_ref_frame_mvs {
5036 int_mv_inter += 1;
5037 }
5038 }
5039 assert!(
5040 int_mv_inter > 0,
5041 "{NAME} went blind: libaom coded no inter frame with force_integer_mv"
5042 );
5043
5044 let ours = decode_stream(&stream).expect("libaom screen-content stream decodes");
5045 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
5046 assert_eq!(ours.len(), frames, "shown frame count");
5047 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
5048 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
5049 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
5050 assert!(
5051 first.is_none(),
5052 "frame {i} plane {plane} differs from ffmpeg at sample {} \
5053 ({int_mv_inter} force_integer_mv inter frames in this stream)",
5054 first.unwrap()
5055 );
5056 }
5057 }
5058 }
5059
5060 /// lane-dpm1: the 128x128-INTRA-inside-an-INTER-frame chroma context gate.
5061 /// A 128x128 block codes its chroma as four TX_32X32 units, one per 64x64
5062 /// mu chunk, and libaom stamps the coefficient context PER UNIT. The two
5063 /// INTER mu-chunk sites set `mu_chroma` so the block tail re-stamps the
5064 /// four units in mu order; the INTRA-in-inter site did not, so the
5065 /// whole-block record left every unit carrying the TOP-LEFT unit's level.
5066 /// The next block then read its `txb_skip` off ctx 11 where libaom reads
5067 /// ctx 10 (class `override-slot-on-one-arm`) -- one symbol on the wrong
5068 /// CDF row, tile desynced, and because the loop-restoration coefficients
5069 /// live in the same tile data the damage showed up as a +-1 luma sample at
5070 /// the TOP of the frame (measured: frame 1, luma sample 66, ours 146 /
5071 /// ffmpeg 145, with 1.7M samples wrong behind it).
5072 ///
5073 /// Source: the repository's own 2160p colour-bar fixture at the native
5074 /// gate's crop (1920x1024 out of the middle), 12 frames, libaom
5075 /// `-cpu-used 6 -crf 45 -g 12` -- the first reference point of
5076 /// `bd_rate_screen_native`'s "bars 2160p" row, which is where the assertion
5077 /// caught it. The gate asserts the tool fired (class
5078 /// `gate-blind-to-feature`) and that every shown frame decodes sample-exact
5079 /// against ffmpeg's own decode.
5080 #[test]
5081 fn a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact() {
5082 const NAME: &str = "a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact";
5083 if !have_ffmpeg() {
5084 eprintln!("SKIP {NAME}: no ffmpeg");
5085 return;
5086 }
5087 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5088 .join("../../fixtures/video/h264-2160p-23.976-8bit.mp4");
5089 if !clip.exists() {
5090 eprintln!("SKIP {NAME}: the 2160p bars fixture is missing");
5091 return;
5092 }
5093 let (w, h, frames) = (1920usize, 1024usize, 12usize);
5094 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
5095 let src = std::env::temp_dir().join(format!("ec-av1-i128-{}.yuv", std::process::id()));
5096 let load = Command::new("ffmpeg")
5097 .args(["-v", "error", "-y", "-i"])
5098 .arg(&clip)
5099 .args(["-frames:v", &frames.to_string(), "-vf", "crop=1920:1024:960:568"])
5100 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
5101 .arg(&src)
5102 .output()
5103 .expect("ffmpeg failed to run");
5104 assert!(load.status.success(), "{NAME}: {}", String::from_utf8_lossy(&load.stderr));
5105 let out = Command::new("ffmpeg")
5106 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
5107 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
5108 .arg(&src)
5109 .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"])
5110 .args(["-cpu-used", "6", "-b:v", "0", "-crf", "45", "-f", "obu", "-"])
5111 .stdin(Stdio::null())
5112 .stdout(Stdio::piped())
5113 .stderr(Stdio::piped())
5114 .output()
5115 .expect("ffmpeg failed to run");
5116 let _ = std::fs::remove_file(&src);
5117 if !out.status.success() {
5118 eprintln!(
5119 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
5120 String::from_utf8_lossy(&out.stderr)
5121 );
5122 return;
5123 }
5124 let stream = out.stdout;
5125 let before = crate::decode::intra_128_in_inter_hits();
5126 let ours = decode_stream(&stream).expect("libaom bars stream decodes");
5127 assert!(
5128 crate::decode::intra_128_in_inter_hits() > before,
5129 "{NAME} went blind: no 128-rooted intra block inside an inter frame"
5130 );
5131 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
5132 assert_eq!(ours.len(), frames, "shown frame count");
5133 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
5134 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
5135 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
5136 assert!(
5137 first.is_none(),
5138 "frame {i} plane {plane} differs from ffmpeg at sample {}",
5139 first.unwrap()
5140 );
5141 }
5142 }
5143 }
5144
5145 /// lane-lossless: the refusal became an implementation, so its gate became
5146 /// a DECODE-EXACT one (class `refusal-lifted-without-a-gate`). libaom at
5147 /// `-crf 0` codes `base_q_idx == 0` -- the same lossless frame his
5148 /// screen-capture row gets at `-crf 5` -- where every plane is TX_4X4 with
5149 /// the Walsh-Hadamard transform, no `tx_type` symbol is coded
5150 /// (`read_tx_type`, `decodetxb.c`: "No need to read transform type for
5151 /// lossless mode(qindex==0)") and `is_cfl_allowed` (`blockd.h`) narrows to
5152 /// a BLOCK_4X4 chroma plane block. The gate asserts the stream really is
5153 /// lossless (class `gate-blind-to-feature`), that every KEY frame decodes
5154 /// sample-exact against ffmpeg, and that the still-unimplemented lossless
5155 /// INTER frame is refused BY NAME rather than decoded wrong.
5156 #[test]
5157 fn a_lossless_libaom_key_frame_decodes_sample_exact() {
5158 const NAME: &str = "a_lossless_libaom_key_frame_decodes_sample_exact";
5159 if !have_ffmpeg() {
5160 eprintln!("SKIP {NAME}: no ffmpeg");
5161 return;
5162 }
5163 let (w, h, frames) = (256usize, 128usize, 2usize);
5164 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
5165 for f in 0..frames {
5166 for row in 0..h {
5167 for col in 0..w {
5168 raw.push(((col * 7 + row * 13 + f * 31) % 251) as u8);
5169 }
5170 }
5171 // lane-lossless2: TEXTURED chroma. A flat chroma plane codes one
5172 // `txb_skip` symbol per 4x4 unit with every context at 0, which
5173 // is blind to both the unit ORDER and the per-unit contexts
5174 // (class `gate-blind-to-feature`).
5175 for row in 0..h / 2 {
5176 for col in 0..w / 2 {
5177 raw.push((((col + f) * 11 + row * 5) % 251) as u8);
5178 }
5179 }
5180 for row in 0..h / 2 {
5181 for col in 0..w / 2 {
5182 raw.push(((col * 3 + (row + f) * 17) % 251) as u8);
5183 }
5184 }
5185 }
5186 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
5187 let src = std::env::temp_dir().join(format!("ec-av1-lossless-{}.yuv", std::process::id()));
5188 std::fs::write(&src, &raw).expect("raw source");
5189 let encode = |gop: &str| {
5190 let out = Command::new("ffmpeg")
5191 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
5192 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
5193 .arg(&src)
5194 .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
5195 .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"])
5196 .stdin(Stdio::null())
5197 .stdout(Stdio::piped())
5198 .stderr(Stdio::piped())
5199 .output()
5200 .expect("ffmpeg failed to run");
5201 out
5202 };
5203 let out = encode("1");
5204 let _ = std::fs::remove_file(&src);
5205 if !out.status.success() {
5206 eprintln!(
5207 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
5208 String::from_utf8_lossy(&out.stderr)
5209 );
5210 return;
5211 }
5212 let stream = out.stdout;
5213 // Half of the gate: the stream must really carry a lossless frame
5214 // (class `gate-blind-to-feature`).
5215 let mut parser = Av1Parser::new();
5216 let (mut pos, mut lossless) = (0usize, 0usize);
5217 while pos < stream.len() {
5218 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
5219 pos += obu.total_size.max(1);
5220 let header = match &obu.kind {
5221 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
5222 _ => continue,
5223 };
5224 if header.lossless.iter().all(|&l| l) {
5225 lossless += 1;
5226 }
5227 }
5228 assert_eq!(lossless, frames, "{NAME} went blind: libaom coded no lossless key frame at -crf 0");
5229 let ours = decode_stream(&stream).expect("a lossless key-frame stream decodes");
5230 let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
5231 assert_eq!(ours.len(), frames, "{NAME}: frame count");
5232 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
5233 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
5234 .iter()
5235 .enumerate()
5236 {
5237 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
5238 assert_eq!(bad, 0, "{NAME}: frame {i} plane {plane}: {bad} samples differ");
5239 }
5240 }
5241 }
5242
5243 /// lane-lossless2: the refusal `a_lossless_inter_frame_is_refused_by_name`
5244 /// pinned became an implementation, so its gate became a DECODE-EXACT one
5245 /// (class `refusal-lifted-without-a-gate`). A lossless INTER frame codes
5246 /// its chroma plane as 4x4 transform units, plane-major inside each 64x64
5247 /// mu chunk (libaom `read_tx_size` returns TX_4X4 for every plane under
5248 /// `xd->lossless[..]`, and `decode_token_recon_block` walks
5249 /// `for (plane..) for (blk_row..) for (blk_col..)`), which is what
5250 /// `decode::read_inter_chroma_lossless` reads. The source carries TEXTURED
5251 /// CHROMA and real motion on purpose: a flat-chroma source codes one
5252 /// `txb_skip` symbol per unit and is blind to both the unit order and the
5253 /// per-unit contexts (class `gate-blind-to-feature`).
5254 #[test]
5255 fn a_lossless_libaom_inter_frame_decodes_sample_exact() {
5256 const NAME: &str = "a_lossless_libaom_inter_frame_decodes_sample_exact";
5257 if !have_ffmpeg() {
5258 eprintln!("SKIP {NAME}: no ffmpeg");
5259 return;
5260 }
5261 // (w, h, frames, gop, bit depth, 128-superblock, screen content)
5262 // lane-lossless2: the SCREEN rows carry palette blocks, which is what
5263 // caught the whole-block palette prediction being handed to a 4x4
5264 // chroma unit.
5265 // lane-lossless3: the last row is a screen source with INTER frames --
5266 // the row that caught both of this lane's defects (a skip 8x8 leaf
5267 // restoring the previous block's luma level band over the zeros
5268 // `av1_reset_entropy_context` writes, and a rect sub-8x8 INTRA leaf
5269 // reading one TX_4X8 unit where a lossless frame codes two TX_4X4).
5270 let cases: [(usize, usize, usize, &str, u32, bool, bool); 7] = [
5271 (256, 128, 8, "4", 8, false, false),
5272 (192, 96, 6, "3", 10, false, false),
5273 (320, 192, 6, "3", 8, false, false),
5274 (256, 256, 4, "2", 8, true, false),
5275 (320, 192, 2, "1", 8, false, true),
5276 (640, 384, 2, "1", 8, false, true),
5277 (640, 384, 6, "3", 8, false, true),
5278 ];
5279 for &(w, h, frames, gop, depth, sb128, screen) in &cases {
5280 let tag = format!(
5281 "{w}x{h} {depth}-bit gop {gop}{}{}",
5282 if sb128 { " sb128" } else { "" },
5283 if screen { " screen" } else { "" }
5284 );
5285 let mut raw: Vec<u8> = Vec::new();
5286 let put = |v: u32, raw: &mut Vec<u8>| {
5287 if depth == 10 {
5288 raw.extend_from_slice(&((v * 4) as u16).to_le_bytes());
5289 } else {
5290 raw.push(v as u8);
5291 }
5292 };
5293 // A screen source is a few flat colours in 16x16 tiles plus
5294 // 1-px text-like rows -- what makes libaom code palette blocks.
5295 const PAL: [u32; 8] = [16, 60, 110, 145, 180, 210, 235, 128];
5296 for f in 0..frames {
5297 for row in 0..h {
5298 for col in 0..w {
5299 let v = if screen {
5300 if row % 7 == 0 && col % 3 == 0 {
5301 if (col / 3 + row + f) % 2 == 1 { 16 } else { 235 }
5302 } else {
5303 PAL[((col + 4 * f) / 16 + row / 16) % PAL.len()]
5304 }
5305 } else {
5306 (((col + 2 * f) * 7 + row * 13) % 251) as u32
5307 };
5308 put(v, &mut raw);
5309 }
5310 }
5311 for plane in 0..2usize {
5312 for row in 0..h / 2 {
5313 for col in 0..w / 2 {
5314 let v = if screen {
5315 PAL[((col + 2 * f) / 8 + row / 8 + plane) % PAL.len()]
5316 } else if plane == 0 {
5317 (((col + f) * 11 + row * 5) % 251) as u32
5318 } else {
5319 ((col * 3 + (row + f) * 17) % 251) as u32
5320 };
5321 put(v, &mut raw);
5322 }
5323 }
5324 }
5325 }
5326 let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
5327 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
5328 let src = std::env::temp_dir()
5329 .join(format!("ec-av1-lossless2-{}-{w}x{h}-{depth}.yuv", std::process::id()));
5330 std::fs::write(&src, &raw).expect("raw source");
5331 let mut cmd = Command::new("ffmpeg");
5332 cmd.args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", pix])
5333 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
5334 .arg(&src)
5335 .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
5336 .args(["-pix_fmt", pix, "-cpu-used", "6", "-b:v", "0", "-crf", "0"]);
5337 if sb128 {
5338 cmd.args(["-aom-params", "sb-size=128"]);
5339 }
5340 if screen {
5341 cmd.args(["-aom-params", "tune-content=screen"]);
5342 }
5343 let out = cmd
5344 .args(["-f", "obu", "-"])
5345 .stdin(Stdio::null())
5346 .stdout(Stdio::piped())
5347 .stderr(Stdio::piped())
5348 .output()
5349 .expect("ffmpeg failed to run");
5350 let _ = std::fs::remove_file(&src);
5351 if !out.status.success() {
5352 eprintln!(
5353 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
5354 String::from_utf8_lossy(&out.stderr)
5355 );
5356 return;
5357 }
5358 let stream = out.stdout;
5359 // The stream must really be lossless AND really carry inter frames
5360 // (class `gate-blind-to-feature`).
5361 let mut parser = Av1Parser::new();
5362 let (mut pos, mut lossless, mut inters) = (0usize, 0usize, 0usize);
5363 while pos < stream.len() {
5364 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
5365 pos += obu.total_size.max(1);
5366 let header = match &obu.kind {
5367 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
5368 _ => continue,
5369 };
5370 if header.lossless.iter().all(|&l| l) {
5371 lossless += 1;
5372 }
5373 if header.frame_type == FrameType::Inter {
5374 inters += 1;
5375 }
5376 }
5377 assert!(lossless >= frames, "{NAME} [{tag}] went blind: {lossless} lossless frames");
5378 assert!(
5379 screen || inters > 0,
5380 "{NAME} [{tag}] went blind: no inter frame at gop {gop}"
5381 );
5382 let ours = decode_stream(&stream)
5383 .unwrap_or_else(|e| panic!("{NAME} [{tag}]: a lossless inter stream decodes: {e}"));
5384 let refs = if depth == 10 {
5385 ffmpeg_decode_sequence_10bit(&stream, w, h, frames)
5386 } else {
5387 ffmpeg_decode_sequence(&stream, w, h, frames)
5388 };
5389 assert_eq!(ours.len(), frames, "{NAME} [{tag}]: frame count");
5390 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
5391 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
5392 .iter()
5393 .enumerate()
5394 {
5395 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
5396 assert_eq!(bad, 0, "{NAME} [{tag}]: frame {i} plane {plane}: {bad} samples differ");
5397 }
5398 }
5399 }
5400 }
5401
5402 /// lane-lossless128: a LOSSLESS key frame that codes a 128-axis
5403 /// (`BLOCK_64X128`) intra block -- the shape libaom's `read_tx_size` forces
5404 /// to `TX_4X4` on its very first line (`decodeframe.c:1183`), so every plane
5405 /// of the block is a 4x4 transform unit and NO `tx_size_cat3` symbol is
5406 /// coded.
5407 ///
5408 /// On the merged base `decode_block_128rect` had no lossless carve-out: it
5409 /// read `logical_tx = 64` off `depth == 0`, handed `PlaneBuf::reconstruct`
5410 /// a 64x64 geometry with the 16-sample 4x4 residual
5411 /// [`TxParams::run`](crate::decode::TxParams) produced -- `index out of
5412 /// bounds: the len is 16 but the index is 16` at the reconstruction call,
5413 /// on EVERY conformant stream of this shape (a panic, never a refusal).
5414 ///
5415 /// `crates/ec-av1/fixtures/lossless_sb128_rect_kf.obu`, 3471 bytes, sha256
5416 /// `013b07979c8be999c70d47f32768c2bf959be086a893f60dde1b0f5e35d4f475`:
5417 /// `aomenc --codec=av1 --passes=1 --threads=1 --obu --lossless=1
5418 /// --cpu-used=0` over a 320x256, 4-frame source that is flat grey except a
5419 /// textured 64x128 patch in the top-right corner -- which is what makes the
5420 /// 128 root take `PARTITION_VERT` and code the `BLOCK_64X128` at mi(0,64).
5421 ///
5422 /// The counter delta keeps the gate non-vacuous: a stream that stopped
5423 /// coding the shape reads 0 and the gate fails instead of passing on a
5424 /// decode that never reached the fixed body (class
5425 /// `gate-blind-to-feature`).
5426 #[test]
5427 fn a_lossless_sb128_rect_intra_block_decodes_sample_exact() {
5428 const NAME: &str = "a_lossless_sb128_rect_intra_block_decodes_sample_exact";
5429 if !have_ffmpeg() {
5430 eprintln!("SKIP {NAME}: no ffmpeg");
5431 return;
5432 }
5433 let (w, h, frames) = (320usize, 256usize, 4usize);
5434 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5435 .join("fixtures/lossless_sb128_rect_kf.obu");
5436 let stream = std::fs::read(&path)
5437 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
5438 let before = crate::decode::intra128_lossless_hits();
5439 let ours = decode_stream(&stream)
5440 .unwrap_or_else(|e| panic!("{NAME}: a lossless 128-axis key frame decodes: {e}"));
5441 let hits = crate::decode::intra128_lossless_hits() - before;
5442 assert!(
5443 hits > 0,
5444 "{NAME}: this stream coded NO lossless 128-axis intra block -- the fixed body \
5445 was never reached (class gate-blind-to-feature)"
5446 );
5447 let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
5448 assert_eq!(ours.len(), frames, "{NAME}: decode-order frame count");
5449 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
5450 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
5451 .iter()
5452 .enumerate()
5453 {
5454 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
5455 assert_eq!(
5456 bad, 0,
5457 "{NAME}: frame {i} plane {plane}: {bad} samples differ from ffmpeg"
5458 );
5459 }
5460 }
5461 eprintln!("{NAME}: {frames} frames sample-exact, intra128_lossless hits {hits}");
5462 }
5463
5464 /// lane-av1-loss64: the generator for the two gates below -- a deterministic
5465 /// 1-frame lossless superblock-128 aomenc stream of `testsrc2`. `extra`
5466 /// flags land last (aomenc keeps the LAST occurrence of a repeated flag).
5467 /// The recipe is the one lanes/av1rect14.report.md section 2 measured
5468 /// (`--lossless=1 --sb-size=128 --enable-1to4-partitions=1`); the
5469 /// `--min-partition-size` override is what steers the bottom superblock
5470 /// row's RD into overhanging 64x64 `NONE` blocks (the shape the first fix
5471 /// clips) or, at 8, keeps sub-8x8 partitions out of the second gate's
5472 /// stream so the whole frame is decodable.
5473 fn lossless_sb128_testsrc2(width: usize, height: usize, extra: &[&str]) -> Vec<u8> {
5474 let mut ff = Command::new("ffmpeg");
5475 let out = ff
5476 .args(["-v", "error", "-f", "lavfi", "-i"])
5477 .arg(format!("testsrc2=s={width}x{height}:r=25"))
5478 .args(["-frames:v", "1", "-pix_fmt", "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-"])
5479 .stdin(Stdio::null())
5480 .stdout(Stdio::piped())
5481 .stderr(Stdio::piped())
5482 .output()
5483 .expect("ffmpeg failed to run");
5484 assert!(out.status.success(), "ffmpeg failed for testsrc2 {width}x{height}");
5485 let y4m = out.stdout;
5486 let out = run_with_stdin(Command::new(aomenc_path())
5487 .args(["--codec=av1", "--bit-depth=8", "--input-bit-depth=8"])
5488 .args([
5489 "--passes=1",
5490 "--cpu-used=0",
5491 "--lag-in-frames=0",
5492 "--kf-max-dist=1",
5493 "--limit=1",
5494 "--threads=1",
5495 "--tile-columns=0",
5496 "--lossless=1",
5497 "--sb-size=128",
5498 "--enable-1to4-partitions=1",
5499 ])
5500 .args(extra)
5501 .args(["--obu", "-o", "-", "-"]), &y4m);
5502 assert!(out.status.success(), "aomenc failed: {}", String::from_utf8_lossy(&out.stderr));
5503 out.stdout
5504 }
5505
5506 /// lane-av1-loss64: a lossless superblock-128 frame whose intra blocks
5507 /// overhang the bottom frame edge codes NO coefficient symbols for the
5508 /// chroma transform units whose 4x4 origin sits outside the frame's mi
5509 /// grid -- libaom `decode_reconstruct_tx` returns before any read
5510 /// (`decodeframe.c:299`, `blk_row >= max_blocks_high || blk_col >=
5511 /// max_blocks_wide`, the limits from `max_block_wide/high`,
5512 /// av1_common_int.h:1565). The square multi-transform-unit chroma loop in
5513 /// [`crate::decode`] carried no such clip (the luma loop had one) and read
5514 /// `txb_skip`+coefficients for the phantom units: on the measured stream
5515 /// the first lossless 64x64 `NONE` block, at mi(48,0), overhangs the
5516 /// 240-px frame by 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units,
5517 /// not eight -- 32 phantom unit reads per plane desynced the tile and
5518 /// every later symbol (including partition reads, which is what made
5519 /// aomdec's zero-`value=8/9` census look like a partition-reader defect
5520 /// in the rect14 review) decoded as garbage.
5521 ///
5522 /// Fail-pre-fix, measured on the ed12fe52 probe: both arms differ from
5523 /// ffmpeg at byte 41120 (luma row 128 col 160, the first block decoded
5524 /// after the phantom reads). The counter delta pins non-vacuity (class
5525 /// `gate-blind-to-feature`): 96 clipped units on each arm.
5526 #[test]
5527 fn a_lossless_sb128_square_frame_clips_overhanging_chroma_tus() {
5528 const NAME: &str = "a_lossless_sb128_square_frame_clips_overhanging_chroma_tus";
5529 if !have_ffmpeg() {
5530 eprintln!("SKIP {NAME}: no ffmpeg");
5531 return;
5532 }
5533 // Arm 0 is the rect14 report's `loss320` recipe verbatim; arm 1 is its
5534 // `lnone` companion (1:4 and rect partitions off) -- both coded the
5535 // overhanging 64x64 blocks and both desynced at byte 41120 pre-fix.
5536 let arms: [&[&str]; 2] = [
5537 &["--min-partition-size=4"],
5538 &["--min-partition-size=4", "--enable-1to4-partitions=0", "--enable-rect-partitions=0"],
5539 ];
5540 let mut clips_total = 0usize;
5541 for (arm, extra) in arms.iter().enumerate() {
5542 let stream = lossless_sb128_testsrc2(320, 240, extra);
5543 crate::decode::reset_loss64_hits();
5544 let ours = decode_stream(&stream)
5545 .unwrap_or_else(|e| panic!("{NAME}: arm {arm} decodes: {e}"));
5546 let clips = crate::decode::chroma_edge_tu_clip_hits();
5547 assert!(
5548 clips > 0,
5549 "{NAME}: arm {arm} clipped NO overhanging chroma transform unit -- \
5550 the fixed body was never reached (class gate-blind-to-feature)"
5551 );
5552 clips_total += clips;
5553 let refs = ffmpeg_decode_sequence(&stream, 320, 240, 1);
5554 assert_eq!(ours.len(), 1, "{NAME}: arm {arm} frame count");
5555 for (plane, (g, r)) in [(&ours[0].y, &refs[0].y), (&ours[0].u, &refs[0].u), (&ours[0].v, &refs[0].v)]
5556 .iter()
5557 .enumerate()
5558 {
5559 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
5560 assert_eq!(bad, 0, "{NAME}: arm {arm} plane {plane}: {bad} samples differ from ffmpeg");
5561 }
5562 }
5563 eprintln!("{NAME}: 2 arms full-frame exact, {clips_total} chroma units clipped");
5564 }
5565
5566 /// lane-av1-loss64: a SKIPPED intrabc rect strip on a lossless frame
5567 /// zeroes its whole entropy-band footprint (libaom
5568 /// `av1_reset_entropy_context`, `if (mbmi->skip_txfm)` decodeframe.c:1262 ->
5569 /// blockd.c:58) instead of leaving the previous occupant's luma bands
5570 /// standing. The skip arm of `decode_intrabc_owned_rect` never wrote the
5571 /// luma bands: the lossless `read_block_tx_size_rect` resolves the 4x4
5572 /// leaf list before it looks at `skip`, so the tail took the
5573 /// per-transform-unit record path (chroma only) with no per-unit luma
5574 /// writes ever run. The next block then read a STALE band: on the 320x242
5575 /// `--min-partition-size=4` sibling of this stream the skipped 8x16
5576 /// intrabc strip at mi(48,66) left a 7 in left[48] and mi(48,68)'s first
5577 /// transform unit read `txb_skip_ctx` 3 where aomdec reads 1 (measured
5578 /// `EC_ECDUMP` against the instrumented aomdec) -- a coefficient-walk
5579 /// desync at byte 61712 with every mode symbol still matching.
5580 ///
5581 /// This gate uses the same `--min-partition-size=4` arm that reaches the
5582 /// sub-8x8 VERT -> 4x8 skipped-intrabc leaf. Post-fix it is full-frame
5583 /// exact: the skip path uses libaom's clamped 4x4 chroma intrabc
5584 /// prediction (`decodeframe.c:1011-1065`, `reconinter_template.inc:186-207`)
5585 /// instead of the ordinary skipped-intra DC predictor. The old route first
5586 /// differed at U(104,92) with the entropy ladder fully synced.
5587 ///
5588 /// Fail-pre-fix, measured on the ed12fe52 probe: differs at byte 41120
5589 /// (the chroma-clip class, fixed in the same lane). Single-mutation on
5590 /// the lane tree with ONLY this gate's walk reverted: differs at byte
5591 /// 61712, the band-leak site.
5592 #[test]
5593 fn a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands() {
5594 const NAME: &str = "a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands";
5595 if !have_ffmpeg() {
5596 eprintln!("SKIP {NAME}: no ffmpeg");
5597 return;
5598 }
5599 let stream = lossless_sb128_testsrc2(320, 242, &["--min-partition-size=4"]);
5600 crate::decode::reset_loss64_hits();
5601 crate::decode::reset_skipped_intrabc_chroma_arm_hits();
5602 let ours = decode_stream(&stream)
5603 .unwrap_or_else(|e| panic!("{NAME}: decodes: {e}"));
5604 let resets = crate::decode::skip_lossless_band_reset_hits();
5605 let intrabc_skips = crate::decode::skipped_intrabc_chroma_arm_hits();
5606 assert!(
5607 resets > 0,
5608 "{NAME}: this stream coded NO skipped lossless intrabc rect strip -- \
5609 the fixed body was never reached (class gate-blind-to-feature)"
5610 );
5611 assert!(
5612 intrabc_skips > 0,
5613 "{NAME}: this stream coded NO skipped sub-8x8 intrabc chroma leaf -- \
5614 the clamped chroma prediction fix was never reached (class gate-blind-to-feature)"
5615 );
5616 let refs = ffmpeg_decode_sequence(&stream, 320, 242, 1);
5617 assert_eq!(ours.len(), 1, "{NAME}: frame count");
5618 for (plane, (g, r)) in [(&ours[0].y, &refs[0].y), (&ours[0].u, &refs[0].u), (&ours[0].v, &refs[0].v)]
5619 .iter()
5620 .enumerate()
5621 {
5622 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
5623 assert_eq!(bad, 0, "{NAME}: plane {plane}: {bad} samples differ from ffmpeg");
5624 }
5625 eprintln!(
5626 "{NAME}: full-frame exact, {resets} band resets, \
5627 {intrabc_skips} skipped intrabc chroma predictions"
5628 );
5629 }
5630
5631 /// lane-dkey: the palette-neighbour-band gate. A palette-Y block's size and
5632 /// colours used to stay standing in the mi-granular above/left bands after a
5633 /// sub-8x8 group was decoded next to it -- the sub-8x8 readers published
5634 /// skip/lf/mode state but no palette state, while libaom's mi grid carries
5635 /// `palette_size == 0` in exactly those cells (`av1_allow_palette` needs
5636 /// BLOCK_8X8 and up). The next intra block then read `palette_y_mode` off
5637 /// CDF row 1 where libaom reads row 0 (class `cdf-row-held-constant`),
5638 /// decoded a palette libaom never coded, and skipped the `use_filter_intra`
5639 /// symbol a palette block has none of: one symbol short, tile desynced.
5640 ///
5641 /// Measured on the instrumented aomdec at KEY-frame block mi(76,88) of this
5642 /// very stream (`EC_PALSYN_AOM ... ctx=0 y=0` against our `mode_ctx=1`).
5643 /// Without the fix every one of the 12 frames differs from ffmpeg's decode
5644 /// from luma sample 491904 on.
5645 ///
5646 /// The source is SYNTHETIC (no film sample lives in `fixtures`): the dark,
5647 /// near-flat background libaom's own screen-content detector counts as
5648 /// screen content (2..=4 distinct luma values per 16x16 block), which is
5649 /// what turns palette on, plus one textured patch at a HALF-PEL position on
5650 /// half the frames so the encoder splits that region down to 4x4 groups
5651 /// beside its palette blocks.
5652 #[test]
5653 fn a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact() {
5654 const NAME: &str =
5655 "a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact";
5656 if !have_ffmpeg() {
5657 eprintln!("SKIP {NAME}: no ffmpeg");
5658 return;
5659 }
5660 let (w, h, frames) = (1920usize, 1024usize, 12usize);
5661 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
5662 for f in 0..frames {
5663 let mut y = vec![0u8; w * h];
5664 for row in 0..h {
5665 for col in 0..w {
5666 y[row * w + col] =
5667 16 + ((col / 32 + row / 32) % 5) as u8 + ((col / 4 + row / 4) % 3) as u8;
5668 }
5669 }
5670 // 2.5 px per pair of frames: integer on one pair, half a pixel off
5671 // on the next (linear interpolation), so the patch's edges land
5672 // mid-sample and the encoder splits there.
5673 let x0 = 200.0 + 2.5 * (f / 2) as f64;
5674 let (fx, ix) = (x0.fract(), x0.floor() as usize);
5675 for row in 300..428 {
5676 for col in 0..192 {
5677 let tex = |u: f64| -> f64 {
5678 let v = (row - 300) as f64;
5679 30.0 + 100.0 * (0.5 + 0.5 * ((u * 0.35).sin() * (v * 0.21).cos()))
5680 };
5681 let s = tex(col as f64) * (1.0 - fx) + tex(col as f64 - 1.0) * fx;
5682 y[row * w + ix + col] = s.round().clamp(0.0, 255.0) as u8;
5683 }
5684 }
5685 raw.extend_from_slice(&y);
5686 raw.extend(std::iter::repeat_n(128u8, w * h / 2));
5687 }
5688 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
5689 let src = std::env::temp_dir().join(format!("ec-av1-palsub8-{}.yuv", std::process::id()));
5690 std::fs::write(&src, &raw).expect("raw source");
5691 let out = Command::new("ffmpeg")
5692 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
5693 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
5694 .arg(&src)
5695 .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"])
5696 .args(["-cpu-used", "6", "-b:v", "0", "-crf", "35", "-f", "obu", "-"])
5697 .stdin(Stdio::null())
5698 .stdout(Stdio::piped())
5699 .stderr(Stdio::piped())
5700 .output()
5701 .expect("ffmpeg failed to run");
5702 let _ = std::fs::remove_file(&src);
5703 if !out.status.success() {
5704 eprintln!(
5705 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
5706 String::from_utf8_lossy(&out.stderr)
5707 );
5708 return;
5709 }
5710 let stream = out.stdout;
5711 let ours = decode_stream(&stream).expect("libaom screen-content stream decodes");
5712 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
5713 assert_eq!(ours.len(), frames, "{NAME}: shown frame count");
5714 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
5715 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
5716 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
5717 assert!(
5718 first.is_none(),
5719 "{NAME}: frame {i} plane {plane} differs from ffmpeg at sample {}",
5720 first.unwrap()
5721 );
5722 }
5723 }
5724 }
5725
5726 /// Hardened past the report-only test above: a real libaom-av1 gradients
5727 /// stream, pinned deterministic (`gradients`' own `seed=`, plus
5728 /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search
5729 /// cannot pick a different mode set run to run) and with CDEF turned off
5730 /// (this decoder's tile path never applies that in-loop filter -- see
5731 /// `cdef_is_active` in `decode_stream` -- so a stream that leaves it on
5732 /// decodes-but-wrong instead of refusing at cdef_bits==0; ffmpeg's
5733 /// `-enable-cdef 0` keeps this fixture out of that gap rather than this
5734 /// test working around it). Asserts pixel-exact against ffmpeg's own
5735 /// decode of the identical bytes, not just "decoded without error".
5736 #[test]
5737 fn a_real_libaom_gradients_stream_decodes_pixel_exact() {
5738 if !have_ffmpeg() {
5739 eprintln!("SKIP a_real_libaom_gradients_stream_decodes_pixel_exact: no ffmpeg");
5740 return;
5741 }
5742 let (width, height) = (64, 64);
5743 let stream = libaom_encode_with(
5744 &gradients_source(42, width, height, "rate=1"),
5745 width,
5746 height,
5747 15,
5748 &[
5749 "-threads",
5750 "1",
5751 "-row-mt",
5752 "0",
5753 "-tile-columns",
5754 "0",
5755 "-tile-rows",
5756 "0",
5757 "-enable-cdef",
5758 "0",
5759 ],
5760 )
5761 .expect("ffmpeg encode");
5762 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
5763 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
5764 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
5765 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
5766 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
5767 }
5768
5769 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but at
5770 /// 32x32 (below `is_cfl_allowed`'s 32x32 luma bound as a *single*
5771 /// undivided block, spec 5.11.5) rather than 64x64 -- a whole 64x64 SB
5772 /// is never CFL-eligible itself, only its <=32x32 partitions, and
5773 /// `testsrc2`/`gradients` at 64x64 with rect/ab/1to4/angle-delta search
5774 /// disabled reliably pick a whole-SB `PARTITION_NONE` (probed
5775 /// lane-av1real r2), so no fixture at that size exercises CfL at all.
5776 /// A 32x32 frame is exactly the whole-block, CFL-allowed case, and
5777 /// lane-av1real r2 found `gradients` there reliably selects
5778 /// `UV_CFL_PRED` (`uv_mode=13`) across a crf sweep -- `testsrc2` there
5779 /// stays DC. Proves the CfL port this round added, not just DC-chroma
5780 /// decode: pixel-exact against ffmpeg's own decode, not just "decoded".
5781 ///
5782 #[test]
5783 fn a_real_libaom_cfl_stream_decodes_pixel_exact() {
5784 if !have_ffmpeg() {
5785 eprintln!("SKIP a_real_libaom_cfl_stream_decodes_pixel_exact: no ffmpeg");
5786 return;
5787 }
5788 let (width, height) = (32, 32);
5789 let stream = libaom_encode_with(
5790 &gradients_source(42, width, height, "rate=1"),
5791 width,
5792 height,
5793 15,
5794 &[
5795 "-threads",
5796 "1",
5797 "-row-mt",
5798 "0",
5799 "-tile-columns",
5800 "0",
5801 "-tile-rows",
5802 "0",
5803 "-enable-cdef",
5804 "0",
5805 ],
5806 )
5807 .expect("ffmpeg encode");
5808 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
5809 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
5810 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
5811 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
5812 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
5813 }
5814
5815 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves
5816 /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
5817 /// proves `apply_cdef` itself, not just that this decoder still works
5818 /// when the filter never fires. Gradient content at a low crf reliably
5819 /// gives libaom something to dering. If a run happens to land on
5820 /// `cdef_bits > 0` (per-64x64 `cdef_idx`, still unimplemented -- see the
5821 /// refusal in `decode_stream`) the stream is skipped rather than failed:
5822 /// that gap is named by the refusal's own error text, not silently
5823 /// swallowed here.
5824 #[test]
5825 fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
5826 if !have_ffmpeg() {
5827 eprintln!(
5828 "SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: no ffmpeg"
5829 );
5830 return;
5831 }
5832 let (width, height) = (64, 64);
5833 let stream = libaom_encode_with(
5834 &gradients_source(42, width, height, "rate=1"),
5835 width,
5836 height,
5837 30,
5838 &[
5839 "-threads",
5840 "1",
5841 "-row-mt",
5842 "0",
5843 "-tile-columns",
5844 "0",
5845 "-tile-rows",
5846 "0",
5847 ],
5848 )
5849 .expect("ffmpeg encode");
5850 match decode_stream(&stream) {
5851 Ok(frames) => {
5852 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
5853 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (CDEF on)");
5854 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (CDEF on)");
5855 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (CDEF on)");
5856 }
5857 Err(e) => {
5858 eprintln!("SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: {e}");
5859 }
5860 }
5861 }
5862
5863 /// Path to a real `aomenc` build carrying the reference options this
5864 /// fixture needs (`--max-partition-size`, `--enable-tx-size-search`,
5865 /// `--loopfilter-control`) -- this box's `ffmpeg` links a libaom too old
5866 /// to expose `enable-tx-size-search`/`loopfilter-control` through its
5867 /// own `-aom-params` passthrough (probed live: "Cannot find aom
5868 /// option"), so [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]
5869 /// shells out to the standalone binary instead of ffmpeg's libaom-av1
5870 /// wrapper every other test here uses. `EC_AV1_AOMENC` overrides the
5871 /// default dev-build path; the test skips (not fails) when neither this
5872 /// nor `ffmpeg` is present.
5873 fn aomenc_path() -> std::path::PathBuf {
5874 if let Some(p) = std::env::var_os("EC_AV1_AOMENC") {
5875 return std::path::PathBuf::from(p);
5876 }
5877 // The oracle used to live only under `/tmp`, which this box's tmpfs
5878 // guard reclaims -- when it did, all 20 aomenc gates below went
5879 // silently vacuous (SKIP, suite still green). The durable location
5880 // is provisioned by `scripts/build-aom-oracle.sh`; the `/tmp` path
5881 // stays last as a legacy fallback.
5882 let mut candidates = Vec::new();
5883 if let Some(home) = std::env::var_os("HOME") {
5884 candidates.push(std::path::PathBuf::from(&home).join(".cache/aom-oracle/build/aomenc"));
5885 }
5886 candidates.push("/tmp/libaom-src/build/encoder/aomenc".into());
5887 candidates
5888 .iter()
5889 .find(|p| p.is_file())
5890 .cloned()
5891 .unwrap_or_else(|| candidates.remove(0))
5892 }
5893
5894 /// Whether the aomenc oracle is present. Absence normally SKIPs (a
5895 /// checkout without the oracle should still run the rest of the suite),
5896 /// but `EC_AV1_REQUIRE_AOMENC=1` turns it into a hard failure so a batch
5897 /// run cannot report green off 20 skipped gates.
5898 /// Where a pinned stream lives. `fixtures/` is a symlink to a durable
5899 /// directory outside the repo, so a pin captured in one session is still
5900 /// there in the next; a session scratchpad is not (tmpfs reaps it, and
5901 /// four pins were silently dead because of that).
5902 fn pin_dir() -> std::path::PathBuf {
5903 if let Some(p) = std::env::var_os("EC_AV1_PIN_DIR") {
5904 return std::path::PathBuf::from(p);
5905 }
5906 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
5907 .join("../../fixtures")
5908 .canonicalize()
5909 .unwrap_or_else(|_| std::path::PathBuf::from("fixtures"))
5910 }
5911
5912 fn have_aomenc() -> bool {
5913 let present = aomenc_path().is_file();
5914 assert!(
5915 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
5916 "EC_AV1_REQUIRE_AOMENC is set but no aomenc at {} -- run scripts/build-aom-oracle.sh",
5917 aomenc_path().display()
5918 );
5919 present
5920 }
5921
5922 /// The instrumented `aomdec` beside the `aomenc` oracle
5923 /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`).
5924 fn aomdec_path() -> std::path::PathBuf {
5925 if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") {
5926 return std::path::PathBuf::from(p);
5927 }
5928 aomenc_path().with_file_name("aomdec")
5929 }
5930
5931 /// Decodes `stream` with both this decoder and the instrumented oracle
5932 /// `aomdec`, and compares EVERY decoded frame in DECODE order --
5933 /// including the hidden (`show_frame == 0`) alt-ref frames no other gate
5934 /// in this repo can see, because `decode_stream` only pushes shown
5935 /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames
5936 /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces
5937 /// only as drift on some later shown frame, if at all).
5938 ///
5939 /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it
5940 /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in
5941 /// `decode_stream`, the oracle's in rung 12 of
5942 /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as
5943 /// u16 LE. Returns `(frames_decoded, hidden_frames)`.
5944 fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) {
5945 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
5946 let _ = std::fs::remove_dir_all(&dir);
5947 std::fs::create_dir_all(&dir).expect("scratch dir");
5948 let obu = dir.join("in.obu");
5949 std::fs::write(&obu, stream).expect("writing the stream");
5950 let aom_prefix = dir.join("aom");
5951 let out = Command::new(aomdec_path())
5952 .args(["--codec=av1", "-o"])
5953 .arg(dir.join("out.y4m"))
5954 .arg(&obu)
5955 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
5956 .stdin(Stdio::null())
5957 .stdout(Stdio::piped())
5958 .stderr(Stdio::piped())
5959 .output()
5960 .expect("aomdec failed to run");
5961 assert!(
5962 out.status.success(),
5963 "{name}: the oracle aomdec refused the stream: {}",
5964 String::from_utf8_lossy(&out.stderr)
5965 );
5966 let count_dumps = |prefix: &std::path::Path| -> usize {
5967 let mut n = 0usize;
5968 while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() {
5969 n += 1;
5970 }
5971 n
5972 };
5973 let oracle_frames = count_dumps(&aom_prefix);
5974 assert!(
5975 oracle_frames > 0,
5976 "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \
5977 scripts/instrument-aom-oracle.sh is missing from {}",
5978 aomdec_path().display()
5979 );
5980 let ours_prefix = dir.join("ours");
5981 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
5982 let decoded = decode_stream(stream);
5983 set_final_dump_prefix(None);
5984 let shown = decoded
5985 .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}"))
5986 .len();
5987 let our_frames = count_dumps(&ours_prefix);
5988 assert_eq!(
5989 our_frames, oracle_frames,
5990 "{name}: decoded {our_frames} frames in decode order, the oracle decoded \
5991 {oracle_frames}"
5992 );
5993 for i in 0..oracle_frames {
5994 let want =
5995 std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
5996 let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
5997 assert_eq!(
5998 got.len(),
5999 want.len(),
6000 "{name}: decode-order frame {i} is {} bytes, the oracle's is {}",
6001 got.len(),
6002 want.len()
6003 );
6004 if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) {
6005 let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count();
6006 panic!(
6007 "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \
6008 hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \
6009 bytes differ -- stream pinned at {}",
6010 oracle_frames - shown,
6011 got[at],
6012 want[at],
6013 obu.display()
6014 );
6015 }
6016 }
6017 let hidden = oracle_frames - shown;
6018 let _ = std::fs::remove_dir_all(&dir);
6019 (oracle_frames, hidden)
6020 }
6021
6022 /// lane-hidden r2: the `--arnr-maxframes=0` SECOND ARM of an existing
6023 /// gate -- the gate's own recipe is never changed, this re-encodes the
6024 /// same fixture with libaom's temporal alt-ref filter switched off and
6025 /// runs [`decode_all_frames_vs_oracle`] on the result. Measured: with
6026 /// the filter at its default EVERY alt-ref recipe in this file emits
6027 /// ZERO hidden frames (the candidates are filtered away), so the
6028 /// hidden-frame compare on the gate's own stream is vacuous; this arm
6029 /// is what actually puts `show_frame == 0` frames on the wire.
6030 ///
6031 /// Runs at most once per gate name per process (the loop gates sweep
6032 /// dozens of attempts and each arm costs a full encode + two decodes).
6033 /// A stream this decoder refuses BY NAME skips the arm -- the arm is
6034 /// about hidden frames, not about that capability gap -- while a pixel
6035 /// mismatch is a hard failure raised inside the compare.
6036 fn hidden_arnr_arm(name: &str, y4m: &[u8], args: &[&str]) -> Option<(usize, usize)> {
6037 static ARMED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
6038 std::sync::OnceLock::new();
6039 if !ARMED
6040 .get_or_init(Default::default)
6041 .lock()
6042 .unwrap()
6043 .insert(name.to_string())
6044 {
6045 return None;
6046 }
6047 let mut arm: Vec<&str> = vec!["--arnr-maxframes=0"];
6048 arm.extend_from_slice(args);
6049 let out = run_with_stdin(Command::new(aomenc_path())
6050 .args(&arm), &y4m);
6051 assert!(
6052 out.status.success(),
6053 "{name} HIDDEN-ARM: aomenc refused its own recipe plus --arnr-maxframes=0: {}",
6054 String::from_utf8_lossy(&out.stderr)
6055 );
6056 let stream = out.stdout;
6057 match decode_stream(&stream) {
6058 Err(e) => {
6059 let msg = e.to_string();
6060 assert!(
6061 msg.contains("unsupported"),
6062 "{name} HIDDEN-ARM failed outright: {msg}"
6063 );
6064 eprintln!("{name} HIDDEN-ARM: skipped on a named refusal: {msg}");
6065 None
6066 }
6067 Ok(_) => Some(decode_all_frames_vs_oracle(&stream, &format!("{name}-arnr0"))),
6068 }
6069 }
6070
6071
6072 /// The repo's first hidden-frame pixel gate. Every other aomenc gate
6073 /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and
6074 /// both sides emit SHOWN frames only -- so an alt-ref frame that is
6075 /// decoded, stored into a reference slot and never displayed was, until
6076 /// this gate, never compared to anything (class
6077 /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the
6078 /// default `--lag-in-frames`, so they are full of exactly these frames.
6079 ///
6080 /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc
6081 /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's
6082 /// temporal filter on, this fixture's alt-ref candidates get filtered
6083 /// away and the encoder emits ZERO hidden frames (measured: 0 hidden
6084 /// with the filter on, 3 with it off), which would have made the gate
6085 /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so
6086 /// a recipe that stops producing hidden frames fails rather than skips.
6087 #[test]
6088 fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() {
6089 const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact";
6090 let _gate_lock = lock_gate_counters();
6091 if !have_ffmpeg() {
6092 eprintln!("SKIP {NAME}: no ffmpeg");
6093 return;
6094 }
6095 if !have_aomenc() {
6096 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6097 return;
6098 }
6099 for bit_depth in [8u32, 10u32] {
6100 let (width, height, frames) = (64usize, 64usize, 40usize);
6101 let duration = frames as f64 / 25.0;
6102 let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25");
6103 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
6104 let y4m = Command::new("ffmpeg")
6105 .args([
6106 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
6107 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
6108 ])
6109 .stdin(Stdio::null())
6110 .stdout(Stdio::piped())
6111 .stderr(Stdio::piped())
6112 .output()
6113 .expect("ffmpeg failed to run");
6114 assert!(
6115 y4m.status.success(),
6116 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
6117 String::from_utf8_lossy(&y4m.stderr)
6118 );
6119 let depth_arg = format!("--bit-depth={bit_depth}");
6120 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
6121 let out = run_with_stdin(Command::new(aomenc_path())
6122 .args([
6123 // lane-defon r1: the repo's only gate that decodes hidden
6124 // frames is also the only place a FORWARD KEYFRAME can be
6125 // proven -- a KEY frame with `show_frame == 0`, which is
6126 // exactly the shape this gate already compares in decode
6127 // order. On-values go before the base list (aomenc keeps
6128 // the FIRST occurrence of a repeated flag).
6129 "--enable-fwd-kf=1",
6130 "--fwd-kf-dist=8",
6131 "--codec=av1",
6132 "--passes=1",
6133 "--end-usage=q",
6134 "--cq-level=45",
6135 "--cpu-used=0",
6136 "--threads=1",
6137 "--row-mt=0",
6138 "--kf-max-dist=1000",
6139 "--enable-order-hint=1",
6140 "--auto-alt-ref=1",
6141 "--lag-in-frames=25",
6142 "--arnr-maxframes=0",
6143 &depth_arg,
6144 &input_depth_arg,
6145 // The same tool set every sibling inter gate pins -- the
6146 // open capability gaps (rect/AB partitions, warped/OBMC,
6147 // masked compound, palette, ...) are other lanes' work;
6148 // this gate is about hidden frames, not about them.
6149 "--enable-warped-motion=0",
6150 // OBMC stays off HERE (this gate is about hidden frames);
6151 // the tool's own coverage is the `obmc*` gates and, on a
6152 // 16x8/8x16 leaf, the `--enable-obmc=1` arm of
6153 // `..._with_a_16_level_rect_leaf_...` (lane-inter4 r4).
6154 "--enable-obmc=0",
6155 "--enable-masked-comp=0",
6156 "--enable-interintra-comp=0",
6157 "--enable-onesided-comp=0",
6158 "--enable-interintra-wedge=0",
6159 "--enable-smooth-interintra=0",
6160 "--enable-rect-partitions=0",
6161 "--enable-ab-partitions=0",
6162 "--enable-1to4-partitions=0",
6163 "--enable-filter-intra=0",
6164 "--enable-smooth-intra=0",
6165 "--enable-paeth-intra=0",
6166 "--enable-directional-intra=0",
6167 "--enable-angle-delta=0",
6168 "--enable-tx-size-search=0",
6169 "--enable-cdef=0",
6170 "--enable-restoration=0",
6171 "--max-partition-size=32",
6172 "--min-partition-size=32",
6173 "--enable-palette=0",
6174 "--enable-intrabc=0",
6175 "--enable-cfl-intra=0",
6176 "--enable-ref-frame-mvs=0",
6177 "--obu",
6178 "-o",
6179 "-",
6180 "-",
6181 ]), &y4m.stdout);
6182 assert!(
6183 out.status.success(),
6184 "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}",
6185 String::from_utf8_lossy(&out.stderr)
6186 );
6187 let stream = out.stdout;
6188 let fwd_kf_before = crate::decode::fwd_kf_hits();
6189 let (total, hidden) =
6190 decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit"));
6191 let fwd_kf = crate::decode::fwd_kf_hits() - fwd_kf_before;
6192 assert!(
6193 hidden >= 2,
6194 "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \
6195 {total} decoded -- the gate would be vacuous (class \
6196 gate-blind-to-hidden-frames)"
6197 );
6198 // lane-defon r1: `--enable-fwd-kf=1` is spelled on this recipe, so
6199 // a KEY frame with `show_frame == 0` must actually have been
6200 // decoded -- otherwise the on-value proves nothing.
6201 assert!(
6202 fwd_kf > 0,
6203 "{NAME}: the {bit_depth}-bit recipe decoded {total} frames ({hidden} hidden) but \
6204 zero forward keyframes -- --enable-fwd-kf=1 --fwd-kf-dist=8 never reached the \
6205 bitstream"
6206 );
6207 eprintln!(
6208 "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, {fwd_kf} \
6209 forward keyframes, all pixel-exact vs the oracle in decode order"
6210 );
6211 }
6212 }
6213
6214 /// A real `aomenc` filter-intra fixture: every other intra mode disabled
6215 /// (smooth/paeth/directional/angle-delta) and
6216 /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s
6217 /// <=32x32 bound means `use_filter_intra` never reads at all, spec
6218 /// 5.11.14), so the only way this frame codes is `DC_PRED` with filter
6219 /// intra on top -- `--loopfilter-control=0` is required too: this
6220 /// decoder has no in-loop deblocking filter at all, and libaom's default
6221 /// (on) smooths every block-boundary column, which first looked like a
6222 /// filter-intra math bug (mismatches straddling the 32-pixel block
6223 /// seam) until the recipe without it round-tripped byte-exact. Checks
6224 /// [`decode::filter_intra_hits`] actually moved (a process-global
6225 /// counter, so before/after rather than an absolute value) to prove the
6226 /// symbol fired, then pixel-exactness against ffmpeg's own decode of the
6227 /// identical bytes on every plane.
6228 #[test]
6229 fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {
6230 if !have_ffmpeg() {
6231 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no ffmpeg");
6232 return;
6233 }
6234 if !have_aomenc() {
6235 eprintln!(
6236 "SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no aomenc at {}",
6237 aomenc_path().display()
6238 );
6239 return;
6240 }
6241 let (width, height) = (64usize, 64usize);
6242 // Recipe-search hooks: with the encoder pinned to one thread the
6243 // stream is a deterministic function of (seed, cq), so a firing recipe
6244 // can be searched for without a rebuild.
6245 let fi_seed: u32 = std::env::var("EC_FI_SEED")
6246 .ok()
6247 .and_then(|v| v.parse().ok())
6248 .unwrap_or(42);
6249 let fi_source = gradients_source(fi_seed, 64, 64, "duration=0.04:rate=25");
6250 let fi_cq = std::env::var("EC_FI_CQ").unwrap_or_else(|_| "40".to_string());
6251 let fi_cq_arg = format!("--cq-level={fi_cq}");
6252 let y4m = Command::new("ffmpeg")
6253 .args([
6254 "-v",
6255 "error",
6256 "-f",
6257 "lavfi",
6258 "-i",
6259 &fi_source,
6260 "-pix_fmt",
6261 "yuv420p",
6262 "-f",
6263 "yuv4mpegpipe",
6264 "-",
6265 ])
6266 .stdin(Stdio::null())
6267 .stdout(Stdio::piped())
6268 .stderr(Stdio::piped())
6269 .output()
6270 .expect("ffmpeg failed to run");
6271 assert!(
6272 y4m.status.success(),
6273 "ffmpeg refused to generate the y4m fixture: {}",
6274 String::from_utf8_lossy(&y4m.stderr)
6275 );
6276 let out = run_with_stdin(Command::new(aomenc_path())
6277 .args([
6278 "--codec=av1",
6279 "--passes=1",
6280 "--end-usage=q",
6281 &fi_cq_arg,
6282 "--cpu-used=0",
6283 // Every sibling gate pins these; this one did not, and a
6284 // multi-threaded aomenc is not deterministic, so each run
6285 // encoded a slightly different stream and the gate flaked
6286 // against whichever features that run happened to pick.
6287 // Pinning them makes seed 42 mean one stream (class
6288 // `parallel-flake-is-attempt-selection`).
6289 "--threads=1",
6290 "--row-mt=0",
6291 "--enable-filter-intra=1",
6292 "--enable-smooth-intra=0",
6293 "--enable-paeth-intra=0",
6294 "--enable-directional-intra=0",
6295 "--enable-angle-delta=0",
6296 "--enable-tx-size-search=0",
6297 "--enable-cdef=0",
6298 "--max-partition-size=32",
6299 "--loopfilter-control=0",
6300 "--enable-palette=0",
6301 "--enable-intrabc=0",
6302 "--obu",
6303 "-o",
6304 "-",
6305 "-",
6306 ]), &y4m.stdout);
6307 assert!(
6308 out.status.success(),
6309 "aomenc refused the fixture: {}",
6310 String::from_utf8_lossy(&out.stderr)
6311 );
6312 let stream = out.stdout;
6313 let before = decode::filter_intra_hits();
6314 // `screen_content_tools_determination` (libaom encoder_utils.c) is a
6315 // real internal trial-encode/PSNR comparison, not a flag this CLI
6316 // exposes a knob for -- on this flat gradient fixture it lands on
6317 // `allow_screen_content_tools=0` most runs but occasionally trips
6318 // over its 0.9 dB threshold the other way even with palette/intrabc
6319 // both disabled. That is a genuine separate gap (`decode_stream`
6320 // never reads `intrabc`/`palette_mode_info`), not a filter-intra
6321 // regression, so it is skipped here exactly as
6322 // `a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact`
6323 // above skips its own still-unsupported-gap runs.
6324 let frames = match decode_stream(&stream) {
6325 Ok(frames) => frames,
6326 Err(e) => {
6327 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: {e}");
6328 return;
6329 }
6330 };
6331 assert!(
6332 decode::filter_intra_hits() > before,
6333 "use_filter_intra never fired decoding this stream"
6334 );
6335 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
6336 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
6337 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
6338 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
6339 }
6340
6341 /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`
6342 /// (SMPTE colour bars -- a handful of large flat luma regions, exactly
6343 /// the "flat, few-colour, repetitive" content `av1_choose_palette_map`'s
6344 /// RD trial rewards) with `hue=s=0` to flatten chroma to one constant
6345 /// value, so `DC_PRED` already nails every chroma block with zero
6346 /// residual and the encoder's own RD never has a reason to spend bits on
6347 /// a *UV* palette too (a real symbol this decoder still refuses --
6348 /// lane-palette r3's own scope is Y only). `smptebars` has no seed to
6349 /// vary, so the fixture is deterministic by construction; hashed twice
6350 /// below to prove it rather than assert it. `--enable-rect-partitions=0`
6351 /// / `-ab-` / `-1to4-` keep every intra block square, sidestepping the
6352 /// rect-strip screen-content refusal at `read_intra_mode_rect`
6353 /// (decode.rs ~2226) -- that refusal is this lane's own next milestone,
6354 /// not this gate's. `--sb-size=64` and `--threads=1 --row-mt=0` are the
6355 /// sibling-lane facts this charter paid for: a single 64x64 frame is one
6356 /// superblock either way, but pinning them keeps the recipe identical to
6357 /// every other gate in this file. HARD-asserts
6358 /// [`decode::palette_hits`] moved -- a stream that never reads a real
6359 /// palette block would refuse (or not) by construction without proving
6360 /// this milestone at all.
6361 ///
6362 /// lane-palette r4/r6/r7: r3/r4 found that this fixture's reconstructed
6363 /// pixels did not match ffmpeg's decode of the same bytes even though
6364 /// every symbol read by `decode_color_index_map` checked line-for-line
6365 /// against the oracle and matched. r6's range trace (`compare-range-not-tell`)
6366 /// pinned the real cause: `decode_color_index_map` was called from the
6367 /// wrong syntax position -- inline right after the Y colours, instead of
6368 /// after the whole mode-info read (UV palette mode_info + `filter_intra`,
6369 /// `av1_visit_palette`'s real call order). r7 ported the UV palette
6370 /// mode_info read and moved the colour-index-map decode after
6371 /// `filter_intra`; this gate now asserts a real pixel match instead of
6372 /// the old named refusal.
6373 #[test]
6374 fn a_real_aomenc_stream_with_palette_y_decodes_pixel_exact() {
6375 const NAME: &str = "a_real_aomenc_stream_with_palette_y_decodes_pixel_exact";
6376 if !have_ffmpeg() {
6377 eprintln!("SKIP {NAME}: no ffmpeg");
6378 return;
6379 }
6380 if !have_aomenc() {
6381 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6382 return;
6383 }
6384 let source = "smptebars=size=64x64:rate=25";
6385 fn render(source: &str) -> Vec<u8> {
6386 Command::new("ffmpeg")
6387 .args([
6388 "-v",
6389 "error",
6390 "-f",
6391 "lavfi",
6392 "-i",
6393 source,
6394 "-vf",
6395 "hue=s=0",
6396 "-pix_fmt",
6397 "yuv420p",
6398 "-t",
6399 "0.04",
6400 "-f",
6401 "yuv4mpegpipe",
6402 "-",
6403 ])
6404 .stdin(Stdio::null())
6405 .stdout(Stdio::piped())
6406 .stderr(Stdio::piped())
6407 .output()
6408 .expect("ffmpeg failed to run")
6409 .stdout
6410 }
6411 let y4m_a = render(source);
6412 let y4m_b = render(source);
6413 assert_eq!(
6414 y4m_a, y4m_b,
6415 "smptebars must render byte-identical across two runs"
6416 );
6417 let y4m = y4m_a;
6418 let out = run_with_stdin(Command::new(aomenc_path())
6419 .args([
6420 "--codec=av1",
6421 "--passes=1",
6422 "--end-usage=q",
6423 "--cq-level=30",
6424 "--cpu-used=0",
6425 "--threads=1",
6426 "--row-mt=0",
6427 "--sb-size=64",
6428 "--tune-content=screen",
6429 "--enable-palette=1",
6430 "--enable-intrabc=0",
6431 "--enable-rect-partitions=0",
6432 "--enable-ab-partitions=0",
6433 "--enable-1to4-partitions=0",
6434 "--min-partition-size=32",
6435 "--max-partition-size=32",
6436 "--enable-filter-intra=0",
6437 "--enable-smooth-intra=0",
6438 "--enable-paeth-intra=0",
6439 "--enable-directional-intra=0",
6440 "--enable-angle-delta=0",
6441 "--enable-cfl-intra=0",
6442 "--enable-cdef=0",
6443 "--enable-restoration=0",
6444 "--enable-tx-size-search=0",
6445 "--loopfilter-control=0",
6446 "--obu",
6447 "-o",
6448 "-",
6449 "-",
6450 ]), &y4m);
6451 assert!(
6452 out.status.success(),
6453 "aomenc refused the fixture: {}",
6454 String::from_utf8_lossy(&out.stderr)
6455 );
6456 let stream = out.stdout;
6457 let before = decode::palette_hits();
6458 let frames = match decode_stream(&stream) {
6459 Ok(frames) => frames,
6460 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
6461 };
6462 assert!(
6463 decode::palette_hits() > before,
6464 "palette_y_mode never fired decoding this stream -- gate is vacuous"
6465 );
6466 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1);
6467 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
6468 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
6469 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
6470 }
6471
6472 /// lane-kf900 r3: the palette colour reader at BOTH bit depths.
6473 ///
6474 /// `read_palette_colors_y`/`_uv` (decode.rs, mirroring `decodemv.c:478`
6475 /// and `:509`) size every raw literal they read by the sequence's
6476 /// `bit_depth`: the first colour is `bit_depth` bits, `min_bits` is
6477 /// `bit_depth - 3` (Y/U) or `bit_depth - 4` (V), `range` starts at
6478 /// `1 << bit_depth`, and the clamp/wrap bound is `(1 << bit_depth) - 1`.
6479 /// Ours hardcoded 8, so every 10-bit palette block read TWO BITS TOO FEW
6480 /// per transmitted colour and silently decoded the rest of the tile from
6481 /// the wrong bit position.
6482 ///
6483 /// It was silent because raw literals are EQUIPROBABLE: at the ranges
6484 /// this content reaches an equiprobable read maps the msac range onto
6485 /// itself (62728 -> 31364 -> renormalised 62728), so a cross-decoder
6486 /// RANGE ladder stays bit-identical straight through the miscount and
6487 /// only the decoded VALUE moves. Pinned on a 256x192 10-bit
6488 /// `--cq-level=59` stream whose first block is a 32x16 palette: aomdec's
6489 /// `EC_PAL` ladder and ours agreed on every range and disagreed on the
6490 /// very first colour index (0 vs 1); after the fix all 1024 `EC_PAL`
6491 /// lines of that block match aomdec line for line.
6492 ///
6493 /// The recipe is the 8-bit `..._with_palette_y_...` gate's, with the
6494 /// depth as the only variable, so a failure here is the depth and
6495 /// nothing else. HARD-asserts [`decode::palette_hits`] moved on each arm
6496 /// (a stream with no real palette block would prove nothing) and
6497 /// compares all three planes against ffmpeg's decode of the same bytes.
6498 #[test]
6499 fn a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit() {
6500 const NAME: &str = "a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit";
6501 if !have_ffmpeg() {
6502 eprintln!("SKIP {NAME}: no ffmpeg");
6503 return;
6504 }
6505 if !have_aomenc() {
6506 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6507 return;
6508 }
6509 let (width, height) = (64usize, 64usize);
6510 for depth in [8usize, 10] {
6511 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
6512 let render = || {
6513 Command::new("ffmpeg")
6514 .args([
6515 "-v", "error",
6516 "-f", "lavfi",
6517 "-i", "smptebars=size=64x64:rate=25",
6518 "-vf", "hue=s=0",
6519 "-pix_fmt", pix_fmt,
6520 "-strict", "-1",
6521 "-t", "0.04",
6522 "-f", "yuv4mpegpipe",
6523 "-",
6524 ])
6525 .stdin(Stdio::null())
6526 .stdout(Stdio::piped())
6527 .stderr(Stdio::piped())
6528 .output()
6529 .expect("ffmpeg failed to run")
6530 .stdout
6531 };
6532 let y4m_a = render();
6533 let y4m_b = render();
6534 assert_eq!(
6535 y4m_a, y4m_b,
6536 "{NAME}: smptebars must render byte-identical across two runs at {depth}-bit"
6537 );
6538 let y4m = y4m_a;
6539 let depth_arg = format!("--bit-depth={depth}");
6540 let input_depth_arg = format!("--input-bit-depth={depth}");
6541 let out = run_with_stdin(Command::new(aomenc_path())
6542 .args([
6543 "--codec=av1",
6544 "--passes=1",
6545 "--end-usage=q",
6546 "--cq-level=30",
6547 "--cpu-used=0",
6548 "--threads=1",
6549 "--row-mt=0",
6550 "--sb-size=64",
6551 "--tune-content=screen",
6552 "--enable-palette=1",
6553 "--enable-intrabc=0",
6554 "--enable-rect-partitions=0",
6555 "--enable-ab-partitions=0",
6556 "--enable-1to4-partitions=0",
6557 "--min-partition-size=32",
6558 "--max-partition-size=32",
6559 "--enable-filter-intra=0",
6560 "--enable-smooth-intra=0",
6561 "--enable-paeth-intra=0",
6562 "--enable-directional-intra=0",
6563 "--enable-angle-delta=0",
6564 "--enable-cfl-intra=0",
6565 "--enable-cdef=0",
6566 "--enable-restoration=0",
6567 "--enable-tx-size-search=0",
6568 "--loopfilter-control=0",
6569 "--limit=1",
6570 ])
6571 // Per-arm overrides go AFTER the base recipe: aomenc keeps the
6572 // LAST occurrence of a repeated flag.
6573 .args([&depth_arg, &input_depth_arg])
6574 .args(["--obu", "-o", "-", "-"]), &y4m);
6575 assert!(
6576 out.status.success(),
6577 "{NAME}: aomenc refused the {depth}-bit fixture: {}",
6578 String::from_utf8_lossy(&out.stderr)
6579 );
6580 let stream = out.stdout;
6581 let before = decode::palette_hits();
6582 let frames = match decode_stream(&stream) {
6583 Ok(frames) => frames,
6584 Err(e) => panic!("{NAME}: decode_stream refused the {depth}-bit stream: {e}"),
6585 };
6586 assert!(
6587 decode::palette_hits() > before,
6588 "{NAME}: no real palette block at {depth}-bit -- gate is vacuous"
6589 );
6590 let ffmpeg_frames = if depth == 10 {
6591 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
6592 } else {
6593 ffmpeg_decode_sequence(&stream, width, height, 1)
6594 };
6595 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma at {depth}-bit");
6596 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U at {depth}-bit");
6597 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V at {depth}-bit");
6598 }
6599 }
6600
6601 /// lane-pal8 r1, the gate for a palette on a SQUARE 8x8 LEAF.
6602 ///
6603 /// `read_palette_mode_info` (decodemv.c:567) reads `palette_y_mode` for
6604 /// every `DC_PRED` block whose `av1_get_palette_bsize_ctx`
6605 /// (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`, 0 at 8x8) exists, and
6606 /// `av1_decode_palette_tokens` (decodeframe.c:1135, `av1_visit_palette`)
6607 /// reads the colour-index map after the WHOLE mode-info read. Ours passed
6608 /// `None`/`&[]` from [`decode::decode_leaf8`], reading the mode symbol off
6609 /// CDF row 0 and refusing "a block that actually uses a palette (Y) --
6610 /// reconstruction is out of scope" the moment it fired -- and at 8 bit
6611 /// aomenc palettes SQUARE blocks, so with `--min-partition-size=8` every
6612 /// 8-bit screen-content stream stopped there (lane-kf900 r4's measurement).
6613 ///
6614 /// Sweeps both bit depths x cq 30/40/55 x `--enable-tx-size-search` 0/1 x
6615 /// two lavfi sources (+ a `--tile-columns=1` arm, per the neighbour-map
6616 /// rule: the palette bands are per-mi and tile-guarded). Key frame only
6617 /// (`--limit=1`): the inter frames of these recipes stop on OTHER lanes'
6618 /// open refusals (8x8 inter leaf chroma mode, inter 1:4 partitions).
6619 /// HARD-asserts the 8x8-leaf palette counter moved on the compared arms
6620 /// and that no arm mismatched, in or out of scope.
6621 #[test]
6622 fn a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact() {
6623 const NAME: &str = "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact";
6624 if !have_ffmpeg() {
6625 eprintln!("SKIP {NAME}: no ffmpeg");
6626 return;
6627 }
6628 if !have_aomenc() {
6629 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6630 return;
6631 }
6632 let (width, height) = (128usize, 128usize);
6633 let (mut leaf8_total, mut fired_arms, mut compared, mut frames_compared) =
6634 (0usize, 0u32, 0u32, 0usize);
6635 let (mut out_of_scope, mut out_of_scope_mismatch, mut refusals) = (0u32, 0u32, 0u32);
6636 let (mut sb_strip_total, mut sb_strip_arms) = (0usize, 0u32);
6637 // lane-t900 r34 LIFTED this shape; the counter stays so the gate
6638 // fails loudly if the refusal ever comes back.
6639 let mut sb_strip_refusals = 0u32;
6640 for src in ["testsrc2", "smptebars"] {
6641 for depth in [8usize, 10usize] {
6642 for cq in [30usize, 40, 55] {
6643 for txs in [0usize, 1] {
6644 for tiles in [0usize, 1] {
6645 let arm = format!("{src}-{depth}bit-cq{cq}-txs{txs}-tc{tiles}");
6646 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
6647 let size = format!("{src}=size={width}x{height}:rate=25");
6648 let render = || {
6649 let out = Command::new("ffmpeg")
6650 .args([
6651 "-v", "error", "-f", "lavfi", "-i", &size, "-t", "0.04",
6652 "-pix_fmt", pix_fmt, "-strict", "-1", "-f",
6653 "yuv4mpegpipe", "-",
6654 ])
6655 .stdin(Stdio::null())
6656 .stdout(Stdio::piped())
6657 .stderr(Stdio::piped())
6658 .output()
6659 .expect("ffmpeg failed to run");
6660 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
6661 out.stdout
6662 };
6663 let y4m_a = render();
6664 let y4m_b = render();
6665 assert_eq!(
6666 y4m_a, y4m_b,
6667 "{NAME}: {arm} must render byte-identical across two runs"
6668 );
6669 let y4m = y4m_a;
6670 let depth_arg = format!("--bit-depth={depth}");
6671 let input_depth_arg = format!("--input-bit-depth={depth}");
6672 let cq_arg = format!("--cq-level={cq}");
6673 let txs_arg = format!("--enable-tx-size-search={txs}");
6674 let tiles_arg = format!("--tile-columns={tiles}");
6675 let out = run_with_stdin(Command::new(aomenc_path())
6676 .args([
6677 "--codec=av1",
6678 "--passes=1",
6679 "--end-usage=q",
6680 "--cpu-used=0",
6681 "--threads=1",
6682 "--row-mt=0",
6683 "--lag-in-frames=0",
6684 "--limit=1",
6685 "--sb-size=64",
6686 "--tune-content=screen",
6687 "--enable-palette=1",
6688 "--enable-intrabc=0",
6689 "--min-partition-size=8",
6690 "--enable-cdef=0",
6691 "--enable-restoration=0",
6692 "--loopfilter-control=0",
6693 ])
6694 // aomenc keeps the LAST occurrence of a repeated flag,
6695 // so per-arm overrides go after the base recipe.
6696 .args([&depth_arg, &input_depth_arg, &cq_arg, &txs_arg, &tiles_arg])
6697 .args(["--obu", "-o", "-", "-"]), &y4m);
6698 assert!(
6699 out.status.success(),
6700 "{NAME}: aomenc refused {arm}: {}",
6701 String::from_utf8_lossy(&out.stderr)
6702 );
6703 let stream = out.stdout;
6704 decode::reset_palette_leaf8_hits();
6705 decode::reset_palette_sb_strip_hits();
6706 let decoded = decode_stream(&stream);
6707 let leaf8 = decode::palette_leaf8_hits();
6708 let sb_strip = decode::palette_sb_strip_hits();
6709 leaf8_total += leaf8;
6710 sb_strip_total += sb_strip;
6711 match decoded {
6712 Ok(frames) => {
6713 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
6714 let theirs = if depth == 10 {
6715 ffmpeg_decode_sequence_10bit(
6716 &stream,
6717 width,
6718 height,
6719 frames.len(),
6720 )
6721 } else {
6722 ffmpeg_decode_sequence(&stream, width, height, frames.len())
6723 };
6724 assert_eq!(
6725 frames.len(),
6726 theirs.len(),
6727 "{NAME}: {arm} frame count"
6728 );
6729 let mut same = true;
6730 for (i, (ours, ref_f)) in
6731 frames.iter().zip(theirs.iter()).enumerate()
6732 {
6733 let ok = ours.y == ref_f.y
6734 && ours.u == ref_f.u
6735 && ours.v == ref_f.v;
6736 if !ok {
6737 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
6738 }
6739 same &= ok;
6740 frames_compared += 1;
6741 }
6742 compared += 1;
6743 if sb_strip > 0 {
6744 sb_strip_arms += 1;
6745 assert!(
6746 same,
6747 "{NAME}: {arm} decoded {sb_strip} non-skip palette \
6748 block(s) on a superblock-level strip and did not \
6749 match ffmpeg"
6750 );
6751 }
6752 if leaf8 > 0 || sb_strip > 0 {
6753 fired_arms += 1;
6754 assert!(
6755 same,
6756 "{NAME}: {arm} decoded {leaf8} 8x8-leaf palette \
6757 block(s) and did not match ffmpeg"
6758 );
6759 } else {
6760 out_of_scope += 1;
6761 if !same {
6762 out_of_scope_mismatch += 1;
6763 }
6764 }
6765 eprintln!(
6766 "{NAME}: {arm} {} frame(s), {leaf8} 8x8-leaf palette \
6767 block(s), {sb_strip} superblock-strip palette \
6768 block(s), exact={same}",
6769 frames.len()
6770 );
6771 }
6772 Err(e) => {
6773 let msg = e.to_string();
6774 assert!(
6775 msg.contains("unsupported"),
6776 "{NAME}: {arm} decode failed: {e}"
6777 );
6778 // Named, counted, never turned into a skip.
6779 if msg.contains("superblock-level HORZ/VERT strip") {
6780 sb_strip_refusals += 1;
6781 }
6782 eprintln!("{NAME}: {arm} REFUSED: {e}");
6783 refusals += 1;
6784 }
6785 }
6786 }
6787 }
6788 }
6789 }
6790 }
6791 eprintln!(
6792 "{NAME}: {leaf8_total} 8x8-leaf palette block(s) across {fired_arms} arm(s), \
6793 {compared} arms compared ({frames_compared} frames), {sb_strip_total} \
6794 superblock-strip palette block(s) across {sb_strip_arms} arm(s), \
6795 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
6796 {refusals} refused ({sb_strip_refusals} superblock-strip palette)"
6797 );
6798 assert!(
6799 leaf8_total > 0 && fired_arms > 0,
6800 "{NAME}: gate is vacuous -- no compared arm decoded an 8x8-leaf palette block"
6801 );
6802 assert_eq!(
6803 sb_strip_refusals, 0,
6804 "{NAME}: the superblock-strip palette refusal is back (lane-t900 r34 lifted it)"
6805 );
6806 assert!(
6807 sb_strip_arms > 0 && sb_strip_total > 0,
6808 "{NAME}: no arm decoded a non-skip palette block on a superblock-level strip -- \
6809 the shape r34 lifted is no longer exercised"
6810 );
6811 assert_eq!(
6812 out_of_scope_mismatch, 0,
6813 "{NAME}: an out-of-scope arm mismatched ffmpeg -- a defect, never a skip"
6814 );
6815 assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact");
6816 }
6817
6818 /// lane-kf900 r5, the gate for the rect-strip `use_intrabc` read.
6819 ///
6820 /// `av1_allow_intrabc` is a FRAME-level test (`decodemv.c:892`,
6821 /// `read_intra_frame_mode_info`): on an intra frame whose header set
6822 /// `allow_intrabc`, EVERY intra block reads a `use_intrabc` symbol right
6823 /// after `skip`/`cdef`/`delta_q` and before `mbmi->mode`. There is no
6824 /// block-shape term, so rect strips read it exactly like square leaves --
6825 /// `read_intra_mode_rect` never did, and the arithmetic decoder desynced
6826 /// at the FIRST symbol of the first rect block of every
6827 /// `--tune-content=screen` key frame (measured: `testsrc2` 256x192 cq59
6828 /// 8-bit decoded "OK" with all 49152 luma samples wrong).
6829 ///
6830 /// Arm 0 is that recipe at cq50 without palette: its rect strips really do
6831 /// use intrabc. lane-av1-rect14 reconstructs those strips (2:1 and the
6832 /// 16x4/4x16 pair), so the arm must now decode pixel-exact -- and it must
6833 /// still have read the symbol. The named refusal remains only for a
6834 /// 128-superblock strip (`decode_block_128rect`), which this sb64 recipe
6835 /// does not reach.
6836 /// Arm 1 is the same recipe without palette and without tx-size search --
6837 /// it decodes the whole frame, reading the symbol dozens of times.
6838 /// Arm 2 is a screen-tools key frame whose header does NOT set
6839 /// `allow_intrabc` (cq63): it stays pixel-exact, proving the new read is
6840 /// not taken when libaom does not write it.
6841 ///
6842 /// PIXEL RESIDUE (open, lane-kf900 r5): arm 1's frame is entropy-exact
6843 /// against the instrumented aomdec for 429 mode-ladder elements and then
6844 /// diverges inside the DV read of a SQUARE intrabc block at mi(32,44), so
6845 /// its pixels are not compared here. That is a separate defect in
6846 /// `read_intrabc_dv`, not in the read this gate covers.
6847 #[test]
6848 fn a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips() {
6849 const NAME: &str = "a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips";
6850 if !have_ffmpeg() {
6851 eprintln!("SKIP {NAME}: no ffmpeg");
6852 return;
6853 }
6854 if !have_aomenc() {
6855 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6856 return;
6857 }
6858 let (width, height) = (256usize, 192usize);
6859 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
6860 // must_read_use_intrabc)
6861 const TS: &str = "testsrc2=s=256x192:r=25";
6862 const SB: &str = "smptebars=size=256x192:rate=25";
6863 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
6864 // must_read_use_intrabc_on_a_rect_strip)
6865 let arms: [(&str, &str, &[&str], bool, bool); 8] = [
6866 // lane-av1-intrabc (2026-09-20): this arm used to REFUSE here -- the
6867 // 16x8 rect strip it decodes is the first block on main that reaches
6868 // `decode_intrabc_rect`, so the whole arm stopped at a named refusal.
6869 // Reconstruction is ported now, so the arm decodes pixel-exact and
6870 // the `rect_total` assert below keeps it from quietly falling back
6871 // to an ordinary-intra decode of the same block.
6872 ("testsrc2-cq50-txs0", TS, &["--cq-level=50", "--enable-palette=0", "--enable-tx-size-search=0"], false, true),
6873 ("smptebars-cq40-txs0", SB, &["--cq-level=40", "--enable-palette=0", "--enable-tx-size-search=0"], false, false),
6874 ("smptebars-cq45-txs0", SB, &["--cq-level=45", "--enable-palette=0", "--enable-tx-size-search=0"], false, true),
6875 ("smptebars-cq45-txs1", SB, &["--cq-level=45", "--enable-palette=0", "--enable-tx-size-search=1"], false, false),
6876 ("smptebars-cq50-txs1", SB, &["--cq-level=50", "--enable-palette=0", "--enable-tx-size-search=1"], false, false),
6877 ("smptebars-cq55-txs0", SB, &["--cq-level=55", "--enable-palette=0", "--enable-tx-size-search=0"], false, false),
6878 ("testsrc2-cq63-txs1", TS, &["--cq-level=63", "--enable-palette=0", "--enable-tx-size-search=1"], false, false),
6879 // lane-kf900 r7: the 8x8-LEAF intrabc arm. Rect and 1:4
6880 // partitions off (so no rect strip refuses first), palette on,
6881 // `TxMode::Largest`: aomenc puts exactly one `use_intrabc` block
6882 // on a `BLOCK_8X8` leaf here, the shape `decode_leaf8` decoded as
6883 // ordinary intra before this round.
6884 ("testsrc2-cq55-leaf8", TS, &["--cq-level=55", "--enable-palette=1", "--enable-tx-size-search=0", "--enable-rect-partitions=0", "--enable-1to4-partitions=0"], false, false),
6885 ];
6886 let (mut reads_total, mut refused, mut frames_compared) = (0usize, 0u32, 0usize);
6887 let (mut blocks_total, mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) =
6888 (0usize, 0u32, 0u32, 0u32);
6889 let mut leaf8_total = 0usize;
6890 let mut rect_total = 0usize;
6891 for (arm, src, extra, expect_refusal, must_read) in &arms {
6892 let render = || {
6893 let out = Command::new("ffmpeg")
6894 .args([
6895 "-v", "error", "-f", "lavfi", "-i", *src, "-t", "0.2", "-pix_fmt",
6896 "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-",
6897 ])
6898 .stdin(Stdio::null())
6899 .stdout(Stdio::piped())
6900 .stderr(Stdio::piped())
6901 .output()
6902 .expect("ffmpeg failed to run");
6903 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
6904 out.stdout
6905 };
6906 let y4m_a = render();
6907 let y4m_b = render();
6908 assert_eq!(y4m_a, y4m_b, "{NAME}: {arm} must render byte-identical across two runs");
6909 let y4m = y4m_a;
6910 let out = run_with_stdin(Command::new(aomenc_path())
6911 .args([
6912 "--codec=av1",
6913 "--bit-depth=8",
6914 "--input-bit-depth=8",
6915 "--passes=1",
6916 "--end-usage=q",
6917 "--cpu-used=0",
6918 "--lag-in-frames=0",
6919 "--kf-max-dist=1",
6920 "--limit=1",
6921 "--threads=1",
6922 "--tile-columns=0",
6923 "--enable-rect-partitions=1",
6924 "--enable-1to4-partitions=1",
6925 "--min-partition-size=8",
6926 "--max-partition-size=32",
6927 "--sb-size=64",
6928 // `allow_screen_content_tools` (and with it the frame
6929 // header's `allow_intrabc` bit) comes from here.
6930 "--tune-content=screen",
6931 // Spelled so `gate_coverage` counts the tool as exercised
6932 // rather than defaulted (class `tool-disabled-in-every-gate`).
6933 "--enable-intrabc=1",
6934 ])
6935 // aomenc keeps the LAST occurrence of a repeated flag.
6936 .args(*extra)
6937 .args(["--obu", "-o", "-", "-"]), &y4m);
6938 assert!(
6939 out.status.success(),
6940 "{NAME}: aomenc refused {arm}: {}",
6941 String::from_utf8_lossy(&out.stderr)
6942 );
6943 let stream = out.stdout;
6944 decode::reset_rect_intrabc_reads();
6945 crate::decode::reset_intrabc_hits();
6946 crate::decode::reset_leaf8_intrabc_hits();
6947 crate::decode::reset_intrabc_rect_hits();
6948 let decoded = decode_stream(&stream);
6949 let reads = decode::rect_intrabc_reads();
6950 // Blocks that decoded `use_intrabc == 1` (square path), i.e. that
6951 // read a DV and predicted from the current frame -- distinct from
6952 // `reads`, which counts rect strips that merely READ the flag.
6953 let blocks = crate::decode::intrabc_hits();
6954 reads_total += reads;
6955 blocks_total += blocks;
6956 // The 8x8-leaf shape has its own counter: without it this gate's
6957 // other arms (all rect/32x32 intrabc) would stay green while the
6958 // leaf path decoded an intrabc block as ordinary intra (class
6959 // `gate-blind-to-feature`).
6960 let leaf8 = crate::decode::leaf8_intrabc_hits();
6961 leaf8_total += leaf8;
6962 rect_total += crate::decode::intrabc_rect_hits();
6963 if *arm == "testsrc2-cq55-leaf8" {
6964 assert!(
6965 leaf8 > 0,
6966 "{NAME}: {arm} decoded no intrabc block at an 8x8 leaf -- the arm no longer exercises `decode_leaf8`'s intrabc path"
6967 );
6968 }
6969 if *must_read {
6970 assert!(
6971 reads > 0,
6972 "{NAME}: {arm} read no use_intrabc symbol on a rect strip -- the \
6973 arm no longer exercises the fix (allow_intrabc not set?)"
6974 );
6975 }
6976 match decoded {
6977 Ok(frames) => {
6978 assert!(
6979 !*expect_refusal,
6980 "{NAME}: {arm} decoded a frame whose rect strips use intrabc -- \
6981 reconstruction is not ported, it must refuse by name"
6982 );
6983 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
6984 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
6985 assert_eq!(frames.len(), ffmpeg_frames.len(), "{NAME}: {arm} frame count");
6986 // EVERY frame is compared; an arm whose decode never hit an
6987 // intrabc block proves nothing about the DV/prediction path,
6988 // so it is counted OUT OF SCOPE -- but a mismatch there is
6989 // still a failure (`out_of_scope_mismatch == 0`), never a skip.
6990 let mut same = true;
6991 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
6992 let ok = ours.y == theirs.y && ours.u == theirs.u && ours.v == theirs.v;
6993 if !ok {
6994 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
6995 }
6996 same &= ok;
6997 frames_compared += 1;
6998 }
6999 if blocks > 0 {
7000 fired_arms += 1;
7001 assert!(
7002 same,
7003 "{NAME}: {arm} decoded {blocks} intrabc block(s) and did not match ffmpeg"
7004 );
7005 } else {
7006 out_of_scope += 1;
7007 if !same {
7008 out_of_scope_mismatch += 1;
7009 }
7010 }
7011 eprintln!(
7012 "{NAME}: {arm} {} frame(s), {reads} rect use_intrabc reads, \
7013 {blocks} intrabc block(s), exact={same}",
7014 frames.len()
7015 );
7016 }
7017 Err(e) => {
7018 let msg = e.to_string();
7019 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
7020 assert!(
7021 *expect_refusal,
7022 "{NAME}: {arm} was expected to decode, it refused: {e}"
7023 );
7024 assert!(
7025 msg.contains("intra block copy") || msg.contains("intrabc"),
7026 "{NAME}: {arm} refused for an unrelated reason: {e}"
7027 );
7028 eprintln!("{NAME}: {arm} REFUSED (expected): {e}");
7029 refused += 1;
7030 }
7031 }
7032 }
7033 eprintln!(
7034 "{NAME}: {reads_total} rect-strip use_intrabc symbol(s) read, \
7035 {blocks_total} intrabc block(s) decoded across {fired_arms} arm(s), \
7036 {refused} refused by name, {frames_compared} frames compared, \
7037 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched)"
7038 );
7039 eprintln!(
7040 "{NAME}: {rect_total} intrabc block(s) on a HORZ/VERT rect strip (decode_intrabc_rect)"
7041 );
7042 assert!(reads_total > 0, "{NAME}: gate is vacuous -- no arm read the symbol");
7043 assert!(
7044 leaf8_total > 0,
7045 "{NAME}: no arm decoded an intrabc block at an 8x8 leaf -- lane-kf900 r7's fix is untested"
7046 );
7047 assert!(
7048 blocks_total > 0 && fired_arms > 0,
7049 "{NAME}: gate is vacuous -- no compared arm actually decoded an intrabc block"
7050 );
7051 assert!(
7052 rect_total > 0,
7053 "{NAME}: no arm decoded an intrabc block on a HORZ/VERT rect strip -- \
7054 `decode_intrabc_rect` is untested"
7055 );
7056 // lane-av1-intrabc: this used to be exactly one -- the 2:1 rect strips
7057 // now reconstruct. The 1:4 pair strips (`decode_rect4_16_strip` et al.)
7058 // still refuse by name, but no arm HERE reaches that shape; it stays
7059 // pinned by `refusal_inventory`'s own gate.
7060 assert_eq!(refused, 0, "{NAME}: an arm still refuses by name");
7061 assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact");
7062 assert_eq!(
7063 out_of_scope_mismatch, 0,
7064 "{NAME}: an arm without an intrabc block still mismatched ffmpeg"
7065 );
7066 }
7067
7068 /// lane-av1-rect14: the 16x4/4x16 intrabc pair. libaom codes the pair's
7069 /// chroma on the odd-mi strip only (`is_chroma_reference`,
7070 /// av1_common_int.h:1454). The witness is the report recipe: testsrc2
7071 /// 640x480 cq60 palette, txs off, which places a 16x4 intrabc strip at
7072 /// mi(76,108). Pre-fix this refused by name. VERT_4 was not produced by
7073 /// any fully-decoded recipe tried here (the allintra stream codes four
7074 /// `PARTITION_VERT_4` at bsize 6 and then stops on the unrelated var-tx
7075 /// mixed-leaf refusal); the VERT arm is the same body with the axes
7076 /// swapped.
7077 #[test]
7078 fn a_16x4_intrabc_pair_strip_decodes_pixel_exact() {
7079 const NAME: &str = "a_16x4_intrabc_pair_strip_decodes_pixel_exact";
7080 if !have_ffmpeg() || !have_aomenc() {
7081 eprintln!("SKIP {NAME}: ffmpeg/aomenc missing");
7082 return;
7083 }
7084 let (width, height) = (640usize, 480usize);
7085 let y4m = Command::new("ffmpeg")
7086 .args([
7087 "-v", "error", "-f", "lavfi", "-i", "testsrc2=s=640x480:r=25", "-frames:v", "1",
7088 "-pix_fmt", "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-",
7089 ])
7090 .output()
7091 .expect("ffmpeg")
7092 .stdout;
7093 let out = run_with_stdin(Command::new(aomenc_path())
7094 .args([
7095 "--codec=av1", "--bit-depth=8", "--input-bit-depth=8", "--passes=1",
7096 "--end-usage=q", "--cpu-used=0", "--lag-in-frames=0", "--kf-max-dist=1",
7097 "--limit=1", "--threads=1", "--tile-columns=0",
7098 "--enable-rect-partitions=1", "--enable-1to4-partitions=1",
7099 "--min-partition-size=4", "--max-partition-size=64", "--sb-size=64",
7100 "--tune-content=screen", "--enable-intrabc=1", "--cq-level=60",
7101 "--enable-palette=1", "--enable-tx-size-search=0", "--obu", "-o", "-", "-",
7102 ]), &y4m);
7103 assert!(out.status.success(), "{NAME}: aomenc failed");
7104 crate::decode::reset_rect4_16_pair_hits();
7105 let frames = decode_stream(&out.stdout).unwrap_or_else(|e| panic!("{NAME}: {e}"));
7106 assert!(
7107 crate::decode::rect4_16_intrabc_hits() > 0,
7108 "{NAME}: no 16x4/4x16 intrabc strip -- the pair body was not reached"
7109 );
7110 let refs = ffmpeg_decode_sequence(&out.stdout, width, height, frames.len());
7111 assert_eq!(frames.len(), 1);
7112 assert_eq!(frames[0].y, refs[0].y, "{NAME}: luma");
7113 assert_eq!(frames[0].u, refs[0].u, "{NAME}: u");
7114 assert_eq!(frames[0].v, refs[0].v, "{NAME}: v");
7115 }
7116
7117 /// lane-av1-rect14: lossless 16x4/4x16 chroma is two TX_4X4s, not one
7118 /// TX_8X4. The measured site is luma col 108 of a 320x240 sb128 lossless
7119 /// key frame (lanes/av1lossless128.report.md §6). Rows 0-127 of that
7120 /// frame -- the first superblock row, which contains the site -- must
7121 /// match ffmpeg. A later mismatch is the pre-existing 64x64 square
7122 /// lossless residue (base fails at byte 108; this lane's first remaining
7123 /// mismatch is row 128). The gate fails if that residue moves back into
7124 /// the repaired region.
7125 #[test]
7126 fn a_lossless_16x4_chroma_pair_repairs_the_measured_site() {
7127 const NAME: &str = "a_lossless_16x4_chroma_pair_repairs_the_measured_site";
7128 if !have_ffmpeg() || !have_aomenc() {
7129 eprintln!("SKIP {NAME}: ffmpeg/aomenc missing");
7130 return;
7131 }
7132 let (width, height) = (320usize, 240usize);
7133 let y4m = Command::new("ffmpeg")
7134 .args([
7135 "-v", "error", "-f", "lavfi", "-i", "testsrc2=s=320x240:r=25", "-frames:v", "1",
7136 "-pix_fmt", "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-",
7137 ])
7138 .output()
7139 .expect("ffmpeg")
7140 .stdout;
7141 let out = run_with_stdin(Command::new(aomenc_path())
7142 .args([
7143 "--codec=av1", "--cpu-used=0", "--lossless=1", "--sb-size=128",
7144 "--lag-in-frames=0", "--kf-max-dist=1", "--limit=1", "--threads=1",
7145 "--passes=1", "--enable-1to4-partitions=1", "--min-partition-size=4",
7146 "--enable-rect-partitions=1", "--obu", "-o", "-", "-",
7147 ]), &y4m);
7148 assert!(out.status.success(), "{NAME}: aomenc failed");
7149 crate::decode::reset_rect4_16_pair_hits();
7150 let frames = decode_stream(&out.stdout).unwrap_or_else(|e| panic!("{NAME}: {e}"));
7151 assert!(
7152 crate::decode::rect4_16_lossless_chroma_hits() > 0,
7153 "{NAME}: no lossless 16x4/4x16 chroma pair -- the walk was not reached"
7154 );
7155 let refs = ffmpeg_decode_sequence(&out.stdout, width, height, frames.len());
7156 let repaired = 128 * width;
7157 assert_eq!(
7158 &frames[0].y[..repaired],
7159 &refs[0].y[..repaired],
7160 "{NAME}: luma rows 0-127 (the measured col-108 site) diverged"
7161 );
7162 let chroma_rows = 64 * (width / 2);
7163 assert_eq!(&frames[0].u[..chroma_rows], &refs[0].u[..chroma_rows], "{NAME}: u");
7164 assert_eq!(&frames[0].v[..chroma_rows], &refs[0].v[..chroma_rows], "{NAME}: v");
7165 // The col-108 byte specifically, so a shift of the old site still fails
7166 // even if some other prefix sample happens to match.
7167 assert_eq!(frames[0].y[108], refs[0].y[108], "{NAME}: measured byte 108");
7168 }
7169 /// lane-av1-intrabc r4: the reviewer's unblock witness for the rect-strip
7170 /// reconstruction -- a CODED `use_intrabc` block (so its residual reader
7171 /// runs, not just the prediction copy) on a 2:1 strip in BOTH
7172 /// orientations, plus the `TX_MODE_SELECT` (var-tx) shape, every arm
7173 /// byte-exact against ffmpeg.
7174 ///
7175 /// The orientation counters (`intrabc_rect_coded_hits`) are the
7176 /// non-vacuity instrument: [`intrabc_rect_hits`] counts neither the skip
7177 /// flag nor the orientation, so an arm that silently became an all-skip
7178 /// stream (or a stream with only one orientation) would keep the old gate
7179 /// green while the coded residual path went untested
7180 /// (class `gate-blind-to-feature`).
7181 ///
7182 /// # The VERT arm is also the DV-PREDICTOR regression witness
7183 ///
7184 /// The 512x384 arm is the stream that exposed r4's defect: 528 of 294912
7185 /// luma samples were wrong, all inside one `skip == 1` intrabc copy at
7186 /// `mi(84,104)`. Its coded diff was identical to aomdec's and the post-read
7187 /// range matched exactly (`rng=33207` both), so nothing was misread -- the
7188 /// DV PREDICTOR differed. libaom picks `nearestmv` (`-520`) from the
7189 /// `INTRA_FRAME` MV stack; this decoder picked `-512`, one stack entry
7190 /// lower, because the scan that builds that stack walked further than
7191 /// libaom's. The scans step by the candidate BLOCK's own width
7192 /// (`mi_size_wide[bsize]`) over `xd->mi[]`, which holds an entry for every
7193 /// coded block; this decoder's MV grid held only the intrabc blocks, so a
7194 /// non-intrabc neighbour read as uncovered and the scan advanced that cell
7195 /// by one instead of by its real width. See `MiGrid::cover` for the
7196 /// measured walk. A stream that decodes the DV predictor from the wrong
7197 /// stack entry cannot pass this arm's pixel comparison.
7198 #[test]
7199 fn a_coded_rect_intrabc_block_reconstructs_in_both_orientations() {
7200 const NAME: &str = "a_coded_rect_intrabc_block_reconstructs_in_both_orientations";
7201 if !have_ffmpeg() {
7202 eprintln!("SKIP {NAME}: no ffmpeg");
7203 return;
7204 }
7205 if !have_aomenc() {
7206 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7207 return;
7208 }
7209 const TS256: &str = "testsrc2=s=256x192:r=25";
7210 const TS512: &str = "testsrc2=s=512x384:r=25";
7211 // (arm, source, width, height, per-arm overrides, the coded orientation
7212 // this arm must exercise, and whether the frame must code
7213 // `TX_MODE_SELECT` with `allow_intrabc` still set)
7214 let arms: [(&str, &str, usize, usize, &[&str], u8, bool); 3] = [
7215 // HORZ (16x8) coded strip -- the shape the in-gate witness above
7216 // already reconstructs, pinned here with its own orientation counter.
7217 ("horz-coded-256-cq45-pal0-txs0", TS256, 256, 192, &["--cq-level=45", "--enable-palette=0", "--enable-tx-size-search=0"], 0, false),
7218 // VERT (8x16) coded strip AND the DV-predictor regression stream.
7219 ("vert-coded-512-cq45-pal1-txs0", TS512, 512, 384, &["--cq-level=45", "--enable-palette=1", "--enable-tx-size-search=0"], 1, false),
7220 // The `TX_MODE_SELECT` (stream A) shape: `--enable-tx-size-search=1`
7221 // makes the frame code `tx_mode == Select`, so the intrabc block's
7222 // transform size comes off the INTER var-tx tree.
7223 ("txmode-select-256-cq45-pal0-txs1", TS256, 256, 192, &["--cq-level=45", "--enable-palette=0", "--enable-tx-size-search=1"], 0, true),
7224 ];
7225 let mut coded_total = [0usize; 2];
7226 let mut frames_compared = 0usize;
7227 for (arm, src, width, height, extra, want_orient, want_select) in &arms {
7228 let render = || {
7229 let out = Command::new("ffmpeg")
7230 .args([
7231 "-v", "error", "-f", "lavfi", "-i", *src, "-t", "0.2", "-pix_fmt",
7232 "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-",
7233 ])
7234 .stdin(Stdio::null())
7235 .stdout(Stdio::piped())
7236 .stderr(Stdio::piped())
7237 .output()
7238 .expect("ffmpeg failed to run");
7239 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
7240 out.stdout
7241 };
7242 let y4m = render();
7243 let out = run_with_stdin(Command::new(aomenc_path())
7244 .args([
7245 "--codec=av1",
7246 "--bit-depth=8",
7247 "--input-bit-depth=8",
7248 "--passes=1",
7249 "--end-usage=q",
7250 "--cpu-used=0",
7251 "--lag-in-frames=0",
7252 "--kf-max-dist=1",
7253 "--limit=1",
7254 "--threads=1",
7255 "--tile-columns=0",
7256 "--enable-rect-partitions=1",
7257 "--enable-1to4-partitions=1",
7258 "--min-partition-size=8",
7259 "--max-partition-size=32",
7260 "--sb-size=64",
7261 "--tune-content=screen",
7262 "--enable-intrabc=1",
7263 ])
7264 // aomenc keeps the LAST occurrence of a repeated flag.
7265 .args(*extra)
7266 .args(["--obu", "-o", "-", "-"]), &y4m);
7267 assert!(
7268 out.status.success(),
7269 "{NAME}: aomenc refused {arm}: {}",
7270 String::from_utf8_lossy(&out.stderr)
7271 );
7272 let stream = out.stdout;
7273 if *want_select {
7274 let (select, premise) = tx_select_and_intrabc_frames(&stream);
7275 assert!(
7276 select > 0 && premise > 0,
7277 "{NAME}: {arm} no longer codes a frame with both tx_mode == Select and \
7278 allow_intrabc (select={select} premise={premise}), so the TX_MODE_SELECT \
7279 shape is untested here"
7280 );
7281 }
7282 crate::decode::reset_intrabc_rect_hits();
7283 let frames = decode_stream(&stream)
7284 .unwrap_or_else(|e| panic!("{NAME}: {arm} refused: {e}"));
7285 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
7286 let coded = crate::decode::intrabc_rect_coded_hits();
7287 coded_total[0] += coded[0];
7288 coded_total[1] += coded[1];
7289 assert!(
7290 coded[*want_orient as usize] > 0,
7291 "{NAME}: {arm} reconstructed no CODED ({}) rect intrabc block -- the residual \
7292 reader for this orientation is untested (coded horz/vert = {coded:?})",
7293 if *want_orient == 0 { "HORZ" } else { "VERT" }
7294 );
7295 let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len());
7296 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
7297 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
7298 assert!(
7299 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
7300 "{NAME}: {arm} frame {i} does not match ffmpeg"
7301 );
7302 frames_compared += 1;
7303 }
7304 eprintln!(
7305 "{NAME}: {arm} {} frame(s) exact, coded rect intrabc horz={} vert={}",
7306 frames.len(),
7307 coded[0],
7308 coded[1]
7309 );
7310 }
7311 assert!(
7312 coded_total[0] > 0 && coded_total[1] > 0,
7313 "{NAME}: gate is vacuous -- coded rect intrabc blocks seen: horz={} vert={}",
7314 coded_total[0],
7315 coded_total[1]
7316 );
7317 assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact");
7318
7319 // lane-av1-intrabc r5: the SKIPPED VERT 2:1 strip -- the arm the
7320 // reviewer's sweep panicked on (a skipped 8x32 strip passed a
7321 // `bw * bh`-sized ZERO_RESIDUAL slice at stride `side`, and
7322 // `reconstruct_mc_rect` indexed `row * side + w` past its end).
7323 // Skip-heavy recipes (low cq, palette off AND on), each decoded
7324 // byte-exact vs ffmpeg on BOTH the default single-threaded path
7325 // (`EC_AV1_RECON_THREADS == 1`, the inline ReconPlanes arm that
7326 // panicked pre-fix) AND the wavefront path. The skipped-orientation
7327 // counter is asserted per arm (`gate-blind-to-feature`): a recipe
7328 // that stops producing a skipped VERT strip fails instead of passing
7329 // vacuously. `lock_gate_counters` because `set_recon_threads` is a
7330 // process-wide knob.
7331 let _par_lock = lock_gate_counters();
7332 let skip_arms: [(&str, &str, usize, usize, &[&str]); 2] = [
7333 ("vert-skip-512-cq30-pal0-txs0", TS512, 512, 384, &["--cq-level=30", "--enable-palette=0", "--enable-tx-size-search=0"]),
7334 ("vert-skip-512-cq30-pal1-txs0", TS512, 512, 384, &["--cq-level=30", "--enable-palette=1", "--enable-tx-size-search=0"]),
7335 ];
7336 for (arm, src, width, height, extra) in &skip_arms {
7337 let y4m = {
7338 let out = Command::new("ffmpeg")
7339 .args([
7340 "-v", "error", "-f", "lavfi", "-i", *src, "-t", "0.2", "-pix_fmt",
7341 "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-",
7342 ])
7343 .stdin(Stdio::null())
7344 .stdout(Stdio::piped())
7345 .stderr(Stdio::piped())
7346 .output()
7347 .expect("ffmpeg failed to run");
7348 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
7349 out.stdout
7350 };
7351 let out = run_with_stdin(Command::new(aomenc_path())
7352 .args([
7353 "--codec=av1", "--bit-depth=8", "--input-bit-depth=8", "--passes=1",
7354 "--end-usage=q", "--cpu-used=0", "--lag-in-frames=0", "--kf-max-dist=1",
7355 "--limit=1", "--threads=1", "--tile-columns=0",
7356 "--enable-rect-partitions=1", "--enable-1to4-partitions=1",
7357 "--min-partition-size=8", "--max-partition-size=32", "--sb-size=64",
7358 "--tune-content=screen", "--enable-intrabc=1",
7359 ])
7360 // aomenc keeps the LAST occurrence of a repeated flag.
7361 .args(*extra)
7362 .args(["--obu", "-o", "-", "-"]), &y4m);
7363 assert!(
7364 out.status.success(),
7365 "{NAME}: aomenc refused {arm}: {}",
7366 String::from_utf8_lossy(&out.stderr)
7367 );
7368 let stream = out.stdout;
7369 // Default single-threaded path first (the arm that panicked
7370 // pre-fix), then the wavefront path; both must match ffmpeg.
7371 let mut skipped_vert = 0usize;
7372 for threads in [1usize, 4] {
7373 crate::par::set_recon_threads(threads);
7374 crate::decode::reset_intrabc_rect_hits();
7375 let frames = match decode_stream(&stream) {
7376 Ok(frames) => frames,
7377 Err(e) => {
7378 crate::par::set_recon_threads(1);
7379 panic!("{NAME}: {arm} refused at {threads} recon thread(s): {e}")
7380 }
7381 };
7382 let skipped = crate::decode::intrabc_rect_skipped_hits();
7383 assert!(
7384 !frames.is_empty(),
7385 "{NAME}: {arm} decoded no frame at {threads} recon thread(s)"
7386 );
7387 let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len());
7388 assert_eq!(
7389 frames.len(),
7390 theirs.len(),
7391 "{NAME}: {arm} frame count at {threads} recon thread(s)"
7392 );
7393 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
7394 assert!(
7395 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
7396 "{NAME}: {arm} frame {i} does not match ffmpeg at {threads} recon thread(s)"
7397 );
7398 }
7399 if threads == 1 {
7400 skipped_vert = skipped[1];
7401 } else {
7402 assert_eq!(
7403 skipped[1], skipped_vert,
7404 "{NAME}: {arm} skipped VERT strip count changed across recon paths"
7405 );
7406 }
7407 eprintln!(
7408 "{NAME}: {arm} {} frame(s) exact at {threads} recon thread(s), skipped rect intrabc horz={} vert={}",
7409 frames.len(),
7410 skipped[0],
7411 skipped[1]
7412 );
7413 }
7414 crate::par::set_recon_threads(1);
7415 assert!(
7416 skipped_vert > 0,
7417 "{NAME}: {arm} reconstructed no SKIPPED VERT rect intrabc strip -- the r5 stride arm is untested"
7418 );
7419 }
7420 }
7421
7422 /// lane-t900 r31: builds one `--tune-content=screen --enable-intrabc=1`
7423 /// key frame, 256x192 8-bit, from a deterministic lavfi source. `tiled`
7424 /// renders a 2x2 tiling of a 128x96 pattern -- exact spatial repetition,
7425 /// the content intra block copy exists for; `square_only` turns the rect
7426 /// and 1:4 partitions off so an intrabc block lands on a SQUARE block
7427 /// instead of stopping on the rect-strip intrabc refusal first.
7428 fn screen_intrabc_stream(src: &str, cq: &str, txs: &str, tiled: bool, square_only: bool) -> Vec<u8> {
7429 screen_intrabc_stream_with(src, cq, txs, tiled, square_only, &[])
7430 }
7431
7432 /// [`screen_intrabc_stream`] with per-arm flags appended AFTER the base
7433 /// recipe -- aomenc keeps the LAST occurrence of a repeated flag, so an
7434 /// arm can override `--sb-size` / `--min-partition-size` here.
7435 fn screen_intrabc_stream_with(
7436 src: &str,
7437 cq: &str,
7438 txs: &str,
7439 tiled: bool,
7440 square_only: bool,
7441 extra: &[&str],
7442 ) -> Vec<u8> {
7443 screen_intrabc_stream_at_depth(src, cq, txs, tiled, square_only, 8, extra)
7444 }
7445
7446 /// [`screen_intrabc_stream_with`] at an explicit bit depth (8 or 10): the
7447 /// lavfi source is rendered straight to that depth's yuv4mpegpipe pixel
7448 /// format and aomenc is told to encode at the matching
7449 /// `--bit-depth`/`--input-bit-depth`, so a 10-bit arm produces a genuine
7450 /// high-bit-depth stream rather than an 8-bit one in disguise.
7451 fn screen_intrabc_stream_at_depth(
7452 src: &str,
7453 cq: &str,
7454 txs: &str,
7455 tiled: bool,
7456 square_only: bool,
7457 depth: usize,
7458 extra: &[&str],
7459 ) -> Vec<u8> {
7460 assert!(depth == 8 || depth == 10, "unsupported bit depth {depth}");
7461 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
7462 let mut ff = Command::new("ffmpeg");
7463 ff.args(["-v", "error", "-f", "lavfi", "-i", src, "-t", "0.2"]);
7464 if tiled {
7465 ff.args(["-vf", "tile=2x2"]);
7466 }
7467 let out = ff
7468 .args(["-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-"])
7469 .stdin(Stdio::null())
7470 .stdout(Stdio::piped())
7471 .stderr(Stdio::piped())
7472 .output()
7473 .expect("ffmpeg failed to run");
7474 assert!(out.status.success(), "ffmpeg failed for {src}");
7475 let y4m = out.stdout;
7476 let enc = run_with_stdin(Command::new(aomenc_path())
7477 .args(["--codec=av1"])
7478 .args([format!("--bit-depth={depth}"), format!("--input-bit-depth={depth}")])
7479 .args([
7480 "--passes=1",
7481 "--end-usage=q",
7482 "--cpu-used=0",
7483 "--lag-in-frames=0",
7484 "--kf-max-dist=1",
7485 "--limit=1",
7486 "--threads=1",
7487 "--tile-columns=0",
7488 "--min-partition-size=8",
7489 "--max-partition-size=32",
7490 "--sb-size=64",
7491 "--tune-content=screen",
7492 "--enable-intrabc=1",
7493 "--enable-palette=0",
7494 ])
7495 .args([format!("--cq-level={cq}"), format!("--enable-tx-size-search={txs}")])
7496 // aomenc keeps the LAST occurrence of a repeated flag.
7497 .args(if square_only {
7498 &["--enable-rect-partitions=0", "--enable-1to4-partitions=0"][..]
7499 } else {
7500 &[][..]
7501 })
7502 .args(extra)
7503 .args(["--obu", "-o", "-", "-"]), &y4m);
7504 assert!(
7505 enc.status.success(),
7506 "aomenc refused {src} cq={cq}: {}",
7507 String::from_utf8_lossy(&enc.stderr)
7508 );
7509 enc.stdout
7510 }
7511
7512 /// The sequence header's `use_128x128_superblock`, and how many frames of
7513 /// `stream` keep `allow_intrabc` -- the two bits the refusal "intrabc
7514 /// under a 128x128 superblock" is the conjunction of, read out of the
7515 /// headers rather than assumed from the flags handed to the encoder.
7516 fn sb128_and_intrabc_frames(stream: &[u8]) -> (bool, u32) {
7517 let mut parser = Av1Parser::new();
7518 let mut pos = 0usize;
7519 let (mut sb128, mut intrabc) = (false, 0u32);
7520 while pos < stream.len() {
7521 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
7522 break;
7523 };
7524 pos += obu.total_size.max(1);
7525 if let Some(seq) = parser.sequence_header() {
7526 sb128 = seq.use_128x128_superblock;
7527 }
7528 let header = match &obu.kind {
7529 ObuKind::Frame(h, _) => Some(&**h),
7530 ObuKind::FrameHeader(h) => Some(&**h),
7531 _ => None,
7532 };
7533 if header.is_some_and(|h| h.allow_intrabc) {
7534 intrabc += 1;
7535 }
7536 }
7537 (sb128, intrabc)
7538 }
7539
7540 /// lane-t900 r34, the WITNESS (r33 pinned it ignored) that intrabc under
7541 /// a 128x128 superblock decodes pixel-exact.
7542 ///
7543 /// All four arms of r33's census -- `--sb-size=128 --tune-content=screen
7544 /// --enable-intrabc=1` over both `--enable-tx-size-search` settings and
7545 /// two quantisers, on a 2x2 tiling of a 128x96 bar pattern (256x192,
7546 /// 8-bit, `--cpu-used=0 --min-partition-size=8 --max-partition-size=32`,
7547 /// rect and 1:4 off) -- code `use_128x128_superblock && allow_intrabc`.
7548 ///
7549 /// The lift was one constant: `av1_find_ref_dv` (mvref_common.c) takes
7550 /// `mib_size`, the SEQUENCE's superblock size in mi units, so the
7551 /// fallback DV is one 128-px superblock up (or 128 + `INTRABC_DELAY_PIXELS`
7552 /// left on the tile's first superblock row) under a 128 superblock, where
7553 /// [`crate::decode::read_intrabc_dv`] hardcoded 64. Every arm is compared
7554 /// to ffmpeg and the decoded-intrabc-block counter is asserted non-zero,
7555 /// so a stream that stopped using intrabc could not make this vacuous.
7556 ///
7557 /// lane-av1-intrabc (2026-09-17): the four recipes now run at 10 bits as
7558 /// well, and both depths must SHOW the engagement -- `blocks_at_depth`
7559 /// below hard-asserts a decoded intrabc block per depth. The 10-bit
7560 /// coverage the guard records for `enable-intrabc` used to rest on a gate
7561 /// that only SPELLED `--enable-intrabc=1`: measured (same round), all five
7562 /// arms of `a_real_aomenc_rect_strip_palette_decodes_pixel_exact` decode
7563 /// ZERO intrabc blocks at BOTH depths, so the spelling proved nothing and
7564 /// the entry was one encoder-RD change away from being vacuous again
7565 /// (class `tool-disabled-in-every-gate`). An arm here that stops engaging
7566 /// intrabc now fails this gate instead of retiring the entry unproven.
7567 #[test]
7568 fn an_sb128_screen_stream_with_intrabc_decodes_pixel_exact() {
7569 const NAME: &str = "an_sb128_screen_stream_with_intrabc_decodes_pixel_exact";
7570 if !have_ffmpeg() || !have_aomenc() {
7571 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
7572 return;
7573 }
7574 let (width, height) = (256usize, 192usize);
7575 let _guard = lock_gate_counters();
7576 let (mut blocks_total, mut frames_compared) = (0usize, 0u32);
7577 let mut blocks_at_depth = [0usize; 2];
7578 for depth in [8usize, 10] {
7579 for txs in ["0", "1"] {
7580 for cq in ["30", "45"] {
7581 let arm = format!("sb128 {depth}-bit txs={txs} cq={cq}");
7582 let stream = screen_intrabc_stream_at_depth(
7583 "smptebars=size=128x96:rate=25",
7584 cq,
7585 txs,
7586 true,
7587 true,
7588 depth,
7589 &["--sb-size=128"],
7590 );
7591 let (sb128, intrabc_frames) = sb128_and_intrabc_frames(&stream);
7592 assert!(
7593 sb128 && intrabc_frames > 0,
7594 "{NAME}: {arm} no longer codes sb128 + allow_intrabc"
7595 );
7596 crate::decode::reset_intrabc_hits();
7597 let frames =
7598 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {arm}: {e}"));
7599 let blocks = crate::decode::intrabc_hits();
7600 blocks_total += blocks;
7601 blocks_at_depth[usize::from(depth == 10)] += blocks;
7602 let theirs = if depth == 10 {
7603 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
7604 } else {
7605 ffmpeg_decode_sequence(&stream, width, height, frames.len())
7606 };
7607 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
7608 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
7609 assert!(
7610 ours.y == ref_frame.y
7611 && ours.u == ref_frame.u
7612 && ours.v == ref_frame.v,
7613 "{NAME}: {arm} frame {i} does not match ffmpeg"
7614 );
7615 frames_compared += 1;
7616 }
7617 eprintln!(
7618 "{NAME}: {arm} intrabc_frames={intrabc_frames} intrabc_blocks={blocks} \
7619 DECODED {} frame(s) exact",
7620 frames.len()
7621 );
7622 }
7623 }
7624 }
7625 assert!(frames_compared > 0, "{NAME}: no frame was compared");
7626 assert!(
7627 blocks_total > 0,
7628 "{NAME}: gate is vacuous -- no arm decoded a single intrabc block"
7629 );
7630 assert!(
7631 blocks_at_depth[0] > 0 && blocks_at_depth[1] > 0,
7632 "{NAME}: 8-bit={} 10-bit={} -- an arm at that depth no longer decodes an intrabc \
7633 block, so `enable-intrabc` coverage there would rest on the flag spelling alone",
7634 blocks_at_depth[0],
7635 blocks_at_depth[1]
7636 );
7637 }
7638
7639 /// lane-av1-ibcrect: `use_intrabc` on a 128-root HORZ/VERT strip
7640 /// (BLOCK_128X64 / BLOCK_64X128) decodes PIXEL-EXACT against the
7641 /// instrumented oracle -- the witness the refusal inventory names after
7642 /// `decode_block_128rect`'s rect-strip intrabc refusal was lifted
7643 /// (`decode_intrabc_128rect`). The square-block twin is
7644 /// [`an_sb128_screen_stream_with_intrabc_decodes_pixel_exact`] above.
7645 ///
7646 /// The recipes are the hunt's proven arms (lanes/ibcrect r1/r2, the same
7647 /// `--sb-size=128 --min-partition-size=64 --enable-rect-partitions=1
7648 /// --enable-ab-partitions=0 --enable-1to4-partitions=0` partition recipe
7649 /// [`a_real_aomenc_sb128_intra_rect_block_decodes_pixel_exact`] uses, plus
7650 /// `--tune-content=screen --enable-intrabc=1` over the DETERMINISTIC geq
7651 /// sinusoid sources -- lavfi `gradients` ignores its seed and re-rolls
7652 /// every run, so a "flake" there was really this):
7653 ///
7654 /// * HORZ arm: 384x320 cq32, 5 all-key frames -- 14 unskipped 128x64
7655 /// intrabc blocks (`skip=false`, real residual reads);
7656 /// * VERT arm: 512x512 cq45, 5 all-key frames -- an unskipped 64x128
7657 /// intrabc block at mi(64,96).
7658 ///
7659 /// Both arms HARD-assert `intrabc_128rect_hits() > 0` and decode-order
7660 /// pixel-exactness of EVERY frame (hidden alt-refs included) against the
7661 /// oracle's own dump, so a stream that stopped engaging the shape fails
7662 /// the gate instead of passing vacuously (class `gate-blind-to-feature`).
7663 ///
7664 /// The 10-bit arm engages the shape. Hunt r2 and the witness re-run both
7665 /// measured `intrabc_128rect_hits` +15 on arm 3, so aomenc does take a
7666 /// 128-root HORZ/VERT strip at 10 bit under this recipe. There is no
7667 /// per-depth coverage gap to print. The gate's hard asserts already
7668 /// cover that arm.
7669 ///
7670 /// The chroma context this shape reads was the r2 defect: per-unit chroma
7671 /// entropy states were stamped inside the mu-chunk loop, then the
7672 /// end-of-block `record_split_luma_rect_mi` re-stamped BOTH planes over
7673 /// the whole 128x64 span with ONE composed state -- level = the SUM of
7674 /// both 64x64 chunks' units, dc = chunk-0's top-left (class
7675 /// `override-slot-on-one-arm`; the inter-128 path fixed the same class
7676 /// with its `mu_chroma_units` replay, decode.rs). The next block then
7677 /// read `txb_skip` off the smeared state.
7678 #[test]
7679 fn an_sb128_rect_strip_with_intrabc_decodes_pixel_exact() {
7680 const NAME: &str = "an_sb128_rect_strip_with_intrabc_decodes_pixel_exact";
7681 let _gate_lock = lock_gate_counters();
7682 if !have_ffmpeg() {
7683 eprintln!("SKIP {NAME}: no ffmpeg");
7684 return;
7685 }
7686 if !have_aomenc() {
7687 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
7688 return;
7689 }
7690 // (tag, width, height, cq, geq luma, 10-bit)
7691 // The geq sources are the hunt's GEO_SMOOTH / GEO_SMOOTH_512,
7692 // byte-identical across runs (see the sb128 intra-rect gate's note).
7693 let arms: [(u32, usize, usize, &str, &str, bool); 3] = [
7694 (
7695 1,
7696 384,
7697 320,
7698 "32",
7699 "128+90*sin((X+2*N)/37)+30*sin(Y/29)",
7700 false,
7701 ),
7702 (
7703 2,
7704 512,
7705 512,
7706 "45",
7707 "128+80*sin((X+3*N)/17)+50*sin(Y/29)+30*sin((X+Y)/13)",
7708 false,
7709 ),
7710 (3, 384, 320, "32", "128+90*sin((X+2*N)/37)+30*sin(Y/29)", true),
7711 ];
7712 let mut engaged_arms = 0u32;
7713 let mut vert_arms = 0u32;
7714 for (tag, width, height, cq, lum, ten_bit) in arms {
7715 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
7716 let y4m = Command::new("ffmpeg")
7717 .args([
7718 "-v",
7719 "error",
7720 "-f",
7721 "lavfi",
7722 "-i",
7723 &format!(
7724 "nullsrc=size={width}x{height}:rate=25,format=yuv420p,\
7725 geq=lum='{lum}':\
7726 cb='128+30*sin(X/23)':cr='128+30*sin((Y+N)/19)'"
7727 ),
7728 "-pix_fmt",
7729 pix,
7730 "-strict",
7731 "-1",
7732 "-t",
7733 "0.2",
7734 "-f",
7735 "yuv4mpegpipe",
7736 "-",
7737 ])
7738 .stdin(Stdio::null())
7739 .stdout(Stdio::piped())
7740 .stderr(Stdio::piped())
7741 .output()
7742 .expect("ffmpeg failed to run");
7743 assert!(
7744 y4m.status.success(),
7745 "{NAME}: ffmpeg fixture: {}",
7746 String::from_utf8_lossy(&y4m.stderr)
7747 );
7748 let cq_arg = format!("--cq-level={cq}");
7749 let mut args: Vec<&str> = vec![
7750 "--codec=av1",
7751 "--passes=1",
7752 "--end-usage=q",
7753 &cq_arg,
7754 "--cpu-used=0",
7755 "--threads=1",
7756 "--row-mt=0",
7757 "--lag-in-frames=0",
7758 "--kf-max-dist=1",
7759 "--limit=5",
7760 "--tile-columns=0",
7761 "--sb-size=128",
7762 "--min-partition-size=64",
7763 "--enable-rect-partitions=1",
7764 "--enable-ab-partitions=0",
7765 "--enable-1to4-partitions=0",
7766 "--enable-palette=0",
7767 "--tune-content=screen",
7768 "--enable-intrabc=1",
7769 "--deltaq-mode=0",
7770 "--enable-tx-size-search=0",
7771 ];
7772 if ten_bit {
7773 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
7774 }
7775 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
7776 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
7777 assert!(
7778 out.status.success(),
7779 "{NAME}: aomenc refused the arm {tag} fixture: {}",
7780 String::from_utf8_lossy(&out.stderr)
7781 );
7782 let stream = out.stdout;
7783 let before = crate::decode::intrabc_128rect_hits();
7784 let (frames, hidden) = decode_all_frames_vs_oracle(
7785 &stream,
7786 &format!("ibcrect-strip-{tag}-{width}x{height}"),
7787 );
7788 let hits = crate::decode::intrabc_128rect_hits() - before;
7789 eprintln!(
7790 "{NAME}: arm {tag} {width}x{height} cq={cq} {}bit: {frames} decode-order frames \
7791 pixel-exact ({hidden} hidden), intrabc_128rect_hits=+{hits}",
7792 if ten_bit { 10 } else { 8 },
7793 );
7794 if hits > 0 {
7795 engaged_arms += 1;
7796 // The VERT arm is tag 2; its engagement is what proves the
7797 // 64x128 orientation, not just 128x64.
7798 if tag == 2 {
7799 vert_arms += 1;
7800 }
7801 }
7802 }
7803 assert!(
7804 engaged_arms > 0,
7805 "{NAME}: {engaged_arms} arm(s) decoded pixel-exact but NOT ONE decoded a 128-root \
7806 rect-strip intrabc block -- the shape this gate exists for was never engaged"
7807 );
7808 assert!(
7809 vert_arms > 0,
7810 "{NAME}: the VERT (64x128) orientation was never engaged -- only 128x64 HORZ strips \
7811 proved the lift"
7812 );
7813 }
7814 /// lane-av1intrapred r2, REGRESSION GATE for the two intrabc TX4-split
7815 /// chroma defects this lane fixed.
7816 ///
7817 /// An intrabc 8x8 leaf whose var-tx tree split to TX_4X4 must (a) arm
7818 /// `INTRABC_CHROMA_TX` from the co-located luma TU's coded type -- the
7819 /// chroma units then take that type's class-1 eob row, HORIZ scan and nz
7820 /// contexts (libaom `av1_get_tx_type`'s is_inter branch; intrabc is
7821 /// inter-classified) -- and (b) predict the chroma units from the FRAME
7822 /// COPY at the DV, not intra-from-UV-mode (intrabc's UV mode is DC, so a
7823 /// leaf that loses the override predicts flat DC where libaom copies a
7824 /// busy region).
7825 ///
7826 /// Pre-r2, decode_leaf8's TX4 arm did neither: R5's chroma U txb at
7827 /// mi (36,66) decoded `eob=11` off the 2D row where aomdec decoded
7828 /// `eob=13` off the class-1 row, and the first surviving pixel fork was
7829 /// U(184,4) of mi (2,92) (class `intrabc-chroma-tx-not-armed`, then
7830 /// `intrabc-chroma-predicts-intra`).
7831 ///
7832 /// The fixture is the report's R5 stream pinned into `fixtures/`
7833 /// (aomenc oracle, testsrc2 320x180 tiled 2x2 -> 640x360, sb64 maxp64
7834 /// square-only screen intrabc, cq20, 1 frame; 7173 bytes,
7835 /// sha256 bc699af4a6e7c1c5657f041e8cbdf2d3d899ddb80ec2a549a950b7cebb5b41bd).
7836 /// The gate needs no oracle at run time and cannot be skipped: a missing
7837 /// fixture, a decode error, a zero counter, a moved pixel patch or a
7838 /// changed full-frame fingerprint each fail by name. The fingerprint is
7839 /// FNV-1a (dependency-free, same rationale as the cdf-forwarding gate's).
7840 #[test]
7841 fn an_intrabc_tx4_leaf_chroma_inherits_the_luma_type_and_predicts_from_the_frame_copy() {
7842 const NAME: &str =
7843 "an_intrabc_tx4_leaf_chroma_inherits_the_luma_type_and_predicts_from_the_frame_copy";
7844 const FIXTURE_LEN: usize = 7173;
7845 const FIXTURE_FNV: u64 = 0x3a57_d075_5e4c_fe5b;
7846 const RAW_LEN: usize = 640 * 360 * 3 / 2;
7847 const RAW_FNV: u64 = 0xf271_df27_ce4d_ba66;
7848 // The 4x4 chroma patches at (184,4) -- the first surviving pixel fork
7849 // -- as the oracles (aomdec and ffmpeg agree) reconstruct them.
7850 const U_PATCH: [u16; 16] = [
7851 86, 116, 55, 110, 114, 114, 51, 83, 99, 121, 48, 114, 103, 117, 102, 67,
7852 ];
7853 const V_PATCH: [u16; 16] = [
7854 179, 158, 199, 105, 155, 158, 195, 147, 163, 153, 194, 108, 170, 148, 168, 172,
7855 ];
7856
7857 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7858 .join("fixtures/intrabc_tx4_chroma_kf.obu");
7859 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
7860 panic!(
7861 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
7862 which is a failure, not a skip",
7863 obu.display()
7864 )
7865 });
7866 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
7867 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
7868
7869 let _guard = lock_gate_counters();
7870 crate::decode::reset_leaf8_intrabc_hits();
7871 crate::decode::reset_intrabc_tx4_chroma_copy_hits();
7872 let frames = decode_stream(&stream).unwrap_or_else(|e| {
7873 panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}")
7874 });
7875 assert_eq!(frames.len(), 1, "{NAME}: frame count");
7876 let frame = &frames[0];
7877 assert_eq!((frame.width, frame.height), (640, 360), "{NAME}: dimensions");
7878
7879 // Non-vacuity, both halves: the leaf shape must be reached at all,
7880 // and its chroma route must have consulted the ARMED slot (pre-r2
7881 // this counter is 0 -- the arm never armed the slot).
7882 assert!(
7883 crate::decode::leaf8_intrabc_hits() > 0,
7884 "{NAME}: gate is vacuous -- no intrabc 8x8 leaf was decoded"
7885 );
7886 assert!(
7887 crate::decode::intrabc_tx4_chroma_copy_hits() > 0,
7888 "{NAME}: gate is vacuous -- no intrabc TX4-split leaf's chroma read consulted \
7889 the armed slot (class intrabc-chroma-tx-not-armed)"
7890 );
7891
7892 // The first surviving pixel fork: chroma 4x4 at (184,4). The wrong
7893 // wirings put flat intra-DC predictions or the wrong eob class here.
7894 let cw = frame.width / 2;
7895 let u_patch: Vec<u16> = (0..4)
7896 .flat_map(|dy| (0..4).map(move |dx| frame.u[(4 + dy) * cw + 184 + dx]))
7897 .collect();
7898 let v_patch: Vec<u16> = (0..4)
7899 .flat_map(|dy| (0..4).map(move |dx| frame.v[(4 + dy) * cw + 184 + dx]))
7900 .collect();
7901 assert_eq!(u_patch, U_PATCH, "{NAME}: U(184,4) patch moved");
7902 assert_eq!(v_patch, V_PATCH, "{NAME}: V(184,4) patch moved");
7903 // The unit the FRAME-COPY override specifically pins: chroma 4x4 at
7904 // (168,0) is an intrabc TX4-split leaf's chroma whose copy source is
7905 // a busy ramp region; without the `palette_uv_bufs` intrabc wrap the
7906 // read predicts flat intra-DC here (78k chroma bytes drift from this
7907 // unit alone), with it the copy reproduces the oracle exactly.
7908 const U_COPY_PATCH: [u16; 16] = [
7909 91, 91, 91, 91, 120, 120, 120, 120, 120, 120, 120, 120, 73, 102, 116, 116,
7910 ];
7911 const V_COPY_PATCH: [u16; 16] = [
7912 241, 241, 241, 241, 156, 156, 156, 156, 158, 158, 158, 158, 181, 163, 154, 154,
7913 ];
7914 let u_copy: Vec<u16> = (0..4)
7915 .flat_map(|dy| (0..4).map(move |dx| frame.u[dy * cw + 168 + dx]))
7916 .collect();
7917 let v_copy: Vec<u16> = (0..4)
7918 .flat_map(|dy| (0..4).map(move |dx| frame.v[dy * cw + 168 + dx]))
7919 .collect();
7920 assert_eq!(
7921 u_copy, U_COPY_PATCH,
7922 "{NAME}: U(168,0) patch moved -- the intrabc TX4 chroma read no longer \
7923 predicts from the frame copy (class intrabc-chroma-predicts-intra)"
7924 );
7925 assert_eq!(v_copy, V_COPY_PATCH, "{NAME}: V(168,0) patch moved");
7926
7927 // The whole frame, packed as the rawvideo byte stream the oracles
7928 // produce: any remaining byte anywhere in Y/U/V fails the gate.
7929 let mut raw = Vec::with_capacity(RAW_LEN);
7930 for plane in [&frame.y, &frame.u, &frame.v] {
7931 raw.extend(plane.iter().map(|&s| s as u8));
7932 }
7933 assert_eq!(raw.len(), RAW_LEN, "{NAME}: raw size");
7934 assert_eq!(fnv1a64(&raw), RAW_FNV, "{NAME}: full-frame fingerprint moved");
7935 }
7936
7937 /// lane-t900 r33, CENSUS for "a sub-8x8 leaf that uses intrabc".
7938 ///
7939 /// The `use_intrabc` symbol IS read at that reader for every sub-8x8 leaf
7940 /// of an `allow_intrabc` frame, so arrival is provable rather than
7941 /// assumed: the arms below force 4x4 leaves (`--min-partition-size=4`) on
7942 /// the exact-repetition screen content that keeps `allow_intrabc`, and the
7943 /// gate requires both counters -- `allow_intrabc` frames and decoded sub-8
7944 /// leaves -- to be non-zero before it reads anything into the refusal
7945 /// firing 0 times (class `gate-blind-to-feature`).
7946 #[test]
7947 fn a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal() {
7948 const NAME: &str = "a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal";
7949 if !have_ffmpeg() || !have_aomenc() {
7950 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
7951 return;
7952 }
7953 let (width, height) = (256usize, 192usize);
7954 let _guard = lock_gate_counters();
7955 let (mut premise_arms, mut reached, mut sub8_total, mut frames_compared) =
7956 (0u32, 0u32, 0usize, 0u32);
7957 for cq in ["30", "45"] {
7958 let arm = format!("sub8 cq={cq}");
7959 let stream = screen_intrabc_stream_with(
7960 "smptebars=size=128x96:rate=25",
7961 cq,
7962 "0",
7963 true,
7964 true,
7965 &["--min-partition-size=4"],
7966 );
7967 let (_, intrabc_frames) = sb128_and_intrabc_frames(&stream);
7968 if intrabc_frames > 0 {
7969 premise_arms += 1;
7970 }
7971 // No reset for this counter, so measure the delta (the gate lock
7972 // above keeps another gate's decode out of it).
7973 let sub8_before = crate::decode::sub8_split_hits();
7974 match decode_stream(&stream) {
7975 Ok(frames) => {
7976 let sub8 = crate::decode::sub8_split_hits() - sub8_before;
7977 sub8_total += sub8;
7978 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
7979 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
7980 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
7981 assert!(
7982 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
7983 "{NAME}: {arm} frame {i} does not match ffmpeg"
7984 );
7985 frames_compared += 1;
7986 }
7987 eprintln!(
7988 "{NAME}: {arm} intrabc_frames={intrabc_frames} sub8_leaves={sub8} \
7989 DECODED {} frame(s) exact",
7990 frames.len()
7991 );
7992 }
7993 Err(e) => {
7994 let msg = e.to_string();
7995 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
7996 if msg.contains("a sub-8x8 leaf that uses intrabc") {
7997 reached += 1;
7998 }
7999 sub8_total += crate::decode::sub8_split_hits() - sub8_before;
8000 eprintln!(
8001 "{NAME}: {arm} intrabc_frames={intrabc_frames} REFUSED: {e}"
8002 );
8003 }
8004 }
8005 }
8006 eprintln!(
8007 "{NAME}: {premise_arms}/2 arm(s) keep allow_intrabc, {sub8_total} sub-8 leaf/leaves \
8008 decoded, {reached} reach the refusal, {frames_compared} frame(s) exact"
8009 );
8010 assert!(
8011 premise_arms > 0,
8012 "{NAME}: census is vacuous -- no arm kept allow_intrabc, so the refusal's own \
8013 premise was never within reach"
8014 );
8015 assert!(
8016 sub8_total > 0,
8017 "{NAME}: census is vacuous -- no sub-8 leaf was decoded at all, so the \
8018 `use_intrabc` symbol this refusal guards was never read"
8019 );
8020 }
8021
8022 /// lane-t900 r33, CENSUS for "an intrabc block whose var-tx tree resolved
8023 /// to mixed leaf transform sizes" -- the residue lane-t900 r32 left when
8024 /// it lifted the intrabc `TX_MODE_SELECT` refusal.
8025 ///
8026 /// The tree is read in full; lane-av1-ibcvtx taught the luma reconstruct
8027 /// to walk the tree's own leaf list, so mixed trees now decode. This
8028 /// census sweeps the quantiser across the exact-repetition recipe that
8029 /// reaches the tree at all and requires the tree to actually be read
8030 /// (`intrabc_vartx_hits`); it stays as the premise witness for the lifted
8031 /// refusal (`reached` is 0 by construction now).
8032 #[test]
8033 fn an_intrabc_vartx_census_measures_the_mixed_leaf_refusal() {
8034 const NAME: &str = "an_intrabc_vartx_census_measures_the_mixed_leaf_refusal";
8035 if !have_ffmpeg() || !have_aomenc() {
8036 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
8037 return;
8038 }
8039 let (width, height) = (256usize, 192usize);
8040 let _guard = lock_gate_counters();
8041 let (mut vartx_total, mut reached, mut frames_compared) = (0usize, 0u32, 0u32);
8042 for cq in ["20", "30", "45", "55"] {
8043 let arm = format!("vartx cq={cq}");
8044 let stream =
8045 screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
8046 let (select, premise) = tx_select_and_intrabc_frames(&stream);
8047 crate::decode::reset_intrabc_vartx_hits();
8048 match decode_stream(&stream) {
8049 Ok(frames) => {
8050 let vartx = crate::decode::intrabc_vartx_hits();
8051 vartx_total += vartx;
8052 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
8053 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
8054 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
8055 assert!(
8056 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
8057 "{NAME}: {arm} frame {i} does not match ffmpeg"
8058 );
8059 frames_compared += 1;
8060 }
8061 eprintln!(
8062 "{NAME}: {arm} select={select} premise={premise} vartx_blocks={vartx} \
8063 DECODED {} frame(s) exact",
8064 frames.len()
8065 );
8066 }
8067 Err(e) => {
8068 let msg = e.to_string();
8069 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
8070 vartx_total += crate::decode::intrabc_vartx_hits();
8071 if msg.contains("mixed leaf transform sizes") {
8072 reached += 1;
8073 }
8074 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
8075 }
8076 }
8077 }
8078 eprintln!(
8079 "{NAME}: {vartx_total} intrabc block(s) read the var-tx tree, {reached} resolved to \
8080 mixed leaves, {frames_compared} frame(s) exact"
8081 );
8082 assert!(
8083 vartx_total > 0,
8084 "{NAME}: census is vacuous -- no intrabc block read the var-tx tree at all"
8085 );
8086 assert_eq!(
8087 reached, 0,
8088 "{NAME}: an intrabc var-tx tree was REFUSED -- the mixed-leaf refusal \
8089 is lifted (lane-av1-ibcvtx) and must stay gone"
8090 );
8091 }
8092
8093 /// lane-av1-ibcvtx, capability gate for the LIFTED refusal "an intrabc
8094 /// block whose var-tx tree resolved to mixed leaf transform sizes": the
8095 /// t900 r33 census recipe class (screen content, square partitions,
8096 /// tx-size search) reaches mixed trees the moment the canvas carries
8097 /// testsrc2's texture and blocks grow past 32 -- on the PRE-fix tree this
8098 /// exact stream refused by name on its first mixed tree (5 of the 12
8099 /// hunt recipes hit it, `lanes/av1ibcvtx.report.md`).
8100 ///
8101 /// The luma reconstruct walks the tree's own leaf list per leaf (libaom
8102 /// `decode_token_recon_block`), and the block's chroma inherits the
8103 /// co-located luma unit's coded tx type (`av1_get_tx_type`,
8104 /// `blockd.h:1278`) -- the inheritance the uniform multi-TU intrabc path
8105 /// was missing as well: symbol-aligned against an instrumented aomdec,
8106 /// the 640x360 cq20 witness desynced inside the FIRST chroma unit of its
8107 /// first mixed tree until the arm landed, then matched every subsequent
8108 /// read.
8109 ///
8110 /// NOT yet asserted: full pixel-exactness against ffmpeg. A second,
8111 /// PRE-EXISTING defect that is not this refusal -- a NON-intrabc intra
8112 /// block (R5 witness: mi (32,32), 64x64, uniform 4x TX_32X32 tree, every
8113 /// coefficient all_zero, reads symbol-identical to aomdec) mispredicts
8114 /// isolated samples on testsrc2 content (first divergence px (128,296)
8115 /// of the 640x360 cq20 recipe) and cascades over roughly a third of the
8116 /// frame. It is pinned in `lanes/av1ibcvtx.report.md`; when it lands,
8117 /// tighten this gate to a full pixel-exact assert.
8118 #[test]
8119 fn a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal() {
8120 const NAME: &str = "a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal";
8121 if !have_ffmpeg() || !have_aomenc() {
8122 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
8123 return;
8124 }
8125 let (width, height) = (640usize, 360usize);
8126 let _guard = lock_gate_counters();
8127 let stream = screen_intrabc_stream_with(
8128 "testsrc2=size=320x180:rate=25",
8129 "30",
8130 "1",
8131 true,
8132 true,
8133 &["--max-partition-size=64"],
8134 );
8135 let (select, premise) = tx_select_and_intrabc_frames(&stream);
8136 assert!(
8137 premise > 0,
8138 "{NAME}: vacuous -- no frame keeps allow_intrabc under TxMode::Select, \
8139 so the refusal's premise was never within reach (select={select})"
8140 );
8141 crate::decode::reset_intrabc_vartx_hits();
8142 crate::decode::reset_intrabc_vartx_mixed_leaves_hits();
8143 match decode_stream(&stream) {
8144 Ok(frames) => {
8145 let trees = crate::decode::intrabc_vartx_hits();
8146 let mixed = crate::decode::intrabc_vartx_mixed_leaves_hits();
8147 assert!(
8148 trees > 0 && mixed > 0,
8149 "{NAME}: vacuous -- {trees} var-tx tree(s), {mixed} mixed: the \
8150 capability this gate pins was never exercised"
8151 );
8152 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
8153 assert_eq!(frames.len(), theirs.len(), "{NAME}: frame count");
8154 let mut mismatched = 0usize;
8155 for (ours, ref_frame) in frames.iter().zip(theirs.iter()) {
8156 mismatched += ours
8157 .y
8158 .iter()
8159 .zip(ref_frame.y.iter())
8160 .filter(|(x, y)| x != y)
8161 .count();
8162 mismatched += ours
8163 .u
8164 .iter()
8165 .zip(ref_frame.u.iter())
8166 .filter(|(x, y)| x != y)
8167 .count();
8168 mismatched += ours
8169 .v
8170 .iter()
8171 .zip(ref_frame.v.iter())
8172 .filter(|(x, y)| x != y)
8173 .count();
8174 }
8175 eprintln!(
8176 "{NAME}: select={select} premise={premise} vartx_blocks={trees} \
8177 mixed_trees={mixed}, {mismatched} sample(s) differ from ffmpeg \
8178 (the pinned non-intrabc second defect, see the doc comment)"
8179 );
8180 }
8181 Err(e) => panic!(
8182 "{NAME}: the mixed-leaf refusal is lifted (lane-av1-ibcvtx); the \
8183 witness stream must decode, not stop: {e}"
8184 ),
8185 }
8186 }
8187
8188 /// How many frames of `stream` carry `tx_mode == Select`, and how many of
8189 /// those also keep `allow_intrabc` -- the frame-level premise of the
8190 /// refusal "an intrabc block under TxMode::Select", read out of the
8191 /// headers rather than assumed from the flags handed to the encoder
8192 /// (libaom clears `allow_intrabc` again when no block picked it,
8193 /// encodeframe.c:2336).
8194 fn tx_select_and_intrabc_frames(stream: &[u8]) -> (u32, u32) {
8195 let (mut select, mut premise) = (0u32, 0u32);
8196 let mut p = Av1Parser::new();
8197 let mut pos = 0usize;
8198 while pos < stream.len() {
8199 let obu = p.parse_obu(&stream[pos..]).expect("parse");
8200 pos += obu.total_size;
8201 let header = match &obu.kind {
8202 ObuKind::Frame(h, _) => Some(&**h),
8203 ObuKind::FrameHeader(h) => Some(&**h),
8204 _ => None,
8205 };
8206 if let Some(h) = header {
8207 if h.tx_mode == TxMode::Select {
8208 select += 1;
8209 if h.allow_intrabc {
8210 premise += 1;
8211 }
8212 }
8213 }
8214 }
8215 (select, premise)
8216 }
8217
8218 /// lane-t900 r31, CENSUS for the refusal "an intrabc block under
8219 /// TxMode::Select" -- which this gate DISPROVES as an "no encoder writes
8220 /// one" claim and pins as a real capability gap instead.
8221 ///
8222 /// The premise is reachable by the SPEC: `tx_mode` (5.9.21) is forced to
8223 /// `ONLY_4X4` only under `CodedLossless`, while `allow_intrabc` (5.9.2)
8224 /// needs `allow_screen_content_tools` at unscaled resolution -- two
8225 /// independent conditions. libaom leaves it open too: `select_tx_mode`
8226 /// (encodeframe.c:2355) never consults `allow_intrabc`, and the only
8227 /// downgrade to `TX_MODE_LARGEST` is `txb_split_count == 0`
8228 /// (encodeframe.c:2690).
8229 ///
8230 /// The measurement over 14 real `--tune-content=screen --enable-intrabc=1`
8231 /// recipes:
8232 ///
8233 /// * the 10 non-repeating arms never present the premise at all -- with
8234 /// `--enable-tx-size-search=1` the frame codes `TX_MODE_SELECT` but RD
8235 /// never picks intrabc, so libaom clears `allow_intrabc` again; with
8236 /// `=0` intrabc IS used and the frame is `TX_MODE_LARGEST`. That
8237 /// correlation, not any rule, is why earlier rounds never saw this;
8238 /// * the four EXACT-REPETITION arms (a 2x2 tiling of one 128x96 bar
8239 /// pattern) all code `allow_intrabc && tx_mode == Select`. Two of them
8240 /// stop on the older rect-strip intrabc refusal (the shape that fires
8241 /// first, class `refusal-hides-a-defect`), and the two with rect/1:4
8242 /// partitions off put intrabc on a SQUARE block: `cq=30` reaches THIS
8243 /// refusal by name, `cq=45`'s intrabc blocks are all `skip` and decode
8244 /// pixel-exact against ffmpeg.
8245 ///
8246 /// So the refusal is correct and load-bearing, exactly one arm reaches it,
8247 /// and the lift it names has a waiting witness:
8248 /// [`an_intrabc_block_under_tx_mode_select_decodes_pixel_exact`] (ignored
8249 /// until the intra path reads the inter var-tx tree for an intrabc block).
8250 #[test]
8251 fn an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal() {
8252 const NAME: &str =
8253 "an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal";
8254 if !have_ffmpeg() {
8255 eprintln!("SKIP {NAME}: no ffmpeg");
8256 return;
8257 }
8258 if !have_aomenc() {
8259 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8260 return;
8261 }
8262 const TS: &str = "testsrc2=s=256x192:r=25";
8263 const SB: &str = "smptebars=size=256x192:rate=25";
8264 const PB: &str = "pal75bars=size=256x192:rate=25";
8265 const TILE: &str = "smptebars=size=128x96:rate=25";
8266 let (width, height) = (256usize, 192usize);
8267 // (arm, source, cq, tx-size-search, tiled, square_only)
8268 let arms: [(&str, &str, &str, &str, bool, bool); 14] = [
8269 ("smptebars-cq40-txs1", SB, "40", "1", false, false),
8270 ("smptebars-cq45-txs1", SB, "45", "1", false, false),
8271 ("smptebars-cq55-txs1", SB, "55", "1", false, false),
8272 ("smptebars-cq63-txs1", SB, "63", "1", false, false),
8273 ("pal75bars-cq40-txs1", PB, "40", "1", false, false),
8274 ("pal75bars-cq55-txs1", PB, "55", "1", false, false),
8275 ("testsrc2-cq50-txs1", TS, "50", "1", false, false),
8276 ("testsrc2-cq63-txs1", TS, "63", "1", false, false),
8277 ("smptebars-cq45-txs0", SB, "45", "0", false, false),
8278 ("pal75bars-cq45-txs0", PB, "45", "0", false, false),
8279 ("tiled-cq30-txs1", TILE, "30", "1", true, false),
8280 ("tiled-cq45-txs1", TILE, "45", "1", true, false),
8281 ("tiled-square-cq30-txs1", TILE, "30", "1", true, true),
8282 // lane-t900 r32: both square arms are now ORDINARY census members
8283 // -- cq30 (unskipped intrabc, the inter var-tx tree) and cq45
8284 // (all-skip intrabc, `maxRectTxSize` with no symbol at all) decode
8285 // pixel-exact, so nothing here reaches the lifted refusal.
8286 ("tiled-square-cq45-txs1", TILE, "45", "1", true, true),
8287 ];
8288 let (mut select_arms, mut premise_arms, mut intrabc_arms, mut blocks_total) =
8289 (0u32, 0u32, 0u32, 0usize);
8290 let (mut refused_tx_select, mut frames_compared) = (0u32, 0usize);
8291 for (arm, src, cq, txs, tiled, square_only) in &arms {
8292 let stream = screen_intrabc_stream(src, cq, txs, *tiled, *square_only);
8293 let (select, premise) = tx_select_and_intrabc_frames(&stream);
8294 if select > 0 {
8295 select_arms += 1;
8296 }
8297 if premise > 0 {
8298 premise_arms += 1;
8299 }
8300 crate::decode::reset_intrabc_hits();
8301 let decoded = decode_stream(&stream);
8302 let blocks = crate::decode::intrabc_hits();
8303 blocks_total += blocks;
8304 if blocks > 0 {
8305 intrabc_arms += 1;
8306 }
8307 match decoded {
8308 Ok(frames) => {
8309 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
8310 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
8311 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
8312 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
8313 assert!(
8314 ours.y == ref_frame.y
8315 && ours.u == ref_frame.u
8316 && ours.v == ref_frame.v,
8317 "{NAME}: {arm} frame {i} does not match ffmpeg"
8318 );
8319 frames_compared += 1;
8320 }
8321 eprintln!(
8322 "{NAME}: {arm} select={select} premise={premise} {blocks} intrabc \
8323 block(s), {} frame(s) exact",
8324 frames.len()
8325 );
8326 }
8327 Err(e) => {
8328 let msg = e.to_string();
8329 assert!(msg.contains("unsupported"), "{NAME}: {arm} decode failed: {e}");
8330 if msg.contains("an intrabc block under TxMode::Select") {
8331 refused_tx_select += 1;
8332 assert!(
8333 premise > 0,
8334 "{NAME}: {arm} reached the TxMode::Select intrabc refusal in a \
8335 frame that codes no such header"
8336 );
8337 } else {
8338 assert!(
8339 msg.contains("intra block copy"),
8340 "{NAME}: {arm} refused for an unrelated reason: {e}"
8341 );
8342 }
8343 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
8344 }
8345 }
8346 }
8347 eprintln!(
8348 "{NAME}: {select_arms}/{n} arm(s) code a TX_MODE_SELECT frame, {premise_arms} of \
8349 those keep allow_intrabc, {intrabc_arms} arm(s) decode an intrabc block \
8350 ({blocks_total} total), {refused_tx_select} reach the refusal, \
8351 {frames_compared} frame(s) compared exact",
8352 n = arms.len()
8353 );
8354 assert!(
8355 intrabc_arms > 0 && blocks_total > 0,
8356 "{NAME}: census is vacuous -- no arm decoded an intrabc block at all"
8357 );
8358 assert!(
8359 premise_arms > 0,
8360 "{NAME}: census is vacuous -- no arm coded a frame with both allow_intrabc and \
8361 tx_mode == Select, so the refusal's own premise was never within reach"
8362 );
8363 assert_eq!(
8364 refused_tx_select, 0,
8365 "{NAME}: lane-t900 r32 lifted this refusal -- an intrabc block now reads the \
8366 INTER tx-size syntax, so no arm may reach it again"
8367 );
8368 assert!(frames_compared > 0, "{NAME}: no frame was compared pixel-exact");
8369 }
8370
8371 /// lane-t900 r31, the WAITING witness for the capability
8372 /// [`an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal`]
8373 /// pins: a real aomenc screen key frame whose intrabc block sits on a
8374 /// square block of a `TX_MODE_SELECT` frame, unskipped. libaom's
8375 /// `parse_decode_block` treats an intrabc block as `inter_block_tx`, so
8376 /// its transform size comes off the inter var-tx partition tree
8377 /// (`read_var_tx_size`), which this decoder reads nowhere on the intra
8378 /// path -- reading the intra `tx_depth` symbol instead desyncs.
8379 ///
8380 /// lane-t900 r32 closed both arms. A SKIPPED intrabc block reads no
8381 /// tx-size symbol at all (`allowSelect = !skip || !is_inter`, false for an
8382 /// intrabc block since libaom's `is_inter_block` counts one); reading the
8383 /// intra `tx_depth` for it consumed a symbol libaom never wrote and
8384 /// desynced the tile a whole block later, at the superblock corner
8385 /// (192,64) (class `equal-range-means-unread`). An UNSKIPPED one reads the
8386 /// inter var-tx tree (`read_var_tx_size`). r31's note that cq=45's blocks
8387 /// are all `skip` was read off that desynced decode: with the tx-size read
8388 /// corrected, cq=45 carries 3 unskipped intrabc blocks of 10 and cq=30
8389 /// carries 1 of 16, so both arms exercise both sides of the split.
8390 #[test]
8391 fn an_intrabc_block_under_tx_mode_select_decodes_pixel_exact() {
8392 const NAME: &str = "an_intrabc_block_under_tx_mode_select_decodes_pixel_exact";
8393 if !have_ffmpeg() || !have_aomenc() {
8394 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
8395 return;
8396 }
8397 let (width, height) = (256usize, 192usize);
8398 for cq in ["30", "45"] {
8399 let stream = screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
8400 let (select, premise) = tx_select_and_intrabc_frames(&stream);
8401 assert!(
8402 select > 0 && premise > 0,
8403 "{NAME}: cq={cq} no longer codes allow_intrabc under TX_MODE_SELECT \
8404 (select={select} premise={premise})"
8405 );
8406 crate::decode::reset_intrabc_hits();
8407 crate::decode::reset_intrabc_vartx_hits();
8408 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: cq={cq}: {e}"));
8409 let (blocks, vartx) =
8410 (crate::decode::intrabc_hits(), crate::decode::intrabc_vartx_hits());
8411 assert!(blocks > 0, "{NAME}: cq={cq} no longer decodes an intrabc block");
8412 // r31 recorded cq=45's intrabc blocks as ALL skip; that was read
8413 // off the desynced decode. With the tx-size read corrected both
8414 // arms carry unskipped ones (cq30 1 of 16, cq45 3 of 10), so both
8415 // must reach the var-tx tree or the gate is blind to the lift
8416 // (class `gate-blind-to-feature`).
8417 assert!(
8418 vartx > 0,
8419 "{NAME}: cq={cq} no longer reads the inter var-tx tree for an intrabc block"
8420 );
8421 eprintln!("{NAME}: cq={cq} {blocks} intrabc block(s), {vartx} through var-tx");
8422 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
8423 assert_eq!(frames.len(), theirs.len(), "{NAME}: cq={cq} frame count");
8424 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
8425 assert!(
8426 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
8427 "{NAME}: cq={cq} frame {i} does not match ffmpeg"
8428 );
8429 }
8430 }
8431 }
8432
8433 /// lane-av1txr: a real `aomenc --cdf-update-mode=0` stream (spec 5.9.2
8434 /// `disable_cdf_update`) decodes SAMPLE-EXACT. The read that was missing:
8435 /// `stream.rs` never threaded the header bit, so the tile readers adapted
8436 /// every symbol of a frame the encoder coded against fixed tables -- the
8437 /// stream desynced at its first multi-symbol block and the pixels differed
8438 /// from byte 6 (`EC_PROBE_OUT` vs `ffmpeg -pix_fmt yuv420p`, measured
8439 /// 2026-09-20). The msac unit gate
8440 /// (`a_reader_told_not_to_adapt_matches_a_non_adapting_writer`) pins the
8441 /// mechanism; this one pins the wiring end to end.
8442 #[test]
8443 fn a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact() {
8444 const NAME: &str = "a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact";
8445 if !have_ffmpeg() || !have_aomenc() {
8446 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
8447 return;
8448 }
8449 let (width, height) = (256usize, 192usize);
8450 let stream = screen_intrabc_stream_with(
8451 "testsrc2=size=256x192:rate=25",
8452 "45",
8453 "1",
8454 false,
8455 true,
8456 &["--cdf-update-mode=0", "--limit=3"],
8457 );
8458 // Non-vacuity: the fixture must really code the bit on every frame.
8459 let mut parser = Av1Parser::new();
8460 let mut pos = 0usize;
8461 let mut headers = 0usize;
8462 while pos < stream.len() {
8463 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
8464 break;
8465 };
8466 pos += obu.total_size.max(1);
8467 let header = match &obu.kind {
8468 ObuKind::Frame(h, _) | ObuKind::FrameHeader(h) => h,
8469 _ => continue,
8470 };
8471 assert!(
8472 header.disable_cdf_update,
8473 "{NAME}: frame {headers} does not carry disable_cdf_update -- aomenc ignored \
8474 --cdf-update-mode=0"
8475 );
8476 headers += 1;
8477 }
8478 assert!(headers >= 3, "{NAME}: only {headers} frame headers in the fixture");
8479 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {e}"));
8480 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
8481 assert_eq!(frames.len(), theirs.len(), "{NAME}: frame count");
8482 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
8483 assert!(
8484 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
8485 "{NAME}: frame {i} does not match ffmpeg"
8486 );
8487 }
8488 eprintln!("{NAME}: {headers} disable_cdf_update frame headers, all frames sample-exact");
8489 }
8490
8491 /// lane-kf900 r4, the gate for the two lifted palette refusals ("a 1:4
8492 /// rect strip that actually uses a palette (reconstruction is not ported
8493 /// at this shape)" and "a palette block on a HORZ/VERT intra strip below
8494 /// 16x16 (reconstruction not ported)"): real `aomenc` streams that put a
8495 /// palette on a RECT strip, decoded whole-frame pixel-exact against
8496 /// ffmpeg's own decode of the identical bytes, at 8 AND 10 bit.
8497 ///
8498 /// Arm 0 is the stream lane-kf900 r3 pinned and stopped on -- `testsrc2`
8499 /// 256x192, `--cq-level=59 --cpu-used=0 --min-partition-size=8
8500 /// --enable-rect-partitions=1 --enable-tx-size-search=1`, md5
8501 /// `e5f033d8fe34e4418d8cca3ac9d2b595` at 10 bit. Arms 1-2 force the shape
8502 /// on screen-like content with `--tune-content=screen --enable-palette=1
8503 /// --enable-1to4-partitions=1`.
8504 ///
8505 /// An attempt whose decode never hit a rect-strip palette block proves
8506 /// nothing about the lift, so it is counted OUT OF SCOPE rather than
8507 /// silently passing -- but a mismatch on one is still a failure
8508 /// (`out_of_scope_mismatch == 0`), and at least one attempt must fire the
8509 /// counter or the gate is vacuous.
8510 #[test]
8511 fn a_real_aomenc_rect_strip_palette_decodes_pixel_exact() {
8512 const NAME: &str = "a_real_aomenc_rect_strip_palette_decodes_pixel_exact";
8513 if !have_ffmpeg() {
8514 eprintln!("SKIP {NAME}: no ffmpeg");
8515 return;
8516 }
8517 if !have_aomenc() {
8518 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8519 return;
8520 }
8521 let (width, height) = (256usize, 192usize);
8522 let screen: &[&str] = &[
8523 "--tune-content=screen",
8524 "--enable-palette=1",
8525 "--enable-1to4-partitions=1",
8526 "--min-partition-size=8",
8527 ];
8528 // lane-kf900 r6: arms 3-4 are the palette + `--enable-tx-size-search=1`
8529 // shape whose neighbour palette lookup was SUB-granular -- a 16x8 strip
8530 // pair shares one 16px cell, so strip 1 read strip 0's palette size and
8531 // the colour cache came out short. Both were whole-frame wrong before
8532 // the mi-granular fix (`$HOME/.cache/kf900-r6/sweep.log`: smptebars
8533 // cq40/cq55 txs=1 pal=1 = DIFF).
8534 let screen_txs: &[&str] = &[
8535 "--tune-content=screen",
8536 "--enable-palette=1",
8537 "--enable-1to4-partitions=1",
8538 "--min-partition-size=8",
8539 "--max-partition-size=32",
8540 "--sb-size=64",
8541 "--enable-intrabc=1",
8542 "--enable-tx-size-search=1",
8543 ];
8544 let cq40: Vec<&str> = screen_txs.iter().copied().chain(["--cq-level=40"]).collect();
8545 let cq55: Vec<&str> = screen_txs.iter().copied().chain(["--cq-level=55"]).collect();
8546 let arms: [(&str, String, &[&str]); 5] = [
8547 ("testsrc2-pinned", "testsrc2=s=256x192:r=25".to_string(), &[]),
8548 ("testsrc2-screen", "testsrc2=s=256x192:r=25".to_string(), screen),
8549 ("smptebars-screen", "smptebars=size=256x192:rate=25".to_string(), screen),
8550 ("smptebars-screen-txs-cq40", "smptebars=size=256x192:rate=25".to_string(), &cq40),
8551 ("smptebars-screen-txs-cq55", "smptebars=size=256x192:rate=25".to_string(), &cq55),
8552 ];
8553 let (mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32, 0u32);
8554 let mut refused = 0u32;
8555 let mut fired_at_depth = [0u32; 2];
8556 let mut frames_compared = 0usize;
8557 for (arm, src, extra) in &arms {
8558 for depth in [8usize, 10] {
8559 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
8560 let render = || {
8561 let out = Command::new("ffmpeg")
8562 .args([
8563 "-v", "error", "-f", "lavfi", "-i", src.as_str(), "-t", "0.2",
8564 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
8565 ])
8566 .stdin(Stdio::null())
8567 .stdout(Stdio::piped())
8568 .stderr(Stdio::piped())
8569 .output()
8570 .expect("ffmpeg failed to run");
8571 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
8572 out.stdout
8573 };
8574 let y4m_a = render();
8575 let y4m_b = render();
8576 assert_eq!(
8577 y4m_a, y4m_b,
8578 "{NAME}: {arm} must render byte-identical across two runs at {depth}-bit"
8579 );
8580 let y4m = y4m_a;
8581 let depth_arg = format!("--bit-depth={depth}");
8582 let in_depth_arg = format!("--input-bit-depth={depth}");
8583 let out = run_with_stdin(Command::new(aomenc_path())
8584 .args(["--codec=av1"])
8585 .args([&depth_arg, &in_depth_arg])
8586 .args([
8587 "--passes=1",
8588 "--end-usage=q",
8589 "--cq-level=59",
8590 "--cpu-used=0",
8591 "--lag-in-frames=0",
8592 "--kf-max-dist=1",
8593 "--limit=1",
8594 "--threads=1",
8595 "--tile-columns=0",
8596 "--enable-tx-size-search=1",
8597 "--min-partition-size=8",
8598 "--enable-rect-partitions=1",
8599 ])
8600 // Per-arm overrides go AFTER the base recipe: aomenc keeps
8601 // the LAST occurrence of a repeated flag.
8602 .args(*extra)
8603 // The 8-bit twin of the pinned recipe picks a 128-root
8604 // HORZ partition, which this decoder still refuses by name
8605 // ("a 128x128 superblock HORZ/VERT or AB partition") --
8606 // an open refusal of another lane, unrelated to palette.
8607 // Pinning the superblock to 64 keeps the 8-bit arm on the
8608 // shape this gate is about; the 10-bit arms are the
8609 // untouched pinned recipe.
8610 .args(if depth == 8 { &["--sb-size=64"][..] } else { &[][..] })
8611 .args(["--obu", "-o", "-", "-"]), &y4m);
8612 assert!(
8613 out.status.success(),
8614 "{NAME}: aomenc refused {arm} at {depth}-bit: {}",
8615 String::from_utf8_lossy(&out.stderr)
8616 );
8617 let stream = out.stdout;
8618 let before = decode::rect4_palette_hits();
8619 let frames = match decode_stream(&stream) {
8620 Ok(frames) => frames,
8621 // A NAMED refusal is another lane's open shape (here: a
8622 // palette on an 8x8 SQUARE leaf, still out of scope), never
8623 // a pass -- the attempt is counted out of scope and the
8624 // per-depth firing assert below keeps the gate honest.
8625 Err(e) if e.to_string().contains("unsupported") => {
8626 eprintln!("{NAME}: {arm} {depth}-bit REFUSED: {e}");
8627 refused += 1;
8628 continue;
8629 }
8630 Err(e) => panic!("{NAME}: decode failed on {arm} at {depth}-bit: {e}"),
8631 };
8632 let fired = decode::rect4_palette_hits() - before;
8633 let ffmpeg_frames = if depth == 10 {
8634 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
8635 } else {
8636 ffmpeg_decode_sequence(&stream, width, height, frames.len())
8637 };
8638 assert_eq!(
8639 frames.len(),
8640 ffmpeg_frames.len(),
8641 "{NAME}: {arm} at {depth}-bit -- frame count"
8642 );
8643 assert!(!frames.is_empty(), "{NAME}: {arm} at {depth}-bit decoded no frame");
8644 // EVERY decode-order frame, all three planes.
8645 let mut exact = true;
8646 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
8647 if ours.y != theirs.y || ours.u != theirs.u || ours.v != theirs.v {
8648 exact = false;
8649 eprintln!("{NAME}: {arm} {depth}-bit frame {i} differs");
8650 }
8651 frames_compared += 1;
8652 }
8653 if fired > 0 {
8654 fired_arms += 1;
8655 fired_at_depth[usize::from(depth == 10)] += 1;
8656 assert!(
8657 exact,
8658 "{NAME}: {arm} at {depth}-bit has {fired} rect-strip palette block(s) \
8659 and does NOT decode pixel-exact"
8660 );
8661 } else {
8662 out_of_scope += 1;
8663 if !exact {
8664 out_of_scope_mismatch += 1;
8665 }
8666 }
8667 }
8668 }
8669 eprintln!(
8670 "{NAME}: {fired_arms} attempt(s) with a rect-strip palette block, \
8671 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
8672 {refused} refused, {frames_compared} frames compared, \
8673 fired 8-bit={} 10-bit={}",
8674 fired_at_depth[0], fired_at_depth[1]
8675 );
8676 // MEASURED 2026-09-02, every 8-bit attempt of these recipes: aomenc
8677 // puts its palettes on SQUARE blocks at 8 bit and every 8-bit stream
8678 // that reaches a rect strip with one lands on a palette shape still
8679 // out of scope (8x8 square leaf, or a 64x32/32x64 superblock strip
8680 // with a real transform). So the 8-bit arms here prove the DECODE
8681 // path, not the lift -- `fired_at_depth[0] == 0` is a known, reported
8682 // coverage gap and not a silent pass: the counter is printed.
8683 assert!(
8684 fired_at_depth[1] > 0,
8685 "{NAME}: no attempt put a palette on a rect strip \
8686 (8-bit={}, 10-bit={}) -- gate is vacuous",
8687 fired_at_depth[0],
8688 fired_at_depth[1]
8689 );
8690 assert!(fired_arms > 0, "{NAME}: gate is vacuous");
8691 assert_eq!(
8692 out_of_scope_mismatch, 0,
8693 "{NAME}: {out_of_scope_mismatch} attempt(s) without a rect-strip palette block \
8694 still mismatched -- an unrelated defect, not a SKIP"
8695 );
8696 }
8697
8698 /// lane-hbd r5: a real `aomenc --bit-depth=10` stream, decoded through
8699 /// this crate's own 10-bit planes (`Picture` widened to `u16` in an
8700 /// earlier round) and checked pixel-exact against ffmpeg's own decode of
8701 /// the identical bytes via [`ffmpeg_decode_sequence_10bit`]. Confirms
8702 /// (hard-asserts, not just trusts) the sequence header this stream
8703 /// actually parses to says `bit_depth == 10` before trusting any pixel
8704 /// match -- a stream that silently fell back to 8-bit would still
8705 /// "match" trivially.
8706 // -------------------------------------------------------------------
8707 // lane-av112bit: the 12-bit gate battery. The blanket refusal is lifted
8708 // for what these gates witness byte-exact against ffmpeg on real
8709 // `aomenc --bit-depth=12 --profile=2` streams: the full intra stack,
8710 // dequant/transforms at the 12-bit dequant tables, deblock, CDEF, loop
8711 // restoration (Wiener AND SGR), and translational subpel motion
8712 // compensation through the bit-depth-parameterised `round_0`/`round_1`
8713 // (libaom `convolve.h:81..86`). Everything else stays refused by name:
8714 // warp and screen content tools (palette/intrabc) at the frame level,
8715 // each with its own real-stream refusal gate below.
8716 // lane-av112bitc: compound joined the witnessed set (refusal gate became
8717 // the six-frame compound witness).
8718 // lane-av112bitg: film grain joined the witnessed set (refusal gate became
8719 // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
8720 // -------------------------------------------------------------------
8721
8722 /// The 12-bit witness source, byte-identical to the lane's committed
8723 /// fixture recipe: 160x128 C420p12, a gradient + fine-texture base with a
8724 /// 24x20 box that travels 1.25 px/frame horizontally and 0.75 px/frame
8725 /// vertically with linear edge coverage -- sub-pixel true motion, so an
8726 /// inter frame over it cannot be coded whole-pel-only.
8727 fn y4m_12bit_subpel_source(frames: usize) -> Vec<u8> {
8728 const W: usize = 160;
8729 const H: usize = 128;
8730 let cov = |a: f64, b: f64, i: i64| (b.min(i as f64 + 1.0) - a.max(i as f64)).max(0.0);
8731 let mut y4m = format!("YUV4MPEG2 W{W} H{H} F30:1 Ip A1:1 C420p12\n").into_bytes();
8732 for t in 0..frames {
8733 let (ax, ay) = (12.0 + 1.25 * t as f64, 10.0 + 0.75 * t as f64);
8734 let (bx, by) = (ax + 24.0, ay + 20.0);
8735 y4m.extend_from_slice(b"FRAME\n");
8736 for j in 0..H as i64 {
8737 for i in 0..W as i64 {
8738 let g = (i * 190) / W as i64 + (j * 150) / H as i64;
8739 let mut v = (g * 12
8740 + if (i * 5 + j * 3 + t as i64) % 7 < 3 { 90 } else { 220 }
8741 + if (60..110).contains(&i) && (70..110).contains(&j) { 640 } else { 0 })
8742 as f64;
8743 let c = cov(ax, bx, i) * cov(ay, by, j);
8744 if c > 0.0 {
8745 v = v * (1.0 - c) + 3500.0 * c;
8746 }
8747 y4m.extend_from_slice(&(v.min(4095.0) as u16).to_le_bytes());
8748 }
8749 }
8750 for (base, fx) in [(1900usize, 0usize), (2100, 1)] {
8751 for j in 0..H / 2 {
8752 for i in 0..W / 2 {
8753 let v = if fx == 0 {
8754 base + (((i / 5 + t * 2) % 7) * 120 + (j * 60) / H)
8755 } else {
8756 base + (((j / 4 + t) % 5) * 140 + (i * 40) / W)
8757 };
8758 y4m.extend_from_slice(&(v.min(4095) as u16).to_le_bytes());
8759 }
8760 }
8761 }
8762 }
8763 y4m
8764 }
8765
8766 /// The 12-bit coding recipe shared by the witness gates (cpu-used=0 so
8767 /// every search runs; explicit CDEF/restoration ON). Warp/global-motion
8768 /// are deliberately NOT spelled here: this aomenc honours the LAST
8769 /// occurrence of these flags (measured), so a base pin plus an override
8770 /// would silently take the base value -- each gate spells what it needs
8771 /// exactly once.
8772 fn encode_12bit(y4m: &[u8], frames: usize, extra: &[&str]) -> Vec<u8> {
8773 let limit = format!("--limit={frames}");
8774 let mut args: Vec<&str> = vec![
8775 "--codec=av1",
8776 "--profile=2",
8777 "--passes=1",
8778 "--end-usage=q",
8779 "--cq-level=20",
8780 "--cpu-used=0",
8781 "--threads=1",
8782 "--row-mt=0",
8783 "--sb-size=64",
8784 "--lag-in-frames=0",
8785 "--auto-alt-ref=0",
8786 "--kf-max-dist=1000",
8787 "--input-bit-depth=12",
8788 "--bit-depth=12",
8789 "--enable-cdef=1",
8790 "--enable-restoration=1",
8791 "--obu",
8792 "-o",
8793 "-",
8794 "-",
8795 &limit,
8796 ];
8797 // AOMENC FLAG PRECEDENCE (COMMON): aomenc keeps the FIRST occurrence
8798 // of a flag, so the per-arm override goes BEFORE the base list.
8799 args.splice(1..1, extra.iter().copied());
8800 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m);
8801 assert!(
8802 out.status.success(),
8803 "aomenc refused the 12-bit fixture: {}",
8804 String::from_utf8_lossy(&out.stderr)
8805 );
8806 out.stdout
8807 }
8808
8809 /// Asserts the stream's sequence header really says 12-bit before any
8810 /// pixel comparison is trusted.
8811 fn assert_12bit_sequence_header(stream: &[u8], name: &str) {
8812 let mut probe = Av1Parser::new();
8813 let mut pos = 0usize;
8814 while pos < stream.len() && probe.sequence_header().is_none() {
8815 let obu = probe.parse_obu(&stream[pos..]).unwrap();
8816 pos += obu.total_size;
8817 }
8818 let seq = probe.sequence_header().expect("stream has a sequence header OBU");
8819 assert_eq!(
8820 seq.color_config.bit_depth, 12,
8821 "{name}: aomenc did not actually write a 12-bit sequence header"
8822 );
8823 }
8824
8825 fn ffmpeg_decode_sequence_12bit(stream: &[u8], width: usize, height: usize, frames: usize) -> Vec<Pic> {
8826 let out = run_with_stdin(
8827 Command::new("ffmpeg").args([
8828 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt",
8829 "yuv420p12le", "-",
8830 ]),
8831 stream,
8832 );
8833 assert!(
8834 out.status.success(),
8835 "ffmpeg refused the 12-bit stream: {}",
8836 String::from_utf8_lossy(&out.stderr)
8837 );
8838 let (luma, chroma) = (width * height, width * height / 4);
8839 let frame_bytes = (luma + 2 * chroma) * 2;
8840 assert_eq!(
8841 out.stdout.len(),
8842 frame_bytes * frames,
8843 "expected {frames} 4:2:0 12-bit frames, ffmpeg said: {}",
8844 String::from_utf8_lossy(&out.stderr)
8845 );
8846 fn le16(bytes: &[u8]) -> Vec<u16> {
8847 bytes
8848 .chunks_exact(2)
8849 .map(|c| u16::from_le_bytes([c[0], c[1]]))
8850 .collect()
8851 }
8852 (0..frames)
8853 .map(|i| {
8854 let base = i * frame_bytes;
8855 Pic {
8856 width,
8857 height,
8858 y: le16(&out.stdout[base..base + luma * 2]),
8859 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
8860 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
8861 }
8862 })
8863 .collect()
8864 }
8865
8866 /// The 12-bit KEY witness: CDEF and loop restoration ON, grain off.
8867 /// Byte-exact against ffmpeg, and the 12-bit-sensitive pixel paths hard-
8868 /// assert fired: a CDEF index literal read (bits > 0) and at least one
8869 /// Wiener or SGR restoration unit. Gauntlet for the parameterised
8870 /// rounding sites: MC/Wiener round pairs, `coeff_shift = bd - 8` CDEF,
8871 /// the 12-bit dequant tables, bd-scaled SGR box sums.
8872 #[test]
8873 fn a_real_aomenc_12bit_stream_decodes_pixel_exact() {
8874 const NAME: &str = "a_real_aomenc_12bit_stream_decodes_pixel_exact";
8875 let _gate_lock = lock_gate_counters();
8876 if !have_ffmpeg() {
8877 eprintln!("SKIP {NAME}: no ffmpeg");
8878 return;
8879 }
8880 if !have_aomenc() {
8881 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8882 return;
8883 }
8884 let y4m = y4m_12bit_subpel_source(1);
8885 let stream = encode_12bit(
8886 &y4m,
8887 1,
8888 &["--enable-warped-motion=0", "--enable-global-motion=0"],
8889 );
8890 assert_12bit_sequence_header(&stream, NAME);
8891 let before_cdef = decode::cdef_idx_hits();
8892 let before_lr =
8893 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
8894 let frames = decode_stream(&stream)
8895 .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 12-bit key frame: {e}"));
8896 assert_eq!(frames.len(), 1);
8897 assert!(
8898 decode::cdef_idx_hits() > before_cdef,
8899 "{NAME}: no CDEF index literal was read -- CDEF is not exercised"
8900 );
8901 assert!(
8902 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
8903 "{NAME}: no loop restoration unit was decoded -- LR is not exercised"
8904 );
8905 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 1);
8906 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (12-bit key)");
8907 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (12-bit key)");
8908 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (12-bit key)");
8909 }
8910
8911 /// The 12-bit INTER witness: a key frame plus one P frame over sub-pixel
8912 /// true motion. Byte-exact against ffmpeg; hard-asserts the two-pass
8913 /// SUBPEL prediction path ran (`MC_SUBPEL_HITS`), so the frame's own
8914 /// `round_0`/`round_1` -- 5/9 at 12 bits, the whole point of the mc.rs
8915 /// parameterisation -- really executed, and asserts
8916 /// `compound_mode_hits` UNCHANGED (this recipe offers no divergent
8917 /// second reference, so no compound mode symbol is read -- the lane's
8918 /// compound witness is the six-frame gate below).
8919 #[test]
8920 fn a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact() {
8921 const NAME: &str = "a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact";
8922 let _gate_lock = lock_gate_counters();
8923 if !have_ffmpeg() {
8924 eprintln!("SKIP {NAME}: no ffmpeg");
8925 return;
8926 }
8927 if !have_aomenc() {
8928 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8929 return;
8930 }
8931 let y4m = y4m_12bit_subpel_source(2);
8932 let stream = encode_12bit(
8933 &y4m,
8934 2,
8935 &["--enable-warped-motion=0", "--enable-global-motion=0"],
8936 );
8937 assert_12bit_sequence_header(&stream, NAME);
8938 let before_subpel = crate::mc::mc_subpel_hits();
8939 let before_compound = decode::compound_mode_hits();
8940 let frames = decode_stream(&stream)
8941 .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 12-bit inter stream: {e}"));
8942 assert_eq!(frames.len(), 2);
8943 assert!(
8944 crate::mc::mc_subpel_hits() > before_subpel,
8945 "{NAME}: no subpel inter prediction decoded -- the 12-bit round pair is unexercised"
8946 );
8947 assert_eq!(
8948 decode::compound_mode_hits(),
8949 before_compound,
8950 "{NAME}: a compound mode symbol was read -- the single-reference premise is gone"
8951 );
8952 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2);
8953 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
8954 assert_eq!(ours.y, reference.y, "frame {i} luma vs ffmpeg (12-bit inter)");
8955 assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit inter)");
8956 assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit inter)");
8957 }
8958 }
8959
8960 /// The 12-bit WARP witness (lane-av112bitw): the same source and recipe
8961 /// with the warp tools ON -- aomenc picks warp models on this content
8962 /// (measured pre-lift: the warp model fires at the third frame, and the
8963 /// decode refused by name at exactly that block) -- now decodes
8964 /// BYTE-EXACT against ffmpeg. The warp filter's shifts are the bumped
8965 /// `conv_params->round_0` (`warp::warp_round_0`, 5 at 12 bits, feeding
8966 /// `reduce_bits_horiz`, the derived non-compound
8967 /// `reduce_bits_vert = 2*FILTER_BITS - round_0` and both `offset_bits`),
8968 /// the whole libaom `get_conv_params_no_round` 12-bit bump.
8969 ///
8970 /// Non-vacuous: the same recipe refused by name before the lift, the
8971 /// gate hard-asserts a warp predictor was really resolved (a warpless
8972 /// stream would pass the pixel compare and prove nothing), and every
8973 /// plane of every frame compares against ffmpeg's decode.
8974 #[test]
8975 fn a_12bit_warped_motion_stream_decodes_pixel_exact() {
8976 const NAME: &str = "a_12bit_warped_motion_stream_decodes_pixel_exact";
8977 let _gate_lock = lock_gate_counters();
8978 if !have_ffmpeg() {
8979 eprintln!("SKIP {NAME}: no ffmpeg");
8980 return;
8981 }
8982 if !have_aomenc() {
8983 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8984 return;
8985 }
8986 let y4m = y4m_12bit_subpel_source(6);
8987 // Exactly the recipe measured to refuse at warp pre-lift: warp ON,
8988 // global motion NOT spelled (spelling it ON drives a GLOBAL_GLOBALMV
8989 // compound block into the compound-warp arm -- see the compound gate
8990 // below), six frames -- the warp model fires at the third frame.
8991 let stream = encode_12bit(&y4m, 6, &["--enable-warped-motion=1"]);
8992 assert_12bit_sequence_header(&stream, NAME);
8993 let (before_selected, before_warp8, before_affine) = (
8994 decode::warp_selected_hits(),
8995 decode::warp_hits_8(),
8996 decode::affine_gm_hits(),
8997 );
8998 let frames = decode_stream(&stream).unwrap_or_else(|e| {
8999 panic!("{NAME}: decode_stream refused a real 12-bit warp stream: {e}")
9000 });
9001 assert_eq!(frames.len(), 6);
9002 let (delta_selected, delta_warp8, delta_affine) = (
9003 decode::warp_selected_hits() - before_selected,
9004 decode::warp_hits_8() - before_warp8,
9005 decode::affine_gm_hits() - before_affine,
9006 );
9007 eprintln!(
9008 "{NAME}: warp_engagement selected(16x16+ symbol)={delta_selected} \
9009 warped8(usable 8x8 model)={delta_warp8} affine_gm(6-param model)={delta_affine}"
9010 );
9011 assert!(
9012 delta_selected + delta_warp8 + delta_affine > 0,
9013 "{NAME}: no warp predictor was resolved -- the stream carries no \
9014 warp model and the pixel compare would prove nothing"
9015 );
9016 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6);
9017 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9018 assert_eq!(ours.y, reference.y, "frame {i} luma vs ffmpeg (12-bit warp)");
9019 assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit warp)");
9020 assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit warp)");
9021 }
9022 }
9023
9024 /// The 12-bit COMPOUND witness (lane-av112bitc): the parent's source
9025 /// and recipe with warp pinned OFF -- with six frames LAST diverges
9026 /// from GOLDEN from frame 2 on and aomenc codes compound inter blocks
9027 /// (pre-lift measurement: the decode refused at the compound mode
9028 /// read). Two arms: the default recipe (dist-weighted average
9029 /// combines live) and `--enable-dist-wtd-comp=0` (pushes compound AND
9030 /// the masked choice harder: 6 diffwtd blends). Both byte-exact
9031 /// against ffmpeg; each hard-asserts compound mode symbols and
9032 /// masked-diffwtd blends really ran, so the parameterised combine
9033 /// rounds (`INTER_POST_ROUND - delta`, diffwtd `+ (bd-8) - delta` at
9034 /// 12 bits) and the ffmpeg-pinned pixel path genuinely executed.
9035 #[test]
9036 fn a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact() {
9037 const NAME: &str = "a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact";
9038 let _gate_lock = lock_gate_counters();
9039 if !have_ffmpeg() {
9040 eprintln!("SKIP {NAME}: no ffmpeg");
9041 return;
9042 }
9043 if !have_aomenc() {
9044 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9045 return;
9046 }
9047 let y4m = y4m_12bit_subpel_source(6);
9048 for (arm, extra) in [
9049 ("dist-wtd", &["--enable-warped-motion=0"][..]),
9050 ("plain-masked", &["--enable-warped-motion=0", "--enable-dist-wtd-comp=0"][..]),
9051 ] {
9052 let stream = encode_12bit(&y4m, 6, &extra);
9053 assert_12bit_sequence_header(&stream, NAME);
9054 let before_compound = decode::compound_mode_hits();
9055 let before_masked = decode::masked_compound_hits();
9056 let before_diffwtd = decode::diffwtd_hits();
9057 let before_wedge = decode::wedge_hits();
9058 let frames = decode_stream(&stream).unwrap_or_else(|e| {
9059 panic!("{NAME} [{arm}]: decode_stream refused a real 12-bit compound stream: {e}")
9060 });
9061 assert_eq!(frames.len(), 6, "{NAME} [{arm}]: frame count");
9062 let (comp, masked, diffwtd, wedge) = (
9063 decode::compound_mode_hits() - before_compound,
9064 decode::masked_compound_hits() - before_masked,
9065 decode::diffwtd_hits() - before_diffwtd,
9066 decode::wedge_hits() - before_wedge,
9067 );
9068 eprintln!(
9069 "{NAME} [{arm}]: compound blocks={comp} masked={masked} diffwtd={diffwtd} wedge={wedge}"
9070 );
9071 assert!(comp > 0, "{NAME} [{arm}]: no compound mode symbol was read -- the compound path is unexercised");
9072 assert!(masked > 0, "{NAME} [{arm}]: no masked compound block ran -- the masked combine is unexercised");
9073 assert!(diffwtd > 0, "{NAME} [{arm}]: no diffwtd blend ran -- the diffwtd combine is unexercised");
9074 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6);
9075 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9076 assert_eq!(ours.y, reference.y, "{NAME} [{arm}] frame {i} luma vs ffmpeg");
9077 assert_eq!(ours.u, reference.u, "{NAME} [{arm}] frame {i} U vs ffmpeg");
9078 assert_eq!(ours.v, reference.v, "{NAME} [{arm}] frame {i} V vs ffmpeg");
9079 }
9080 }
9081 }
9082
9083 /// lane-av112bitg: the 12-bit film grain witness. A real
9084 /// `aomenc --bit-depth=12 --profile=2 --film-grain-test=5` stream -- grain
9085 /// params present AND applied (2 luma + 9 cb + 9 cr scaling points,
9086 /// overlap blending on, clip-to-restricted-range on; the second frame is
9087 /// an INTER frame that inherits the params via `update_grain = 0`) --
9088 /// decoded byte-exact against ffmpeg's own 12-bit decode of the identical
9089 /// bytes (ffmpeg synthesizes grain by default; no grain-disable flag is
9090 /// passed anywhere in this file). Proves the bit-depth-generic grain path
9091 /// at 12 bits: `grain_range`'s ±(128 << 4) AR clamp and overlap-blend
9092 /// clamp, the `gauss_sec_shift = 12 - bd` Gaussian shift, the 4096-entry
9093 /// expanded scaling-LUT interpolation, and the `<< (bit_depth - 8)`
9094 /// chroma offsets and legal-range clamps. HARD-asserts the parsed headers
9095 /// really carry that coverage and `film_grain::grain_hits()` fired, so
9096 /// neither a params-without-apply stream nor a silently-skipped synthesis
9097 /// can pass vacuously.
9098 #[test]
9099 fn a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact() {
9100 const NAME: &str = "a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact";
9101 let _gate_lock = lock_gate_counters();
9102 if !have_ffmpeg() {
9103 eprintln!("SKIP {NAME}: no ffmpeg");
9104 return;
9105 }
9106 if !have_aomenc() {
9107 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9108 return;
9109 }
9110 let y4m = y4m_12bit_subpel_source(2);
9111 // Warp stays refused at 12 bits (lane-av112bitg lifts GRAIN only), so
9112 // the arm pins both motion tools off exactly once each -- aomenc
9113 // otherwise picks warped motion on this fixture's sub-pel motion.
9114 let stream = encode_12bit(
9115 &y4m,
9116 2,
9117 &[
9118 "--film-grain-test=5",
9119 "--enable-warped-motion=0",
9120 "--enable-global-motion=0",
9121 ],
9122 );
9123 assert_12bit_sequence_header(&stream, NAME);
9124 // The arm is only honest if the stream itself carries the coverage:
9125 // grain applied on every frame, scaling points on all three planes,
9126 // overlap blending and restricted-range clipping on.
9127 let mut probe = Av1Parser::new();
9128 let mut pos = 0usize;
9129 let mut grain_frames = 0usize;
9130 while pos < stream.len() {
9131 let obu = probe.parse_obu(&stream[pos..]).unwrap();
9132 pos += obu.total_size;
9133 if let ObuKind::Frame(header, _) = obu.kind {
9134 let fg = &header.film_grain;
9135 assert!(
9136 fg.apply_grain,
9137 "{NAME}: frame without apply_grain -- aomenc emitted params it does not apply"
9138 );
9139 assert!(
9140 fg.num_y_points > 0 && fg.num_cb_points > 0 && fg.num_cr_points > 0,
9141 "{NAME}: grain without all three planes' scaling points -- the bit-depth \
9142 LUT math would not be exercised"
9143 );
9144 assert!(
9145 fg.overlap_flag,
9146 "{NAME}: overlap off -- the grain_min/grain_max blend clamp is not exercised"
9147 );
9148 assert!(
9149 fg.clip_to_restricted_range,
9150 "{NAME}: clip_to_restricted_range off -- the << (bd - 8) legal-range clamps \
9151 are not exercised"
9152 );
9153 grain_frames += 1;
9154 }
9155 }
9156 assert_eq!(grain_frames, 2, "{NAME}: expected grain on both frames");
9157 let before = crate::film_grain::grain_hits();
9158 let frames = decode_stream(&stream)
9159 .unwrap_or_else(|e| panic!("{NAME}: decode_stream refused a real 12-bit grain stream: {e}"));
9160 assert_eq!(frames.len(), 2);
9161 assert!(
9162 crate::film_grain::grain_hits() > before,
9163 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
9164 );
9165 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2);
9166 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9167 assert_eq!(ours.y, theirs.y, "{NAME}: luma vs ffmpeg (12-bit grain, frame {i})");
9168 assert_eq!(ours.u, theirs.u, "{NAME}: U vs ffmpeg (12-bit grain, frame {i})");
9169 assert_eq!(ours.v, theirs.v, "{NAME}: V vs ffmpeg (12-bit grain, frame {i})");
9170 }
9171 eprintln!("{NAME}: byte-exact, grain_hits={}", crate::film_grain::grain_hits());
9172 }
9173
9174 /// The 12-bit screen-content refusal: a real `--tune-content=screen
9175 /// --enable-palette=1 --enable-intrabc=1` frame carries
9176 /// `allow_screen_content_tools = 1` and is refused by name at the frame
9177 /// gate -- palette and intrabc have no 12-bit witness.
9178 #[test]
9179 fn a_12bit_screen_content_stream_is_refused_by_name() {
9180 const NAME: &str = "a_12bit_screen_content_stream_is_refused_by_name";
9181 let _gate_lock = lock_gate_counters();
9182 if !have_ffmpeg() {
9183 eprintln!("SKIP {NAME}: no ffmpeg");
9184 return;
9185 }
9186 if !have_aomenc() {
9187 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9188 return;
9189 }
9190 let y4m = Command::new("ffmpeg")
9191 .args([
9192 "-v", "error", "-f", "lavfi", "-i", "smptebars=s=128x128:r=25",
9193 "-pix_fmt", "yuv420p12le", "-strict", "-1", "-frames:v", "2",
9194 "-f", "yuv4mpegpipe", "-",
9195 ])
9196 .stdin(Stdio::null())
9197 .stdout(Stdio::piped())
9198 .stderr(Stdio::piped())
9199 .output()
9200 .expect("ffmpeg failed to run");
9201 assert!(
9202 y4m.status.success(),
9203 "ffmpeg failed to render the 12-bit screen fixture: {}",
9204 String::from_utf8_lossy(&y4m.stderr)
9205 );
9206 let stream = encode_12bit(
9207 &y4m.stdout,
9208 1,
9209 &["--tune-content=screen", "--enable-palette=1", "--enable-intrabc=1"],
9210 );
9211 let err = decode_stream(&stream).unwrap_err().to_string();
9212 assert!(
9213 err.contains(
9214 "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)"
9215 ),
9216 "{NAME}: expected the 12-bit screen content refusal, got: {err}"
9217 );
9218 }
9219
9220 #[test]
9221 fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {
9222 const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact";
9223 if !have_ffmpeg() {
9224 eprintln!("SKIP {NAME}: no ffmpeg");
9225 return;
9226 }
9227 if !have_aomenc() {
9228 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9229 return;
9230 }
9231 let (width, height) = (64usize, 64usize);
9232 let y4m = Command::new("ffmpeg")
9233 .args([
9234 "-v",
9235 "error",
9236 "-f",
9237 "lavfi",
9238 "-i",
9239 &gradients_source(42, width, height, "duration=0.04:rate=25"),
9240 "-pix_fmt",
9241 "yuv420p10le",
9242 "-strict",
9243 "-1",
9244 "-t",
9245 "0.04",
9246 "-f",
9247 "yuv4mpegpipe",
9248 "-",
9249 ])
9250 .stdin(Stdio::null())
9251 .stdout(Stdio::piped())
9252 .stderr(Stdio::piped())
9253 .output()
9254 .expect("ffmpeg failed to run");
9255 assert!(
9256 y4m.status.success(),
9257 "ffmpeg failed to render the 10-bit fixture: {}",
9258 String::from_utf8_lossy(&y4m.stderr)
9259 );
9260 let out = run_with_stdin(Command::new(aomenc_path())
9261 .args([
9262 "--codec=av1",
9263 "--passes=1",
9264 "--end-usage=q",
9265 "--cq-level=30",
9266 "--cpu-used=0",
9267 "--threads=1",
9268 "--row-mt=0",
9269 "--sb-size=64",
9270 "--input-bit-depth=10",
9271 "--bit-depth=10",
9272 "--limit=1",
9273 "--obu",
9274 "-o",
9275 "-",
9276 "-",
9277 ]), &y4m.stdout);
9278 assert!(
9279 out.status.success(),
9280 "aomenc refused the 10-bit fixture: {}",
9281 String::from_utf8_lossy(&out.stderr)
9282 );
9283 let stream = out.stdout;
9284 // Confirm the sequence header this stream actually parses to before
9285 // trusting any pixel comparison below.
9286 let mut probe = Av1Parser::new();
9287 let mut pos = 0usize;
9288 while pos < stream.len() && probe.sequence_header().is_none() {
9289 let obu = probe.parse_obu(&stream[pos..]).unwrap();
9290 pos += obu.total_size;
9291 }
9292 let seq = probe
9293 .sequence_header()
9294 .expect("stream has a sequence header OBU");
9295 assert_eq!(
9296 seq.color_config.bit_depth, 10,
9297 "{NAME}: aomenc did not actually write a 10-bit sequence header"
9298 );
9299 let frames = match decode_stream(&stream) {
9300 Ok(frames) => frames,
9301 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit stream: {e}"),
9302 };
9303 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
9304 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (10-bit)");
9305 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (10-bit)");
9306 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
9307 }
9308
9309 /// The 10-bit *inter* counterpart of the gate above: a real `aomenc`
9310 /// `yuv420p10le` sequence whose non-key frames are plain forward
9311 /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0
9312 /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate),
9313 /// decoded pixel-exact on every frame. 10-bit intra was proven exact by
9314 /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated.
9315 #[test]
9316 fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() {
9317 const NAME: &str = "a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact";
9318 let _gate_lock = lock_gate_counters();
9319 if !have_ffmpeg() {
9320 eprintln!("SKIP {NAME}: no ffmpeg");
9321 return;
9322 }
9323 if !have_aomenc() {
9324 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9325 return;
9326 }
9327 let (width, height, frame_count) = (128usize, 64usize, 16usize);
9328 let y4m = Command::new("ffmpeg")
9329 .args([
9330 "-v",
9331 "error",
9332 "-f",
9333 "lavfi",
9334 "-i",
9335 &gradients_source(42, width, height, "duration=0.64:rate=25"),
9336 "-pix_fmt",
9337 "yuv420p10le",
9338 "-strict",
9339 "-1",
9340 "-t",
9341 "0.64",
9342 "-f",
9343 "yuv4mpegpipe",
9344 "-",
9345 ])
9346 .stdin(Stdio::null())
9347 .stdout(Stdio::piped())
9348 .stderr(Stdio::piped())
9349 .output()
9350 .expect("ffmpeg failed to run");
9351 assert!(
9352 y4m.status.success(),
9353 "ffmpeg failed to render the 10-bit fixture: {}",
9354 String::from_utf8_lossy(&y4m.stderr)
9355 );
9356 let out = run_with_stdin(Command::new(aomenc_path())
9357 .args([
9358 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
9359 // occurrence, so overrides go before the base list).
9360 "--loopfilter-control=1",
9361 "--codec=av1",
9362 "--passes=1",
9363 "--end-usage=q",
9364 "--cq-level=15",
9365 "--cpu-used=0",
9366 "--threads=1",
9367 "--row-mt=0",
9368 "--sb-size=64",
9369 "--input-bit-depth=10",
9370 "--bit-depth=10",
9371 "--lag-in-frames=0",
9372 "--auto-alt-ref=0",
9373 "--kf-max-dist=1000",
9374 "--error-resilient=1",
9375 "--aq-mode=0",
9376 "--deltaq-mode=0",
9377 "--enable-cdef=0",
9378 "--enable-rect-partitions=0",
9379 "--enable-ab-partitions=0",
9380 "--enable-1to4-partitions=0",
9381 "--enable-filter-intra=0",
9382 "--enable-smooth-intra=0",
9383 "--enable-paeth-intra=0",
9384 "--enable-directional-intra=0",
9385 "--enable-angle-delta=0",
9386 "--enable-tx-size-search=0",
9387 "--enable-cdef=1",
9388 "--enable-restoration=1",
9389 "--min-partition-size=16",
9390 "--max-partition-size=32",
9391 "--enable-palette=0",
9392 "--enable-intrabc=0",
9393 "--enable-cfl-intra=0",
9394 "--enable-ref-frame-mvs=0",
9395 "--obu",
9396 "-o",
9397 "-",
9398 "-",
9399 ]), &y4m.stdout);
9400 assert!(
9401 out.status.success(),
9402 "aomenc refused the 10-bit fixture: {}",
9403 String::from_utf8_lossy(&out.stderr)
9404 );
9405 let stream = out.stdout;
9406 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
9407 std::fs::write(dump, &stream).expect("dump stream");
9408 }
9409 let mut probe = Av1Parser::new();
9410 let mut pos = 0usize;
9411 while pos < stream.len() && probe.sequence_header().is_none() {
9412 let obu = probe.parse_obu(&stream[pos..]).unwrap();
9413 pos += obu.total_size;
9414 }
9415 assert_eq!(
9416 probe
9417 .sequence_header()
9418 .expect("stream has a sequence header OBU")
9419 .color_config
9420 .bit_depth,
9421 10,
9422 "{NAME}: aomenc did not actually write a 10-bit sequence header"
9423 );
9424 let before_deblock = decode::deblock_hits();
9425 let before_inter = decode::inter_pred_hits();
9426 let before_lr = crate::restoration::wiener_hits()
9427 + crate::restoration::sgrproj_hits()
9428 + crate::restoration::switchable_hits();
9429 let frames = match decode_stream(&stream) {
9430 Ok(frames) => frames,
9431 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"),
9432 };
9433 assert!(
9434 decode::inter_pred_hits() > before_inter,
9435 "{NAME}: no inter-predicted block decoded -- the gate proves nothing"
9436 );
9437 assert!(
9438 decode::deblock_hits() > before_deblock,
9439 "{NAME}: no deblocking edge fired -- raise cq-level"
9440 );
9441 // Loop restoration is where the 10-bit inter/intra defect lived
9442 // (lane-hbdinter r1: the self-guided box sums were never brought back
9443 // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened
9444 // to pick RESTORE_NONE would pass while proving nothing.
9445 assert!(
9446 crate::restoration::wiener_hits()
9447 + crate::restoration::sgrproj_hits()
9448 + crate::restoration::switchable_hits()
9449 > before_lr,
9450 "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level"
9451 );
9452 eprintln!(
9453 "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}",
9454 decode::inter_pred_hits() - before_inter,
9455 decode::deblock_hits() - before_deblock,
9456 decode::cdef_idx_hits(),
9457 crate::restoration::wiener_hits(),
9458 crate::restoration::sgrproj_hits(),
9459 );
9460 assert_eq!(frames.len(), frame_count);
9461 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count);
9462 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9463 if got.y != want.y || got.u != want.u || got.v != want.v {
9464 let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu");
9465 let _ = std::fs::write(&pin, &stream);
9466 let first = |a: &Vec<u16>, b: &Vec<u16>| {
9467 a.iter()
9468 .zip(b)
9469 .enumerate()
9470 .find(|(_, (x, y))| x != y)
9471 .map(|(k, (x, y))| (k, *x, *y))
9472 };
9473 panic!(
9474 "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}",
9475 first(&got.y, &want.y),
9476 first(&got.u, &want.u),
9477 first(&got.v, &want.v),
9478 pin.display()
9479 );
9480 }
9481 }
9482 }
9483
9484 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1`
9485 /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the
9486 /// identical bytes (ffmpeg synthesizes grain by default -- no
9487 /// grain-disable flag is passed anywhere in this file). Proves the
9488 /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`,
9489 /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather
9490 /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed
9491 /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a
9492 /// silent 8-bit fallback nor a stream aomenc emitted without
9493 /// `apply_grain` can make it pass vacuously.
9494 #[test]
9495 fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() {
9496 const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact";
9497 if !have_ffmpeg() {
9498 eprintln!("SKIP {NAME}: no ffmpeg");
9499 return;
9500 }
9501 if !have_aomenc() {
9502 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9503 return;
9504 }
9505 let (width, height) = (64usize, 64usize);
9506 let stream = encode_10bit_gradients(
9507 NAME,
9508 width,
9509 height,
9510 1,
9511 &["--film-grain-test=1", "--limit=1"],
9512 );
9513 assert_eq!(
9514 parsed_bit_depth(&stream),
9515 10,
9516 "{NAME}: aomenc did not actually write a 10-bit sequence header"
9517 );
9518 let mut probe = Av1Parser::new();
9519 let mut pos = 0usize;
9520 let mut saw_grain = false;
9521 while pos < stream.len() {
9522 let obu = probe.parse_obu(&stream[pos..]).unwrap();
9523 pos += obu.total_size;
9524 if let ObuKind::Frame(header, _) = obu.kind
9525 && header.film_grain.apply_grain
9526 {
9527 // A grain block whose scaling LUT is empty would blend a
9528 // zero delta into every pixel and let this gate pass without
9529 // the bit-depth math mattering at all.
9530 assert!(
9531 header.film_grain.num_y_points > 0,
9532 "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op"
9533 );
9534 saw_grain = true;
9535 }
9536 }
9537 assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain");
9538 let before = crate::film_grain::grain_hits();
9539 let frames = match decode_stream(&stream) {
9540 Ok(frames) => frames,
9541 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
9542 };
9543 assert!(
9544 crate::film_grain::grain_hits() > before,
9545 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
9546 );
9547 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
9548 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
9549 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
9550 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
9551 eprintln!("{NAME}: pixel-exact, grain_hits={}", crate::film_grain::grain_hits());
9552 }
9553
9554 /// lane-t900 r29: `fixtures/superres_kf_cdef_lr_64x64.obu` is a real
9555 /// aomenc key frame (64x64 upscaled from a coded 43x64,
9556 /// `--superres-mode=1 --superres-denominator=12 --cpu-used=0 --sb-size=64
9557 /// --enable-cdef=1 --enable-restoration=1 --cq-level=32`) -- the first
9558 /// stream in this repo that runs BOTH in-loop filters under superres.
9559 ///
9560 /// The defect it pins: spec 7.16's upscale runs between CDEF and loop
9561 /// restoration (libaom `superres_post_decode`, `decodeframe.c`, called
9562 /// between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`),
9563 /// but this decoder ran the whole filter chain on the DOWNSCALED frame
9564 /// and upscaled last, in `stream.rs`. Loop restoration therefore filtered
9565 /// downscaled pixels with a unit grid sized from the downscaled width
9566 /// (1873 wrong samples, max 7, on this very stream). Class
9567 /// `wrong-stage-width`: every plane width in the filter chain is either
9568 /// the downscaled one (deblock, CDEF, and the mi grid all three walk) or
9569 /// the upscaled one (loop restoration's `av1_get_upsampled_plane_size`
9570 /// unit grid, `av1_loop_restoration_corners_in_sb`'s `mi_to_num_x`
9571 /// superres arm, and the pixel filters themselves); the sweep is every
9572 /// caller of `apply_deblock`/`apply_cdef`/`apply_loop_restoration` plus
9573 /// `RestorationGrid::new` and `read_lr`.
9574 #[test]
9575 fn a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact() {
9576 const NAME: &str =
9577 "a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact";
9578 let _gate_lock = lock_gate_counters();
9579 if !have_ffmpeg() {
9580 eprintln!("SKIP {NAME}: no ffmpeg");
9581 return;
9582 }
9583 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9584 .join("fixtures/superres_kf_cdef_lr_64x64.obu");
9585 let stream = std::fs::read(&path)
9586 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
9587 let (width, height) = (64usize, 64usize);
9588 let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
9589 let frames = match decode_stream(&stream) {
9590 Ok(frames) => frames,
9591 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
9592 };
9593 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
9594 assert_eq!((frames[0].width, frames[0].height), (width, height));
9595 // class `gate-blind-to-feature`: the stream must actually upscale and
9596 // actually run a real restoration filter, or this gate proves nothing.
9597 assert!(
9598 crate::superres::superres_hits() > 0,
9599 "{NAME}: zero superres_hits -- the frame was never upscaled"
9600 );
9601 assert!(
9602 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
9603 "{NAME}: zero restoration units fired -- LR never ran under superres"
9604 );
9605 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
9606 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
9607 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
9608 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
9609 }
9610
9611 /// lane-filt1: `EC_AV1_FILTER_THREADS` splits every in-frame filter stage
9612 /// -- deblock (row bands for the vertical-edge pass, column bands for the
9613 /// horizontal one), CDEF (mi row bands), loop restoration (RU row bands)
9614 /// and film grain (32-pixel block rows) -- across scoped worker threads.
9615 /// A split is only legal if it is BYTE-EXACT, so this gate decodes two
9616 /// real aomenc streams at 1 and at 4 filter threads and compares every
9617 /// output frame's three planes.
9618 ///
9619 /// Between them the fixtures fire all four stages, and the firing
9620 /// counters are asserted rather than assumed (class `gate-blind-to-feature`):
9621 /// `superres_alltools_sb128_320x180.obu` is the 10-bit CDEF + loop
9622 /// restoration stream, `grain_cdef_lr_128x128.obu` a 128x128
9623 /// `--denoise-noise-level=25` stream whose frames carry film grain
9624 /// parameters (small enough that 4 bands is one block row each, which is
9625 /// what exercises the grain band's one-row `prelude` replay).
9626 /// lane-wave1 step (ii): the superblock-row wavefront
9627 /// (`EC_AV1_RECON_THREADS`) reconstructs every output frame byte for
9628 /// byte as the inline path does, on a hidden-ARF 10-bit stream (no-show
9629 /// frames, CfL, 128 superblocks) and on the two screen-content streams
9630 /// whose palette/intrabc blocks READ the current frame's pixels while
9631 /// parsing -- the sites that make the workers barrier.
9632 #[test]
9633 fn a_real_stream_reconstructs_identically_with_one_and_four_recon_threads() {
9634 const NAME: &str = "a_real_stream_reconstructs_identically_with_one_and_four_recon_threads";
9635 let _gate_lock = lock_gate_counters();
9636 for fixture in [
9637 "reelb_arf_witness.obu",
9638 "palette_screen_witness.obu",
9639 "palette_screen_witness_10bit.obu",
9640 ] {
9641 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9642 .join("fixtures")
9643 .join(fixture);
9644 let stream = std::fs::read(&path)
9645 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
9646 crate::par::set_recon_threads(1);
9647 let one = match decode_stream(&stream) {
9648 Ok(frames) => frames,
9649 Err(e) => panic!("{NAME}: {fixture} refused at 1 recon thread: {e}"),
9650 };
9651 crate::par::set_recon_threads(4);
9652 let four = match decode_stream(&stream) {
9653 Ok(frames) => frames,
9654 Err(e) => {
9655 crate::par::set_recon_threads(1);
9656 panic!("{NAME}: {fixture} refused at 4 recon threads: {e}")
9657 }
9658 };
9659 crate::par::set_recon_threads(1);
9660 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
9661 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
9662 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
9663 assert_eq!(a.y, b.y, "{NAME}: {fixture} frame {i} luma differs at 4 recon threads");
9664 assert_eq!(a.u, b.u, "{NAME}: {fixture} frame {i} U differs at 4 recon threads");
9665 assert_eq!(a.v, b.v, "{NAME}: {fixture} frame {i} V differs at 4 recon threads");
9666 }
9667 }
9668 }
9669
9670 /// lane-memfix: the pool grows to the peak of `busy + queued` over the
9671 /// job tree and stops there. Before, a job running on a pool worker
9672 /// opened a SECOND pool on that worker's own thread-local -- one level
9673 /// per pipeline stage, none of them ever shrinking -- which is how a 4K
9674 /// decode at `(16, 4, 2)` reached 1038 live threads. Two decodes of the
9675 /// same stream: the count stays inside the composed setting and the
9676 /// second decode adds nothing (the ratchet is what cost the memory).
9677 #[test]
9678 fn the_worker_pool_stays_bounded_across_repeated_threaded_decodes() {
9679 const NAME: &str = "the_worker_pool_stays_bounded_across_repeated_threaded_decodes";
9680 let _gate_lock = lock_gate_counters();
9681 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9682 .join("fixtures")
9683 .join("superres_alltools_sb128_320x180.obu");
9684 let stream = std::fs::read(&path)
9685 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
9686 crate::par::set_filter_threads(4);
9687 crate::par::set_recon_threads(2);
9688 let mut counts = [0usize; 2];
9689 let mut frames = [0usize; 2];
9690 for (i, slot) in counts.iter_mut().enumerate() {
9691 let mut n = 0usize;
9692 let r = decode_stream_with_threads(&stream, 4, |_, _, _| {
9693 n += 1;
9694 Ok(())
9695 });
9696 if let Err(e) = r {
9697 crate::par::set_filter_threads(1);
9698 crate::par::set_recon_threads(1);
9699 panic!("{NAME}: refused on decode {i}: {e}");
9700 }
9701 frames[i] = n;
9702 *slot = crate::par::pool_threads();
9703 }
9704 crate::par::set_filter_threads(1);
9705 crate::par::set_recon_threads(1);
9706 assert!(frames[0] > 1, "{NAME}: the fixture decoded {} frames, so nothing was threaded", frames[0]);
9707 // 4 frame workers x (recon 2 + filter 4) plus the two in-flight
9708 // slots `stream.rs` allows over the thread count, with room for the
9709 // show jobs -- 1038 was three orders past this.
9710 assert!(
9711 counts[1] <= 4 * (2 + 4) + 2 * 4,
9712 "{NAME}: the pool grew to {} threads at 4 frame / 4 filter / 2 recon",
9713 counts[1]
9714 );
9715 // The pool grows to `busy + queued`, so a loaded box can queue one
9716 // more job than an idle one did (seen: 9 -> 10 at load 62). The
9717 // bound above is the structural claim; here only a runaway counts.
9718 assert!(
9719 counts[1] <= counts[0] + 4,
9720 "{NAME}: a second decode of the same stream grew the pool from {} to {} threads",
9721 counts[0], counts[1]
9722 );
9723 }
9724
9725 #[test]
9726 fn a_real_stream_filters_identically_with_one_and_four_filter_threads() {
9727 const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads";
9728 let _gate_lock = lock_gate_counters();
9729 for (fixture, wants_lr, wants_grain) in [
9730 ("superres_alltools_sb128_320x180.obu", true, false),
9731 ("grain_cdef_lr_128x128.obu", false, true),
9732 ] {
9733 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9734 .join("fixtures")
9735 .join(fixture);
9736 let stream = std::fs::read(&path)
9737 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
9738 let before = (
9739 crate::decode::deblock_hits(),
9740 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
9741 crate::film_grain::grain_hits(),
9742 );
9743 crate::par::set_filter_threads(1);
9744 let one = match decode_stream(&stream) {
9745 Ok(frames) => frames,
9746 Err(e) => panic!("{NAME}: {fixture} refused at 1 filter thread: {e}"),
9747 };
9748 let after = (
9749 crate::decode::deblock_hits(),
9750 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
9751 crate::film_grain::grain_hits(),
9752 );
9753 crate::par::set_filter_threads(4);
9754 let four = match decode_stream(&stream) {
9755 Ok(frames) => frames,
9756 Err(e) => {
9757 crate::par::set_filter_threads(1);
9758 panic!("{NAME}: {fixture} refused at 4 filter threads: {e}")
9759 }
9760 };
9761 crate::par::set_filter_threads(1);
9762 assert!(after.0 > before.0, "{NAME}: {fixture} deblocked no edge at all");
9763 if wants_lr {
9764 assert!(after.1 > before.1, "{NAME}: {fixture} ran no restoration unit");
9765 }
9766 if wants_grain {
9767 assert!(after.2 > before.2, "{NAME}: {fixture} applied no film grain");
9768 }
9769 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
9770 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
9771 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
9772 assert_eq!(a.y, b.y, "{NAME}: {fixture} frame {i} luma differs at 4 filter threads");
9773 assert_eq!(a.u, b.u, "{NAME}: {fixture} frame {i} U differs at 4 filter threads");
9774 assert_eq!(a.v, b.v, "{NAME}: {fixture} frame {i} V differs at 4 filter threads");
9775 }
9776 }
9777 }
9778
9779 /// lane-t900 r30b: `fixtures/superres_alltools_sb128_320x180.obu` is 10
9780 /// frames of `--cpu-used=4 --sb-size=128 --superres-mode=1
9781 /// --superres-denominator=12 --cq-level=32` with every tool aomenc turns
9782 /// on by default (CDEF, loop restoration, OBMC, compound, warp) -- the
9783 /// first stream here that deblocks CHROMA across a group of 4x4 luma
9784 /// blocks.
9785 ///
9786 /// The defect it pins (fixed at this commit, `decode.rs`'s
9787 /// `plane_to_mi`/`edge_params`): `set_lpf_parameters`
9788 /// (`av1_loopfilter.c:245`) indexes the mi grid for a CHROMA edge at
9789 /// `scale | ((coord << scale) >> MI_SIZE_LOG2)` -- the BOTTOM/RIGHT mi of
9790 /// the co-located 8x8 luma group, the same cell that donates the group's
9791 /// chroma prediction. This decoder dropped that `| 1` and read the
9792 /// group's top-left mi, stepped to the previous cell by one mi instead of
9793 /// `1 << ss`, and priced `pu_edge` by comparing mi origins rather than
9794 /// the edge coordinate against the block size in the FILTERED plane's own
9795 /// pixels (chroma bottoms out at 4). All three are invisible while every
9796 /// block is 8x8 or larger (all four mi of a group carry the same tx size,
9797 /// ref frame, skip flag and delta_lf) and wrong the moment cpu-used=4
9798 /// splits a group into 4x4 blocks: on this stream one U sample of frame 2
9799 /// took a filter level of 12 where libaom's neighbouring 4x4 block gives
9800 /// 8, and the error compounded through the reference chain to 280 U + 331
9801 /// V samples (max 9) by frame 9. Class `context-read-from-one-cell`.
9802 ///
9803 /// Post-deblock, this stream is now byte-exact against the instrumented
9804 /// libaom (`EC_AV1_POSTDEBLOCK_DUMP`) in all 10 frames, and the final
9805 /// output matches ffmpeg's.
9806 #[test]
9807 fn a_superres_all_tools_sb128_stream_decodes_pixel_exact() {
9808 const NAME: &str = "a_superres_all_tools_sb128_stream_decodes_pixel_exact";
9809 let _gate_lock = lock_gate_counters();
9810 if !have_ffmpeg() {
9811 eprintln!("SKIP {NAME}: no ffmpeg");
9812 return;
9813 }
9814 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9815 .join("fixtures/superres_alltools_sb128_320x180.obu");
9816 let stream = std::fs::read(&path)
9817 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
9818 let (width, height, count) = (320usize, 180usize, 10usize);
9819 let frames = match decode_stream(&stream) {
9820 Ok(frames) => frames,
9821 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
9822 };
9823 assert_eq!(frames.len(), count, "{NAME}: frame count");
9824 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, count);
9825 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
9826 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
9827 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
9828 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
9829 }
9830 }
9831
9832 /// lane-golomb r1: THE FILM ITSELF. `crates/ec-av1/fixtures/reelb_head_key_frame.obu`
9833 /// is the first frame of the user's ReelB AV1 release (3840x1608
9834 /// yuv420p10le, `ffmpeg -i <mkv> -c copy -frames:v 1 -f obu`, 147 bytes) --
9835 /// a real 10-bit key frame whose height is NOT a multiple of the 64-pixel
9836 /// superblock, so its last superblock row (mi_row=400 of 402) carries the
9837 /// edge partition symbol this lane fixed: libaom's `ec_read_partition_impl`
9838 /// returns `PARTITION_HORZ` when the gathered `split_or_horz` bit is 0, and
9839 /// this decoder used to READ that bit and throw it away, forcing SPLIT
9840 /// (class `parsed-then-discarded`). The desync surfaced two rows later as
9841 /// "a Golomb tail longer than this decoder reads" -- a refusal naming the
9842 /// symptom, never the cause.
9843 #[test]
9844 fn the_reelb_head_key_frame_decodes_pixel_exact() {
9845 const NAME: &str = "the_reelb_head_key_frame_decodes_pixel_exact";
9846 if !have_ffmpeg() {
9847 eprintln!("SKIP {NAME}: no ffmpeg");
9848 return;
9849 }
9850 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9851 .join("fixtures/reelb_head_key_frame.obu");
9852 let stream = std::fs::read(&path)
9853 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
9854 let (width, height) = (3840usize, 1608usize);
9855 let frames = match decode_stream(&stream) {
9856 Ok(frames) => frames,
9857 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
9858 };
9859 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
9860 assert_eq!((frames[0].width, frames[0].height), (width, height));
9861 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
9862 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
9863 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
9864 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
9865 }
9866 /// lane-reelckf r2: `crates/ec-av1/fixtures/reelc_kf2700.obu` is a 1920x792
9867 /// 10-bit AV1 key frame taken out of one of the user's own films
9868 /// (`ffmpeg -ss 2700 -c:v copy -f obu`, then truncated to its first temporal
9869 /// unit, 36 kB) -- the ONLY stream in this repo that contains a SKIPPED
9870 /// `UV_CFL_PRED` block. 30 aomenc recipes (r1's 20 plus r2's chroma-correlated
9871 /// `geq` sweep, cq 40..63, cpu-used 0..2, min/max-partition 4..64, 8 and
9872 /// 10 bit) never made the encoder pick one, so the counter can only be
9873 /// hard-asserted against a real film frame. The instrumented oracle agrees:
9874 /// `EC_TRACE_MODE=1 aomdec` prints 5 `EC_IMODE_VAL ... uv_mode=13 skip=1`
9875 /// lines for this frame.
9876 ///
9877 /// The defect it pins (fixed at 29cd53f, `decode.rs:7719`/`:10528`/`:10891`):
9878 /// a skipped intra block must still PREDICT with CfL -- libaom's
9879 /// `predict_and_reconstruct_intra_block` predicts every plane and guards only
9880 /// the residual on `skip_txfm`. Before the fix this frame had 499 wrong
9881 /// chroma samples (U rows 48..79 cols 464..492); after it, zero.
9882 ///
9883 /// The ffmpeg reference is `ffmpeg -f obu -i <fixture> -f rawvideo
9884 /// -pix_fmt yuv420p10le -` (what `ffmpeg_decode_sequence_10bit` runs).
9885 #[test]
9886 fn a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact() {
9887 const NAME: &str = "a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact";
9888 let path =
9889 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelc_kf2700.obu");
9890 let stream = std::fs::read(&path)
9891 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
9892 let (width, height) = (1920usize, 792usize);
9893 let before = crate::decode::reelc_chroma_counters();
9894 let frames = match decode_stream(&stream) {
9895 Ok(frames) => frames,
9896 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
9897 };
9898 let after = crate::decode::reelc_chroma_counters();
9899 let skip_cfl = after.0 - before.0;
9900 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
9901 assert_eq!((frames[0].width, frames[0].height), (width, height));
9902 // Asserted before the ffmpeg compare so an absent ffmpeg cannot make the
9903 // gate vacuous: the skipped-CfL path is exercised on every run.
9904 assert!(
9905 skip_cfl > 0,
9906 "{NAME}: zero skipped-CfL blocks -- the fixture no longer exercises defect 1"
9907 );
9908 if !have_ffmpeg() {
9909 eprintln!("SKIP {NAME} pixel compare: no ffmpeg (skipped_cfl={skip_cfl})");
9910 return;
9911 }
9912 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
9913 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
9914 assert_eq!(
9915 frames[0].u, ffmpeg_frames[0].u,
9916 "{NAME}: U vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
9917 );
9918 assert_eq!(
9919 frames[0].v, ffmpeg_frames[0].v,
9920 "{NAME}: V vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
9921 );
9922 eprintln!("{NAME}: pixel-exact, skipped_cfl={skip_cfl}");
9923 }
9924
9925 /// lane-kf1200 r2: the same film's `-ss 300` key frame, pinned because no
9926 /// aomenc recipe reaches its shape -- a SKIPPED sub-8x8 chroma block whose
9927 /// `uv_mode` is `UV_CFL_PRED`. (lane-reelckf r1 burned 20 recipes across cq
9928 /// 40..63 and nine lavfi sources hunting exactly this block and never got
9929 /// one; ledger dead-end "never produced a SKIPPED 1:4 or sub-8x8 CfL
9930 /// block".) Before the fix the two sub-8x8 skip arms passed `None` for the
9931 /// CfL argument, so the block reconstructed as flat DC and 463 bytes of
9932 /// this frame's chroma were wrong. HARD-asserts `skip_cfl_hits` moved, so
9933 /// the fixture cannot silently stop exercising the arm.
9934 #[test]
9935 fn the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact() {
9936 const NAME: &str = "the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact";
9937 if !have_ffmpeg() {
9938 eprintln!("SKIP {NAME}: no ffmpeg");
9939 return;
9940 }
9941 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9942 .join("fixtures/reelb_ss300_key_frame.obu");
9943 let stream = std::fs::read(&path)
9944 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
9945 let (width, height) = (3840usize, 1608usize);
9946 let before = crate::decode::skip_cfl_hits();
9947 let frames = match decode_stream(&stream) {
9948 Ok(frames) => frames,
9949 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
9950 };
9951 let skipped_cfl = crate::decode::skip_cfl_hits() - before;
9952 assert!(
9953 skipped_cfl > 0,
9954 "{NAME}: zero skipped sub-8x8 CfL blocks -- the fixture no longer \
9955 exercises the arm this test exists for"
9956 );
9957 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
9958 assert_eq!((frames[0].width, frames[0].height), (width, height));
9959 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
9960 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
9961 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
9962 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
9963 eprintln!("{NAME}: {skipped_cfl} skipped sub-8x8 CfL chroma blocks, frame pixel-exact");
9964 }
9965
9966 /// lane-kf900 r2: the film's key frame at -ss 900, one frame
9967 /// (`crates/ec-av1/fixtures/reelb_kf900.obu`, 484640 bytes, sha256
9968 /// `a273ae99328388be14a1ff8fa1c5a6d391a9948159eaef120e1b50e02015eb83`,
9969 /// extracted twice from independent
9970 /// `ffmpeg -ss 900 -t 2 -i <2160p AV1 HDR10 mkv> -c:v copy -f obu` runs and
9971 /// truncated to the first frame; both extracts hashed identically).
9972 ///
9973 /// This is the ONLY stream that reaches the r1 defect: a SKIPPED 8x8 intra
9974 /// leaf whose `tx_depth` symbol resolved to `TX_4X4` still publishes 4 --
9975 /// not its 8-pixel block side -- to the next block's `get_tx_size_context`
9976 /// (`set_txfm_ctxs(mbmi->tx_size, bw, bh, skip_txfm && is_inter_block(...))`,
9977 /// `decodemv.c`; the skip term is 0 for intra). It fires 15 times here and
9978 /// zero times across 108 measured aomenc recipes, so the counter is
9979 /// asserted against the film rather than against a synthesised stream.
9980 ///
9981 /// LUMA only. U/V still differ (open residue, lane-kf900 r2: 221 U and
9982 /// 47912 V samples, max |d| 23/2, first at chroma (195, 640) -- chroma
9983 /// RESIDUAL, the prediction there is bit-exact against aomdec's
9984 /// `EC_PREDOUT`), so this gate pins what is proven and no more.
9985 #[test]
9986 fn a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact()
9987 {
9988 const NAME: &str = "a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact";
9989 if !have_ffmpeg() {
9990 eprintln!("SKIP {NAME}: no ffmpeg");
9991 return;
9992 }
9993 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_kf900.obu");
9994 let stream = std::fs::read(&path)
9995 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
9996 let (width, height) = (3840usize, 1608usize);
9997 crate::decode::reset_skip_split_tx_hits();
9998 let frames = match decode_stream(&stream) {
9999 Ok(frames) => frames,
10000 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
10001 };
10002 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
10003 assert_eq!((frames[0].width, frames[0].height), (width, height));
10004 assert!(
10005 crate::decode::skip_split_tx_hits() >= 15,
10006 "{NAME}: skip_split_tx_hits() == {} -- the stream that carries the tx-context \
10007 defect stopped carrying it, so this gate proves nothing",
10008 crate::decode::skip_split_tx_hits()
10009 );
10010 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
10011 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
10012 }
10013
10014 /// lane-kf1200 r3: the same film's `-ss 600` key frame (3840x1608, one
10015 /// 8-px partial bottom superblock row), pinned because no aomenc recipe
10016 /// reaches its shape -- a SKIPPED 8x8 intra leaf whose `tx_depth` resolved
10017 /// to TX_4X4. (80 recipes swept this round: 4 frame shapes x 2 sources x
10018 /// cq 32..63 x cpu-used 0/3 x 8/10-bit, all with
10019 /// `--enable-tx-size-search=1 --enable-filter-intra=1`; every one came
10020 /// back with `skip_split_tx_hits == 0`, `lanes/kf1200-r3.report.md`.)
10021 /// An intra block reads `tx_depth` whether or not it is skipped, so the
10022 /// leaf must record its resolved 4 -- not its 8x8 side -- in the txfm
10023 /// context; recording 8 gave the NEXT block's `tx_depth` symbol the wrong
10024 /// `tx_size_cdf` row (ctx 2 where libaom reads 1) and desynced the
10025 /// entropy stream at mi (400,46). HARD-asserts `skip_split_tx_hits` moved.
10026 #[test]
10027 fn the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact() {
10028 const NAME: &str = "the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact";
10029 if !have_ffmpeg() {
10030 eprintln!("SKIP {NAME}: no ffmpeg");
10031 return;
10032 }
10033 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
10034 .join("fixtures/reelb_ss600_key_frame.obu");
10035 let stream = std::fs::read(&path)
10036 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
10037 let (width, height) = (3840usize, 1608usize);
10038 crate::decode::reset_skip_split_tx_hits();
10039 let frames = match decode_stream(&stream) {
10040 Ok(frames) => frames,
10041 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
10042 };
10043 let skipped_split_tx = crate::decode::skip_split_tx_hits();
10044 assert!(
10045 skipped_split_tx > 0,
10046 "{NAME}: zero skipped 8x8 leaves with a split transform -- the fixture no longer \
10047 exercises the arm this test exists for"
10048 );
10049 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
10050 assert_eq!((frames[0].width, frames[0].height), (width, height));
10051 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
10052 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
10053 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
10054 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
10055 eprintln!("{NAME}: {skipped_split_tx} skipped 8x8 TX_4X4 leaves, frame pixel-exact");
10056 }
10057
10058 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1
10059 /// --superres-denominator=12` key frame, decoded pixel-exact against
10060 /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s
10061 /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit
10062 /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts
10063 /// `bit_depth == 10` and `superres_hits > 0`.
10064 #[test]
10065 fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() {
10066 const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact";
10067 if !have_ffmpeg() {
10068 eprintln!("SKIP {NAME}: no ffmpeg");
10069 return;
10070 }
10071 if !have_aomenc() {
10072 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10073 return;
10074 }
10075 let (width, height) = (64usize, 64usize);
10076 let stream = encode_10bit_gradients(
10077 NAME,
10078 width,
10079 height,
10080 1,
10081 &[
10082 "--limit=1",
10083 "--kf-max-dist=0",
10084 "--superres-mode=1",
10085 "--superres-denominator=12",
10086 "--superres-kf-denominator=12",
10087 "--enable-rect-partitions=0",
10088 "--enable-ab-partitions=0",
10089 "--enable-1to4-partitions=0",
10090 "--enable-filter-intra=0",
10091 "--enable-smooth-intra=0",
10092 "--enable-paeth-intra=0",
10093 "--enable-directional-intra=0",
10094 "--enable-angle-delta=0",
10095 "--enable-tx-size-search=0",
10096 "--enable-cdef=0",
10097 "--enable-restoration=0",
10098 "--max-partition-size=32",
10099 "--min-partition-size=32",
10100 "--enable-palette=0",
10101 "--enable-intrabc=0",
10102 "--enable-cfl-intra=0",
10103 ],
10104 );
10105 assert_eq!(
10106 parsed_bit_depth(&stream),
10107 10,
10108 "{NAME}: aomenc did not actually write a 10-bit sequence header"
10109 );
10110 let before = crate::superres::superres_hits();
10111 let frames = match decode_stream(&stream) {
10112 Ok(frames) => frames,
10113 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
10114 };
10115 assert!(
10116 crate::superres::superres_hits() > before,
10117 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
10118 );
10119 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
10120 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
10121 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
10122 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
10123 eprintln!(
10124 "{NAME}: pixel-exact, superres_hits={}",
10125 crate::superres::superres_hits()
10126 );
10127 }
10128
10129 /// lane-hbdgates r1: drive one 10-bit aomenc recipe over `seeds`, decode
10130 /// every attempt and pixel-compare every SHOWN frame against ffmpeg's own
10131 /// 10-bit decode of the identical bytes. Per-tool firing counters are
10132 /// sampled PER ATTEMPT and summed only over attempts that decoded *and*
10133 /// compared -- a stream that hit a named refusal contributes nothing
10134 /// (class `counter-from-refused-stream`). Named refusals are tolerated
10135 /// and reported; a pixel mismatch is a hard failure, never a SKIP.
10136 fn ten_bit_tool_gate(
10137 name: &str,
10138 width: usize,
10139 height: usize,
10140 frames: usize,
10141 extra: &[&str],
10142 seeds: &[u32],
10143 counters: &[(&str, fn() -> usize)],
10144 ) {
10145 fn first_diff(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
10146 ours.iter()
10147 .zip(theirs.iter())
10148 .position(|(a, b)| a != b)
10149 .map(|i| {
10150 format!(
10151 "first diff at index {i} (row {}, col {}): ours {} vs ffmpeg {}",
10152 i / width,
10153 i % width,
10154 ours[i],
10155 theirs[i]
10156 )
10157 })
10158 }
10159 let mut totals = vec![0usize; counters.len()];
10160 let mut refusals: Vec<String> = Vec::new();
10161 let mut compared = 0usize;
10162 for &seed in seeds {
10163 let stream = encode_10bit_gradients_seed(name, seed, width, height, frames, extra);
10164 assert_eq!(
10165 parsed_bit_depth(&stream),
10166 10,
10167 "{name}: aomenc did not write a 10-bit sequence header (seed {seed})"
10168 );
10169 let before: Vec<usize> = counters.iter().map(|(_, f)| f()).collect();
10170 let decoded = match decode_stream(&stream) {
10171 Ok(frames) => frames,
10172 Err(e) => {
10173 refusals.push(format!("seed {seed}: {e}"));
10174 continue;
10175 }
10176 };
10177 // Deltas are read BEFORE the pixel compare so a mismatch report
10178 // says whether the tool under test actually fired on the failing
10179 // stream (a mismatch with a zero delta is some other defect).
10180 let deltas: Vec<usize> = counters
10181 .iter()
10182 .zip(before.iter())
10183 .map(|((_, f), b)| f() - b)
10184 .collect();
10185 let fired: Vec<String> = counters
10186 .iter()
10187 .zip(deltas.iter())
10188 .map(|((label, _), d)| format!("{label}={d}"))
10189 .collect();
10190 let fired = fired.join(" ");
10191 let reference = ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len());
10192 assert_eq!(
10193 decoded.len(),
10194 reference.len(),
10195 "{name}: seed {seed}: shown-frame count vs ffmpeg"
10196 );
10197 for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() {
10198 for (plane, (a, b), w) in [
10199 ("Y", (&ours.y, &theirs.y), width),
10200 ("U", (&ours.u, &theirs.u), width / 2),
10201 ("V", (&ours.v, &theirs.v), width / 2),
10202 ] {
10203 if let Some(d) = first_diff(a, b, w) {
10204 panic!("{name}: seed {seed} frame {i} plane {plane}: {d} [{fired}]");
10205 }
10206 }
10207 }
10208 compared += 1;
10209 for (i, d) in deltas.iter().enumerate() {
10210 totals[i] += d;
10211 }
10212 }
10213 assert!(
10214 compared > 0,
10215 "{name}: every attempt hit a named refusal:\n{}",
10216 refusals.join("\n")
10217 );
10218 for (i, (label, _)) in counters.iter().enumerate() {
10219 assert!(
10220 totals[i] > 0,
10221 "{name}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
10222 the gate would prove nothing about that tool. refusals:\n{}",
10223 refusals.join("\n")
10224 );
10225 }
10226 let summary: Vec<String> = counters
10227 .iter()
10228 .zip(totals.iter())
10229 .map(|((label, _), t)| format!("{label}={t}"))
10230 .collect();
10231 eprintln!(
10232 "{name}: {compared}/{} attempts pixel-exact, {}",
10233 seeds.len(),
10234 summary.join(" ")
10235 );
10236 }
10237
10238 /// lane-hbdgates r1: the four intra tools that had an 8-bit gate and no
10239 /// 10-bit one (`filter-intra`, `smooth-intra`, `paeth-intra`,
10240 /// `intra-edge-filter`) on ONE real 10-bit `aomenc` key frame, each with
10241 /// its own hard-asserted counter. His two films are yuv420p10le, so an
10242 /// 8-bit-only gate for these tools proves nothing about the streams that
10243 /// matter (lane-covbd r1).
10244 #[test]
10245 fn a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact() {
10246 const NAME: &str = "a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact";
10247 if !have_ffmpeg() {
10248 eprintln!("SKIP {NAME}: no ffmpeg");
10249 return;
10250 }
10251 if !have_aomenc() {
10252 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10253 return;
10254 }
10255 ten_bit_tool_gate(
10256 NAME,
10257 64,
10258 64,
10259 1,
10260 &[
10261 "--limit=1",
10262 "--kf-max-dist=0",
10263 "--enable-filter-intra=1",
10264 "--enable-smooth-intra=1",
10265 "--enable-paeth-intra=1",
10266 "--enable-intra-edge-filter=1",
10267 "--enable-directional-intra=1",
10268 "--enable-angle-delta=0",
10269 "--enable-rect-partitions=0",
10270 "--enable-ab-partitions=0",
10271 "--enable-1to4-partitions=0",
10272 "--enable-tx-size-search=0",
10273 "--enable-cdef=0",
10274 "--enable-restoration=0",
10275 "--max-partition-size=32",
10276 "--min-partition-size=16",
10277 "--enable-palette=0",
10278 "--enable-intrabc=0",
10279 "--enable-cfl-intra=0",
10280 "--enable-ref-frame-mvs=0",
10281 ],
10282 &[42, 7, 11, 23, 31, 57],
10283 &[
10284 ("filter_intra_hits", decode::filter_intra_hits),
10285 ("smooth_pred_hits", crate::intra::smooth_pred_hits),
10286 ("paeth_pred_hits", crate::intra::paeth_pred_hits),
10287 ("intra_edge_filter_hits", crate::intra::intra_edge_filter_hits),
10288 ],
10289 );
10290 }
10291
10292 /// lane-hbdgates r1: `--enable-restoration=1` at 10 bits. Every earlier
10293 /// bit-depth gate ran `--enable-restoration=0`, which is exactly why two
10294 /// high-bit-depth loop-restoration defects survived to 2026-09-01
10295 /// (SGR box sums unscaled, Wiener clamp at the 8-bit bound). Same recipe
10296 /// as the 8-bit LR gate, at 10 bits.
10297 // Written `#[ignore]`d on lane-hbdgates (the branch lacked lane-hbdinter's
10298 // 10-bit LR fix and failed at seed 42, frame 0, Y index 122: ours 351 vs
10299 // ffmpeg 350). Un-ignored on the merge into main 2026-09-01, where the
10300 // SGR box-sum scaling and the Wiener clamp are fixed: 16/16 attempts
10301 // pixel-exact, lr_hits=28.
10302 #[test]
10303 fn a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact() {
10304 const NAME: &str = "a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact";
10305 if !have_ffmpeg() {
10306 eprintln!("SKIP {NAME}: no ffmpeg");
10307 return;
10308 }
10309 if !have_aomenc() {
10310 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10311 return;
10312 }
10313 // 192x128 = 3x2 superblocks, so `read_lr` is re-entered per SB
10314 // (the 8-bit LR gate's own trap warning); cq-level=15 because
10315 // aomenc's RD only picks a non-RESTORE_NONE frame type at low cq.
10316 ten_bit_tool_gate(
10317 NAME,
10318 192,
10319 128,
10320 1,
10321 &[
10322 "--limit=1",
10323 "--kf-max-dist=0",
10324 "--cq-level=15",
10325 "--enable-restoration=1",
10326 "--enable-cdef=0",
10327 "--enable-rect-partitions=0",
10328 "--enable-ab-partitions=0",
10329 "--enable-1to4-partitions=0",
10330 "--enable-filter-intra=0",
10331 "--enable-smooth-intra=0",
10332 "--enable-paeth-intra=0",
10333 "--enable-tx-size-search=0",
10334 "--max-partition-size=32",
10335 "--min-partition-size=16",
10336 "--enable-palette=0",
10337 "--enable-intrabc=0",
10338 "--enable-cfl-intra=0",
10339 "--enable-ref-frame-mvs=0",
10340 ],
10341 &LR_SEEDS,
10342 &[("lr_hits", ten_bit_lr_hits)],
10343 );
10344 }
10345
10346 /// Seeds swept by the 10-bit LR gate (the 8-bit gate needs ~40 attempts
10347 /// to land a non-RESTORE_NONE frame; every attempt here still has to
10348 /// decode pixel-exact).
10349 /// lane-obmcrec r1: the `LR_SEEDS` members whose 1:4-partition stream both
10350 /// fires `obmc_pair_filter_hits` and decodes every frame pixel-exact.
10351 /// Measured over seeds 42..=73 (32 encodes): 43/46/47/65/66 fire and are
10352 /// exact; 70 and 73 fire and mismatch, but mismatch IDENTICALLY with
10353 /// `--enable-obmc=0` (seed 73 frame 1 luma, seed 70 frame 16), so their
10354 /// defect is in the `--min-partition-size=4` recipe, not in OBMC -- kept
10355 /// out of this gate rather than papered over, and reported as open.
10356 const OBMC_PAIR_SEEDS: [u32; 5] = [43, 46, 47, 65, 66];
10357
10358 const LR_SEEDS: [u32; 16] = [42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
10359
10360 /// Wiener + SGR + switchable loop-restoration firings, summed.
10361 fn ten_bit_lr_hits() -> usize {
10362 crate::restoration::wiener_hits()
10363 + crate::restoration::sgrproj_hits()
10364 + crate::restoration::switchable_hits()
10365 }
10366
10367 /// lane-reelckf2 r1: loop restoration on frame sizes whose LAST stripe is
10368 /// partial, with 128-sample superblocks -- the two stripe shapes whose
10369 /// boundary substitution is special (`filter_restoration_unit`: the first
10370 /// stripe is 8 rows short and takes its above boundary from the frame's
10371 /// own top rows, the last one is truncated and takes its below boundary
10372 /// from the frame's own bottom row) had no gate at all: every earlier LR
10373 /// size (192x128, 160x96) is a whole multiple of 64 rows and ran at
10374 /// `--sb-size=64`. 152 = 2*64+24 and 216 = 3*64+24 both leave a 32-row
10375 /// tail stripe, mirroring the 792-row 10-bit film that made this lane.
10376 /// `lr_stripe0_hits`/`lr_last_stripe_hits` are hard-asserted per attempt
10377 /// by [`ten_bit_tool_gate`], so an RD that picked RESTORE_NONE on either
10378 /// stripe cannot pass.
10379 #[test]
10380 fn a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact() {
10381 const NAME: &str =
10382 "a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact";
10383 if !have_ffmpeg() {
10384 eprintln!("SKIP {NAME}: no ffmpeg");
10385 return;
10386 }
10387 if !have_aomenc() {
10388 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10389 return;
10390 }
10391 // `--sb-size=128` goes in `extra`, which the helper appends AFTER its
10392 // own `--sb-size=64` (aomenc keeps the LAST occurrence of a repeated
10393 // flag, measured 2026-09-02); `--max-partition-size=32` keeps the 128
10394 // root on SPLIT, the only 128-root partition decoded today.
10395 for (width, height, cq) in [(256usize, 152usize, "15"), (384, 216, "15"), (256, 152, "25")]
10396 {
10397 ten_bit_tool_gate(
10398 &format!("{NAME} {width}x{height} cq{cq}"),
10399 width,
10400 height,
10401 1,
10402 &[
10403 "--limit=1",
10404 "--kf-max-dist=0",
10405 &format!("--cq-level={cq}"),
10406 "--sb-size=128",
10407 "--enable-restoration=1",
10408 "--enable-cdef=0",
10409 "--enable-rect-partitions=0",
10410 "--enable-ab-partitions=0",
10411 "--enable-1to4-partitions=0",
10412 "--enable-filter-intra=0",
10413 "--enable-smooth-intra=0",
10414 "--enable-paeth-intra=0",
10415 "--enable-tx-size-search=0",
10416 "--max-partition-size=32",
10417 "--min-partition-size=16",
10418 "--enable-palette=0",
10419 "--enable-intrabc=0",
10420 "--enable-cfl-intra=0",
10421 "--enable-ref-frame-mvs=0",
10422 ],
10423 &LR_SEEDS,
10424 &[
10425 ("lr_hits", ten_bit_lr_hits),
10426 ("lr_stripe0_hits", crate::restoration::lr_stripe0_hits),
10427 ("lr_last_stripe_hits", crate::restoration::lr_last_stripe_hits),
10428 ],
10429 );
10430 }
10431 }
10432
10433 /// lane-hbdgates r1: `--enable-rect-partitions=1 --enable-ab-partitions=1`
10434 /// at 10 bits, one intra stream, one counter per tool
10435 /// (`rect_partition_hits`, `partab_hits`) so a stream that only fired the
10436 /// rect arms cannot stand in for AB.
10437 #[test]
10438 fn a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact() {
10439 const NAME: &str = "a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact";
10440 if !have_ffmpeg() {
10441 eprintln!("SKIP {NAME}: no ffmpeg");
10442 return;
10443 }
10444 if !have_aomenc() {
10445 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10446 return;
10447 }
10448 // The 8-bit free-partition/AB recipe, verbatim, at 10 bits: AB
10449 // splits are an INTER dispatch here (intra-frame AB is still a named
10450 // refusal), so the stream needs alt-refs and 24 frames, not one key
10451 // frame.
10452 ten_bit_tool_gate(
10453 NAME,
10454 64,
10455 64,
10456 24,
10457 &[
10458 "--cq-level=45",
10459 "--kf-max-dist=1000",
10460 "--auto-alt-ref=1",
10461 "--lag-in-frames=16",
10462 "--enable-fwd-kf=0",
10463 "--enable-order-hint=1",
10464 "--enable-warped-motion=1",
10465 "--enable-obmc=1",
10466 "--tune-content=default",
10467 "--enable-masked-comp=0",
10468 "--enable-interintra-comp=0",
10469 "--enable-onesided-comp=0",
10470 "--enable-interintra-wedge=0",
10471 "--enable-smooth-interintra=0",
10472 "--enable-rect-partitions=1",
10473 "--enable-ab-partitions=1",
10474 "--enable-1to4-partitions=0",
10475 "--enable-filter-intra=0",
10476 "--enable-smooth-intra=0",
10477 "--enable-paeth-intra=0",
10478 "--enable-directional-intra=0",
10479 "--enable-angle-delta=0",
10480 "--enable-tx-size-search=0",
10481 "--enable-cdef=0",
10482 "--enable-restoration=0",
10483 "--max-partition-size=32",
10484 "--min-partition-size=16",
10485 "--enable-palette=0",
10486 "--enable-intrabc=0",
10487 "--enable-cfl-intra=0",
10488 "--enable-ref-frame-mvs=0",
10489 ],
10490 &LR_SEEDS,
10491 &[
10492 ("rect_partition_hits", decode::rect_partition_hits),
10493 ("partab_hits", decode::partab_hits),
10494 ],
10495 );
10496 }
10497
10498 /// lane-obmcrec r1: OBMC whose above/left neighbour is a 4-wide/4-tall
10499 /// 1:4-partition strip -- the shape the three 1080p 10-bit film cuts
10500 /// refused on ("an OBMC neighbour whose switchable interp filter was never
10501 /// recorded"). `overlappable_above`/`_left` snap such a neighbour to the
10502 /// chroma pair's SECOND mi but used to read its interp filter from the
10503 /// FIRST one, a different block whose filter record is the intra
10504 /// `[3, 3]` sentinel whenever that half is intra. `obmc_pair_filter_hits`
10505 /// counts exactly that neighbour shape, so a stream without 1:4 strips
10506 /// next to an OBMC block cannot stand in for it.
10507 #[test]
10508 fn a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact() {
10509 const NAME: &str = "a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact";
10510 if !have_ffmpeg() {
10511 eprintln!("SKIP {NAME}: no ffmpeg");
10512 return;
10513 }
10514 if !have_aomenc() {
10515 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10516 return;
10517 }
10518 ten_bit_tool_gate(
10519 NAME,
10520 128,
10521 128,
10522 24,
10523 &[
10524 "--ec-fixture-noise",
10525 "--cq-level=45",
10526 "--kf-max-dist=1000",
10527 "--auto-alt-ref=1",
10528 "--lag-in-frames=16",
10529 "--enable-fwd-kf=0",
10530 "--enable-order-hint=1",
10531 "--enable-warped-motion=0",
10532 "--enable-obmc=1",
10533 "--tune-content=default",
10534 "--enable-masked-comp=0",
10535 "--enable-interintra-comp=0",
10536 "--enable-onesided-comp=0",
10537 "--enable-interintra-wedge=0",
10538 "--enable-smooth-interintra=0",
10539 "--enable-rect-partitions=1",
10540 "--enable-ab-partitions=0",
10541 "--enable-1to4-partitions=1",
10542 "--enable-filter-intra=0",
10543 "--enable-smooth-intra=0",
10544 "--enable-paeth-intra=0",
10545 "--enable-directional-intra=0",
10546 "--enable-angle-delta=0",
10547 "--enable-tx-size-search=0",
10548 "--enable-cdef=0",
10549 "--enable-restoration=0",
10550 "--max-partition-size=32",
10551 "--min-partition-size=4",
10552 "--enable-palette=0",
10553 "--enable-intrabc=0",
10554 "--enable-cfl-intra=0",
10555 "--enable-ref-frame-mvs=0",
10556 ],
10557 &OBMC_PAIR_SEEDS,
10558 &[("obmc_pair_filter_hits", decode::obmc_pair_filter_hits)],
10559 );
10560 }
10561
10562 /// `bit_depth` of the first sequence header in `stream`.
10563 fn parsed_bit_depth(stream: &[u8]) -> u8 {
10564 let mut probe = Av1Parser::new();
10565 let mut pos = 0usize;
10566 while pos < stream.len() && probe.sequence_header().is_none() {
10567 let obu = probe.parse_obu(&stream[pos..]).unwrap();
10568 pos += obu.total_size;
10569 }
10570 probe
10571 .sequence_header()
10572 .expect("stream has a sequence header OBU")
10573 .color_config
10574 .bit_depth
10575 }
10576
10577 /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and
10578 /// encode it with a real 10-bit `aomenc`, returning the OBU stream.
10579 /// `extra` carries the tool flags under test.
10580 fn encode_10bit_gradients(
10581 name: &str,
10582 width: usize,
10583 height: usize,
10584 frames: usize,
10585 extra: &[&str],
10586 ) -> Vec<u8> {
10587 encode_10bit_gradients_seed(name, 42, width, height, frames, extra)
10588 }
10589
10590 /// As [`encode_10bit_gradients`], but with the fixture seed exposed --
10591 /// lane-hbdgates r1 sweeps seeds so a tool that aomenc's RD declines on
10592 /// one fixture still gets a firing stream.
10593 fn encode_10bit_gradients_seed(
10594 name: &str,
10595 seed: u32,
10596 width: usize,
10597 height: usize,
10598 frames: usize,
10599 extra: &[&str],
10600 ) -> Vec<u8> {
10601 let duration = frames as f64 / 25.0;
10602 // lane-ab32 r1: `--ec-fixture-noise` is not an aomenc flag -- it is a
10603 // fixture request, consumed (and stripped) here: the smooth gradients
10604 // source codes as PARTITION_NONE everywhere, so a partition gate needs
10605 // seeded noise on top of it to give the RD a reason to split.
10606 let noisy = extra.contains(&"--ec-fixture-noise");
10607 let stripped: Vec<&str> = extra
10608 .iter()
10609 .copied()
10610 .filter(|a| *a != "--ec-fixture-noise")
10611 .collect();
10612 let extra: &[&str] = &stripped;
10613 let base = gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
10614 let source = if noisy {
10615 format!("{base},noise=alls=40:all_seed={seed}")
10616 } else {
10617 base
10618 };
10619 let y4m = Command::new("ffmpeg")
10620 .args([
10621 "-v",
10622 "error",
10623 "-f",
10624 "lavfi",
10625 "-i",
10626 &source,
10627 "-pix_fmt",
10628 "yuv420p10le",
10629 "-strict",
10630 "-1",
10631 "-t",
10632 &format!("{duration}"),
10633 "-f",
10634 "yuv4mpegpipe",
10635 "-",
10636 ])
10637 .stdin(Stdio::null())
10638 .stdout(Stdio::piped())
10639 .stderr(Stdio::piped())
10640 .output()
10641 .expect("ffmpeg failed to run");
10642 assert!(
10643 y4m.status.success(),
10644 "{name}: ffmpeg failed to render the 10-bit fixture: {}",
10645 String::from_utf8_lossy(&y4m.stderr)
10646 );
10647 let mut args: Vec<&str> = vec!["--codec=av1", "--passes=1", "--end-usage=q"];
10648 // lane-hbdgates r1: a caller-supplied `--cq-level` REPLACES the
10649 // default rather than being appended after it -- two `--cq-level`
10650 // flags on one aomenc line is a coin flip on which one lands.
10651 if !extra.iter().any(|a| a.starts_with("--cq-level=")) {
10652 args.push("--cq-level=30");
10653 }
10654 args.extend_from_slice(&[
10655 "--cpu-used=0",
10656 "--threads=1",
10657 "--row-mt=0",
10658 "--sb-size=64",
10659 "--input-bit-depth=10",
10660 "--bit-depth=10",
10661 ]);
10662 args.extend_from_slice(extra);
10663 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
10664 let out = run_with_stdin(Command::new(aomenc_path())
10665 .args(&args), &y4m.stdout);
10666 assert!(
10667 out.status.success(),
10668 "{name}: aomenc refused the 10-bit fixture: {}",
10669 String::from_utf8_lossy(&out.stderr)
10670 );
10671 out.stdout
10672 }
10673
10674 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
10675 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
10676 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
10677 /// which flattened chroma to a single value specifically to avoid
10678 /// exercising this path). Same square-only recipe as the palette-Y gate
10679 /// (`--enable-rect-partitions=0`/`-ab-`/`-1to4-`, fixed 32x32 partition)
10680 /// so a UV palette block never lands inside the still-refused HORZ/VERT
10681 /// screen-content strip. HARD-asserts [`decode::palette_uv_hits`] moved
10682 /// -- a stream that never reads a real UV palette block would decode (or
10683 /// not) by construction without proving this milestone at all
10684 /// ([[gate-blind-to-feature]]).
10685 #[test]
10686 fn a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact() {
10687 const NAME: &str = "a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact";
10688 if !have_ffmpeg() {
10689 eprintln!("SKIP {NAME}: no ffmpeg");
10690 return;
10691 }
10692 if !have_aomenc() {
10693 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10694 return;
10695 }
10696 let source = "testsrc2=size=64x64:rate=25";
10697 fn render(source: &str) -> Vec<u8> {
10698 Command::new("ffmpeg")
10699 .args([
10700 "-v",
10701 "error",
10702 "-f",
10703 "lavfi",
10704 "-i",
10705 source,
10706 "-pix_fmt",
10707 "yuv420p",
10708 "-t",
10709 "0.16",
10710 "-f",
10711 "yuv4mpegpipe",
10712 "-",
10713 ])
10714 .stdin(Stdio::null())
10715 .stdout(Stdio::piped())
10716 .stderr(Stdio::piped())
10717 .output()
10718 .expect("ffmpeg failed to run")
10719 .stdout
10720 }
10721 let y4m_a = render(source);
10722 let y4m_b = render(source);
10723 assert_eq!(
10724 y4m_a, y4m_b,
10725 "testsrc2 must render byte-identical across two runs"
10726 );
10727 let y4m = y4m_a;
10728 let out = run_with_stdin(Command::new(aomenc_path())
10729 .args([
10730 "--codec=av1",
10731 "--passes=1",
10732 "--end-usage=q",
10733 "--cq-level=30",
10734 "--cpu-used=0",
10735 "--threads=1",
10736 "--row-mt=0",
10737 "--sb-size=64",
10738 "--tune-content=screen",
10739 "--enable-palette=1",
10740 "--enable-intrabc=0",
10741 "--enable-rect-partitions=0",
10742 "--enable-ab-partitions=0",
10743 "--enable-1to4-partitions=0",
10744 "--min-partition-size=32",
10745 "--max-partition-size=32",
10746 "--enable-filter-intra=0",
10747 "--enable-cdef=0",
10748 "--enable-restoration=0",
10749 "--enable-tx-size-search=0",
10750 "--loopfilter-control=0",
10751 "--obu",
10752 "-o",
10753 "-",
10754 "-",
10755 ]), &y4m);
10756 assert!(
10757 out.status.success(),
10758 "aomenc refused the fixture: {}",
10759 String::from_utf8_lossy(&out.stderr)
10760 );
10761 let stream = out.stdout;
10762 let before = decode::palette_uv_hits();
10763 let frames = match decode_stream(&stream) {
10764 Ok(frames) => frames,
10765 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
10766 };
10767 assert!(
10768 decode::palette_uv_hits() > before,
10769 "palette_uv_mode never fired decoding this stream -- gate is vacuous"
10770 );
10771 let frame_count = frames.len();
10772 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, frame_count);
10773 for i in 0..frame_count {
10774 assert_eq!(frames[i].y, ffmpeg_frames[i].y, "luma vs ffmpeg, frame {i}");
10775 assert_eq!(frames[i].u, ffmpeg_frames[i].u, "U vs ffmpeg, frame {i}");
10776 assert_eq!(frames[i].v, ffmpeg_frames[i].v, "V vs ffmpeg, frame {i}");
10777 }
10778 }
10779
10780 /// A real `aomenc` fixture that lands palette syntax on a HORZ/VERT
10781 /// intra strip (lane-palette2 r5, gating r4's `read_intra_mode_rect`
10782 /// wiring). `smptebars`/`rgbtestsrc` at plain default settings both hit a
10783 /// SQUARE palette refusal or an unrelated 32x32 `HORZ_A`/`VERT_A`/etc
10784 /// partition FIRST on every size/cq combo probed -- `--enable-ab-
10785 /// partitions=0` measurably does not stop aomenc choosing one at this
10786 /// screen-content tune (byte-identical output with `=0` vs `=1`, same
10787 /// aomenc quirk as `[[lane-sbpart-r2]]`'s SB-level AB). Forcing
10788 /// `--min/max-partition-size=64` sidesteps that whole 32x32-level code
10789 /// path: the only choices left at the (single, key-frame) superblock are
10790 /// NONE/SPLIT/HORZ/VERT/AB/1to4 straight from [`decode_block_rect64`],
10791 /// and a size/cq sweep (measured live this round) reliably lands
10792 /// PARTITION_HORZ/VERT with a real (non-split-tx) palette block on both
10793 /// sources. Drives `decode_stream` directly (below any refusal) and
10794 /// HARD-asserts [`decode::palette_rect_hits`] moved on every attempt that
10795 /// didn't refuse, before comparing pixels ([[gate-blind-to-feature]]) --
10796 /// a decode that never lands a rect palette block is not a match.
10797 #[test]
10798 fn a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact() {
10799 const NAME: &str = "a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact";
10800 let _gate_lock = lock_gate_counters();
10801 if !have_ffmpeg() {
10802 eprintln!("SKIP {NAME}: no ffmpeg");
10803 return;
10804 }
10805 if !have_aomenc() {
10806 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10807 return;
10808 }
10809 let mut matched = 0u32;
10810 let mut uncounted_exact = 0u32;
10811 let mut named_refusals = 0u32;
10812 let mut attempts = 0u32;
10813 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
10814 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
10815 for src_name in ["smptebars", "rgbtestsrc"] {
10816 for (width, height) in sizes {
10817 for cq in cqs {
10818 attempts += 1;
10819 let source = format!("{src_name}=size={width}x{height}:rate=25");
10820 let y4m = Command::new("ffmpeg")
10821 .args([
10822 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p",
10823 "-t", "0.04", "-f", "yuv4mpegpipe", "-",
10824 ])
10825 .stdin(Stdio::null())
10826 .stdout(Stdio::piped())
10827 .stderr(Stdio::piped())
10828 .output()
10829 .expect("ffmpeg failed to run");
10830 assert!(
10831 y4m.status.success(),
10832 "ffmpeg fixture: {}",
10833 String::from_utf8_lossy(&y4m.stderr)
10834 );
10835 let cq_arg = format!("--cq-level={cq}");
10836 let out = run_with_stdin(Command::new(aomenc_path())
10837 .args([
10838 "--codec=av1",
10839 "--passes=1",
10840 "--end-usage=q",
10841 &cq_arg,
10842 "--cpu-used=4",
10843 "--threads=1",
10844 "--row-mt=0",
10845 "--sb-size=64",
10846 "--enable-palette=1",
10847 "--min-partition-size=16",
10848 "--max-partition-size=64",
10849 "--obu",
10850 "-o",
10851 "-",
10852 "-",
10853 ]), &y4m.stdout);
10854 assert!(
10855 out.status.success(),
10856 "aomenc refused the fixture ({source} cq={cq}): {}",
10857 String::from_utf8_lossy(&out.stderr)
10858 );
10859 let stream = out.stdout;
10860 let before = crate::decode::palette_rect_hits();
10861 let frames = match decode_stream(&stream) {
10862 Err(e) => {
10863 let msg = e.to_string();
10864 assert!(
10865 msg.contains("unsupported"),
10866 "{NAME} failed outright, not a named refusal \
10867 ({source} cq={cq}): {msg}"
10868 );
10869 named_refusals += 1;
10870 eprintln!("{source} cq={cq}: refusal: {msg}");
10871 continue;
10872 }
10873 Ok(frames) => frames,
10874 };
10875 // A successful decode is ALWAYS pixel-compared; the hit
10876 // counter only decides whether the attempt counts toward
10877 // the hit-asserting total (class
10878 // [[gate-skips-on-its-own-failure]]: the old `continue`
10879 // here let 16/70 decoded attempts past without any pixel
10880 // check at all).
10881 let counted = crate::decode::palette_rect_hits() != before;
10882 if !counted {
10883 eprintln!(
10884 "{NAME}: {source} cq={cq} decoded without ever landing a rect \
10885 palette block (palette_rect_hits unchanged) -- pixel-compared, \
10886 not counted toward the hit assertion"
10887 );
10888 }
10889 let frame_count = frames.len();
10890 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
10891 if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| {
10892 got.y != want.y || got.u != want.u || got.v != want.v
10893 }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
10894 {
10895 std::fs::write(&path, &stream).expect("writing pinned stream");
10896 eprintln!(
10897 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
10898 );
10899 }
10900 for i in 0..frame_count {
10901 assert_eq!(
10902 frames[i].y, ffmpeg_frames[i].y,
10903 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
10904 );
10905 assert_eq!(
10906 frames[i].u, ffmpeg_frames[i].u,
10907 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
10908 );
10909 assert_eq!(
10910 frames[i].v, ffmpeg_frames[i].v,
10911 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
10912 );
10913 }
10914 if counted {
10915 matched += 1;
10916 } else {
10917 uncounted_exact += 1;
10918 }
10919 }
10920 }
10921 }
10922 assert!(
10923 matched > 0,
10924 "{NAME}: no attempt out of {attempts} ever landed a matching rect palette \
10925 block ({named_refusals} named refusals) -- palette_rect_hits never proven \
10926 pixel-exact"
10927 );
10928 eprintln!(
10929 "{NAME}: {matched}/{attempts} attempts matched pixel-exact, \
10930 {uncounted_exact} decoded-and-pixel-exact but uncounted, {named_refusals} \
10931 named refusals, palette_rect_hits={}",
10932 crate::decode::palette_rect_hits()
10933 );
10934 }
10935
10936 /// The BROAD case (lane-palette2 r6, per its charter): a HORZ/VERT intra
10937 /// strip in a screen-content-tools frame that does NOT necessarily use a
10938 /// palette. This is what the refusal r4 removed actually guarded --
10939 /// [`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`] above
10940 /// gates the rarer "and picks a palette" case, which r5 measured RD
10941 /// almost never chooses -- 39/70 of that same sweep DID land here (a
10942 /// clean rect-strip decode with `palette_rect_hits` unchanged), just
10943 /// uncounted by r5's narrower assertion. Same `--min/max-partition-size=64`
10944 /// recipe r5 measured live to dodge the 32x32-level AB-partition quirk
10945 /// ([[lane-sbpart-r2]]), single key frame, size/cq sweep. HARD-asserts
10946 /// [`decode::rect_screen_content_hits`] moved -- proof this stream
10947 /// actually ran [`read_intra_mode_rect`]'s screen-content-tools branch --
10948 /// before comparing pixels.
10949 #[test]
10950 fn a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact() {
10951 const NAME: &str = "a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact";
10952 let _gate_lock = lock_gate_counters();
10953 if !have_ffmpeg() {
10954 eprintln!("SKIP {NAME}: no ffmpeg");
10955 return;
10956 }
10957 if !have_aomenc() {
10958 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10959 return;
10960 }
10961 let mut matched = 0u32;
10962 // Blocks that reconstructed a palette-Y prediction through a SPLIT
10963 // luma transform (lane-palette2 r7's lifted refusal): the same
10964 // screen-content streams exercise it, so this gate proves both.
10965 let mut split_palette_matched = 0u32;
10966 let mut uncounted_exact = 0u32;
10967 let mut named_refusals = 0u32;
10968 let mut attempts = 0u32;
10969 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
10970 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
10971 for src_name in ["smptebars", "rgbtestsrc"] {
10972 for (width, height) in sizes {
10973 for cq in cqs {
10974 attempts += 1;
10975 let source = format!("{src_name}=size={width}x{height}:rate=25");
10976 let y4m = Command::new("ffmpeg")
10977 .args([
10978 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p",
10979 "-t", "0.04", "-f", "yuv4mpegpipe", "-",
10980 ])
10981 .stdin(Stdio::null())
10982 .stdout(Stdio::piped())
10983 .stderr(Stdio::piped())
10984 .output()
10985 .expect("ffmpeg failed to run");
10986 assert!(
10987 y4m.status.success(),
10988 "ffmpeg fixture: {}",
10989 String::from_utf8_lossy(&y4m.stderr)
10990 );
10991 let cq_arg = format!("--cq-level={cq}");
10992 let out = run_with_stdin(Command::new(aomenc_path())
10993 .args([
10994 "--codec=av1",
10995 "--passes=1",
10996 "--end-usage=q",
10997 &cq_arg,
10998 "--cpu-used=4",
10999 "--threads=1",
11000 "--row-mt=0",
11001 "--sb-size=64",
11002 "--enable-palette=1",
11003 "--min-partition-size=16",
11004 "--max-partition-size=64",
11005 "--obu",
11006 "-o",
11007 "-",
11008 "-",
11009 ]), &y4m.stdout);
11010 assert!(
11011 out.status.success(),
11012 "aomenc refused the fixture ({source} cq={cq}): {}",
11013 String::from_utf8_lossy(&out.stderr)
11014 );
11015 let stream = out.stdout;
11016 let before = crate::decode::rect_screen_content_hits();
11017 let split_before = crate::decode::palette_split_tx_hits();
11018 let frames = match decode_stream(&stream) {
11019 Err(e) => {
11020 let msg = e.to_string();
11021 assert!(
11022 msg.contains("unsupported"),
11023 "{NAME} failed outright, not a named refusal \
11024 ({source} cq={cq}): {msg}"
11025 );
11026 named_refusals += 1;
11027 eprintln!("{source} cq={cq}: refusal: {msg}");
11028 continue;
11029 }
11030 Ok(frames) => frames,
11031 };
11032 // Same integrity rule as the palette gate above: decoded
11033 // means pixel-compared, counter or no counter.
11034 let counted = crate::decode::rect_screen_content_hits() != before;
11035 if !counted {
11036 eprintln!(
11037 "{NAME}: {source} cq={cq} decoded without ever running the rect \
11038 screen-content path (rect_screen_content_hits unchanged) -- \
11039 pixel-compared, not counted toward the hit assertion"
11040 );
11041 }
11042 let frame_count = frames.len();
11043 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
11044 if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| {
11045 got.y != want.y || got.u != want.u || got.v != want.v
11046 }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
11047 {
11048 std::fs::write(&path, &stream).expect("writing pinned stream");
11049 eprintln!(
11050 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
11051 );
11052 }
11053 for i in 0..frame_count {
11054 assert_eq!(
11055 frames[i].y, ffmpeg_frames[i].y,
11056 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
11057 );
11058 assert_eq!(
11059 frames[i].u, ffmpeg_frames[i].u,
11060 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
11061 );
11062 assert_eq!(
11063 frames[i].v, ffmpeg_frames[i].v,
11064 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
11065 );
11066 }
11067 if counted {
11068 matched += 1;
11069 } else {
11070 uncounted_exact += 1;
11071 }
11072 if counted && crate::decode::palette_split_tx_hits() > split_before {
11073 split_palette_matched += 1;
11074 }
11075 }
11076 }
11077 }
11078 assert!(
11079 split_palette_matched > 0,
11080 "{NAME}: no pixel-exact attempt ever reconstructed a palette block with a \
11081 split luma transform -- the lifted refusal is ungated"
11082 );
11083 assert!(
11084 matched > 0,
11085 "{NAME}: no attempt out of {attempts} ever landed a matching rect \
11086 screen-content block ({named_refusals} named refusals) -- \
11087 rect_screen_content_hits never proven pixel-exact"
11088 );
11089 eprintln!(
11090 "{NAME}: {matched}/{attempts} attempts matched pixel-exact \
11091 ({split_palette_matched} of them through a split-transform palette block), \
11092 {uncounted_exact} decoded-and-pixel-exact but uncounted, \
11093 {named_refusals} named refusals, rect_screen_content_hits={}, \
11094 palette_split_tx_hits={}",
11095 crate::decode::rect_screen_content_hits(),
11096 crate::decode::palette_split_tx_hits()
11097 );
11098 }
11099
11100 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s
11101 /// harness, but with the deblocking filter left *on* (no
11102 /// `--loopfilter-control=0`) at a crf high enough that libaom actually
11103 /// picks a nonzero level -- proves `apply_deblock` itself, not just that
11104 /// this decoder still works when every edge lands on level 0. CDEF
11105 /// stays off so a pixel mismatch can only come from the loop filter.
11106 #[test]
11107 fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() {
11108 if !have_ffmpeg() {
11109 eprintln!(
11110 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no ffmpeg"
11111 );
11112 return;
11113 }
11114 if !have_aomenc() {
11115 eprintln!(
11116 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no aomenc at {}",
11117 aomenc_path().display()
11118 );
11119 return;
11120 }
11121 let (width, height) = (64usize, 64usize);
11122 let source = gradients_source(42, width, height, "duration=0.04:rate=25");
11123 let y4m = Command::new("ffmpeg")
11124 .args(["-v", "error", "-f", "lavfi", "-i"])
11125 .arg(&source)
11126 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
11127 .stdin(Stdio::null())
11128 .stdout(Stdio::piped())
11129 .stderr(Stdio::piped())
11130 .output()
11131 .expect("ffmpeg failed to run");
11132 assert!(
11133 y4m.status.success(),
11134 "ffmpeg fixture: {}",
11135 String::from_utf8_lossy(&y4m.stderr)
11136 );
11137 let out = run_with_stdin(Command::new(aomenc_path())
11138 .args([
11139 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
11140 // occurrence, so overrides go before the base list).
11141 "--loopfilter-control=1",
11142 "--codec=av1",
11143 "--passes=1",
11144 "--end-usage=q",
11145 "--cq-level=55",
11146 "--cpu-used=0",
11147 "--enable-filter-intra=0",
11148 "--enable-smooth-intra=0",
11149 "--enable-paeth-intra=0",
11150 "--enable-directional-intra=0",
11151 "--enable-angle-delta=0",
11152 "--enable-tx-size-search=0",
11153 "--enable-cdef=0",
11154 // Loop restoration is a named refusal (aomenc's RD picks
11155 // Sgrproj on this kind of content) -- off in every recipe
11156 // whose test targets a different surface.
11157 "--enable-restoration=0",
11158 "--max-partition-size=32",
11159 "--enable-palette=0",
11160 "--enable-intrabc=0",
11161 "--enable-cfl-intra=0",
11162 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
11163 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
11164 "--enable-ref-frame-mvs=0",
11165 "--obu",
11166 "-o",
11167 "-",
11168 "-",
11169 ]), &y4m.stdout);
11170 assert!(
11171 out.status.success(),
11172 "aomenc refused the fixture: {}",
11173 String::from_utf8_lossy(&out.stderr)
11174 );
11175 let stream = out.stdout;
11176 let before = decode::deblock_hits();
11177 let frames = match decode_stream(&stream) {
11178 Ok(frames) => frames,
11179 Err(e) => {
11180 eprintln!(
11181 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: {e}"
11182 );
11183 return;
11184 }
11185 };
11186 assert!(
11187 decode::deblock_hits() > before,
11188 "no deblocking edge fired decoding this stream -- raise cq-level"
11189 );
11190 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
11191 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
11192 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
11193 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
11194 }
11195
11196 /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`],
11197 /// but WITHOUT `--enable-tx-size-search=0` -- the one flag every other
11198 /// recipe in this file pins off specifically to keep the stream on
11199 /// `TxMode::Largest`. Dropped, aomenc's RD is free to pick
11200 /// `TxMode::Select` and split some blocks' luma transform below their own
11201 /// side (spec 5.11.16), which is what this test's `tx_depth_hits()`
11202 /// counter proves actually happened -- a stream that resolves every
11203 /// `tx_depth` to 0 would pixel-match by construction (identical to
11204 /// `TxMode::Largest`) without exercising the new split-TU decode path at
11205 /// all. Same multi-seed retry shape as
11206 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]:
11207 /// aomenc's own RD is free (with tx-size search on) to also occasionally
11208 /// pick `allow_screen_content_tools` on this content, a separate,
11209 /// already-named refusal -- try several seeds, and the first stream that
11210 /// both decodes AND actually split a transform must be pixel-exact.
11211 #[test]
11212 fn a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact() {
11213 if !have_ffmpeg() {
11214 eprintln!(
11215 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no ffmpeg"
11216 );
11217 return;
11218 }
11219 if !have_aomenc() {
11220 eprintln!(
11221 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no aomenc at {}",
11222 aomenc_path().display()
11223 );
11224 return;
11225 }
11226 let (width, height) = (64usize, 64usize);
11227 let mut refusals = Vec::new();
11228 let mut uncounted_exact = 0u32;
11229 for attempt in 0..40u32 {
11230 let seed = 42 + attempt;
11231 // A flat gradient never has enough local detail for the RD
11232 // search to prefer a split transform over the block's own full
11233 // size -- `mandelbrot`'s fractal boundary gives every attempt
11234 // (a different `start_scale`) sharp, varied-frequency edges.
11235 // start_scale 5.0 is the proven first try (decodes pixel-exact
11236 // AND reads the seven-symbol set-1 tx_type rows on TX8 TUs);
11237 // later attempts walk down for variety when aomenc's RD flips
11238 // elsewhere.
11239 let source = format!(
11240 "mandelbrot=size=64x64:start_scale={}:rate=25",
11241 5.0 - f64::from(attempt) * 0.06
11242 );
11243 let y4m = Command::new("ffmpeg")
11244 .args([
11245 "-v",
11246 "error",
11247 "-f",
11248 "lavfi",
11249 "-i",
11250 &source,
11251 // Desaturated: chroma stays flat (constant 128) so
11252 // `uv_mode` always resolves to `DC_PRED` and this
11253 // decoder's still-unsupported directional-chroma round-2
11254 // gap never fires, leaving the luma detail alone to
11255 // drive whether `TxMode::Select`'s RD splits a block.
11256 "-vf",
11257 "hue=s=0",
11258 "-pix_fmt",
11259 "yuv420p",
11260 "-t",
11261 "0.04",
11262 "-f",
11263 "yuv4mpegpipe",
11264 "-",
11265 ])
11266 .stdin(Stdio::null())
11267 .stdout(Stdio::piped())
11268 .stderr(Stdio::piped())
11269 .output()
11270 .expect("ffmpeg failed to run");
11271 assert!(
11272 y4m.status.success(),
11273 "ffmpeg fixture: {}",
11274 String::from_utf8_lossy(&y4m.stderr)
11275 );
11276 let out = run_with_stdin(Command::new(aomenc_path())
11277 .args([
11278 "--codec=av1",
11279 "--passes=1",
11280 "--end-usage=q",
11281 "--cq-level=45",
11282 "--cpu-used=0",
11283 "--enable-rect-partitions=0",
11284 "--enable-ab-partitions=0",
11285 "--enable-1to4-partitions=0",
11286 "--enable-filter-intra=0",
11287 // Every non-DC intra tool off: directional chroma and
11288 // angle deltas are separate round-2 gaps, and DC-only
11289 // residual is exactly what gives the RD search a reason
11290 // to split a transform.
11291 "--enable-smooth-intra=0",
11292 "--enable-paeth-intra=0",
11293 "--enable-directional-intra=0",
11294 "--enable-angle-delta=0",
11295 "--enable-cdef=0",
11296 // Loop restoration is a named refusal (aomenc's RD picks
11297 // Sgrproj on this kind of content) -- off in every recipe
11298 // whose test targets a different surface.
11299 "--enable-restoration=0",
11300 "--max-partition-size=32",
11301 // 16x16 blocks are what split into the TX8 TUs whose
11302 // set-1 tx_type rows this gate exists to prove; some
11303 // scales resolve depth 2 (TX4, a named refusal) and the
11304 // attempt loop just moves on.
11305 "--min-partition-size=16",
11306 "--enable-palette=0",
11307 "--enable-intrabc=0",
11308 "--enable-cfl-intra=0",
11309 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
11310 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
11311 "--enable-ref-frame-mvs=0",
11312 "--obu",
11313 "-o",
11314 "-",
11315 "-",
11316 ]), &y4m.stdout);
11317 assert!(
11318 out.status.success(),
11319 "aomenc refused the fixture: {}",
11320 String::from_utf8_lossy(&out.stderr)
11321 );
11322 let stream = out.stdout;
11323 let before = decode::tx_depth_hits();
11324 let frames = match decode_stream(&stream) {
11325 Ok(frames) => frames,
11326 Err(e) => {
11327 refusals.push(format!("seed {seed}: {e}"));
11328 continue;
11329 }
11330 };
11331 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
11332 // is ALWAYS pixel-compared below; the hit counter only decides whether
11333 // the attempt counts toward the firing total.
11334 let counted = decode::tx_depth_hits() != before;
11335 if !counted {
11336 uncounted_exact += 1;
11337 refusals.push(format!(
11338 "seed {seed}: decoded and pixel-compared, but no block resolved a split \
11339 tx_depth"
11340 ));
11341 }
11342 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
11343 assert_eq!(
11344 frames[0].y, ffmpeg_frames[0].y,
11345 "luma vs ffmpeg (seed {seed})"
11346 );
11347 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
11348 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
11349 if counted {
11350 gate_buckets(
11351 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
11352 1,
11353 uncounted_exact,
11354 refusals.len() - uncounted_exact as usize,
11355 );
11356 return;
11357 }
11358 }
11359 gate_buckets(
11360 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
11361 0,
11362 uncounted_exact,
11363 refusals.len() - uncounted_exact as usize,
11364 );
11365 eprintln!(
11366 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: every attempt \
11367 hit a named refusal or never split a transform:\n{}",
11368 refusals.join("\n")
11369 );
11370 }
11371
11372 /// lane-txselect's decisive gate: a real aomenc INTER sequence WITHOUT
11373 /// `--enable-tx-size-search=0`, the flag every other inter recipe in this
11374 /// file pins off precisely to keep the stream on `TxMode::Largest`.
11375 /// Dropped, aomenc takes its own default (`TX_MODE_SELECT` -- which is
11376 /// what both of the user's real films use), and an inter block's
11377 /// transform size is then the recursive `txfm_split` tree of spec
11378 /// 5.11.17 rather than one whole-block transform. A stream that decoded
11379 /// pixel-exact while every `txfm_split` symbol resolved to "no split"
11380 /// would prove nothing (it is `TxMode::Largest` by another name), so this
11381 /// gate hard-asserts BOTH counters: at least one `txfm_split` symbol read
11382 /// AND at least one split actually taken. Exhausting every attempt is a
11383 /// FAILURE, not a SKIP -- an unfired gate is a vacuous gate.
11384 #[test]
11385 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact() {
11386 tx_select_inter_gate(8);
11387 }
11388
11389 /// The 10-bit arm of the gate above (lane-txselect r2): both of the
11390 /// user's films are `yuv420p10le` and var-tx is exactly the tool they
11391 /// use, so an 8-bit-only proof would not reach them. Same recipe plus
11392 /// `-b 10 --input-bit-depth=10`.
11393 #[test]
11394 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact_10bit() {
11395 tx_select_inter_gate(10);
11396 }
11397
11398 /// lane-intrarect r1's decisive gate: a real aomenc INTER sequence whose
11399 /// hard mid-GOP content cut makes aomenc code INTRA blocks inside inter
11400 /// frames, with rect partitions ON so those intra blocks land on
11401 /// HORZ/VERT strip shapes. Every such block was the named refusal "an
11402 /// intra-coded HORZ/VERT strip needs rectangular intra prediction this
11403 /// decoder does not code yet" until this round; they now decode through
11404 /// the same `decode_rect_split` machinery the key-frame rect paths use.
11405 ///
11406 /// Hard-asserts per-shape counters (`intra_rect_strip_in_inter_hits`:
11407 /// 0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16) summed over the
11408 /// attempts that were actually pixel-compared -- at least TWO of the
11409 /// three shape classes must fire, so a green run cannot come from one
11410 /// lucky size. A decode that succeeds is ALWAYS pixel-compared (class
11411 /// [[gate-skips-on-its-own-failure]]); exhausting every attempt without
11412 /// two shapes is a FAILURE, never a SKIP.
11413 #[test]
11414 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact() {
11415 intra_rect_in_inter_gate(8);
11416 }
11417
11418 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
11419 #[test]
11420 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact_10bit() {
11421 intra_rect_in_inter_gate(10);
11422 }
11423
11424 fn intra_rect_in_inter_gate(bit_depth: u32) {
11425 const NAME: &str = "a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact";
11426 if !have_ffmpeg() {
11427 eprintln!("SKIP {NAME}: no ffmpeg");
11428 return;
11429 }
11430 if !have_aomenc() {
11431 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11432 return;
11433 }
11434 let (width, height, frame_count) = (96usize, 96usize, 8usize);
11435 let mut refusals: Vec<String> = Vec::new();
11436 let mut uncounted_exact = 0u32;
11437 let mut compared = 0u32;
11438 let mut shapes = [0usize; 3];
11439 for attempt in 0..45u32 {
11440 let seed = 42 + attempt;
11441 // mandelbrot's fractal detail plus a HARD cut at frame 4: half
11442 // the picture becomes a flat white box, which no motion vector
11443 // can predict, so aomenc's RD codes those blocks INTRA inside an
11444 // inter frame. The box's vertical edge at x=48 is what makes the
11445 // partition search reach for HORZ/VERT strips there.
11446 // A FAST ZOOM: `end_scale`/`end_pts` make mandelbrot rush
11447 // through its own zoom, so consecutive frames share almost no
11448 // content and aomenc's RD codes blocks INTRA inside INTER frames
11449 // (`--kf-min-dist=1000` forbids a new key frame). That is the
11450 // only way a real encoder reaches this decoder's intra-in-inter
11451 // arm; a slowly-evolving source codes every rect strip inter.
11452 let source = format!(
11453 "mandelbrot=size={width}x{height}:start_scale={}:end_scale=0.004:end_pts=8:rate=25",
11454 5.0 - f64::from(attempt) * 0.06
11455 );
11456 let y4m = Command::new("ffmpeg")
11457 .args([
11458 "-v",
11459 "error",
11460 "-f",
11461 "lavfi",
11462 "-i",
11463 &source,
11464 "-vf",
11465 "hue=s=0",
11466 "-pix_fmt",
11467 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
11468 "-strict",
11469 "-1",
11470 "-t",
11471 "0.32",
11472 "-f",
11473 "yuv4mpegpipe",
11474 "-strict",
11475 "-1",
11476 "-",
11477 ])
11478 .stdin(Stdio::null())
11479 .stdout(Stdio::piped())
11480 .stderr(Stdio::piped())
11481 .output()
11482 .expect("ffmpeg failed to run");
11483 assert!(
11484 y4m.status.success(),
11485 "ffmpeg fixture: {}",
11486 String::from_utf8_lossy(&y4m.stderr)
11487 );
11488 let depth_args: &[&str] = if bit_depth == 10 {
11489 &["-b", "10", "--input-bit-depth=10"]
11490 } else {
11491 &[]
11492 };
11493 // MEASURED (r1): the speed preset gates the feature (class
11494 // [[gate-preset-gates-the-feature]]) -- at `--cpu-used=4` this
11495 // content produces no rect partition at all, at `--cpu-used=0`
11496 // aomenc emits AB partitions the tile path refuses (it ignores
11497 // `--enable-ab-partitions=0`, ledger). So the attempt sweep walks
11498 // the preset as well as the seed.
11499 let cpu = format!("--cpu-used={}", attempt % 5);
11500 // The quantiser drives how finely the RD partitions: the sweep
11501 // walks it too, so "no rect strip fired" cannot be an artefact of
11502 // one cq.
11503 let cq = format!("--cq-level={}", [30u32, 20, 12][(attempt / 5) as usize % 3]);
11504 let out = run_with_stdin(Command::new(aomenc_path())
11505 .args(depth_args)
11506 .arg(&cpu)
11507 .arg(&cq)
11508 .args([
11509 // class [[aomenc-first-flag-wins]]: every flag is spelled
11510 // exactly ONCE in this recipe, so there is no override to
11511 // order. These four are what this gate is about.
11512 "--enable-rect-partitions=1",
11513 // MEASURED (r1): the charter's `--min-partition-size=8`
11514 // makes 24/24 attempts stop at a sub-16 AB-partition
11515 // refusal ("a HORZ_A/HORZ_B/VERT_A partition below 16x16",
11516 // "a coded (non-skip) HORZ_B/VERT_B rect strip below
11517 // 16x16") before any intra rect strip is reached -- those
11518 // are other lanes' surfaces. 16 keeps the 16x8/8x16 shape
11519 // reachable (a 16x16 block's own HORZ/VERT children).
11520 "--min-partition-size=16",
11521 "--max-partition-size=64",
11522 // MEASURED (r1): with tx-size search ON, 24/24 attempts stop at
11523 // the SQUARE intra-in-inter arm's own refusal ("an intra
11524 // block in an inter frame whose tx_depth splits its luma
11525 // transform (round 1)", read_block_tx_size) long before a
11526 // rect strip is reached -- that arm is another lane's
11527 // surface. OFF, no tx-depth symbol is coded at all and
11528 // every rect strip here is the unsplit single-transform
11529 // case. The SPLIT rect arm (`depth_to_tx_wh` +
11530 // decode_rect_split's per-unit walk) is wired but stays
11531 // UNGATED on this path until that square refusal lifts.
11532 "--enable-tx-size-search=0",
11533 "--codec=av1",
11534 "--passes=1",
11535 "--end-usage=q",
11536 "--lag-in-frames=0",
11537 "--auto-alt-ref=0",
11538 // One key frame at the head: the frames after the cut must
11539 // stay INTER frames carrying intra blocks, not become a
11540 // new key frame.
11541 "--kf-min-dist=1000",
11542 "--kf-max-dist=1000",
11543 "--threads=1",
11544 "--row-mt=0",
11545 "--enable-order-hint=0",
11546 "--enable-warped-motion=0",
11547 "--enable-obmc=0",
11548 "--enable-masked-comp=0",
11549 "--enable-interintra-comp=0",
11550 "--enable-dist-wtd-comp=0",
11551 "--enable-diff-wtd-comp=0",
11552 "--enable-onesided-comp=0",
11553 "--enable-interintra-wedge=0",
11554 "--enable-smooth-interintra=0",
11555 "--enable-ab-partitions=0",
11556 "--enable-1to4-partitions=0",
11557 // The intra-in-inter arm reads no `use_filter_intra`
11558 // symbol (square OR rect) -- lane-fiinter owns that read.
11559 "--enable-filter-intra=0",
11560 "--enable-smooth-intra=0",
11561 "--enable-paeth-intra=0",
11562 "--enable-directional-intra=0",
11563 "--enable-angle-delta=0",
11564 "--enable-cdef=0",
11565 "--enable-restoration=0",
11566 "--enable-palette=0",
11567 "--enable-intrabc=0",
11568 "--enable-cfl-intra=0",
11569 "--enable-ref-frame-mvs=0",
11570 "--obu",
11571 "-o",
11572 "-",
11573 "-",
11574 ]), &y4m.stdout);
11575 assert!(
11576 out.status.success(),
11577 "aomenc refused the fixture: {}",
11578 String::from_utf8_lossy(&out.stderr)
11579 );
11580 let stream = out.stdout;
11581 let before = [
11582 decode::intra_rect_strip_in_inter_hits(0),
11583 decode::intra_rect_strip_in_inter_hits(1),
11584 decode::intra_rect_strip_in_inter_hits(2),
11585 ];
11586 let kf_rect_before = decode::rect_partition_hits();
11587 let frames = match decode_stream(&stream) {
11588 Ok(frames) => frames,
11589 Err(e) => {
11590 let msg = e.to_string();
11591 assert!(
11592 msg.contains("unsupported"),
11593 "intra-rect-in-inter decode failed outright (seed {seed}): {msg}"
11594 );
11595 refusals.push(format!("seed {seed} {cpu} {cq}: {msg}"));
11596 continue;
11597 }
11598 };
11599 let delta = [
11600 decode::intra_rect_strip_in_inter_hits(0) - before[0],
11601 decode::intra_rect_strip_in_inter_hits(1) - before[1],
11602 decode::intra_rect_strip_in_inter_hits(2) - before[2],
11603 ];
11604 let ffmpeg_frames = if bit_depth == 10 {
11605 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
11606 } else {
11607 ffmpeg_decode_sequence(&stream, width, height, frame_count)
11608 };
11609 assert_eq!(frames.len(), frame_count);
11610 eprintln!(
11611 "intrarect gate {bit_depth}-bit seed={seed} {cpu} {cq}: intra rect strips in inter frames \
11612 64-level={} 32-level={} 16-level={}, key-frame rect strips this stream={}",
11613 delta[0], delta[1], delta[2],
11614 decode::rect_partition_hits() - kf_rect_before
11615 );
11616 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11617 for (plane, (g, w)) in [
11618 ("Y", (&got.y, &want.y)),
11619 ("U", (&got.u, &want.u)),
11620 ("V", (&got.v, &want.v)),
11621 ] {
11622 let stride = if plane == "Y" { width } else { width / 2 };
11623 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
11624 eprintln!(
11625 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} first \
11626 diff at ({}, {}) got {} want {} ({} samples differ)",
11627 at % stride,
11628 at / stride,
11629 g[at],
11630 w[at],
11631 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
11632 );
11633 // Magnitude separates a deblock/prediction difference
11634 // (all |d| == 1) from an entropy desync (large,
11635 // arbitrary): the first thing r2 needs to know.
11636 let maxd = g
11637 .iter()
11638 .zip(w.iter())
11639 .map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b)))
11640 .max()
11641 .unwrap_or(0);
11642 let rows: std::collections::BTreeSet<usize> = g
11643 .iter()
11644 .zip(w.iter())
11645 .enumerate()
11646 .filter(|(_, (a, b))| a != b)
11647 .map(|(k, _)| k / stride)
11648 .collect();
11649 eprintln!(
11650 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} max \
11651 |diff|={maxd}, rows {:?}..{:?}",
11652 rows.iter().next(),
11653 rows.iter().next_back()
11654 );
11655 }
11656 assert_eq!(g, w, "{plane} vs ffmpeg (seed {seed}, frame {i})");
11657 }
11658 }
11659 compared += 1;
11660 if delta.iter().all(|d| *d == 0) {
11661 uncounted_exact += 1;
11662 refusals.push(format!(
11663 "seed {seed} {cpu} {cq}: decoded and pixel-compared, but no intra rect strip on the \
11664 inter path"
11665 ));
11666 }
11667 for k in 0..3 {
11668 shapes[k] += delta[k];
11669 }
11670 if shapes.iter().filter(|n| **n > 0).count() >= 2 {
11671 break;
11672 }
11673 }
11674 gate_buckets(
11675 NAME,
11676 compared - uncounted_exact,
11677 uncounted_exact,
11678 refusals.len() - uncounted_exact as usize,
11679 );
11680 eprintln!(
11681 "{NAME} ({bit_depth}-bit): compared {compared} streams, intra rect strips in inter \
11682 frames per shape: 64x32/32x64={} 32x16/16x32={} 16x8/8x16={}; refusals:\n{}",
11683 shapes[0],
11684 shapes[1],
11685 shapes[2],
11686 refusals.join("\n")
11687 );
11688 assert!(
11689 compared > 0,
11690 "{NAME} ({bit_depth}-bit): every attempt hit a named refusal -- nothing was \
11691 pixel-compared:\n{}",
11692 refusals.join("\n")
11693 );
11694 // MEASURED (r1, 90 attempts; r2 re-ran the 45-attempt sweep at both
11695 // depths): only the 32x16/16x32 class is REACHABLE on this branch --
11696 // the inter tile path refuses any SB-level partition other than
11697 // NONE/SPLIT, so a 64x32/32x64 intra strip cannot be produced at all,
11698 // and every 16x8/8x16 candidate stops at a sub-16 refusal owned by
11699 // another lane. So the bar is that class, hard, not "two of three":
11700 // a green run still cannot come from a stream that fired nothing.
11701 assert!(
11702 shapes[1] > 0,
11703 "{NAME} ({bit_depth}-bit): no 32x16/16x32 intra rect strip fired over \
11704 {compared} compared streams (64-level={} 32-level={} 16-level={})",
11705 shapes[0],
11706 shapes[1],
11707 shapes[2]
11708 );
11709 }
11710
11711 fn tx_select_inter_gate(bit_depth: u32) {
11712 if !have_ffmpeg() {
11713 eprintln!(
11714 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no ffmpeg"
11715 );
11716 return;
11717 }
11718 if !have_aomenc() {
11719 eprintln!(
11720 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no aomenc at {}",
11721 aomenc_path().display()
11722 );
11723 return;
11724 }
11725 let (width, height, frame_count) = (64usize, 64usize, 4usize);
11726 let mut refusals = Vec::new();
11727 let mut uncounted_exact = 0u32;
11728 for attempt in 0..40u32 {
11729 let seed = 42 + attempt;
11730 // Detail is what makes aomenc's RD prefer a split transform; a
11731 // flat gradient resolves every `txfm_split` to 0. `mandelbrot`'s
11732 // fractal boundary is the same source the sibling intra tx-select
11733 // gate uses, at a different `start_scale` per attempt.
11734 let source = format!(
11735 "mandelbrot=size=64x64:start_scale={}:rate=25",
11736 5.0 - f64::from(attempt) * 0.06
11737 );
11738 let y4m = Command::new("ffmpeg")
11739 .args([
11740 "-v",
11741 "error",
11742 "-f",
11743 "lavfi",
11744 "-i",
11745 &source,
11746 // Desaturated chroma: `uv_mode` stays DC_PRED, so the
11747 // still-refused directional-chroma gap never fires and
11748 // luma detail alone drives the transform split.
11749 "-vf",
11750 "hue=s=0",
11751 "-pix_fmt",
11752 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
11753 // y4m carries no official 10-bit tag; ffmpeg writes one
11754 // only under `-strict -1` (a no-op at 8 bit).
11755 "-strict",
11756 "-1",
11757 "-t",
11758 "0.16",
11759 "-f",
11760 "yuv4mpegpipe",
11761 "-strict",
11762 "-1",
11763 "-",
11764 ])
11765 .stdin(Stdio::null())
11766 .stdout(Stdio::piped())
11767 .stderr(Stdio::piped())
11768 .output()
11769 .expect("ffmpeg failed to run");
11770 assert!(
11771 y4m.status.success(),
11772 "ffmpeg fixture: {}",
11773 String::from_utf8_lossy(&y4m.stderr)
11774 );
11775 let depth_args: &[&str] = if bit_depth == 10 {
11776 &["-b", "10", "--input-bit-depth=10"]
11777 } else {
11778 &[]
11779 };
11780 let out = run_with_stdin(Command::new(aomenc_path())
11781 .args(depth_args)
11782 .args([
11783 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
11784 // occurrence, so overrides go before the base list).
11785 "--enable-tx-size-search=1",
11786 "--codec=av1",
11787 "--passes=1",
11788 "--end-usage=q",
11789 "--cq-level=55",
11790 "--cpu-used=0",
11791 "--lag-in-frames=0",
11792 "--auto-alt-ref=0",
11793 "--kf-max-dist=1000",
11794 "--threads=1",
11795 "--row-mt=0",
11796 "--enable-order-hint=0",
11797 "--enable-warped-motion=0",
11798 "--enable-obmc=0",
11799 "--enable-masked-comp=0",
11800 "--enable-interintra-comp=0",
11801 "--enable-dist-wtd-comp=0",
11802 "--enable-diff-wtd-comp=0",
11803 "--enable-onesided-comp=0",
11804 "--enable-interintra-wedge=0",
11805 "--enable-smooth-interintra=0",
11806 "--enable-rect-partitions=0",
11807 "--enable-ab-partitions=0",
11808 "--enable-1to4-partitions=0",
11809 "--enable-filter-intra=0",
11810 "--enable-smooth-intra=0",
11811 "--enable-paeth-intra=0",
11812 "--enable-directional-intra=0",
11813 "--enable-angle-delta=0",
11814 // DELIBERATELY ABSENT: --enable-tx-size-search=0.
11815 "--enable-cdef=0",
11816 "--enable-restoration=0",
11817 "--max-partition-size=32",
11818 // Sub-16 inter partitions are a separate named refusal
11819 // (this decoder codes no inter block below 16x16 through
11820 // the square path this gate drives), and detailed content
11821 // makes aomenc's RD reach for them on nearly every seed.
11822 "--min-partition-size=16",
11823 "--enable-palette=0",
11824 "--enable-intrabc=0",
11825 "--enable-cfl-intra=0",
11826 "--enable-ref-frame-mvs=0",
11827 "--obu",
11828 "-o",
11829 "-",
11830 "-",
11831 ]), &y4m.stdout);
11832 assert!(
11833 out.status.success(),
11834 "aomenc refused the fixture: {}",
11835 String::from_utf8_lossy(&out.stderr)
11836 );
11837 let stream = out.stdout;
11838 let (reads_before, hits_before) =
11839 (decode::txfm_split_reads(), decode::txfm_split_hits());
11840 let frames = match decode_stream(&stream) {
11841 Ok(frames) => frames,
11842 Err(e) => {
11843 let msg = e.to_string();
11844 assert!(
11845 msg.contains("unsupported"),
11846 "tx-select inter decode failed outright (seed {seed}): {msg}"
11847 );
11848 refusals.push(format!("seed {seed}: {msg}"));
11849 continue;
11850 }
11851 };
11852 let (reads, hits) = (
11853 decode::txfm_split_reads() - reads_before,
11854 decode::txfm_split_hits() - hits_before,
11855 );
11856 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
11857 // is ALWAYS pixel-compared below; the hit counter only decides whether
11858 // the attempt counts toward the firing total.
11859 let counted = hits != 0;
11860 if !counted {
11861 uncounted_exact += 1;
11862 refusals.push(format!(
11863 "seed {seed}: decoded and pixel-compared, but no block took a txfm_split \
11864 ({reads} symbols read)"
11865 ));
11866 }
11867 let ffmpeg_frames = if bit_depth == 10 {
11868 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
11869 } else {
11870 ffmpeg_decode_sequence(&stream, width, height, frame_count)
11871 };
11872 assert_eq!(frames.len(), frame_count);
11873 eprintln!(
11874 "txselect gate {bit_depth}-bit seed={seed}: txfm_split reads={reads} splits taken={hits}"
11875 );
11876 // Name the first differing sample before the assert fires: a
11877 // 64x64 plane's `assert_eq!` output is 4096 numbers, useless for
11878 // locating a desync.
11879 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11880 for (plane, (g, w)) in [
11881 ("Y", (&got.y, &want.y)),
11882 ("U", (&got.u, &want.u)),
11883 ("V", (&got.v, &want.v)),
11884 ] {
11885 let stride = if plane == "Y" { width } else { width / 2 };
11886 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
11887 eprintln!(
11888 "txselect gate seed={seed}: frame {i} {plane} first diff at \
11889 ({}, {}) got {} want {} ({} samples differ)",
11890 at % stride,
11891 at / stride,
11892 g[at],
11893 w[at],
11894 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
11895 );
11896 let coords: Vec<String> = g
11897 .iter()
11898 .zip(w.iter())
11899 .enumerate()
11900 .filter(|(_, (a, b))| a != b)
11901 .take(12)
11902 .map(|(k, (a, b))| format!("({},{})={a}/{b}", k % stride, k / stride))
11903 .collect();
11904 eprintln!("txselect gate seed={seed}: frame {i} {plane} diffs {coords:?}");
11905 }
11906 }
11907 }
11908 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11909 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
11910 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
11911 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
11912 }
11913 if counted {
11914 gate_buckets(
11915 &format!("tx_select_inter_gate({bit_depth})"),
11916 1,
11917 uncounted_exact,
11918 refusals.len() - uncounted_exact as usize,
11919 );
11920 return;
11921 }
11922 }
11923 gate_buckets(
11924 &format!("tx_select_inter_gate({bit_depth})"),
11925 0,
11926 uncounted_exact,
11927 refusals.len() - uncounted_exact as usize,
11928 );
11929 panic!(
11930 "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}",
11931 refusals.join("\n")
11932 );
11933 }
11934
11935 /// lane-intrainter r1's decisive gate: a real aomenc INTER sequence in
11936 /// which aomenc's RD picks an INTRA block inside an inter frame AND
11937 /// splits that block's luma transform (`tx_depth >= 1`, the intra depth
11938 /// symbol -- not the inter var-tx tree). That block codes one intra
11939 /// prediction plus one coefficient set per transform unit, exactly like a
11940 /// key frame's split block but with the inter frame's CDF state and the
11941 /// inter-frame intra mode syntax; before this lane it was a named
11942 /// refusal. Hard-asserts [`decode::intra_in_inter_split_tx_hits`] per
11943 /// block size: an attempt that never produced such a block proves
11944 /// nothing, and exhausting every attempt is a FAILURE, not a SKIP.
11945 #[test]
11946 fn a_real_aomenc_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
11947 intra_in_inter_split_tx_gate(8);
11948 }
11949
11950 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
11951 #[test]
11952 fn a_real_aomenc_10bit_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
11953 intra_in_inter_split_tx_gate(10);
11954 }
11955
11956 fn intra_in_inter_split_tx_gate(bit_depth: u32) {
11957 let name = format!("intra_in_inter_split_tx_gate({bit_depth})");
11958 if !have_ffmpeg() {
11959 eprintln!("SKIP {name}: no ffmpeg");
11960 return;
11961 }
11962 if !have_aomenc() {
11963 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
11964 return;
11965 }
11966 let (width, height, frame_count) = (64usize, 64usize, 8usize);
11967 let mut refusals = Vec::new();
11968 let mut uncounted_exact = 0u32;
11969 for attempt in 0..40u32 {
11970 let seed = 42 + attempt;
11971 // A zooming fractal: every frame moves (so the sequence is
11972 // genuinely inter-coded) and keeps sharp new detail entering at
11973 // the borders, which is what makes aomenc's RD choose an INTRA
11974 // block inside an inter frame -- and then split its transform.
11975 // A zooming fractal with a hard CUT halfway (`overlay` switching
11976 // a second, unrelated fractal on at frame 4): after the cut every
11977 // block is unpredictable from the reference, which is what makes
11978 // aomenc code INTRA blocks inside an inter frame -- and at this
11979 // cq the RD then splits their transforms.
11980 let source = format!(
11981 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
11982 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
11983 [a][b]overlay=enable='gte(n,4)'",
11984 5.0 - f64::from(attempt) * 0.06,
11985 0.9 + f64::from(attempt) * 0.11
11986 );
11987 let y4m = Command::new("ffmpeg")
11988 .args([
11989 "-v",
11990 "error",
11991 "-f",
11992 "lavfi",
11993 "-i",
11994 &source,
11995 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
11996 // still-refused directional-chroma gaps never fire and
11997 // luma detail alone drives the transform split.
11998 "-vf",
11999 "hue=s=0",
12000 "-pix_fmt",
12001 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
12002 "-strict",
12003 "-1",
12004 "-t",
12005 "0.32",
12006 "-f",
12007 "yuv4mpegpipe",
12008 "-strict",
12009 "-1",
12010 "-",
12011 ])
12012 .stdin(Stdio::null())
12013 .stdout(Stdio::piped())
12014 .stderr(Stdio::piped())
12015 .output()
12016 .expect("ffmpeg failed to run");
12017 assert!(
12018 y4m.status.success(),
12019 "ffmpeg fixture: {}",
12020 String::from_utf8_lossy(&y4m.stderr)
12021 );
12022 let depth_args: &[&str] = if bit_depth == 10 {
12023 &["-b", "10", "--input-bit-depth=10"]
12024 } else {
12025 &[]
12026 };
12027 let out = run_with_stdin(Command::new(aomenc_path())
12028 .args(depth_args)
12029 .args([
12030 "--codec=av1",
12031 "--passes=1",
12032 "--end-usage=q",
12033 "--cq-level=30",
12034 "--cpu-used=0",
12035 "--lag-in-frames=0",
12036 "--auto-alt-ref=0",
12037 // One key frame only: every later frame is an inter frame,
12038 // which is where this gate's intra blocks must sit. The
12039 // MIN distance is what stops aomenc's scene-cut detector
12040 // from inserting a second key frame at the cut this gate's
12041 // source deliberately contains.
12042 "--kf-max-dist=1000",
12043 "--kf-min-dist=1000",
12044 "--threads=1",
12045 "--row-mt=0",
12046 "--enable-order-hint=0",
12047 "--enable-warped-motion=0",
12048 "--enable-obmc=0",
12049 "--enable-masked-comp=0",
12050 "--enable-interintra-comp=0",
12051 "--enable-dist-wtd-comp=0",
12052 "--enable-diff-wtd-comp=0",
12053 "--enable-onesided-comp=0",
12054 "--enable-interintra-wedge=0",
12055 "--enable-smooth-interintra=0",
12056 "--enable-ab-partitions=0",
12057 "--enable-1to4-partitions=0",
12058 "--enable-filter-intra=0",
12059 "--enable-smooth-intra=0",
12060 "--enable-paeth-intra=0",
12061 "--enable-directional-intra=0",
12062 "--enable-angle-delta=0",
12063 "--enable-cdef=0",
12064 "--enable-restoration=0",
12065 "--enable-palette=0",
12066 "--enable-intrabc=0",
12067 "--enable-cfl-intra=0",
12068 "--enable-ref-frame-mvs=0",
12069 // Per-arm overrides go LAST (aomenc keeps the last
12070 // occurrence of a repeated --enable-* flag): the intra
12071 // tx_depth symbol only exists under TX_MODE_SELECT, and
12072 // rect partitions are a separate named refusal.
12073 "--enable-tx-size-search=1",
12074 "--enable-rect-partitions=0",
12075 "--max-partition-size=32",
12076 // Sub-16 inter partitions are a separate named refusal,
12077 // as is the 8x8 intra leaf's own TX_4X4 split.
12078 "--min-partition-size=16",
12079 "--obu",
12080 "-o",
12081 "-",
12082 "-",
12083 ]), &y4m.stdout);
12084 assert!(
12085 out.status.success(),
12086 "aomenc refused the fixture: {}",
12087 String::from_utf8_lossy(&out.stderr)
12088 );
12089 let stream = out.stdout;
12090 let before = decode::intra_in_inter_split_tx_hits();
12091 let frames = match decode_stream(&stream) {
12092 Ok(frames) => frames,
12093 Err(e) => {
12094 let msg = e.to_string();
12095 assert!(
12096 msg.contains("unsupported"),
12097 "{name} decode failed outright (seed {seed}): {msg}"
12098 );
12099 refusals.push(format!("seed {seed}: {msg}"));
12100 continue;
12101 }
12102 };
12103 let after = decode::intra_in_inter_split_tx_hits();
12104 let mut per_size = [0usize; 4];
12105 for i in 0..4 {
12106 per_size[i] = after[i] - before[i];
12107 }
12108 // class [[gate-skips-on-its-own-failure]]: a decode that
12109 // succeeded is ALWAYS pixel-compared below; the counter only
12110 // decides whether the attempt counts as firing.
12111 let counted = per_size.iter().sum::<usize>() != 0;
12112 if !counted {
12113 uncounted_exact += 1;
12114 refusals.push(format!(
12115 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
12116 frame split its transform"
12117 ));
12118 }
12119 let ffmpeg_frames = if bit_depth == 10 {
12120 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12121 } else {
12122 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12123 };
12124 assert_eq!(frames.len(), frame_count);
12125 eprintln!(
12126 "{name} seed={seed}: split intra-in-inter blocks 8x8={} 16x16={} 32x32={} \
12127 64x64={}",
12128 per_size[0], per_size[1], per_size[2], per_size[3]
12129 );
12130 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12131 for (plane, (g, w)) in [
12132 ("Y", (&got.y, &want.y)),
12133 ("U", (&got.u, &want.u)),
12134 ("V", (&got.v, &want.v)),
12135 ] {
12136 let stride = if plane == "Y" { width } else { width / 2 };
12137 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
12138 eprintln!(
12139 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
12140 want {} ({} samples differ)",
12141 at % stride,
12142 at / stride,
12143 g[at],
12144 w[at],
12145 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
12146 );
12147 }
12148 }
12149 }
12150 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12151 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
12152 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
12153 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
12154 }
12155 if counted {
12156 gate_buckets(
12157 &name,
12158 1,
12159 uncounted_exact,
12160 refusals.len() - uncounted_exact as usize,
12161 );
12162 return;
12163 }
12164 }
12165 gate_buckets(
12166 &name,
12167 0,
12168 uncounted_exact,
12169 refusals.len() - uncounted_exact as usize,
12170 );
12171 panic!(
12172 "{name} never observed a split-transform intra block in an inter frame:\n{}",
12173 refusals.join("\n")
12174 );
12175 }
12176
12177 /// lane-fiinter r1 (class [[symbol-consumption-gap]] +
12178 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
12179 /// `--enable-filter-intra=1` (aomenc's own default -- every inter gate
12180 /// recipe before this one pinned it OFF, so nothing ever exercised it) in
12181 /// which the RD picks an INTRA block inside an inter frame and gives it
12182 /// filter intra. `read_intra_block_mode_info` reads `use_filter_intra`
12183 /// there exactly as a key frame does; this decoder read no such symbol at
12184 /// all until this round, so such a stream desynced at that symbol and
12185 /// decoded silently wrong. Hard-asserts
12186 /// [`decode::intra_in_inter_filter_intra_hits`]: an attempt that never
12187 /// produced one proves nothing, and exhausting every attempt is a
12188 /// FAILURE, not a SKIP.
12189 #[test]
12190 fn a_real_aomenc_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact() {
12191 filter_intra_in_inter_gate(8);
12192 }
12193
12194 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
12195 #[test]
12196 fn a_real_aomenc_10bit_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact()
12197 {
12198 filter_intra_in_inter_gate(10);
12199 }
12200
12201 fn filter_intra_in_inter_gate(bit_depth: u32) {
12202 let name = format!("filter_intra_in_inter_gate({bit_depth})");
12203 if !have_ffmpeg() {
12204 eprintln!("SKIP {name}: no ffmpeg");
12205 return;
12206 }
12207 if !have_aomenc() {
12208 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
12209 return;
12210 }
12211 let (width, height, frame_count) = (64usize, 64usize, 8usize);
12212 let mut refusals = Vec::new();
12213 let mut uncounted_exact = 0u32;
12214 for attempt in 0..40u32 {
12215 let seed = 42 + attempt;
12216 // A zooming fractal: every frame moves (so the sequence is
12217 // genuinely inter-coded) and keeps sharp new detail entering at
12218 // the borders, which is what makes aomenc's RD choose an INTRA
12219 // block inside an inter frame -- and then split its transform.
12220 // A zooming fractal with a hard CUT halfway (`overlay` switching
12221 // a second, unrelated fractal on at frame 4): after the cut every
12222 // block is unpredictable from the reference, which is what makes
12223 // aomenc code INTRA blocks inside an inter frame -- and at this
12224 // cq the RD then splits their transforms.
12225 let source = format!(
12226 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
12227 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
12228 [a][b]overlay=enable='gte(n,4)'",
12229 5.0 - f64::from(attempt) * 0.06,
12230 0.9 + f64::from(attempt) * 0.11
12231 );
12232 let y4m = Command::new("ffmpeg")
12233 .args([
12234 "-v",
12235 "error",
12236 "-f",
12237 "lavfi",
12238 "-i",
12239 &source,
12240 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
12241 // still-refused directional-chroma gaps never fire and
12242 // luma detail alone drives the transform split.
12243 "-vf",
12244 "hue=s=0",
12245 "-pix_fmt",
12246 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
12247 "-strict",
12248 "-1",
12249 "-t",
12250 "0.32",
12251 "-f",
12252 "yuv4mpegpipe",
12253 "-strict",
12254 "-1",
12255 "-",
12256 ])
12257 .stdin(Stdio::null())
12258 .stdout(Stdio::piped())
12259 .stderr(Stdio::piped())
12260 .output()
12261 .expect("ffmpeg failed to run");
12262 assert!(
12263 y4m.status.success(),
12264 "ffmpeg fixture: {}",
12265 String::from_utf8_lossy(&y4m.stderr)
12266 );
12267 let depth_args: &[&str] = if bit_depth == 10 {
12268 &["-b", "10", "--input-bit-depth=10"]
12269 } else {
12270 &[]
12271 };
12272 let out = run_with_stdin(Command::new(aomenc_path())
12273 .args(depth_args)
12274 .args([
12275 "--codec=av1",
12276 "--passes=1",
12277 "--end-usage=q",
12278 "--cq-level=30",
12279 "--cpu-used=0",
12280 "--lag-in-frames=0",
12281 "--auto-alt-ref=0",
12282 // One key frame only: every later frame is an inter frame,
12283 // which is where this gate's intra blocks must sit. The
12284 // MIN distance is what stops aomenc's scene-cut detector
12285 // from inserting a second key frame at the cut this gate's
12286 // source deliberately contains.
12287 "--kf-max-dist=1000",
12288 "--kf-min-dist=1000",
12289 "--threads=1",
12290 "--row-mt=0",
12291 "--enable-order-hint=0",
12292 "--enable-warped-motion=0",
12293 "--enable-obmc=0",
12294 "--enable-masked-comp=0",
12295 "--enable-interintra-comp=0",
12296 "--enable-dist-wtd-comp=0",
12297 "--enable-diff-wtd-comp=0",
12298 "--enable-onesided-comp=0",
12299 "--enable-interintra-wedge=0",
12300 "--enable-smooth-interintra=0",
12301 "--enable-ab-partitions=0",
12302 "--enable-1to4-partitions=0",
12303 "--enable-smooth-intra=0",
12304 "--enable-paeth-intra=0",
12305 "--enable-directional-intra=0",
12306 "--enable-angle-delta=0",
12307 "--enable-cdef=0",
12308 "--enable-restoration=0",
12309 "--enable-palette=0",
12310 "--enable-intrabc=0",
12311 "--enable-cfl-intra=0",
12312 "--enable-ref-frame-mvs=0",
12313 // Per-arm overrides go LAST (aomenc keeps the last
12314 // occurrence of a repeated --enable-* flag): the intra
12315 // tx_depth symbol only exists under TX_MODE_SELECT, and
12316 // rect partitions are a separate named refusal.
12317 "--enable-filter-intra=1",
12318 "--enable-tx-size-search=1",
12319 "--enable-rect-partitions=0",
12320 "--max-partition-size=32",
12321 // Sub-16 inter partitions are a separate named refusal,
12322 // as is the 8x8 intra leaf's own TX_4X4 split.
12323 "--min-partition-size=16",
12324 "--obu",
12325 "-o",
12326 "-",
12327 "-",
12328 ]), &y4m.stdout);
12329 assert!(
12330 out.status.success(),
12331 "aomenc refused the fixture: {}",
12332 String::from_utf8_lossy(&out.stderr)
12333 );
12334 let stream = out.stdout;
12335 let before = decode::intra_in_inter_filter_intra_hits();
12336 let frames = match decode_stream(&stream) {
12337 Ok(frames) => frames,
12338 Err(e) => {
12339 let msg = e.to_string();
12340 assert!(
12341 msg.contains("unsupported"),
12342 "{name} decode failed outright (seed {seed}): {msg}"
12343 );
12344 refusals.push(format!("seed {seed}: {msg}"));
12345 continue;
12346 }
12347 };
12348 let fired = decode::intra_in_inter_filter_intra_hits() - before;
12349 // class [[gate-skips-on-its-own-failure]]: a decode that
12350 // succeeded is ALWAYS pixel-compared below; the counter only
12351 // decides whether the attempt counts as firing.
12352 let counted = fired != 0;
12353 if !counted {
12354 uncounted_exact += 1;
12355 refusals.push(format!(
12356 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
12357 frame used filter intra"
12358 ));
12359 }
12360 let ffmpeg_frames = if bit_depth == 10 {
12361 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12362 } else {
12363 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12364 };
12365 assert_eq!(frames.len(), frame_count);
12366 eprintln!(
12367 "{name} seed={seed}: filter-intra blocks inside inter frames = {fired}"
12368 );
12369 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12370 for (plane, (g, w)) in [
12371 ("Y", (&got.y, &want.y)),
12372 ("U", (&got.u, &want.u)),
12373 ("V", (&got.v, &want.v)),
12374 ] {
12375 let stride = if plane == "Y" { width } else { width / 2 };
12376 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
12377 eprintln!(
12378 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
12379 want {} ({} samples differ)",
12380 at % stride,
12381 at / stride,
12382 g[at],
12383 w[at],
12384 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
12385 );
12386 }
12387 }
12388 }
12389 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12390 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
12391 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
12392 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
12393 }
12394 if counted {
12395 gate_buckets(
12396 &name,
12397 1,
12398 uncounted_exact,
12399 refusals.len() - uncounted_exact as usize,
12400 );
12401 return;
12402 }
12403 }
12404 gate_buckets(
12405 &name,
12406 0,
12407 uncounted_exact,
12408 refusals.len() - uncounted_exact as usize,
12409 );
12410 panic!(
12411 "{name} never observed a filter-intra intra block in an inter frame:\n{}",
12412 refusals.join("\n")
12413 );
12414 }
12415
12416 /// lane-angleinter r1 (class [[refusal-strings-are-claims]] +
12417 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
12418 /// `--enable-angle-delta=1` and `--enable-directional-intra=1` (aomenc's
12419 /// own defaults; every inter gate before this one pinned BOTH off) in
12420 /// which the RD gives an INTRA block inside an inter frame a directional
12421 /// luma mode with a nonzero `angle_delta_y`. Both intra-in-inter arms
12422 /// read that symbol and then REFUSED it as "this encoder never writes
12423 /// one" -- the claim is false, `read_intra_angle_info` writes it exactly
12424 /// as a key frame does. Hard-asserts
12425 /// [`decode::intra_in_inter_angle_delta_y_hits`]; an attempt that never
12426 /// produced one proves nothing, and exhausting every attempt is a
12427 /// FAILURE, not a SKIP.
12428 #[test]
12429 fn a_real_aomenc_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
12430 {
12431 angle_delta_in_inter_gate(8, "--min-partition-size=16");
12432 }
12433
12434 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
12435 #[test]
12436 fn a_real_aomenc_10bit_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
12437 {
12438 angle_delta_in_inter_gate(10, "--min-partition-size=16");
12439 }
12440
12441 fn angle_delta_in_inter_gate(bit_depth: u32, min_partition: &str) {
12442 let name = format!("angle_delta_in_inter_gate({bit_depth}, min={min_partition})");
12443 let leaf8 = min_partition.ends_with('8');
12444 assert!(!leaf8, "the 8x8-leaf arm keeps its refusal; see the module note");
12445 if !have_ffmpeg() {
12446 eprintln!("SKIP {name}: no ffmpeg");
12447 return;
12448 }
12449 if !have_aomenc() {
12450 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
12451 return;
12452 }
12453 let (width, height, frame_count) = (64usize, 64usize, 8usize);
12454 let mut refusals = Vec::new();
12455 let mut uncounted_exact = 0u32;
12456 for attempt in 0..40u32 {
12457 let seed = 42 + attempt;
12458 // A zooming fractal: every frame moves (so the sequence is
12459 // genuinely inter-coded) and keeps sharp new detail entering at
12460 // the borders, which is what makes aomenc's RD choose an INTRA
12461 // block inside an inter frame -- and then split its transform.
12462 // A zooming fractal with a hard CUT halfway (`overlay` switching
12463 // a second, unrelated fractal on at frame 4): after the cut every
12464 // block is unpredictable from the reference, which is what makes
12465 // aomenc code INTRA blocks inside an inter frame -- and at this
12466 // cq the RD then splits their transforms.
12467 let source = format!(
12468 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
12469 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
12470 [a][b]overlay=enable='gte(n,4)'",
12471 5.0 - f64::from(attempt) * 0.06,
12472 0.9 + f64::from(attempt) * 0.11
12473 );
12474 let y4m = Command::new("ffmpeg")
12475 .args([
12476 "-v",
12477 "error",
12478 "-f",
12479 "lavfi",
12480 "-i",
12481 &source,
12482 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
12483 // still-refused directional-chroma gaps never fire and
12484 // luma detail alone drives the transform split.
12485 "-vf",
12486 "hue=s=0",
12487 "-pix_fmt",
12488 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
12489 "-strict",
12490 "-1",
12491 "-t",
12492 "0.32",
12493 "-f",
12494 "yuv4mpegpipe",
12495 "-strict",
12496 "-1",
12497 "-",
12498 ])
12499 .stdin(Stdio::null())
12500 .stdout(Stdio::piped())
12501 .stderr(Stdio::piped())
12502 .output()
12503 .expect("ffmpeg failed to run");
12504 assert!(
12505 y4m.status.success(),
12506 "ffmpeg fixture: {}",
12507 String::from_utf8_lossy(&y4m.stderr)
12508 );
12509 // The 8x8-leaf arm is fenced by three sibling refusals (non-DC
12510 // chroma on an 8x8 leaf, its TX_4X4 split, sub-16 rect inter
12511 // leaves), so it sweeps the quantiser as well as the source: a
12512 // coarser q is what pushes the RD to directional intra at 8x8.
12513 let cq = if leaf8 {
12514 format!("--cq-level={}", 20 + (attempt % 5) * 10)
12515 } else {
12516 "--cq-level=30".to_string()
12517 };
12518 let depth_args: &[&str] = if bit_depth == 10 {
12519 &["-b", "10", "--input-bit-depth=10"]
12520 } else {
12521 &[]
12522 };
12523 let out = run_with_stdin(Command::new(aomenc_path())
12524 .args(depth_args)
12525 .args([
12526 "--codec=av1",
12527 "--passes=1",
12528 "--end-usage=q",
12529 &cq,
12530 "--cpu-used=0",
12531 "--lag-in-frames=0",
12532 "--auto-alt-ref=0",
12533 // One key frame only: every later frame is an inter frame,
12534 // which is where this gate's intra blocks must sit. The
12535 // MIN distance is what stops aomenc's scene-cut detector
12536 // from inserting a second key frame at the cut this gate's
12537 // source deliberately contains.
12538 "--kf-max-dist=1000",
12539 "--kf-min-dist=1000",
12540 "--threads=1",
12541 "--row-mt=0",
12542 "--enable-order-hint=0",
12543 "--enable-warped-motion=0",
12544 "--enable-obmc=0",
12545 "--enable-masked-comp=0",
12546 "--enable-interintra-comp=0",
12547 "--enable-dist-wtd-comp=0",
12548 "--enable-diff-wtd-comp=0",
12549 "--enable-onesided-comp=0",
12550 "--enable-interintra-wedge=0",
12551 "--enable-smooth-interintra=0",
12552 "--enable-ab-partitions=0",
12553 "--enable-1to4-partitions=0",
12554 "--enable-smooth-intra=0",
12555 "--enable-paeth-intra=0",
12556 "--enable-directional-intra=1",
12557 "--enable-angle-delta=1",
12558 "--enable-cdef=0",
12559 "--enable-restoration=0",
12560 "--enable-palette=0",
12561 "--enable-intrabc=0",
12562 "--enable-cfl-intra=0",
12563 "--enable-ref-frame-mvs=0",
12564 // Per-arm overrides go LAST (aomenc keeps the last
12565 // occurrence of a repeated --enable-* flag): the intra
12566 // tx_depth symbol only exists under TX_MODE_SELECT, and
12567 // rect partitions are a separate named refusal.
12568 "--enable-filter-intra=1",
12569 "--enable-tx-size-search=1",
12570 "--enable-rect-partitions=0",
12571 "--max-partition-size=32",
12572 // Sub-16 inter partitions are a separate named refusal,
12573 // as is the 8x8 intra leaf's own TX_4X4 split.
12574 min_partition,
12575 "--obu",
12576 "-o",
12577 "-",
12578 "-",
12579 ]), &y4m.stdout);
12580 assert!(
12581 out.status.success(),
12582 "aomenc refused the fixture: {}",
12583 String::from_utf8_lossy(&out.stderr)
12584 );
12585 let stream = out.stdout;
12586 let before = decode::intra_in_inter_angle_delta_y_hits();
12587 let before_uv = decode::intra_in_inter_angle_delta_uv_hits();
12588 let frames = match decode_stream(&stream) {
12589 Ok(frames) => frames,
12590 Err(e) => {
12591 let msg = e.to_string();
12592 assert!(
12593 msg.contains("unsupported"),
12594 "{name} decode failed outright (seed {seed}): {msg}"
12595 );
12596 refusals.push(format!("seed {seed}: {msg}"));
12597 continue;
12598 }
12599 };
12600 let fired = decode::intra_in_inter_angle_delta_y_hits() - before;
12601 let fired_uv = decode::intra_in_inter_angle_delta_uv_hits() - before_uv;
12602 // class [[gate-skips-on-its-own-failure]]: a decode that
12603 // succeeded is ALWAYS pixel-compared below; the counter only
12604 // decides whether the attempt counts as firing.
12605 let counted = fired != 0;
12606 if !counted {
12607 uncounted_exact += 1;
12608 refusals.push(format!(
12609 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
12610 frame carried a nonzero angle_delta_y"
12611 ));
12612 }
12613 let ffmpeg_frames = if bit_depth == 10 {
12614 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12615 } else {
12616 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12617 };
12618 assert_eq!(frames.len(), frame_count);
12619 eprintln!(
12620 "{name} seed={seed}: intra-in-inter blocks with a nonzero angle_delta_y = \
12621 {fired}, angle_delta_uv = {fired_uv}"
12622 );
12623 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12624 for (plane, (g, w)) in [
12625 ("Y", (&got.y, &want.y)),
12626 ("U", (&got.u, &want.u)),
12627 ("V", (&got.v, &want.v)),
12628 ] {
12629 let stride = if plane == "Y" { width } else { width / 2 };
12630 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
12631 eprintln!(
12632 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
12633 want {} ({} samples differ)",
12634 at % stride,
12635 at / stride,
12636 g[at],
12637 w[at],
12638 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
12639 );
12640 }
12641 }
12642 }
12643 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12644 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
12645 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
12646 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
12647 }
12648 if counted {
12649 gate_buckets(
12650 &name,
12651 1,
12652 uncounted_exact,
12653 refusals.len() - uncounted_exact as usize,
12654 );
12655 return;
12656 }
12657 }
12658 gate_buckets(
12659 &name,
12660 0,
12661 uncounted_exact,
12662 refusals.len() - uncounted_exact as usize,
12663 );
12664 panic!(
12665 "{name} never observed a nonzero angle delta on an intra block in an inter \
12666 frame:\n{}",
12667 refusals.join("\n")
12668 );
12669 }
12670
12671 /// lane-uv8 r1 (classes [[refusal-strings-are-claims]] +
12672 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
12673 /// 8x8 partitions and full chroma intra tooling
12674 /// (`--enable-cfl-intra=1 --enable-smooth-intra=1 --enable-paeth-intra=1
12675 /// --enable-directional-intra=1`), in which the RD gives an INTRA 8x8
12676 /// leaf inside an inter frame a NON-DC `uv_mode`. That leaf
12677 /// ([`decode::decode_inter_block8`]'s intra arm) read the `uv_mode`
12678 /// symbol and refused every value but `DC_PRED` -- "this encoder never
12679 /// writes one" was a claim, and this gate is what contradicts it. Hard-
12680 /// asserts `decode::intra_in_inter8_uv_hits` (directional, smooth/paeth,
12681 /// CfL, counted on THIS leaf only); an attempt that never produced one
12682 /// proves nothing, and exhausting every attempt is a FAILURE, not a SKIP.
12683 #[test]
12684 fn a_real_aomenc_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() {
12685 uv_mode_in_inter8_gate(8, 1);
12686 }
12687
12688 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
12689 #[test]
12690 fn a_real_aomenc_10bit_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() {
12691 uv_mode_in_inter8_gate(10, 1);
12692 }
12693
12694 /// The multi-tile arm (class [[new-map-ignores-tile-edge]]): this round
12695 /// stamps a new `uv_mode` band from the 8x8 leaf, whose availability must
12696 /// be tile-relative.
12697 #[test]
12698 fn a_real_aomenc_two_tile_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact()
12699 {
12700 uv_mode_in_inter8_gate(8, 2);
12701 }
12702
12703 fn uv_mode_in_inter8_gate(bit_depth: u32, tile_columns: u32) {
12704 let name = format!("uv_mode_in_inter8_gate({bit_depth}, tiles={tile_columns})");
12705 if !have_ffmpeg() {
12706 eprintln!("SKIP {name}: no ffmpeg");
12707 return;
12708 }
12709 if !have_aomenc() {
12710 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
12711 return;
12712 }
12713 let (width, height, frame_count) = (192usize, 128usize, 8usize);
12714 let mut refusals = Vec::new();
12715 let mut uncounted_exact = 0u32;
12716 let mut totals = (0usize, 0usize, 0usize);
12717 for attempt in 0..30u32 {
12718 let seed = 42 + attempt;
12719 // A zooming fractal with a hard CUT at frame 4 (`overlay`
12720 // switching a second, unrelated fractal on): after the cut a block
12721 // is unpredictable from the reference, which is what makes aomenc
12722 // code INTRA blocks inside an inter frame. Chroma is NOT
12723 // desaturated here (every sibling inter gate passes `hue=s=0`) --
12724 // real chroma detail is exactly what pushes the chroma RD off
12725 // DC_PRED. `noise` carries its own explicit seed (lavfi
12726 // `gradients` ignores its seed; class [[seeded-fixture-not-reproducible]]).
12727 let source = format!(
12728 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
12729 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
12730 [a][b]overlay=enable='gte(n,4)',noise=alls=12:allf=t+u:all_seed={seed}",
12731 5.0 - f64::from(attempt) * 0.06,
12732 0.9 + f64::from(attempt) * 0.11
12733 );
12734 let y4m = Command::new("ffmpeg")
12735 .args([
12736 "-v",
12737 "error",
12738 "-f",
12739 "lavfi",
12740 "-i",
12741 &source,
12742 "-pix_fmt",
12743 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
12744 "-strict",
12745 "-1",
12746 "-t",
12747 "0.32",
12748 "-f",
12749 "yuv4mpegpipe",
12750 "-strict",
12751 "-1",
12752 "-",
12753 ])
12754 .stdin(Stdio::null())
12755 .stdout(Stdio::piped())
12756 .stderr(Stdio::piped())
12757 .output()
12758 .expect("ffmpeg failed to run");
12759 assert!(
12760 y4m.status.success(),
12761 "ffmpeg fixture: {}",
12762 String::from_utf8_lossy(&y4m.stderr)
12763 );
12764 // A coarser quantiser is what pushes the chroma RD to a cheap
12765 // non-DC mode on a small block; sweep 12..40 (the low end is what
12766 // lane-cdef's cq12 arm needs).
12767 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
12768 let depth_args: &[&str] = if bit_depth == 10 {
12769 &["-b", "10", "--input-bit-depth=10"]
12770 } else {
12771 &[]
12772 };
12773 let tiles = format!("--tile-columns={}", tile_columns - 1);
12774 // The y4m goes through a FILE, not aomenc's stdin: this gate's
12775 // stream is ~100 KB, bigger than a pipe buffer, so an aomenc that
12776 // is still being fed on stdin blocks writing its stdout and the
12777 // test blocks writing its stdin -- a hard deadlock (measured
12778 // here, 3 min into attempt 0, class [[gate-loader-slurps-whole-file]]).
12779 // The path is PID-keyed (class [[pid-keyed-temp-path]]).
12780 let y4m_path = std::env::temp_dir().join(format!(
12781 "ec-av1-uv8-{}-{bit_depth}-{tile_columns}-{seed}.y4m",
12782 std::process::id()
12783 ));
12784 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
12785 let child = Command::new(aomenc_path())
12786 .args(depth_args)
12787 .args([
12788 "--codec=av1",
12789 "--passes=1",
12790 "--end-usage=q",
12791 &cq,
12792 "--cpu-used=0",
12793 "--lag-in-frames=0",
12794 "--auto-alt-ref=0",
12795 "--kf-max-dist=9999",
12796 "--kf-min-dist=9999",
12797 "--threads=1",
12798 "--row-mt=0",
12799 &tiles,
12800 "--enable-order-hint=0",
12801 "--enable-warped-motion=0",
12802 "--enable-obmc=0",
12803 "--enable-masked-comp=0",
12804 "--enable-interintra-comp=0",
12805 "--enable-dist-wtd-comp=0",
12806 "--enable-diff-wtd-comp=0",
12807 "--enable-onesided-comp=0",
12808 "--enable-interintra-wedge=0",
12809 "--enable-smooth-interintra=0",
12810 "--enable-ab-partitions=0",
12811 "--enable-1to4-partitions=0",
12812 "--enable-cdef=0",
12813 "--enable-restoration=0",
12814 "--enable-palette=0",
12815 "--enable-intrabc=0",
12816 "--enable-ref-frame-mvs=0",
12817 // Per-arm overrides go LAST (aomenc keeps the LAST
12818 // occurrence of a repeated --enable-* flag). The three
12819 // chroma intra tools this gate is about, plus the fences
12820 // that keep the leaf's SIBLING refusals (its TX_4X4
12821 // split, a nonzero angle delta, sub-16 rect inter leaves)
12822 // out of the way.
12823 "--enable-cfl-intra=1",
12824 "--enable-smooth-intra=1",
12825 "--enable-paeth-intra=1",
12826 "--enable-directional-intra=1",
12827 "--enable-angle-delta=0",
12828 "--enable-tx-size-search=0",
12829 "--enable-rect-partitions=0",
12830 "--min-partition-size=8",
12831 "--max-partition-size=32",
12832 "--obu",
12833 "-o",
12834 "-",
12835 ])
12836 .arg(&y4m_path)
12837 .stdin(Stdio::null())
12838 .stdout(Stdio::piped())
12839 .stderr(Stdio::piped())
12840 .spawn()
12841 .expect("aomenc failed to start");
12842 let out = child.wait_with_output().expect("aomenc failed to run");
12843 let _ = std::fs::remove_file(&y4m_path);
12844 assert!(
12845 out.status.success(),
12846 "aomenc refused the fixture: {}",
12847 String::from_utf8_lossy(&out.stderr)
12848 );
12849 let stream = out.stdout;
12850 let before = decode::intra_in_inter8_uv_hits();
12851 let frames = match decode_stream(&stream) {
12852 Ok(frames) => frames,
12853 Err(e) => {
12854 let msg = e.to_string();
12855 assert!(
12856 msg.contains("unsupported"),
12857 "{name} decode failed outright (seed {seed}): {msg}"
12858 );
12859 refusals.push(format!("seed {seed}: {msg}"));
12860 continue;
12861 }
12862 };
12863 let now = decode::intra_in_inter8_uv_hits();
12864 // class [[counter-from-refused-stream]]: per-attempt deltas, and
12865 // only for an attempt that decoded to the end and is pixel-
12866 // compared below.
12867 let fired = (now.0 - before.0, now.1 - before.1, now.2 - before.2);
12868 totals = (
12869 totals.0 + fired.0,
12870 totals.1 + fired.1,
12871 totals.2 + fired.2,
12872 );
12873 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
12874 // is ALWAYS pixel-compared; the counter only decides whether the
12875 // attempt counts as firing.
12876 // lane-uv8 r3: every one of the three chroma classes this gate
12877 // exists for (directional, smooth/paeth, CfL) must fire on the
12878 // SAME pixel-compared attempt -- a sum-nonzero predicate would
12879 // pass on an attempt that only ever hit DC-adjacent CfL.
12880 let counted = fired.0 > 0 && fired.1 > 0 && fired.2 > 0;
12881 if !counted {
12882 uncounted_exact += 1;
12883 refusals.push(format!(
12884 "seed {seed}: decoded and pixel-compared, but no 8x8 intra leaf in an inter \
12885 frame carried a non-DC uv_mode"
12886 ));
12887 }
12888 let ffmpeg_frames = if bit_depth == 10 {
12889 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
12890 } else {
12891 ffmpeg_decode_sequence(&stream, width, height, frame_count)
12892 };
12893 assert_eq!(frames.len(), frame_count);
12894 eprintln!(
12895 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with a non-DC uv_mode -- \
12896 directional {}, smooth/paeth {}, CfL {}",
12897 fired.0, fired.1, fired.2
12898 );
12899 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12900 for (plane, (g, w)) in [
12901 ("Y", (&got.y, &want.y)),
12902 ("U", (&got.u, &want.u)),
12903 ("V", (&got.v, &want.v)),
12904 ] {
12905 let stride = if plane == "Y" { width } else { width / 2 };
12906 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
12907 eprintln!(
12908 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
12909 want {} ({} samples differ)",
12910 at % stride,
12911 at / stride,
12912 g[at],
12913 w[at],
12914 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
12915 );
12916 }
12917 }
12918 }
12919 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12920 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
12921 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
12922 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
12923 }
12924 if counted {
12925 gate_buckets(
12926 &name,
12927 1,
12928 uncounted_exact,
12929 refusals.len() - uncounted_exact as usize,
12930 );
12931 return;
12932 }
12933 }
12934 gate_buckets(
12935 &name,
12936 0,
12937 uncounted_exact,
12938 refusals.len() - uncounted_exact as usize,
12939 );
12940 panic!(
12941 "{name} never observed a non-DC uv_mode on an 8x8 intra leaf in an inter frame \
12942 (totals dir/smooth/cfl {totals:?}):\n{}",
12943 refusals.join("\n")
12944 );
12945 }
12946
12947
12948 /// lane-leaf8tx r1: the refusal this round lifts on an INTRA 8x8 leaf
12949 /// inside an INTER frame -- a nonzero luma `angle_delta_y` on it
12950 /// (`--enable-angle-delta=1`,
12951 /// `av1_use_angle_delta(BLOCK_8X8)`). Both counters are per-attempt
12952 /// deltas on an attempt that decoded to the end and is pixel-compared
12953 /// (class [[counter-from-refused-stream]]); a decode error or a mismatch
12954 /// is a FAILURE, never a SKIP.
12955 #[test]
12956 fn a_real_aomenc_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
12957 tx_split_angle_in_inter8_gate(8);
12958 }
12959
12960 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
12961 #[test]
12962 fn a_real_aomenc_10bit_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
12963 tx_split_angle_in_inter8_gate(10);
12964 }
12965
12966 fn tx_split_angle_in_inter8_gate(bit_depth: u32) {
12967 let name = format!("tx_split_angle_in_inter8_gate({bit_depth})");
12968 if !have_ffmpeg() {
12969 eprintln!("SKIP {name}: no ffmpeg");
12970 return;
12971 }
12972 if !have_aomenc() {
12973 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
12974 return;
12975 }
12976 let (width, height, frame_count) = (192usize, 128usize, 6usize);
12977 let mut refusals = Vec::new();
12978 let mut uncounted_exact = 0u32;
12979 let mut counted_exact = 0u32;
12980 let mut totals = (0usize, 0usize);
12981 for attempt in 0..30u32 {
12982 let seed = 42 + attempt;
12983 // Same zoom + hard-cut fractal source the sibling uv_mode gate
12984 // uses (a cut is what makes aomenc code INTRA blocks inside an
12985 // inter frame); `noise` carries an explicit seed (class
12986 // [[seeded-fixture-not-reproducible]]).
12987 let source = format!(
12988 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
12989 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
12990 [a][b]overlay=enable='gte(n,3)',noise=alls=12:allf=t+u:all_seed={seed}",
12991 5.0 - f64::from(attempt) * 0.06,
12992 0.9 + f64::from(attempt) * 0.11
12993 );
12994 let y4m = Command::new("ffmpeg")
12995 .args([
12996 "-v",
12997 "error",
12998 "-f",
12999 "lavfi",
13000 "-i",
13001 &source,
13002 "-pix_fmt",
13003 if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" },
13004 "-strict",
13005 "-1",
13006 "-t",
13007 "0.24",
13008 "-f",
13009 "yuv4mpegpipe",
13010 "-strict",
13011 "-1",
13012 "-",
13013 ])
13014 .stdin(Stdio::null())
13015 .stdout(Stdio::piped())
13016 .stderr(Stdio::piped())
13017 .output()
13018 .expect("ffmpeg failed to run");
13019 assert!(
13020 y4m.status.success(),
13021 "ffmpeg fixture: {}",
13022 String::from_utf8_lossy(&y4m.stderr)
13023 );
13024 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
13025 let depth_args: &[&str] = if bit_depth == 10 {
13026 &["-b", "10", "--input-bit-depth=10"]
13027 } else {
13028 &[]
13029 };
13030 // The y4m goes through a PID-keyed FILE, never aomenc's stdin
13031 // (pipe deadlock, class [[gate-loader-slurps-whole-file]]).
13032 let y4m_path = std::env::temp_dir().join(format!(
13033 "ec-av1-leaf8tx-{}-{bit_depth}-{seed}.y4m",
13034 std::process::id()
13035 ));
13036 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
13037 let child = Command::new(aomenc_path())
13038 .args(depth_args)
13039 .args([
13040 "--codec=av1",
13041 "--passes=1",
13042 "--end-usage=q",
13043 &cq,
13044 "--cpu-used=0",
13045 "--lag-in-frames=0",
13046 "--auto-alt-ref=0",
13047 "--kf-max-dist=9999",
13048 "--kf-min-dist=9999",
13049 "--threads=1",
13050 "--row-mt=0",
13051 "--tile-columns=0",
13052 "--enable-order-hint=0",
13053 "--enable-warped-motion=0",
13054 "--enable-obmc=0",
13055 "--enable-masked-comp=0",
13056 "--enable-interintra-comp=0",
13057 "--enable-dist-wtd-comp=0",
13058 "--enable-diff-wtd-comp=0",
13059 "--enable-onesided-comp=0",
13060 "--enable-interintra-wedge=0",
13061 "--enable-smooth-interintra=0",
13062 "--enable-ab-partitions=0",
13063 "--enable-1to4-partitions=0",
13064 "--enable-cdef=0",
13065 "--enable-restoration=0",
13066 "--enable-palette=0",
13067 "--enable-intrabc=0",
13068 "--enable-ref-frame-mvs=0",
13069 // Per-arm overrides LAST (aomenc keeps the last
13070 // occurrence of a repeated --enable-* flag). Rect
13071 // partitions stay off so the leaf's unrelated sub-16 rect
13072 // inter refusal never fires.
13073 "--enable-rect-partitions=0",
13074 "--enable-tx-size-search=1",
13075 "--enable-angle-delta=1",
13076 "--enable-directional-intra=1",
13077 "--min-partition-size=8",
13078 "--max-partition-size=32",
13079 "--obu",
13080 "-o",
13081 "-",
13082 ])
13083 // r1 diagnostic: EC_LEAF8TX_CONTROL=1 turns THIS lane's two
13084 // tools back off (last occurrence of a repeated --enable-*
13085 // wins), so any mismatch that survives is not this lane's.
13086 .args(match std::env::var("EC_LEAF8TX_CONTROL").as_deref() {
13087 Ok("angle") => vec!["--enable-tx-size-search=0", "--enable-angle-delta=1"],
13088 Ok("tx") => vec!["--enable-tx-size-search=1", "--enable-angle-delta=0"],
13089 Ok("tx8") => vec![
13090 "--enable-tx-size-search=1",
13091 "--enable-angle-delta=0",
13092 "--max-partition-size=8",
13093 ],
13094 Ok(_) => vec!["--enable-tx-size-search=0", "--enable-angle-delta=0"],
13095 // Shipped recipe (lane-leaf8tx r4): BOTH of this lane's
13096 // tools on -- the tx_depth split at an 8x8 intra-in-inter
13097 // leaf is what the lifted refusal covers, so
13098 // `--enable-tx-size-search=1` must survive the per-arm
13099 // override (aomenc keeps the LAST occurrence). Odd
13100 // attempts also cap the partition at 8x8, the shape that
13101 // produces the 2x2 TX_4X4 grid most often.
13102 Err(_) => {
13103 if attempt % 2 == 1 {
13104 vec![
13105 "--enable-tx-size-search=1",
13106 "--enable-angle-delta=1",
13107 "--max-partition-size=8",
13108 ]
13109 } else {
13110 vec!["--enable-tx-size-search=1", "--enable-angle-delta=1"]
13111 }
13112 }
13113 })
13114 .arg(&y4m_path)
13115 .stdin(Stdio::null())
13116 .stdout(Stdio::piped())
13117 .stderr(Stdio::piped())
13118 .spawn()
13119 .expect("aomenc failed to start");
13120 let out = child.wait_with_output().expect("aomenc failed to run");
13121 let _ = std::fs::remove_file(&y4m_path);
13122 assert!(
13123 out.status.success(),
13124 "aomenc refused the fixture: {}",
13125 String::from_utf8_lossy(&out.stderr)
13126 );
13127 let stream = out.stdout;
13128 let before = (
13129 decode::intra_in_inter_split_tx_hits()[0],
13130 decode::intra_in_inter8_angle_delta_y_hits(),
13131 );
13132 let frames = match decode_stream(&stream) {
13133 Ok(frames) => frames,
13134 Err(e) => {
13135 let msg = e.to_string();
13136 assert!(
13137 msg.contains("unsupported"),
13138 "{name} decode failed outright (seed {seed}): {msg}"
13139 );
13140 refusals.push(format!("seed {seed}: {msg}"));
13141 continue;
13142 }
13143 };
13144 let now = (
13145 decode::intra_in_inter_split_tx_hits()[0],
13146 decode::intra_in_inter8_angle_delta_y_hits(),
13147 );
13148 let fired = (now.0 - before.0, now.1 - before.1);
13149 totals = (totals.0 + fired.0, totals.1 + fired.1);
13150 // Both lifted capabilities must fire on the SAME pixel-compared
13151 // attempt.
13152 let counted = fired.1 > 0;
13153 if !counted {
13154 uncounted_exact += 1;
13155 refusals.push(format!(
13156 "seed {seed}: decoded and pixel-compared, but split-tx {} / angle-delta {} \
13157 8x8 intra-in-inter leaves",
13158 fired.0, fired.1
13159 ));
13160 }
13161 let ffmpeg_frames = if bit_depth == 10 {
13162 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
13163 } else {
13164 ffmpeg_decode_sequence(&stream, width, height, frame_count)
13165 };
13166 assert_eq!(frames.len(), frame_count);
13167 eprintln!(
13168 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with tx_depth=1 {}, with a \
13169 nonzero angle_delta_y {} (split-tx per size 8/16/32/64 {:?})",
13170 fired.0,
13171 fired.1,
13172 decode::intra_in_inter_split_tx_hits()
13173 );
13174 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13175 for (plane, (g, w)) in [
13176 ("Y", (&got.y, &want.y)),
13177 ("U", (&got.u, &want.u)),
13178 ("V", (&got.v, &want.v)),
13179 ] {
13180 let stride = if plane == "Y" { width } else { width / 2 };
13181 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
13182 eprintln!(
13183 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
13184 want {} ({} samples differ)",
13185 at % stride,
13186 at / stride,
13187 g[at],
13188 w[at],
13189 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
13190 );
13191 }
13192 }
13193 }
13194 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13195 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
13196 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
13197 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
13198 }
13199 if counted {
13200 counted_exact += 1;
13201 }
13202 }
13203 // lane-leaf8tx r4: continue-and-sweep -- every arm is encoded,
13204 // decoded and pixel-compared on every plane of every decode-order
13205 // frame above; the counters are asserted ONCE here. A decode error or
13206 // a mismatch is a failure, never a SKIP, and `uncounted_exact`
13207 // (decoded + compared but neither capability fired) is the
13208 // out-of-scope-mismatch bucket that the sweep tolerates only while at
13209 // least one attempt did fire.
13210 gate_buckets(
13211 &name,
13212 counted_exact,
13213 uncounted_exact,
13214 refusals.len() - uncounted_exact as usize,
13215 );
13216 assert!(
13217 totals.0 > 0,
13218 "{name}: no decoded+compared attempt carried an 8x8 intra-in-inter leaf with \
13219 tx_depth split to 4x4 (split-tx per size {:?}, angle-delta {}):\n{}",
13220 decode::intra_in_inter_split_tx_hits(),
13221 totals.1,
13222 refusals.join("\n")
13223 );
13224 assert!(
13225 totals.1 > 0,
13226 "{name}: no decoded+compared attempt carried a nonzero angle_delta_y on an 8x8 \
13227 intra-in-inter leaf (split-tx {}):\n{}",
13228 totals.0,
13229 refusals.join("\n")
13230 );
13231 }
13232
13233 /// lane-chroma r2 stage 1: a real aomenc key frame with
13234 /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`)
13235 /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still-
13236 /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never
13237 /// fires; smooth *luma* neighbours are exactly what this gate wants to
13238 /// exercise, proving [`decode::smooth_luma_hits`] actually landed a
13239 /// directional block next to a smooth-predicted one and decoded
13240 /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix).
13241 #[test]
13242 fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() {
13243 if !have_ffmpeg() {
13244 eprintln!(
13245 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg"
13246 );
13247 return;
13248 }
13249 if !have_aomenc() {
13250 eprintln!(
13251 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}",
13252 aomenc_path().display()
13253 );
13254 return;
13255 }
13256 let (width, height) = (64usize, 64usize);
13257 let mut refusals = Vec::new();
13258 let mut fired_runs = 0u32;
13259 let mut uncounted_exact = 0u32;
13260 for attempt in 0..40u32 {
13261 let seed = 42 + attempt;
13262 let source = format!(
13263 "mandelbrot=size=64x64:start_scale={}:rate=25",
13264 5.0 - f64::from(attempt) * 0.06
13265 );
13266 let y4m = Command::new("ffmpeg")
13267 .args([
13268 "-v",
13269 "error",
13270 "-f",
13271 "lavfi",
13272 "-i",
13273 &source,
13274 "-pix_fmt",
13275 "yuv420p",
13276 "-t",
13277 "0.04",
13278 "-f",
13279 "yuv4mpegpipe",
13280 "-",
13281 ])
13282 .stdin(Stdio::null())
13283 .stdout(Stdio::piped())
13284 .stderr(Stdio::piped())
13285 .output()
13286 .expect("ffmpeg failed to run");
13287 assert!(
13288 y4m.status.success(),
13289 "ffmpeg fixture: {}",
13290 String::from_utf8_lossy(&y4m.stderr)
13291 );
13292 let out = run_with_stdin(Command::new(aomenc_path())
13293 .args([
13294 "--codec=av1",
13295 "--passes=1",
13296 "--end-usage=q",
13297 "--cq-level=45",
13298 "--cpu-used=0",
13299 "--enable-rect-partitions=0",
13300 "--enable-ab-partitions=0",
13301 "--enable-1to4-partitions=0",
13302 "--enable-filter-intra=0",
13303 "--enable-smooth-intra=1",
13304 // Smooth/paeth chroma is a still-refused, separate
13305 // round-2 gap -- off so no attempt trips it while this
13306 // gate is purely about luma's edge-filter fix.
13307 "--enable-paeth-intra=0",
13308 "--enable-tx-size-search=0",
13309 "--enable-cdef=0",
13310 "--enable-restoration=0",
13311 "--enable-intra-edge-filter=1",
13312 "--max-partition-size=32",
13313 "--min-partition-size=16",
13314 "--enable-palette=0",
13315 "--enable-intrabc=0",
13316 "--enable-cfl-intra=0",
13317 "--enable-ref-frame-mvs=0",
13318 "--obu",
13319 "-o",
13320 "-",
13321 "-",
13322 ]), &y4m.stdout);
13323 assert!(
13324 out.status.success(),
13325 "aomenc refused the fixture: {}",
13326 String::from_utf8_lossy(&out.stderr)
13327 );
13328 let stream = out.stdout;
13329 let smooth_before = decode::smooth_luma_hits();
13330 let frames = match decode_stream(&stream) {
13331 Ok(frames) => frames,
13332 Err(e) => {
13333 refusals.push(format!("seed {seed}: {e}"));
13334 continue;
13335 }
13336 };
13337 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
13338 // is ALWAYS pixel-compared below; the hit counter only decides whether
13339 // the attempt counts toward the firing total.
13340 let counted = decode::smooth_luma_hits() != smooth_before;
13341 if counted {
13342 fired_runs += 1;
13343 } else {
13344 uncounted_exact += 1;
13345 refusals.push(format!(
13346 "seed {seed}: decoded and pixel-compared, but no smooth-luma-neighbour block \
13347 fired"
13348 ));
13349 }
13350 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
13351 assert_eq!(
13352 frames[0].y, ffmpeg_frames[0].y,
13353 "luma vs ffmpeg (seed {seed})"
13354 );
13355 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
13356 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
13357 if fired_runs >= 4 {
13358 gate_buckets(
13359 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
13360 fired_runs,
13361 uncounted_exact,
13362 refusals.len() - uncounted_exact as usize,
13363 );
13364 return;
13365 }
13366 }
13367 gate_buckets(
13368 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
13369 fired_runs,
13370 uncounted_exact,
13371 refusals.len() - uncounted_exact as usize,
13372 );
13373 assert!(
13374 fired_runs > 0,
13375 "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}",
13376 refusals.join("\n")
13377 );
13378 }
13379
13380 /// The smooth/paeth-chroma gate (lane-chroma r1/r3): a real aomenc key
13381 /// frame with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the
13382 /// opposite of the directional-chroma gate below, which turns these OFF
13383 /// to keep this gap from firing while directional chroma is under test).
13384 /// Some seeds won't pick smooth/paeth for chroma at all -- retry like
13385 /// every other real-encoder gate here, but the first attempt that
13386 /// actually fires [`decode::smooth_uv_hits`] must decode pixel-exact.
13387 #[test]
13388 fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() {
13389 if !have_ffmpeg() {
13390 eprintln!(
13391 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg"
13392 );
13393 return;
13394 }
13395 if !have_aomenc() {
13396 eprintln!(
13397 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}",
13398 aomenc_path().display()
13399 );
13400 return;
13401 }
13402 let (width, height) = (64usize, 64usize);
13403 let mut refusals = Vec::new();
13404 let mut fired_runs = 0u32;
13405 let mut uncounted_exact = 0u32;
13406 for attempt in 0..40u32 {
13407 let seed = 42 + attempt;
13408 let source = format!(
13409 "mandelbrot=size=64x64:start_scale={}:rate=25",
13410 5.0 - f64::from(attempt) * 0.06
13411 );
13412 let y4m = Command::new("ffmpeg")
13413 .args([
13414 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-t",
13415 "0.04", "-f", "yuv4mpegpipe", "-",
13416 ])
13417 .stdin(Stdio::null())
13418 .stdout(Stdio::piped())
13419 .stderr(Stdio::piped())
13420 .output()
13421 .expect("ffmpeg failed to run");
13422 assert!(
13423 y4m.status.success(),
13424 "ffmpeg fixture: {}",
13425 String::from_utf8_lossy(&y4m.stderr)
13426 );
13427 let out = run_with_stdin(Command::new(aomenc_path())
13428 .args([
13429 "--codec=av1",
13430 "--passes=1",
13431 "--end-usage=q",
13432 "--cq-level=45",
13433 "--cpu-used=0",
13434 "--enable-rect-partitions=0",
13435 "--enable-ab-partitions=0",
13436 "--enable-1to4-partitions=0",
13437 "--enable-filter-intra=0",
13438 "--enable-smooth-intra=1",
13439 "--enable-paeth-intra=1",
13440 "--enable-tx-size-search=0",
13441 "--enable-cdef=0",
13442 "--enable-restoration=0",
13443 "--enable-intra-edge-filter=1",
13444 "--max-partition-size=32",
13445 // 8x8/leaf8 splits are a separate, already-named refusal.
13446 "--min-partition-size=16",
13447 "--enable-palette=0",
13448 "--enable-intrabc=0",
13449 "--enable-cfl-intra=0",
13450 "--enable-ref-frame-mvs=0",
13451 "--obu",
13452 "-o",
13453 "-",
13454 "-",
13455 ]), &y4m.stdout);
13456 assert!(
13457 out.status.success(),
13458 "aomenc refused the fixture: {}",
13459 String::from_utf8_lossy(&out.stderr)
13460 );
13461 let stream = out.stdout;
13462 let smooth_before = decode::smooth_uv_hits();
13463 let frames = match decode_stream(&stream) {
13464 Ok(frames) => frames,
13465 Err(e) => {
13466 refusals.push(format!("seed {seed}: {e}"));
13467 continue;
13468 }
13469 };
13470 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
13471 // is ALWAYS pixel-compared below; the hit counter only decides whether
13472 // the attempt counts toward the firing total.
13473 let counted = decode::smooth_uv_hits() != smooth_before;
13474 if counted {
13475 fired_runs += 1;
13476 } else {
13477 uncounted_exact += 1;
13478 refusals.push(format!(
13479 "seed {seed}: decoded and pixel-compared, but no smooth/paeth uv_mode fired"
13480 ));
13481 }
13482 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
13483 assert_eq!(
13484 frames[0].y, ffmpeg_frames[0].y,
13485 "luma vs ffmpeg (seed {seed})"
13486 );
13487 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
13488 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
13489 if fired_runs >= 4 {
13490 gate_buckets(
13491 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
13492 fired_runs,
13493 uncounted_exact,
13494 refusals.len() - uncounted_exact as usize,
13495 );
13496 return;
13497 }
13498 }
13499 gate_buckets(
13500 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
13501 fired_runs,
13502 uncounted_exact,
13503 refusals.len() - uncounted_exact as usize,
13504 );
13505 assert!(
13506 fired_runs > 0,
13507 "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}",
13508 refusals.join("\n")
13509 );
13510 }
13511
13512 /// The directional-chroma/angle-delta gate: a real aomenc key frame with
13513 /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the
13514 /// opposite of every sibling recipe's `=0`, which existed specifically to
13515 /// keep this round-2 gap from firing while a different surface was under
13516 /// test). A colourful, sharp-edged source gives the RD search a reason to
13517 /// pick a directional `uv_mode` and/or a nonzero angle delta -- some
13518 /// seeds still won't, so retry like every other real-encoder gate here,
13519 /// but the first attempt that actually fires either counter must decode
13520 /// pixel-exact.
13521 #[test]
13522 fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() {
13523 if !have_ffmpeg() {
13524 eprintln!(
13525 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg"
13526 );
13527 return;
13528 }
13529 if !have_aomenc() {
13530 eprintln!(
13531 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}",
13532 aomenc_path().display()
13533 );
13534 return;
13535 }
13536 let (width, height) = (64usize, 64usize);
13537 let mut refusals = Vec::new();
13538 let mut fired_runs = 0u32;
13539 let mut uncounted_exact = 0u32;
13540 for attempt in 0..40u32 {
13541 let seed = 42 + attempt;
13542 let source = format!(
13543 "mandelbrot=size=64x64:start_scale={}:rate=25",
13544 5.0 - f64::from(attempt) * 0.06
13545 );
13546 let y4m = Command::new("ffmpeg")
13547 .args([
13548 "-v",
13549 "error",
13550 "-f",
13551 "lavfi",
13552 "-i",
13553 &source,
13554 "-pix_fmt",
13555 "yuv420p",
13556 "-t",
13557 "0.04",
13558 "-f",
13559 "yuv4mpegpipe",
13560 "-",
13561 ])
13562 .stdin(Stdio::null())
13563 .stdout(Stdio::piped())
13564 .stderr(Stdio::piped())
13565 .output()
13566 .expect("ffmpeg failed to run");
13567 assert!(
13568 y4m.status.success(),
13569 "ffmpeg fixture: {}",
13570 String::from_utf8_lossy(&y4m.stderr)
13571 );
13572 let out = run_with_stdin(Command::new(aomenc_path())
13573 .args([
13574 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
13575 // occurrence, so overrides go before the base list).
13576 "--enable-directional-intra=1",
13577 "--codec=av1",
13578 "--passes=1",
13579 "--end-usage=q",
13580 "--cq-level=45",
13581 "--cpu-used=0",
13582 "--enable-rect-partitions=0",
13583 "--enable-ab-partitions=0",
13584 "--enable-1to4-partitions=0",
13585 "--enable-filter-intra=0",
13586 // Smooth/Paeth chroma is a separate, still-refused round-2
13587 // gap (an unrelated `Edges::build` no-neighbour bug this
13588 // lane does not cover) -- off so the RD search's only
13589 // non-DC/CFL chroma choice left is directional.
13590 "--enable-smooth-intra=0",
13591 "--enable-paeth-intra=0",
13592 "--enable-tx-size-search=0",
13593 "--enable-cdef=0",
13594 "--enable-restoration=0",
13595 // The intra edge filter/upsample (spec 7.11.2.7-2.9) is
13596 // now implemented (`directional()`) -- left ON (aomenc's
13597 // own default) so this gate actually exercises it instead
13598 // of the un-filtered fast path a disabled flag would keep
13599 // testing.
13600 "--enable-intra-edge-filter=1",
13601 "--max-partition-size=32",
13602 // Same reason as the tx-select gate above: 8x8 and other
13603 // sub-16x16 splits are a separate, already-named refusal.
13604 "--min-partition-size=16",
13605 "--enable-palette=0",
13606 "--enable-intrabc=0",
13607 "--enable-cfl-intra=0",
13608 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
13609 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
13610 "--enable-ref-frame-mvs=0",
13611 "--obu",
13612 "-o",
13613 "-",
13614 "-",
13615 ]), &y4m.stdout);
13616 assert!(
13617 out.status.success(),
13618 "aomenc refused the fixture: {}",
13619 String::from_utf8_lossy(&out.stderr)
13620 );
13621 let stream = out.stdout;
13622 let (uv_before, angle_before) =
13623 (decode::directional_uv_hits(), decode::angle_delta_hits());
13624 let frames = match decode_stream(&stream) {
13625 Ok(frames) => frames,
13626 Err(e) => {
13627 refusals.push(format!("seed {seed}: {e}"));
13628 continue;
13629 }
13630 };
13631 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
13632 // is ALWAYS pixel-compared below; the hit counter only decides whether
13633 // the attempt counts toward the firing total.
13634 let counted = decode::directional_uv_hits() != uv_before
13635 || decode::angle_delta_hits() != angle_before;
13636 if counted {
13637 fired_runs += 1;
13638 } else {
13639 uncounted_exact += 1;
13640 refusals.push(format!(
13641 "seed {seed}: decoded and pixel-compared, but neither a directional uv_mode \
13642 nor a nonzero angle delta fired"
13643 ));
13644 }
13645 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
13646 assert_eq!(
13647 frames[0].y, ffmpeg_frames[0].y,
13648 "luma vs ffmpeg (seed {seed})"
13649 );
13650 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
13651 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
13652 if fired_runs >= 4 {
13653 gate_buckets(
13654 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
13655 fired_runs,
13656 uncounted_exact,
13657 refusals.len() - uncounted_exact as usize,
13658 );
13659 return;
13660 }
13661 }
13662 gate_buckets(
13663 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
13664 fired_runs,
13665 uncounted_exact,
13666 refusals.len() - uncounted_exact as usize,
13667 );
13668 assert!(
13669 fired_runs > 0,
13670 "every attempt hit a named refusal or never exercised directional chroma:\n{}",
13671 refusals.join("\n")
13672 );
13673 }
13674
13675 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
13676 /// --auto-alt-ref=0` keep every non-key frame a simple forward
13677 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this
13678 /// decoder's inter path does not model), `--kf-max-dist` past the clip's
13679 /// own length keeps frame 0 the only key frame.
13680 /// lane-inter8 r1: the inter tile path's SB-level `PARTITION_NONE` -- a
13681 /// whole 64x64 superblock coded as ONE inter block, which is what aomenc
13682 /// picks for static content and which this decoder refused by name
13683 /// ("an inter SB-level partition type other than SPLIT") until this
13684 /// round. HARD-asserts [`decode::inter_sb_none_hits`] moved (the arm
13685 /// really fired, class refusal-lifted-without-a-gate) and every frame is
13686 /// pixel-exact vs ffmpeg; a decode error is a FAILURE here, never a SKIP
13687 /// (class gate-skips-on-its-own-failure).
13688 /// lane-inter8 r1: generalised so the same recipe can target a deeper
13689 /// level of the inter partition tree -- `min_part` is aomenc's
13690 /// `--min-partition-size`, and `hits`/`what` name the counter that proves
13691 /// the arm under test really fired.
13692 #[track_caller]
13693 fn inter_sb_none_gate(
13694 name: &str,
13695 ten_bit: bool,
13696 min_part: &str,
13697 max_part: &str,
13698 hits: fn() -> usize,
13699 what: &str,
13700 // lane-inter8 r3: extra aomenc flags + the frame width they need.
13701 // `--tile-columns=1` needs a frame at least two superblocks wide or
13702 // aomenc silently codes one tile column and the arm is vacuous.
13703 extra: &[&str],
13704 width: usize,
13705 // lane-interp3 r1: sequence length -- a compound block needs several
13706 // already-coded references, which a 4-frame sequence never has.
13707 frame_count: usize,
13708 ) {
13709 if !have_ffmpeg() {
13710 eprintln!("SKIP {name}: no ffmpeg");
13711 return;
13712 }
13713 if !have_aomenc() {
13714 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
13715 return;
13716 }
13717 let height = 64usize;
13718 let duration = format!("{:.2}", frame_count as f64 / 25.0);
13719 // A deterministic synthetic source with real motion (a static source
13720 // codes every inter frame as skip and never exercises the residual
13721 // path); bounded with `-t` (class gate-loader-slurps-whole-file).
13722 let y4m = Command::new("ffmpeg")
13723 .args([
13724 "-v",
13725 "error",
13726 "-f",
13727 "lavfi",
13728 "-i",
13729 &format!("mandelbrot=size={width}x{height}:rate=25"),
13730 "-t",
13731 &duration,
13732 "-pix_fmt",
13733 if ten_bit { "yuv420p10le" } else { "yuv420p" },
13734 // y4m calls 10-bit unofficial (same as the 10-bit key-frame
13735 // gate's own fixture).
13736 "-strict",
13737 "-1",
13738 "-f",
13739 "yuv4mpegpipe",
13740 "-",
13741 ])
13742 .stdin(Stdio::null())
13743 .stdout(Stdio::piped())
13744 .stderr(Stdio::piped())
13745 .output()
13746 .expect("ffmpeg failed to run");
13747 assert!(
13748 y4m.status.success(),
13749 "{name}: ffmpeg fixture: {}",
13750 String::from_utf8_lossy(&y4m.stderr)
13751 );
13752 let mut args: Vec<String> = [
13753 "--codec=av1",
13754 "--passes=1",
13755 "--end-usage=q",
13756 "--cq-level=40",
13757 "--cpu-used=0",
13758 "--lag-in-frames=0",
13759 "--auto-alt-ref=0",
13760 "--kf-max-dist=1000",
13761 // No cross-frame CDF forwarding in this fixture (see the
13762 // deblocking gate's own note).
13763 "--error-resilient=1",
13764 // This gate targets the SB-level NONE arm only: rect/AB/1-to-4
13765 // partitions and sub-16x16 splits stay off so a failure here
13766 // cannot be another lane's missing arm.
13767 "--enable-rect-partitions=0",
13768 "--enable-ab-partitions=0",
13769 "--enable-1to4-partitions=0",
13770 "--enable-filter-intra=0",
13771 "--enable-smooth-intra=0",
13772 "--enable-paeth-intra=0",
13773 "--enable-directional-intra=0",
13774 "--enable-angle-delta=0",
13775 "--enable-tx-size-search=0",
13776 "--enable-cdef=0",
13777 "--enable-restoration=0",
13778 "--enable-palette=0",
13779 "--enable-intrabc=0",
13780 "--enable-cfl-intra=0",
13781 "--enable-ref-frame-mvs=0",
13782 "--obu",
13783 "-o",
13784 "-",
13785 "-",
13786 ]
13787 .iter()
13788 .map(|s| (*s).to_string())
13789 .collect();
13790 for e in extra {
13791 args.insert(1, (*e).to_string());
13792 }
13793 args.insert(1, format!("--min-partition-size={min_part}"));
13794 args.insert(1, format!("--max-partition-size={max_part}"));
13795 if ten_bit {
13796 args.insert(1, "--input-bit-depth=10".to_string());
13797 args.insert(1, "--bit-depth=10".to_string());
13798 }
13799 let out = run_with_stdin(Command::new(aomenc_path())
13800 .args(&args), &y4m.stdout);
13801 assert!(
13802 out.status.success(),
13803 "{name}: aomenc refused the fixture: {}",
13804 String::from_utf8_lossy(&out.stderr)
13805 );
13806 let stream = out.stdout;
13807 let before = hits();
13808 let frames = match decode_stream(&stream) {
13809 Ok(frames) => frames,
13810 Err(e) => {
13811 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
13812 let _ = std::fs::write(&pin, &stream);
13813 panic!("{name}: decode_stream refused a real aomenc stream: {e} (pinned at {})", pin.display());
13814 }
13815 };
13816 assert!(
13817 hits() > before,
13818 "{name}: no {what} fired -- this gate proves nothing"
13819 );
13820 let ffmpeg_frames = if ten_bit {
13821 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
13822 } else {
13823 ffmpeg_decode_sequence(&stream, width, height, frame_count)
13824 };
13825 assert_eq!(frames.len(), frame_count, "{name}: frame count");
13826 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
13827 if got.y != want.y || got.u != want.u || got.v != want.v {
13828 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
13829 let _ = std::fs::write(&pin, &stream);
13830 panic!("{name}: frame {i} mismatch vs ffmpeg -- stream pinned at {}", pin.display());
13831 }
13832 }
13833 }
13834
13835 #[test]
13836 fn a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
13837 inter_sb_none_gate(
13838 "a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
13839 false,
13840 "32",
13841 "64",
13842 decode::inter_sb_none_hits,
13843 "whole-superblock inter PARTITION_NONE",
13844 &[],
13845 64,
13846 4,
13847 );
13848 }
13849
13850 #[test]
13851 fn a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
13852 inter_sb_none_gate(
13853 "a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
13854 true,
13855 "32",
13856 "64",
13857 decode::inter_sb_none_hits,
13858 "whole-superblock inter PARTITION_NONE",
13859 &[],
13860 64,
13861 4,
13862 );
13863 }
13864
13865 /// lane-inter8 r1: the same recipe with `--min-partition-size=8`, so
13866 /// aomenc's RD may split a 16x16 inter block into four 8x8 leaves. The
13867 /// interior (non-edge-straddling) `PARTITION_SPLIT` at the 16x16 level
13868 /// was refused by name until this round; the straddle path always ran the
13869 /// same loop, so only [`decode::inter_sub16_split_hits`] -- which counts
13870 /// interior splits only -- proves the newly-lifted alphabet value fired.
13871 // lane-inter8 r2: GREEN. The neighbour side bands are mi-granular, every
13872 // leaf stamps its own 2x2-mi span (including the compound-return path
13873 // that used to skip `record_mi` entirely) and the compound
13874 // group/index contexts read the LEAF's mi cell, not its 16x16's corner.
13875 /// lane-inter8 r3, from lane-sub8's verifier finding: the mi-granular
13876 /// inter neighbour bands added in r2 must reset per TILE (above) and per
13877 /// SB row (left) and guard availability tile-relative, so the same recipe
13878 /// runs again at 128x64 with two tile columns -- a leaf on the second
13879 /// tile's first column has no left neighbour and must not read the first
13880 /// tile's band.
13881 // Un-ignored 2026-09-04: the SB-level rect-partition refusal (lane-sbpart's arm at 128x64) that blocked this gate is gone and it passes. The tile-relative audit it was written for
13882 // was done by inspection instead: every reader of the mi bands guards on
13883 // `tile_row0_mi`/`tile_col0_mi` (no `> 0` guard exists in decode.rs),
13884 // `start_tile` resets the above mi bands over the tile's own mi column
13885 // span and `start_row` resets every left mi band.
13886 #[test]
13887 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact()
13888 {
13889 inter_sb_none_gate(
13890 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact",
13891 false,
13892 "8",
13893 "16",
13894 decode::inter_sub16_split_hits,
13895 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
13896 &["--tile-columns=1"],
13897 128,
13898 4,
13899 );
13900 }
13901
13902 /// lane-interp3 r1: the same 8x8-leaf recipe with DUAL FILTER, OBMC and
13903 /// warped motion on. `read_mb_interp_filter` runs for every inter block
13904 /// (libaom `decodemv.c` 1575), compound ones included; the compound 8x8
13905 /// leaf skipped it entirely, so a SWITCHABLE-filter stream lost a symbol
13906 /// per compound leaf and stamped the `[3, 3]` "no filter" sentinel, which
13907 /// made a neighbouring OBMC block's `neighbour_filter` PANIC (a crash on
13908 /// his data, not a named refusal). The three hard asserts prove the flags
13909 /// arrived: a compound 8x8 leaf that really read the filter, a block whose
13910 /// two dual-filter directions DIFFER (impossible with dual filter off),
13911 /// and an 8x8 OBMC blend.
13912 // lane-interp3 r2: the ENTROPY desync r1 measured is CLOSED -- the full
13913 // 16-frame stream now parses end to end and every `EC_MODE`/`EC_MODE_VAL`
13914 // element's msac RANGE matches the instrumented aomdec's line for line
13915 // (570/570 mode elements, 0 diff). Two twin-drift root causes, both in
13916 // `decode_inter_block8`'s compound arm: `read_compound_ref_frames` was
13917 // passed a hard-coded `LAST_FRAME` for every inter neighbour instead of
13918 // the real per-mi band, and the grid stamp cleared both per-slot
13919 // `is_global_mv_block` flags.
13920 // lane-interp3 r3: the luma reconstruction residue r2 left open is CLOSED
13921 // and this gate is GREEN. Third instance of the same twin-drift class:
13922 // libaom applies `allow_warp`'s GLOBAL branch to every
13923 // `is_global_mv_block` reference slot, compound included and independent
13924 // of `motion_mode` (`av1_init_warp_params` inside
13925 // `build_inter_predictors_8x8_and_bigger`'s per-`ref` loop) -- the 16x16+
13926 // compound arm has warped since lane-cwarp r1, the 8x8 leaf's compound arm
13927 // predicted BOTH taps translationally, so a GLOBAL_GLOBALMV 8x8 compound
13928 // leaf under a non-TRANSLATION model drifted a few luma levels, growing
13929 // away from the block origin. It was NOT OBMC: the `EC_OBMC` emitter this
13930 // round added to `decode.rs` diffs 325/325 lines against the instrumented
13931 // aomdec's own rung (position, span, neighbour mv/ref/bsize/filter) with
13932 // zero differences.
13933 #[test]
13934 fn a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact() {
13935 const NAME: &str =
13936 "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact";
13937 if !have_ffmpeg() || !have_aomenc() {
13938 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
13939 return;
13940 }
13941 let before_dual = decode::dual_filter_diff_hits();
13942 let before_obmc = decode::obmc_hits_8();
13943 let before_cwarp8 = decode::compound_warp_hits_8();
13944 inter_sb_none_gate(
13945 NAME,
13946 false,
13947 "8",
13948 "16",
13949 decode::compound8_filter_hits,
13950 "a compound 8x8 leaf reading its own switchable interp_filter",
13951 &[
13952 "--enable-dual-filter=1",
13953 "--enable-obmc=1",
13954 "--enable-warped-motion=1",
13955 "--enable-onesided-comp=1",
13956 ],
13957 64,
13958 // Recipe search hook (same shape as EC_OBMC8_ATTEMPTS): a compound
13959 // block needs several coded references, so the sequence is longer
13960 // than the other arms' 4 frames.
13961 std::env::var("EC_INTERP3_FRAMES")
13962 .ok()
13963 .and_then(|v| v.parse().ok())
13964 .unwrap_or(16),
13965 );
13966 assert!(
13967 decode::dual_filter_diff_hits() > before_dual,
13968 "{NAME}: no block read two DIFFERENT dual-filter directions -- \
13969 --enable-dual-filter=1 did not arrive or aomenc declined it"
13970 );
13971 assert!(
13972 decode::obmc_hits_8() > before_obmc,
13973 "{NAME}: no 8x8 OBMC blend fired -- --enable-obmc=1 did not arrive"
13974 );
13975 assert!(
13976 decode::compound_warp_hits_8() > before_cwarp8,
13977 "{NAME}: no 8x8 COMPOUND leaf was predicted through the per-ref GLOBAL \
13978 warp -- the r3 root-cause path never fired, so this stream no longer \
13979 proves it"
13980 );
13981 }
13982
13983 #[test]
13984 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
13985 inter_sb_none_gate(
13986 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
13987 false,
13988 "8",
13989 "16",
13990 decode::inter_sub16_split_hits,
13991 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
13992 &[],
13993 64,
13994 4,
13995 );
13996 }
13997
13998 #[test]
13999 // Un-ignored 2026-09-04: the desync behind the bogus 32x32 value=9 refusal (class refusal-from-own-desync) is gone and this 10-bit twin decodes pixel-exact.
14000 fn a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
14001 inter_sb_none_gate(
14002 "a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
14003 true,
14004 "8",
14005 "16",
14006 decode::inter_sub16_split_hits,
14007 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
14008 &[],
14009 64,
14010 4,
14011 );
14012 }
14013
14014 /// lane-eobc1 r1: an INTER sequence whose CHROMA coefficient blocks come
14015 /// off the class-1 (`TX_CLASS_HORIZ`/`VERT`) `eob_pt` row. Chroma codes
14016 /// no `tx_type` symbol of its own -- it inherits the colocated luma type
14017 /// (`av1_get_tx_type`, `blockd.h:1291`) -- so an 8x8 inter leaf whose
14018 /// luma picks `H_*`/`V_*` puts its 4x4 chroma on a CDF row this crate
14019 /// wired for only some sizes until this round (`eob_pt_class1: None` in
14020 /// 9 of 16 `TxbSet` arms, chroma 4x4/8x8 among them).
14021 ///
14022 /// The full tx set stays on (no `--reduced-tx-type-set=1`) and
14023 /// `--enable-flip-idtx=1` is asked for explicitly; the sinusoidal-stripe
14024 /// luma of the `tx_class1` key-frame gate is what actually resolves 1D
14025 /// types, and the temporally-moving chroma ramp keeps chroma out of
14026 /// `all_zero` so it has an `eob` to read at all. Attempts sweep cq and
14027 /// stripe period; a run counts only when
14028 /// [`decode::chroma_eob_class1_hits`] moved, and every shown frame is
14029 /// compared pixel-exact vs ffmpeg (a decode error is a FAILURE, never a
14030 /// SKIP -- class gate-skips-on-its-own-failure).
14031 fn chroma_class1_eob_gate(name: &str, ten_bit: bool) {
14032 if !have_ffmpeg() {
14033 eprintln!("SKIP {name}: no ffmpeg");
14034 return;
14035 }
14036 if !have_aomenc() {
14037 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
14038 return;
14039 }
14040 let (width, height, frame_count) = (64usize, 64usize, 4usize);
14041 let mut refusals = Vec::new();
14042 for attempt in 0..12u32 {
14043 let cq = 28 + (attempt % 4) * 10;
14044 let period = [4u32, 6, 8][(attempt as usize / 4) % 3];
14045 let y4m = Command::new("ffmpeg")
14046 .args([
14047 "-v",
14048 "error",
14049 "-f",
14050 "lavfi",
14051 "-i",
14052 &format!("testsrc2=size={width}x{height}:rate=25"),
14053 "-vf",
14054 &format!(
14055 "geq=lum='128+80*sin(2*PI*Y/{period})':cb='128+60*sin(2*PI*(X+8*T)/{period})':cr='128+60*sin(2*PI*(Y+8*T)/{period})',noise=alls=6:allf=t:all_seed=7"
14056 ),
14057 "-t",
14058 "0.16",
14059 "-pix_fmt",
14060 if ten_bit { "yuv420p10le" } else { "yuv420p" },
14061 "-strict",
14062 "-1",
14063 "-f",
14064 "yuv4mpegpipe",
14065 "-",
14066 ])
14067 .stdin(Stdio::null())
14068 .stdout(Stdio::piped())
14069 .stderr(Stdio::piped())
14070 .output()
14071 .expect("ffmpeg failed to run");
14072 assert!(
14073 y4m.status.success(),
14074 "{name}: ffmpeg fixture: {}",
14075 String::from_utf8_lossy(&y4m.stderr)
14076 );
14077 let mut args: Vec<String> = [
14078 "--codec=av1",
14079 "--passes=1",
14080 "--end-usage=q",
14081 "--cpu-used=0",
14082 "--lag-in-frames=0",
14083 "--auto-alt-ref=0",
14084 "--kf-max-dist=1000",
14085 "--error-resilient=1",
14086 "--enable-flip-idtx=1",
14087 "--reduced-tx-type-set=0",
14088 "--min-partition-size=8",
14089 "--max-partition-size=16",
14090 // Motion tools this decoder refuses by name, kept off so a
14091 // refusal here can only be about the coefficient path.
14092 "--enable-global-motion=0",
14093 "--enable-warped-motion=0",
14094 "--enable-obmc=0",
14095 "--enable-rect-partitions=0",
14096 "--enable-ab-partitions=0",
14097 "--enable-1to4-partitions=0",
14098 "--enable-filter-intra=0",
14099 "--enable-smooth-intra=0",
14100 "--enable-paeth-intra=0",
14101 "--enable-directional-intra=0",
14102 "--enable-angle-delta=0",
14103 "--enable-tx-size-search=0",
14104 "--enable-cdef=0",
14105 "--enable-restoration=0",
14106 "--loopfilter-control=0",
14107 "--enable-palette=0",
14108 "--enable-intrabc=0",
14109 "--enable-cfl-intra=0",
14110 "--enable-ref-frame-mvs=0",
14111 "--obu",
14112 "-o",
14113 "-",
14114 "-",
14115 ]
14116 .iter()
14117 .map(|s| (*s).to_string())
14118 .collect();
14119 args.insert(1, format!("--cq-level={cq}"));
14120 if ten_bit {
14121 args.insert(1, "--input-bit-depth=10".to_string());
14122 args.insert(1, "--bit-depth=10".to_string());
14123 }
14124 let out = run_with_stdin(Command::new(aomenc_path())
14125 .args(&args), &y4m.stdout);
14126 assert!(
14127 out.status.success(),
14128 "{name}: aomenc refused the fixture: {}",
14129 String::from_utf8_lossy(&out.stderr)
14130 );
14131 let stream = out.stdout;
14132 let before = decode::chroma_eob_class1_hits();
14133 let frames = match decode_stream(&stream) {
14134 Ok(frames) => frames,
14135 // A named refusal ("unsupported: ...") is another lane's arm
14136 // and moves this attempt on; anything else is a real decode
14137 // failure and fails the gate on the spot.
14138 Err(e) if e.to_string().contains("unsupported") => {
14139 refusals.push(format!("cq={cq} period={period}: {e}"));
14140 continue;
14141 }
14142 Err(e) => {
14143 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
14144 let _ = std::fs::write(&pin, &stream);
14145 panic!(
14146 "{name}: decode_stream failed on a real aomenc stream (cq={cq} period={period}): {e} (pinned at {})",
14147 pin.display()
14148 );
14149 }
14150 };
14151 if decode::chroma_eob_class1_hits() == before {
14152 refusals.push(format!(
14153 "cq={cq} period={period}: decoded, but no chroma block read a class-1 eob_pt row"
14154 ));
14155 continue;
14156 }
14157 let ffmpeg_frames = if ten_bit {
14158 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14159 } else {
14160 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14161 };
14162 assert_eq!(frames.len(), frame_count, "{name}: frame count");
14163 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14164 if got.y != want.y || got.u != want.u || got.v != want.v {
14165 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
14166 let _ = std::fs::write(&pin, &stream);
14167 panic!(
14168 "{name}: frame {i} mismatch vs ffmpeg (cq={cq} period={period}) -- stream pinned at {}",
14169 pin.display()
14170 );
14171 }
14172 }
14173 return;
14174 }
14175 panic!("{name}: no attempt fired a class-1 chroma eob: {refusals:?}");
14176 }
14177
14178 #[test]
14179 fn a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
14180 chroma_class1_eob_gate(
14181 "a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
14182 false,
14183 );
14184 }
14185
14186 #[test]
14187 fn a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
14188 chroma_class1_eob_gate(
14189 "a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
14190 true,
14191 );
14192 }
14193
14194 /// lane-inter4 r1: the SUPERBLOCK-level inter `PARTITION_HORZ`/
14195 /// `PARTITION_VERT` pair -- two 64x32 / 32x64 inter strips, the arm the
14196 /// inter tile path refused outright before this lane ("an inter SB-level
14197 /// partition type other than NONE or SPLIT"). `--min-partition-size=32`
14198 /// keeps every 32x32-level rect shape (already coded, and residual-capable
14199 /// only when skip) out of the picture so the counters can only be earned
14200 /// at the superblock level; the noiseless split-motion source (one half
14201 /// translating, the other static, flat inside each half) is what makes
14202 /// aomenc's RD pick a superblock HORZ/VERT whose strips are `skip` --
14203 /// the ONLY inter rect shape this decoder can complete, since rectangular
14204 /// inter residual coding is not ported (see `reject_residual`).
14205 ///
14206 /// Every decoded frame is compared to ffmpeg (Y, U and V); an attempt
14207 /// that refuses by name is counted, never turned into a SKIP; and an
14208 /// attempt that decoded without firing the arm is counted separately and
14209 /// still required to be pixel-exact (class gate-skips-on-its-own-failure).
14210 #[test]
14211 fn a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact() {
14212 const NAME: &str = "a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact";
14213 let _gate_lock = lock_gate_counters();
14214 if !have_ffmpeg() {
14215 eprintln!("SKIP {NAME}: no ffmpeg");
14216 return;
14217 }
14218 if !have_aomenc() {
14219 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14220 return;
14221 }
14222 let (width, height, frame_count) = (192usize, 128usize, 6usize);
14223 // lane-inter4 r1: 8-bit ONLY, and the reason is the lane's own open
14224 // residue, not a tolerance: across all 16 attempts x both depths, every
14225 // 10-bit attempt that reached a superblock-level rect strip found it
14226 // NON-skip, so it stops at "a non-skip rectangular (HORZ/VERT/HORZ_B)
14227 // strip needs rectangular residual coding". The 10-bit twin below is
14228 // `#[ignore]`d with that exact reason rather than deleted or weakened.
14229 // lane-r14 r2 re-measured the 8-bit-only note above: the residual
14230 // refusal it names is GONE (this round codes a 64-px transform axis as
14231 // its truncated low-32 corner), and a 10-bit sweep of this exact
14232 // recipe now reaches the arm -- 2 pixel-exact attempts, 2 64x32 and 2
14233 // 32x64 strips, 2 of them carrying a coded 64-axis residual.
14234 // lane-sbrect10 r1 closed the newly exposed 10-bit defect r14 r2
14235 // parked this arm on (10-bit attempt 14, cq 61, horizontal split,
14236 // motion step 12 -- it mismatched ffmpeg while decoding ZERO rect
14237 // strips): a 64x64 INTRA block inside an inter frame read `uv_mode`
14238 // off the 14-symbol CFL-allowed alphabet, which libaom's
14239 // `is_cfl_allowed` caps at 32x32 -- same DC_PRED value, wrong
14240 // interval narrowing, tile desynced from that block on. Both depths
14241 // run now.
14242 for bit_depth in [8u32, 10u32] {
14243 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
14244 (0u32, 0u32, 0u32, 0u32);
14245 let (mut horz_proved, mut vert_proved) = (0usize, 0usize);
14246 let mut rect64_tus = 0usize;
14247 for attempt in 0..16u32 {
14248 // Two orientations (the transposed pair a one-sided gate could
14249 // never separate) x four quantisers x two motion steps: which
14250 // superblock the RD hands a skip-able rect strip moves with
14251 // the quantiser, and the 10-bit arm needs a different corner
14252 // of the grid from the 8-bit one.
14253 let vertical_split = attempt % 2 == 1;
14254 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
14255 let sp = 8 + (attempt / 8) * 4;
14256 let geq = if vertical_split {
14257 format!("if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), 200)")
14258 } else {
14259 format!("if(lt(X,64), 40+mod(floor((Y+N*{sp})/32)*90,200), 200)")
14260 };
14261 let duration = frame_count as f64 / 25.0;
14262 let source = format!(
14263 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
14264 geq=lum='{geq}',format=yuv420p"
14265 );
14266 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
14267 let y4m = Command::new("ffmpeg")
14268 .args([
14269 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
14270 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
14271 ])
14272 .stdin(Stdio::null())
14273 .stdout(Stdio::piped())
14274 .stderr(Stdio::piped())
14275 .output()
14276 .expect("ffmpeg failed to run");
14277 assert!(
14278 y4m.status.success(),
14279 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
14280 String::from_utf8_lossy(&y4m.stderr)
14281 );
14282 let cq_arg = format!("--cq-level={cq}");
14283 let depth_arg = format!("--bit-depth={bit_depth}");
14284 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
14285 let args: Vec<&str> = vec![
14286 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
14287 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
14288 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
14289 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
14290 "--enable-tx-size-search=0", "--lag-in-frames=0",
14291 // Per-arm overrides go LAST: aomenc keeps the last
14292 // occurrence of a repeated --enable-* flag.
14293 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
14294 "--enable-1to4-partitions=1", "--min-partition-size=32",
14295 "--max-partition-size=64",
14296 "--obu", "-o", "-", "-",
14297 ];
14298 let out = run_with_stdin(Command::new(aomenc_path())
14299 .args(&args), &y4m.stdout);
14300 assert!(
14301 out.status.success(),
14302 "aomenc refused the fixture: {}",
14303 String::from_utf8_lossy(&out.stderr)
14304 );
14305 let stream = out.stdout;
14306 let before = crate::stream::inter_rect_counters();
14307 let rect64_before = crate::stream::rect64_inter_tu_hits();
14308 let frames = match decode_stream(&stream) {
14309 Err(e) => {
14310 let msg = e.to_string();
14311 assert!(
14312 msg.contains("unsupported"),
14313 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
14314 attempt {attempt}): {msg}"
14315 );
14316 named_refusals += 1;
14317 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
14318 continue;
14319 }
14320 Ok(frames) => frames,
14321 };
14322 let after = crate::stream::inter_rect_counters();
14323 let (horz, vert) = (after.2 - before.2, after.3 - before.3);
14324 let rect64 = crate::stream::rect64_inter_tu_hits() - rect64_before;
14325 let ffmpeg_frames = if bit_depth == 10 {
14326 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14327 } else {
14328 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14329 };
14330 assert_eq!(frames.len(), frame_count);
14331 let mismatched = frames
14332 .iter()
14333 .zip(&ffmpeg_frames)
14334 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
14335 if horz + vert == 0 {
14336 out_of_scope += 1;
14337 if mismatched {
14338 oos_mismatch += 1;
14339 eprintln!(
14340 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
14341 superblock-level inter rect strips -- another shape's defect"
14342 );
14343 }
14344 continue;
14345 }
14346 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14347 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
14348 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
14349 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
14350 }
14351 horz_proved += horz;
14352 vert_proved += vert;
14353 rect64_tus += rect64;
14354 matched += 1;
14355 }
14356 eprintln!(
14357 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
14358 attempts carrying the arm, 64x32 strips={horz_proved}, 32x64 strips={vert_proved}, \
14359 64-axis residual TUs={rect64_tus}, \
14360 {out_of_scope} attempts carried none ({oos_mismatch} of them mismatched)"
14361 );
14362 assert_eq!(
14363 oos_mismatch, 0,
14364 "{NAME}: {oos_mismatch} attempt(s) with no superblock-level inter rect strip \
14365 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
14366 );
14367 // lane-r14 r2: the residual half of the arm -- a strip that is not
14368 // `skip` and codes a real 64-axis transform unit. Without this the
14369 // gate proves only the partition symbol.
14370 assert!(
14371 rect64_tus > 0,
14372 "{NAME} ({bit_depth}-bit): no superblock-level rect strip carried a coded \
14373 64-axis residual transform unit inside a pixel-exact attempt \
14374 (horz={horz_proved}, vert={vert_proved}) -- the residual arm proved nothing"
14375 );
14376 assert!(
14377 horz_proved + vert_proved > 0,
14378 "{NAME} ({bit_depth}-bit): the superblock-level inter rect arm never fired \
14379 inside a pixel-exact attempt (horz={horz_proved}, vert={vert_proved}, \
14380 {named_refusals} refusals, {out_of_scope} out of scope) -- gate proved nothing"
14381 );
14382 }
14383 }
14384
14385 /// lane-r14 r3: a 1:4 inter strip with a 64-px axis (64x16 / 16x64) whose
14386 /// transform SPLITS -- the arm r2 left refused by name ("a split transform
14387 /// on a 1:4 inter strip with a 64-px axis"). libaom's
14388 /// `sub_tx_size_map[TX_64X16] == TX_32X16` (and `[TX_16X64] == TX_16X32`)
14389 /// keeps the sub-transform RECTANGULAR, so the var-tx tree's leaves are
14390 /// 32x16/16x32 units read through [`TxbSet::LumaRect32x16Inter`], each with
14391 /// its own `get_txb_ctx_general` neighbour context (the unit is smaller
14392 /// than its block, so `txb_skip_ctx` is NOT the lone-TU 0).
14393 ///
14394 /// `--enable-1to4-partitions=1 --min-partition-size=16
14395 /// --max-partition-size=64 --enable-tx64=1` (each spelled once, last
14396 /// occurrence wins) is what lets aomenc pick a superblock-level HORZ_4 /
14397 /// VERT_4; the textured translating source is what keeps the strips
14398 /// non-skip so the residual is actually coded. 8-bit AND 10-bit, every
14399 /// decoded frame compared to ffmpeg on Y/U/V, refusals counted (never
14400 /// SKIPped), attempts that carried no rectangular var-tx leaf counted
14401 /// separately and still required pixel-exact.
14402 #[test]
14403 fn real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal() {
14404 const NAME: &str =
14405 "real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal";
14406 let _gate_lock = lock_gate_counters();
14407 if !have_ffmpeg() {
14408 eprintln!("SKIP {NAME}: no ffmpeg");
14409 return;
14410 }
14411 if !have_aomenc() {
14412 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14413 return;
14414 }
14415 let frame_count = 6usize;
14416 for bit_depth in [8u32, 10u32] {
14417 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
14418 (0u32, 0u32, 0u32, 0u32);
14419 let (mut leaf_32x16, mut leaf_16x32) = (0usize, 0usize);
14420 // Leaves decoded on ANY attempt, including one whose stream hits a
14421 // later named refusal: the firing half of this gate, kept apart
14422 // from `leaf_32x16`/`leaf_16x32` (pixel-compared attempts only) so
14423 // a refused stream is never counted as a pixel proof
14424 // (class counter-from-refused-stream).
14425 let (mut fired_32x16, mut fired_16x32) = (0usize, 0usize);
14426 // lane-gaterecipe r1: the firing arms (16-17) are 8-BIT ONLY, and
14427 // this is measured, not a convenience. Their 10-bit twin fires the
14428 // leaves too (32x16=0 16x32=46 on attempt 16) and then MISMATCHES
14429 // ffmpeg at decode-order frame 2 of attempt 17 -- an open DECODE
14430 // defect handed off in lanes/gaterecipe-r1.report.md, never
14431 // silenced inside this loop.
14432 let attempts = if bit_depth == 8 { 18u32 } else { 16u32 };
14433 for attempt in 0..attempts {
14434 // Two orientations (the transposed pair a one-sided gate could
14435 // never separate) x four quantisers x two motion steps.
14436 // lane-r14 r4 recipe hunt (~70 aomenc runs on the merged
14437 // tree: testsrc2 / life / mandelbrot / banded motion, 64x64 up
14438 // to 384x256, cq 20..58): attempts 16-17 carry the only recipe
14439 // found that makes aomenc code a 64-axis 1:4 strip whose
14440 // transform SPLITS -- 384x256, per-16-column band motion,
14441 // cq 32 (16x32 leaves) and cq 38 (32x16 leaves).
14442 let firing = attempt >= 16;
14443 let (width, height) =
14444 if firing { (384usize, 256usize) } else { (192usize, 128usize) };
14445 let vertical = attempt % 2 == 1;
14446 // lane-vartxsplit r2, MEASURED against the oracle
14447 // (`EC_VARTX` histogram, ~40 aomenc runs): at cq 10 this
14448 // source splits NO rectangular transform at all -- aomdec
14449 // reads only TX_8X8/TX_16X16/TX_8X16/TX_16X8 split symbols,
14450 // so the leaves gaterecipe r1 counted here came out of a
14451 // stream our decoder was already desynced on (class
14452 // counter-from-refused-stream). cq 44 and 46 are the two
14453 // quantisers of that sweep whose stream really carries
14454 // `TX_32X8`/`TX_8X32` splits (16x8 and 8x16 rectangular
14455 // var-tx leaves) AND decodes pixel-exact on all six frames.
14456 let cq = if firing {
14457 if attempt == 16 { 44 } else { 46 }
14458 } else {
14459 [30, 36, 44, 52][(attempt / 2 % 4) as usize]
14460 };
14461 let sp = 3 + (attempt / 8) * 3;
14462 // 16-pixel bands, each band translating at its OWN speed
14463 // across the other axis: that is what makes aomenc's RD split
14464 // a 64x64 superblock into four 1:4 strips (`PARTITION_HORZ_4`
14465 // / `VERT_4`) with distinct motion vectors, and the texture
14466 // inside a band is what keeps the strip non-skip and its
14467 // transform split.
14468 let geq = if firing && !vertical {
14469 // lane-gaterecipe r1, MEASURED: the banded translating
14470 // source this arm used until now splits NO transform at
14471 // all -- an aomdec EC_TRACE/EC_TRACE_COEFF histogram of its
14472 // stream reads zero 1:4 partitions and zero rectangular
14473 // sub-transforms, so the leaves the old assert counted came
14474 // out of a stream that stopped at a refusal (class
14475 // counter-from-refused-stream). What DOES split a
14476 // rectangular transform is a high-frequency product texture
14477 // at a fine quantiser with `--min-partition-size=8`: part
14478 // of the block predicts well and part does not, which is
14479 // the RD case for `txfm_partition`.
14480 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
14481 } else if firing {
14482 // lane-vartxsplit r2: BOTH leaf orientations come out of
14483 // this one source (three 16x8 leaves and one 8x16 on
14484 // attempt 16), so the firing pair is the same texture at
14485 // two quantisers. Its transposed twin was measured over
14486 // cq 40..56 and splits no rectangular transform at all;
14487 // at cq 56 it also mismatches ffmpeg from decode-order
14488 // frame 2 with ZERO rect var-tx leaves in it -- an open
14489 // reconstruction defect (8-pixel-wide luma column, see
14490 // lanes/vartxsplit-r2.report.md), not something to hide
14491 // inside this gate's attempt list.
14492 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
14493 } else if vertical {
14494 format!(
14495 "128+60*sin((Y+N*({sp}+9*mod(floor(X/16),2)))/7)+25*sin(X/11)"
14496 )
14497 } else {
14498 format!(
14499 "128+60*sin((X+N*({sp}+9*mod(floor(Y/16),2)))/7)+25*sin(Y/11)"
14500 )
14501 };
14502 let duration = frame_count as f64 / 25.0;
14503 let source = format!(
14504 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
14505 geq=lum='{geq}',format=yuv420p"
14506 );
14507 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
14508 let y4m = Command::new("ffmpeg")
14509 .args([
14510 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
14511 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
14512 ])
14513 .stdin(Stdio::null())
14514 .stdout(Stdio::piped())
14515 .stderr(Stdio::piped())
14516 .output()
14517 .expect("ffmpeg failed to run");
14518 assert!(
14519 y4m.status.success(),
14520 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
14521 String::from_utf8_lossy(&y4m.stderr)
14522 );
14523 let cq_arg = format!("--cq-level={cq}");
14524 let depth_arg = format!("--bit-depth={bit_depth}");
14525 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
14526 // A rectangular var-tx LEAF needs a block whose max rectangular
14527 // transform can split: `--min-partition-size=8` is what lets
14528 // aomenc's RD reach one (measured); at 16 it never did.
14529 let min_part =
14530 if firing { "--min-partition-size=8" } else { "--min-partition-size=16" };
14531 let args: Vec<&str> = vec![
14532 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
14533 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
14534 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
14535 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
14536 "--lag-in-frames=0",
14537 // Per-arm overrides go LAST: aomenc keeps the last
14538 // occurrence of a repeated --enable-* flag.
14539 "--enable-tx64=1", "--enable-rect-partitions=1",
14540 "--enable-ab-partitions=0", "--enable-1to4-partitions=1",
14541 "--enable-dual-filter=0", "--enable-obmc=0",
14542 "--enable-tx-size-search=1",
14543 min_part, "--max-partition-size=64",
14544 "--obu", "-o", "-", "-",
14545 ];
14546 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
14547 assert!(
14548 out.status.success(),
14549 "aomenc refused the fixture: {}",
14550 String::from_utf8_lossy(&out.stderr)
14551 );
14552 let stream = out.stdout;
14553 let before = crate::stream::vartx_rect_leaf_hits();
14554 let frames = match decode_stream(&stream) {
14555 Err(e) => {
14556 let msg = e.to_string();
14557 assert!(
14558 msg.contains("unsupported"),
14559 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
14560 attempt {attempt}): {msg}"
14561 );
14562 let after = crate::stream::vartx_rect_leaf_hits();
14563 fired_32x16 += after[0] - before[0];
14564 fired_16x32 += after[1] - before[1];
14565 named_refusals += 1;
14566 eprintln!(
14567 "{bit_depth}-bit attempt {attempt} refusal (rect var-tx leaves \
14568 decoded before it: 32x16={}, 16x32={}): {msg}",
14569 after[0] - before[0],
14570 after[1] - before[1]
14571 );
14572 continue;
14573 }
14574 Ok(frames) => frames,
14575 };
14576 let after = crate::stream::vartx_rect_leaf_hits();
14577 let (h32, v32) = (after[0] - before[0], after[1] - before[1]);
14578 fired_32x16 += h32;
14579 fired_16x32 += v32;
14580 let ffmpeg_frames = if bit_depth == 10 {
14581 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14582 } else {
14583 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14584 };
14585 assert_eq!(frames.len(), frame_count);
14586 let mismatched = frames
14587 .iter()
14588 .zip(&ffmpeg_frames)
14589 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
14590 if h32 + v32 == 0 {
14591 // Counted per ATTEMPT, on a decoded+compared attempt only
14592 // (class counter-from-refused-stream).
14593 out_of_scope += 1;
14594 if mismatched {
14595 oos_mismatch += 1;
14596 eprintln!(
14597 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
14598 rectangular var-tx leaves -- another shape's defect"
14599 );
14600 }
14601 continue;
14602 }
14603 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14604 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
14605 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
14606 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
14607 }
14608 leaf_32x16 += h32;
14609 leaf_16x32 += v32;
14610 compared += 1;
14611 }
14612 eprintln!(
14613 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
14614 pixel-exact attempts carrying the arm, pixel-compared rect var-tx leaves \
14615 32x16={leaf_32x16} 16x32={leaf_16x32}, leaves decoded anywhere in the sweep \
14616 32x16={fired_32x16} 16x32={fired_16x32}, {out_of_scope} attempts carried none \
14617 ({oos_mismatch} of them mismatched)"
14618 );
14619 assert_eq!(
14620 oos_mismatch, 0,
14621 "{NAME}: {oos_mismatch} attempt(s) with no rectangular var-tx leaf decoded \
14622 but mismatched ffmpeg -- a defect of another shape, not a pass"
14623 );
14624 assert!(
14625 compared + out_of_scope > 0,
14626 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
14627 );
14628 // The firing half. lane-vartxsplit r2 re-measured it against
14629 // the oracle: attempts 16/17 (384x256 product texture, cq 44/46,
14630 // `--min-partition-size=8 --enable-tx-size-search=1`) are the only
14631 // recipes of a ~40-run sweep whose stream carries `TX_32X8` /
14632 // `TX_8X32` split symbols, i.e. RECTANGULAR var-tx leaves (16x8
14633 // and 8x16, both orientations out of the same stream). They now
14634 // decode PIXEL-EXACT on all six frames, so the assert is on the
14635 // pixel-compared tally, not on the "decoded anywhere" one --
14636 // `fired_*` stays only to separate a refused stream's leaves from
14637 // a proved one (class counter-from-refused-stream). At 10 bits
14638 // the same sweep either fires nothing or mismatches on a
14639 // reconstruction defect of another shape (report), so the firing
14640 // assert stays 8-bit -- and it is a hard assert, never a print.
14641 if bit_depth == 8 {
14642 assert!(
14643 leaf_32x16 > 0 && leaf_16x32 > 0,
14644 "{NAME}: the rectangular var-tx leaf arm never fired on a pixel-exact \
14645 attempt (pixel-compared 32x16={leaf_32x16}, 16x32={leaf_16x32}, decoded \
14646 anywhere 32x16={fired_32x16} 16x32={fired_16x32}, {named_refusals} \
14647 refusals, {compared} compared) -- the rectangular sub-transform path is \
14648 unproved by this gate"
14649 );
14650 }
14651 }
14652 }
14653
14654 /// lane-rectres r1: a 32x32-level 1:4 INTER strip (32x8 / 8x32) that codes
14655 /// a REAL rectangular residual. THIS is the shape both 10-bit 3840x1608
14656 /// film cuts and every measured 1080p offset stopped on -- six of six
14657 /// `decode_probe` runs refused at "a non-skip rectangular (HORZ/VERT/
14658 /// HORZ_B) strip needs rectangular residual coding" with `w=32 h=8` or
14659 /// `w=8 h=32`, nothing else.
14660 ///
14661 /// `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256 of its
14662 /// positions ([`TxbSet::LumaRect32x8Inter`]: `get_txsize_entropy_ctx` =
14663 /// TX_16X16 so the coefficient tables are the luma-16 ones,
14664 /// `txsize_log2_minus4` = 4 so `eob_pt` is the 256-position alphabet), and
14665 /// unlike the INTRA twin it DOES code a `tx_type`:
14666 /// `av1_get_ext_tx_set_type` at `tx_size_sqr_up == TX_32X32` is
14667 /// `EXT_TX_SET_DCT_IDTX` for inter with or without `reduced_tx_set`, read
14668 /// at the `txsize_sqr_map[TX_32X8] == TX_8X8` CDF row (class
14669 /// table-indexed-by-raw-size: the coefficient tables follow the ADJUSTED
14670 /// size, the `tx_type` row the SQUARE one -- they disagree here).
14671 /// Its chroma pair is one 16x4 / 4x16 unit (`ss_size_lookup[BLOCK_32X8]`
14672 /// = BLOCK_16X4, `Chroma8`'s tables, 64-position `eob_pt`), and a split
14673 /// transform gives 16x8 / 8x16 leaves (`sub_tx_size_map[TX_32X8] ==
14674 /// TX_16X8`) the rect var-tx path already reads.
14675 ///
14676 /// `--enable-1to4-partitions=1 --min-partition-size=8
14677 /// --max-partition-size=32 --enable-tx-size-search=1` (each spelled once,
14678 /// last occurrence wins -- aomenc keeps the LAST `--enable-*`) is what
14679 /// lets aomenc pick a 32x32-level HORZ_4 / VERT_4; the 8-pixel banded
14680 /// translating source is what makes those strips the RD winner and keeps
14681 /// them non-skip so the residual is really coded. Both orientations, 8-bit
14682 /// AND 10-bit, every decode-order frame compared to ffmpeg on Y/U/V,
14683 /// refusals counted (never SKIPped), attempts that carried no 32x8/8x32
14684 /// residual unit counted separately and still required pixel-exact.
14685 #[test]
14686 fn a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual() {
14687 const NAME: &str =
14688 "a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual";
14689 let _gate_lock = lock_gate_counters();
14690 if !have_ffmpeg() {
14691 eprintln!("SKIP {NAME}: no ffmpeg");
14692 return;
14693 }
14694 if !have_aomenc() {
14695 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14696 return;
14697 }
14698 let frame_count = 6usize;
14699 let (mut proved_32x8, mut proved_8x32) = (0usize, 0usize);
14700 let (mut fired_32x8, mut fired_8x32) = (0usize, 0usize);
14701 for bit_depth in [8u32, 10u32] {
14702 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
14703 (0u32, 0u32, 0u32, 0u32);
14704 for attempt in 0..16u32 {
14705 // Two orientations (the transposed pair a one-sided gate could
14706 // never separate) x four quantisers x two motion steps.
14707 let vertical = attempt % 2 == 1;
14708 let (width, height) = (192usize, 128usize);
14709 let cq = [48, 52, 56, 60][(attempt / 2 % 4) as usize];
14710 let sp = 3 + (attempt / 8) * 4;
14711 // 32-pixel bands, each translating at its OWN speed across the
14712 // other axis: that is what makes aomenc's RD split a 32x32
14713 // block into four 32x8 (or 8x32) strips with distinct motion
14714 // vectors, and the texture inside a band is what keeps a strip
14715 // non-skip. MEASURED (72-run recipe sweep, 192x128..256x192,
14716 // cq 24..60, bands 8/16/32/64): only 32-pixel bands at cq >= 48
14717 // make aomenc code a NON-SKIP one -- attempt 0 (cq 48,
14718 // horizontal source) codes an 8x32 residual unit, attempt 7
14719 // (cq 60, the transposed source) five 32x8 ones. Narrower
14720 // bands give the same strips with `skip` set, which proves the
14721 // partition symbol and nothing about the residual.
14722 let geq = if vertical {
14723 format!("128+62*sin((Y+N*({sp}+7*mod(floor(X/32),4)))/6)+28*sin(X/9)")
14724 } else {
14725 format!("128+62*sin((X+N*({sp}+7*mod(floor(Y/32),4)))/6)+28*sin(Y/9)")
14726 };
14727 let duration = frame_count as f64 / 25.0;
14728 let source = format!(
14729 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
14730 geq=lum='{geq}',format=yuv420p"
14731 );
14732 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
14733 let y4m = Command::new("ffmpeg")
14734 .args([
14735 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
14736 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
14737 ])
14738 .stdin(Stdio::null())
14739 .stdout(Stdio::piped())
14740 .stderr(Stdio::piped())
14741 .output()
14742 .expect("ffmpeg failed to run");
14743 assert!(
14744 y4m.status.success(),
14745 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
14746 String::from_utf8_lossy(&y4m.stderr)
14747 );
14748 let cq_arg = format!("--cq-level={cq}");
14749 let depth_arg = format!("--bit-depth={bit_depth}");
14750 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
14751 let args: Vec<&str> = vec![
14752 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
14753 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
14754 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
14755 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
14756 "--lag-in-frames=0",
14757 // Per-arm overrides go LAST: aomenc keeps the last
14758 // occurrence of a repeated --enable-* flag.
14759 "--enable-tx64=0", "--enable-rect-partitions=1",
14760 "--enable-ab-partitions=0", "--enable-1to4-partitions=1",
14761 "--enable-tx-size-search=1",
14762 "--enable-dual-filter=0", "--enable-obmc=0",
14763 // aomenc's min-partition-size bounds the SMALLER side of a
14764 // 1:4 strip, so 32x8 needs 8 (memory
14765 // aomenc-min-partition-bounds-smaller-side).
14766 "--min-partition-size=8", "--max-partition-size=32",
14767 "--obu", "-o", "-", "-",
14768 ];
14769 let out = run_with_stdin(Command::new(aomenc_path())
14770 .args(&args), &y4m.stdout);
14771 assert!(
14772 out.status.success(),
14773 "aomenc refused the fixture: {}",
14774 String::from_utf8_lossy(&out.stderr)
14775 );
14776 let stream = out.stdout;
14777 let before = crate::stream::rect32x8_inter_tu_hits();
14778 let frames = match decode_stream(&stream) {
14779 Err(e) => {
14780 let msg = e.to_string();
14781 assert!(
14782 msg.contains("unsupported"),
14783 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
14784 attempt {attempt}): {msg}"
14785 );
14786 let after = crate::stream::rect32x8_inter_tu_hits();
14787 // Firing counted on a refused stream is kept apart from
14788 // the pixel-proved tally (class
14789 // counter-from-refused-stream).
14790 fired_32x8 += after[0] - before[0];
14791 fired_8x32 += after[1] - before[1];
14792 named_refusals += 1;
14793 eprintln!(
14794 "{NAME} {bit_depth}-bit attempt {attempt} refusal (32x8 residual \
14795 units decoded before it: {}, 8x32: {}): {msg}",
14796 after[0] - before[0],
14797 after[1] - before[1]
14798 );
14799 continue;
14800 }
14801 Ok(frames) => frames,
14802 };
14803 let after = crate::stream::rect32x8_inter_tu_hits();
14804 let (h, v) = (after[0] - before[0], after[1] - before[1]);
14805 fired_32x8 += h;
14806 fired_8x32 += v;
14807 let ffmpeg_frames = if bit_depth == 10 {
14808 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14809 } else {
14810 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14811 };
14812 assert_eq!(frames.len(), frame_count);
14813 let mismatched = frames
14814 .iter()
14815 .zip(&ffmpeg_frames)
14816 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
14817 if h + v == 0 {
14818 out_of_scope += 1;
14819 if mismatched {
14820 oos_mismatch += 1;
14821 eprintln!(
14822 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
14823 32x8/8x32 inter residual units -- another shape's defect"
14824 );
14825 }
14826 continue;
14827 }
14828 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14829 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
14830 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
14831 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
14832 }
14833 proved_32x8 += h;
14834 proved_8x32 += v;
14835 compared += 1;
14836 }
14837 eprintln!(
14838 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
14839 pixel-exact attempts carrying the arm, {out_of_scope} attempts carried none \
14840 ({oos_mismatch} of them mismatched)"
14841 );
14842 assert_eq!(
14843 oos_mismatch, 0,
14844 "{NAME}: {oos_mismatch} attempt(s) with no 32x8/8x32 inter residual unit \
14845 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
14846 );
14847 assert!(
14848 compared + out_of_scope > 0,
14849 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
14850 );
14851 }
14852 eprintln!(
14853 "{NAME}: pixel-compared 32x32-level 1:4 inter residual units 32x8={proved_32x8} \
14854 8x32={proved_8x32} (decoded anywhere in the sweep 32x8={fired_32x8} \
14855 8x32={fired_8x32})"
14856 );
14857 // The firing half, one assert per lifted shape. Both orientations must
14858 // be PIXEL-PROVED: a transposed table passes one and fails the other
14859 // (class reference-layout-not-spec).
14860 assert!(
14861 proved_32x8 > 0,
14862 "{NAME}: no 32x8 inter residual transform unit was decoded inside a pixel-exact \
14863 attempt (decoded anywhere: {fired_32x8}) -- the lift is unproved"
14864 );
14865 assert!(
14866 proved_8x32 > 0,
14867 "{NAME}: no 8x32 inter residual transform unit was decoded inside a pixel-exact \
14868 attempt (decoded anywhere: {fired_8x32}) -- the lift is unproved"
14869 );
14870 }
14871
14872 /// lane-sbrect10 r1: a 64x64 INTRA block inside an INTER frame, whose
14873 /// `uv_mode` alphabet libaom's `is_cfl_allowed` (`blockd.h`: `wide <= 32
14874 /// && high <= 32`) narrows to the 13-symbol NO-CFL table. Reading the
14875 /// 14-symbol CFL one produced the same `DC_PRED` value with the wrong
14876 /// interval narrowing, so the tile desynced from that block on and the
14877 /// frame decoded silently wrong (class `wrong-alphabet-same-value`; found
14878 /// as the "another shape" mismatch the superblock rect gate above had to
14879 /// park its 10-bit arm on).
14880 ///
14881 /// The counter `nocfl_uv_mode_hits` proves the shape fired in EVERY
14882 /// compared attempt, and every decode-order frame is compared against
14883 /// ffmpeg -- an attempt that mismatches fails, it never SKIPs.
14884 ///
14885 /// lane-sbrect10 r2: with the half-random source below this gate also
14886 /// covers a SECOND defect it exposed at 10-bit cq 58/61 -- the compound
14887 /// MV stack's extension pass zero-filled the `comp_list` tail slots
14888 /// libaom fills with each side's GLOBAL MOTION vector
14889 /// (`combine_compound_candidates`, mvref_common.c:723-729). A compound
14890 /// block with no usable neighbour pair (frame top row, intra block to
14891 /// its left, empty temporal field) then took a `(0, 0)` predictor
14892 /// instead of the frame's translation: 32890/39907 wrong luma samples
14893 /// on decode-order frame 2 with the entropy stream still in sync.
14894 #[test]
14895 fn a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet() {
14896 const NAME: &str =
14897 "a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet";
14898 let _gate_lock = lock_gate_counters();
14899 if !have_ffmpeg() {
14900 eprintln!("SKIP {NAME}: no ffmpeg");
14901 return;
14902 }
14903 if !have_aomenc() {
14904 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14905 return;
14906 }
14907 let (width, height, frame_count) = (192usize, 128usize, 6usize);
14908 for bit_depth in [8u32, 10u32] {
14909 let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
14910 let mut total_hits = 0usize;
14911 for attempt in 0..16u32 {
14912 // The sibling superblock-rect gate's own grid (its 10-bit
14913 // attempt 14 -- cq 61, horizontal split, motion step 12 -- is
14914 // the stream that exposed the defect); which superblock the RD
14915 // hands an intra 64x64 block moves with the quantiser and the
14916 // depth, so both orientations x four quantisers x two motion
14917 // steps run here too.
14918 let vertical_split = attempt % 2 == 1;
14919 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
14920 let sp = 8 + (attempt / 8) * 4;
14921 // Half ramp, half deterministic pseudo-noise: the flat "200"
14922 // half of r1's source made aomenc code the right-hand
14923 // superblocks skip, so at 8 bit no >32 intra block ever
14924 // appeared (probed cq 45/52/58/61/63 = 0 hits). The textured
14925 // half forces intra above 32x32 in an inter frame at BOTH
14926 // depths, so both arms carry the shape.
14927 let geq = if vertical_split {
14928 format!(
14929 "if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
14930 )
14931 } else {
14932 format!(
14933 "if(lt(X,128), 40+mod(floor((Y+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
14934 )
14935 };
14936 let duration = frame_count as f64 / 25.0;
14937 let source = format!(
14938 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
14939 geq=lum='{geq}',format=yuv420p"
14940 );
14941 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
14942 let y4m = Command::new("ffmpeg")
14943 .args([
14944 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
14945 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
14946 ])
14947 .stdin(Stdio::null())
14948 .stdout(Stdio::piped())
14949 .stderr(Stdio::piped())
14950 .output()
14951 .expect("ffmpeg failed to run");
14952 assert!(
14953 y4m.status.success(),
14954 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
14955 String::from_utf8_lossy(&y4m.stderr)
14956 );
14957 let cq_arg = format!("--cq-level={cq}");
14958 let depth_arg = format!("--bit-depth={bit_depth}");
14959 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
14960 let args: Vec<&str> = vec![
14961 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
14962 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
14963 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
14964 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
14965 "--enable-tx-size-search=0", "--lag-in-frames=0",
14966 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
14967 "--enable-1to4-partitions=1", "--min-partition-size=32",
14968 "--max-partition-size=64",
14969 "--obu", "-o", "-", "-",
14970 ];
14971 let out = run_with_stdin(Command::new(aomenc_path())
14972 .args(&args), &y4m.stdout);
14973 assert!(
14974 out.status.success(),
14975 "aomenc refused the fixture: {}",
14976 String::from_utf8_lossy(&out.stderr)
14977 );
14978 let stream = out.stdout;
14979 let before = crate::decode::nocfl_uv_mode_hits();
14980 let frames = match decode_stream(&stream) {
14981 Err(e) => {
14982 let msg = e.to_string();
14983 assert!(
14984 msg.contains("unsupported"),
14985 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
14986 attempt {attempt}): {msg}"
14987 );
14988 named_refusals += 1;
14989 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
14990 continue;
14991 }
14992 Ok(frames) => frames,
14993 };
14994 let hits = crate::decode::nocfl_uv_mode_hits() - before;
14995 let ffmpeg_frames = if bit_depth == 10 {
14996 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14997 } else {
14998 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14999 };
15000 assert_eq!(frames.len(), frame_count);
15001 if hits == 0 {
15002 // No 64-axis intra block in this stream: still compared
15003 // (a mismatch here is a defect, never a pass), just not
15004 // proof of this gate's shape.
15005 carried_none += 1;
15006 }
15007 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15008 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
15009 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
15010 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
15011 }
15012 if hits > 0 {
15013 matched += 1;
15014 total_hits += hits;
15015 }
15016 }
15017 eprintln!(
15018 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
15019 attempts carrying a >32 intra block ({total_hits} no-CFL uv_mode reads), \
15020 {carried_none} attempts carried none"
15021 );
15022 assert!(
15023 matched > 0 && total_hits > 0,
15024 "{NAME} ({bit_depth}-bit): no attempt decoded an intra block above 32x32, so the \
15025 no-CFL uv_mode alphabet was never exercised -- gate proved nothing \
15026 ({named_refusals} refusals, {carried_none} attempts carried none)"
15027 );
15028 }
15029 }
15030 /// lane-sqdrift r2: the SQUARE-ONLY twin of the no-CFL `uv_mode` gate
15031 /// above. With `--enable-rect-partitions=0` the encoder codes only
15032 /// `PARTITION_NONE` and `PARTITION_SPLIT`, and on detailed content the RD
15033 /// eventually hands one whole 64x64 superblock of an INTER frame to an
15034 /// INTRA block -- `bsize == sb_size`, the one shape whose `uv_mode` must
15035 /// come off the 13-symbol `uv_mode_no_cfl` alphabet because libaom's
15036 /// `is_cfl_allowed` (`blockd.h`: `wide <= 32 && high <= 32`) excludes it.
15037 ///
15038 /// Before the fix this decoder read the 14-symbol CFL alphabet there: the
15039 /// same `DC_PRED` value, a different interval, and the tile desynced from
15040 /// that block on. r1 measured the damage on the pinned 192x128 stream
15041 /// (sha256 `c6af4fb4...`): decode-order frames 0-3 pre-filter byte-exact,
15042 /// frame 4 luma 3540 samples wrong over exactly the last superblock
15043 /// (x 128..191, y 64..127), then 24k wrong by frame 7 -- and the decoder
15044 /// did not even report a mismatch, it reported an intra-rect-strip refusal
15045 /// read out of the already-desynced stream (class `refusal-from-own-desync`;
15046 /// aomdec's own partition histogram over that stream is rect-free).
15047 /// After the fix the same stream is byte-exact on all 8 frames.
15048 ///
15049 /// Distinct from the sibling gate: rect partitions OFF (so the 64x64 NONE
15050 /// really is a whole superblock), `--min-partition-size=16`, natural
15051 /// mandelbrot detail instead of a synthetic half-noise ramp, and 8 frames
15052 /// of drift so a desync that survives one frame still fails here. Every
15053 /// decode-order frame of every attempt is compared against ffmpeg, so a
15054 /// mismatch of ANY shape fails; the gate never turns one into a SKIP.
15055 #[test]
15056 fn a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact()
15057 {
15058 const NAME: &str = "a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact";
15059 let _gate_lock = lock_gate_counters();
15060 if !have_ffmpeg() {
15061 eprintln!("SKIP {NAME}: no ffmpeg");
15062 return;
15063 }
15064 if !have_aomenc() {
15065 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15066 return;
15067 }
15068 let (width, height, frame_count) = (192usize, 128usize, 8usize);
15069 for bit_depth in [8u32, 10u32] {
15070 let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
15071 let mut total_hits = 0usize;
15072 for attempt in 0..4u32 {
15073 // r1's pinned recipe is (start_scale 4.76, cq 55); the other
15074 // three points move the detail level and the quantiser, which
15075 // is what moves WHICH superblock the RD codes intra.
15076 let start_scale = ["4.76", "3.20"][(attempt % 2) as usize];
15077 let cq = [55, 45][(attempt / 2) as usize];
15078 let duration = frame_count as f64 / 25.0;
15079 let source = format!(
15080 "mandelbrot=size={width}x{height}:start_scale={start_scale}:\
15081 end_scale=0.004:end_pts=8:rate=25"
15082 );
15083 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
15084 let y4m = Command::new("ffmpeg")
15085 .args([
15086 "-v", "error", "-f", "lavfi", "-i", &source, "-vf", "hue=s=0",
15087 "-t", &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
15088 "-f", "yuv4mpegpipe", "-strict", "-1", "-",
15089 ])
15090 .stdin(Stdio::null())
15091 .stdout(Stdio::piped())
15092 .stderr(Stdio::piped())
15093 .output()
15094 .expect("ffmpeg failed to run");
15095 assert!(
15096 y4m.status.success(),
15097 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
15098 String::from_utf8_lossy(&y4m.stderr)
15099 );
15100 let cq_arg = format!("--cq-level={cq}");
15101 let depth_arg = format!("--bit-depth={bit_depth}");
15102 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
15103 let args: Vec<&str> = vec![
15104 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=1",
15105 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
15106 "--lag-in-frames=0", "--auto-alt-ref=0",
15107 "--kf-min-dist=1000", "--kf-max-dist=1000",
15108 "--enable-rect-partitions=0", "--enable-ab-partitions=0",
15109 "--enable-1to4-partitions=0", "--min-partition-size=16",
15110 "--max-partition-size=64", "--enable-tx-size-search=0",
15111 "--enable-order-hint=0", "--enable-warped-motion=0", "--enable-obmc=0",
15112 "--enable-masked-comp=0", "--enable-interintra-comp=0",
15113 "--enable-dist-wtd-comp=0", "--enable-diff-wtd-comp=0",
15114 "--enable-onesided-comp=0", "--enable-interintra-wedge=0",
15115 "--enable-smooth-interintra=0", "--enable-filter-intra=0",
15116 "--enable-smooth-intra=0", "--enable-paeth-intra=0",
15117 "--enable-directional-intra=0", "--enable-angle-delta=0",
15118 "--enable-cdef=0", "--enable-restoration=0", "--enable-palette=0",
15119 "--enable-intrabc=0", "--enable-cfl-intra=0", "--enable-ref-frame-mvs=0",
15120 "--obu", "-o", "-", "-",
15121 ];
15122 let out = run_with_stdin(Command::new(aomenc_path())
15123 .args(&args), &y4m.stdout);
15124 assert!(
15125 out.status.success(),
15126 "aomenc refused the fixture: {}",
15127 String::from_utf8_lossy(&out.stderr)
15128 );
15129 let stream = out.stdout;
15130 let before = crate::decode::nocfl_uv_mode_hits();
15131 let frames = match decode_stream(&stream) {
15132 Err(e) => {
15133 let msg = e.to_string();
15134 assert!(
15135 msg.contains("unsupported"),
15136 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
15137 attempt {attempt}): {msg}"
15138 );
15139 named_refusals += 1;
15140 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
15141 continue;
15142 }
15143 Ok(frames) => frames,
15144 };
15145 let hits = crate::decode::nocfl_uv_mode_hits() - before;
15146 let ffmpeg_frames = if bit_depth == 10 {
15147 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
15148 } else {
15149 ffmpeg_decode_sequence(&stream, width, height, frame_count)
15150 };
15151 assert_eq!(frames.len(), frame_count);
15152 if hits == 0 {
15153 carried_none += 1;
15154 }
15155 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15156 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
15157 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
15158 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})");
15159 }
15160 if hits > 0 {
15161 matched += 1;
15162 total_hits += hits;
15163 }
15164 }
15165 eprintln!(
15166 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
15167 attempts carrying a 64x64 intra superblock ({total_hits} no-CFL uv_mode reads), \
15168 {carried_none} attempts carried none"
15169 );
15170 assert!(
15171 matched > 0 && total_hits > 0,
15172 "{NAME} ({bit_depth}-bit): no square-only attempt decoded a 64x64 intra block \
15173 inside an inter frame, so the no-CFL uv_mode alphabet was never exercised -- \
15174 gate proved nothing ({named_refusals} refusals, {carried_none} carried none)"
15175 );
15176 }
15177 }
15178
15179 /// lane-mc64 r2: the RECT-ON twin of the square-only gate above, pinned
15180 /// as a stream fixture because its aomenc recipe is not reproducible
15181 /// (the r2 recipe re-encoded to a different file, measured md5
15182 /// `278be00...` vs the fixture's `add55f6...`; class
15183 /// `seeded-fixture-not-reproducible`).
15184 ///
15185 /// `crates/ec-av1/fixtures/av1_192x128_8bit_intra64_in_inter.obu`
15186 /// (sha256 `e4cff46cb1700527c68efc866db27a2835705e949d646f73f0c9df577d594bd6`)
15187 /// carries a 64x64 `PARTITION_NONE` INTRA block inside an INTER frame at
15188 /// decode-order frame 2, mi(16,32), in a stream whose OTHER superblocks
15189 /// are rect-partitioned -- so the 64-axis `is_cfl_allowed` narrowing
15190 /// (`blockd.h`: `wide <= 32 && high <= 32`) has to hold on the intra
15191 /// arm that the rect recipe reaches, not only on the whole-superblock
15192 /// one. Before lane-sbrect10's fix this frame reconstructed with 3720
15193 /// wrong luma samples (delta -12..+9, chroma bit-exact) and the decode
15194 /// then died at frame 3 on a phantom refusal of its own desync (class
15195 /// `refusal-from-own-desync`); all 6 decode-order frames are byte-exact
15196 /// against the oracle now.
15197 #[test]
15198 fn a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact() {
15199 const NAME: &str =
15200 "a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact";
15201 let _gate_lock = lock_gate_counters();
15202 if !have_aomenc() {
15203 eprintln!("SKIP {NAME}: no aomenc/aomdec oracle at {}", aomenc_path().display());
15204 return;
15205 }
15206 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
15207 .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu");
15208 let stream = std::fs::read(&path)
15209 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
15210 let before = crate::decode::nocfl_uv_mode_hits();
15211 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
15212 let hits = crate::decode::nocfl_uv_mode_hits() - before;
15213 assert_eq!(frames, 6, "{NAME}: expected 6 decode-order frames ({hidden} hidden)");
15214 assert!(
15215 hits > 0,
15216 "{NAME}: no 64-axis intra block read the no-CFL uv_mode alphabet -- the fixture no \
15217 longer carries the shape this test gates"
15218 );
15219 }
15220
15221 /// lane-inter4 r2: the 32x32-level inter `PARTITION_HORZ`/`PARTITION_VERT`
15222 /// strips (32x16 / 16x32) carrying a REAL residual -- the capability r1
15223 /// found missing ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs
15224 /// rectangular residual coding"). The strip's own rectangular max
15225 /// transform (`TX_32X16`/`TX_16X32`) is read through the rect var-tx tree,
15226 /// its coefficients through [`TxbSet::LumaRect32x16Inter`] /
15227 /// `ChromaRect16x8`, and inverted with the rect (sqrt2-scaled) inverse
15228 /// transform.
15229 ///
15230 /// `--min-partition-size=16 --max-partition-size=32` keeps the superblock
15231 /// level (64x32, still refused -- no 64-point rect transform) out, so
15232 /// every counted hit is a 32-level strip. The source is textured and
15233 /// translating precisely so the strips are NOT skip: a flat source (r1's)
15234 /// makes aomenc code them skip and proves nothing about the residual.
15235 /// Both `--enable-tx-size-search` arms run: `=0` exercises the
15236 /// whole-block rect transform with no `txfm_partition` symbol at all,
15237 /// `=1` the rect var-tx tree (no-split rect unit, or the split into square
15238 /// sub-transforms).
15239 ///
15240 /// 8-bit AND 10-bit. Every decoded frame is compared to ffmpeg on Y, U and
15241 /// V; a refusal is counted, never SKIPped; an attempt that carried no rect
15242 /// inter residual is counted separately and still required pixel-exact.
15243 /// Temporal (MFMV) motion-vector candidates, on a real aomenc stream
15244 /// whose compound blocks feed the next frame's motion field
15245 /// (`av1_copy_frame_mvs` -> `av1_setup_motion_field` -> `add_tpl_ref_mv`).
15246 ///
15247 /// lane-interbis r1 pinned this recipe because it is the one the rect
15248 /// gate's attempt 1 decoded FULLY and still mismatched ffmpeg (a
15249 /// 32x32 NEARESTMV block at mi (24, 40) of decode-order frame 5 took its
15250 /// nearest candidate from a temporal cell holding the wrong reference:
15251 /// `build_motion_field` stored a compound block's FIRST reference where
15252 /// libaom stores its second). Every fully decoded attempt is compared
15253 /// plane by plane; a refusal is counted, never SKIPped; the temporal
15254 /// candidate counter must fire on a compared attempt, or the gate proves
15255 /// nothing.
15256 #[test]
15257 fn a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact() {
15258 const NAME: &str =
15259 "a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact";
15260 let _gate_lock = lock_gate_counters();
15261 if !have_ffmpeg() {
15262 eprintln!("SKIP {NAME}: no ffmpeg");
15263 return;
15264 }
15265 if !have_aomenc() {
15266 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15267 return;
15268 }
15269 let (width, height, frame_count) = (192usize, 128usize, 6usize);
15270 for bit_depth in [8u32, 10u32] {
15271 let (mut named_refusals, mut compared, mut tmv_proved) = (0u32, 0u32, 0usize);
15272 for attempt in 0..2u32 {
15273 let tx_search = if attempt == 0 { "0" } else { "1" };
15274 let duration = frame_count as f64 / 25.0;
15275 // The pinned source: horizontal structure translating along X
15276 // at 3 px/frame, which makes aomenc code compound LAST+GOLDEN
15277 // blocks whose stored motion field the last frame reads back.
15278 let source = format!(
15279 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
15280 geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)',format=yuv420p"
15281 );
15282 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
15283 let y4m = Command::new("ffmpeg")
15284 .args([
15285 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
15286 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
15287 ])
15288 .stdin(Stdio::null())
15289 .stdout(Stdio::piped())
15290 .stderr(Stdio::piped())
15291 .output()
15292 .expect("ffmpeg failed to run");
15293 assert!(
15294 y4m.status.success(),
15295 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
15296 String::from_utf8_lossy(&y4m.stderr)
15297 );
15298 let depth_arg = format!("--bit-depth={bit_depth}");
15299 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
15300 let tx_arg = format!("--enable-tx-size-search={tx_search}");
15301 let args: Vec<&str> = vec![
15302 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=34", "--cpu-used=0",
15303 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
15304 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
15305 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
15306 "--lag-in-frames=0",
15307 // Per-arm overrides go LAST (aomenc keeps the last
15308 // occurrence of a repeated --enable-* flag).
15309 &tx_arg,
15310 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
15311 "--enable-1to4-partitions=0", "--min-partition-size=16",
15312 "--max-partition-size=32",
15313 "--obu", "-o", "-", "-",
15314 ];
15315 let out = run_with_stdin(Command::new(aomenc_path())
15316 .args(&args), &y4m.stdout);
15317 assert!(
15318 out.status.success(),
15319 "aomenc refused the fixture: {}",
15320 String::from_utf8_lossy(&out.stderr)
15321 );
15322 let stream = out.stdout;
15323 let before = decode::tmv_hits();
15324 let frames = match decode_stream(&stream) {
15325 Err(e) => {
15326 let msg = e.to_string();
15327 assert!(
15328 msg.contains("unsupported"),
15329 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
15330 attempt {attempt}): {msg}"
15331 );
15332 named_refusals += 1;
15333 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
15334 continue;
15335 }
15336 Ok(frames) => frames,
15337 };
15338 let tmv = decode::tmv_hits() - before;
15339 let ffmpeg_frames = if bit_depth == 10 {
15340 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
15341 } else {
15342 ffmpeg_decode_sequence(&stream, width, height, frame_count)
15343 };
15344 assert_eq!(frames.len(), frame_count);
15345 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15346 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
15347 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
15348 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)");
15349 }
15350 compared += 1;
15351 tmv_proved += tmv;
15352 }
15353 eprintln!(
15354 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
15355 pixel-exact attempts, blocks with a temporal MV candidate={tmv_proved}"
15356 );
15357 assert!(
15358 compared > 0,
15359 "{NAME} ({bit_depth}-bit): every attempt refused -- gate proved nothing"
15360 );
15361 assert!(
15362 tmv_proved > 0,
15363 "{NAME} ({bit_depth}-bit): no compared attempt ever folded a temporal MV \
15364 candidate into a block's stack -- gate proved nothing"
15365 );
15366 }
15367 }
15368
15369 /// lane-refstamp r1: `av1_setup_motion_field`'s `ref_stamp` budget in the
15370 /// presence of FORWARD KEY FRAMES (`--enable-fwd-kf=1`), which is the only
15371 /// configuration where a *forward* reference slot (BWDREF/ALTREF2/ALTREF)
15372 /// holds a key frame while temporal MV projection runs. libaom's
15373 /// `motion_field_projection` returns 0 for such a start frame, so it costs
15374 /// no `ref_stamp`; ours used to project the (empty) field and report
15375 /// success, spending the slot ALTREF/LAST2 should have had and losing
15376 /// their temporal candidates.
15377 ///
15378 /// Both bit depths; EVERY decoded frame (including the hidden alt-refs)
15379 /// compared to the oracle in decode order; a refusal is counted, never
15380 /// SKIPped. Two hard counters make the gate non-vacuous: frames that
15381 /// actually took the >=2-intra-forward-refs `ref_stamp` path, and blocks
15382 /// that folded a temporal MV candidate into their stack.
15383 #[test]
15384 fn a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact() {
15385 const NAME: &str = "a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact";
15386 let _gate_lock = lock_gate_counters();
15387 if !have_ffmpeg() {
15388 eprintln!("SKIP {NAME}: no ffmpeg");
15389 return;
15390 }
15391 if !have_aomenc() {
15392 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15393 return;
15394 }
15395 let (width, height, frame_count) = (192usize, 128usize, 24usize);
15396 for bit_depth in [8u32, 10u32] {
15397 let (mut named_refusals, mut compared, mut tmv_proved, mut stamp_proved) =
15398 (0u32, 0u32, 0usize, 0usize);
15399 let mut stamp2_proved = 0usize;
15400 for attempt in 0..2u32 {
15401 let duration = frame_count as f64 / 25.0;
15402 // Natural-ish motion: structure translating along X at 3 px per
15403 // frame plus a slow vertical drift, the source family the
15404 // temporal-MV gate already decodes fully.
15405 let source = format!(
15406 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
15407 geq=lum='128+58*sin((X+N*3)/6)+18*sin((Y+N*2)/23)',format=yuv420p"
15408 );
15409 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
15410 let y4m = Command::new("ffmpeg")
15411 .args([
15412 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
15413 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
15414 ])
15415 .stdin(Stdio::null())
15416 .stdout(Stdio::piped())
15417 .stderr(Stdio::piped())
15418 .output()
15419 .expect("ffmpeg failed to run");
15420 assert!(
15421 y4m.status.success(),
15422 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
15423 String::from_utf8_lossy(&y4m.stderr)
15424 );
15425 let depth_arg = format!("--bit-depth={bit_depth}");
15426 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
15427 let cq_arg = format!("--cq-level={}", if attempt == 0 { 34 } else { 45 });
15428 let args: Vec<&str> = vec![
15429 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
15430 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
15431 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
15432 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
15433 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
15434 "--enable-1to4-partitions=0", "--min-partition-size=16",
15435 "--max-partition-size=32",
15436 // Per-arm/feature overrides go LAST (aomenc keeps the LAST
15437 // occurrence of a repeated --enable-* flag).
15438 "--enable-order-hint=1", "--enable-ref-frame-mvs=1",
15439 "--enable-fwd-kf=1", "--fwd-kf-dist=8", "--kf-max-dist=1000",
15440 "--lag-in-frames=16", "--auto-alt-ref=1", "--arnr-maxframes=0",
15441 "--obu", "-o", "-", "-",
15442 ];
15443 let out = run_with_stdin(Command::new(aomenc_path())
15444 .args(&args), &y4m.stdout);
15445 assert!(
15446 out.status.success(),
15447 "aomenc refused the fixture: {}",
15448 String::from_utf8_lossy(&out.stderr)
15449 );
15450 let stream = out.stdout;
15451 let before_tmv = decode::tmv_hits();
15452 let before_stamp = crate::motion_field::refstamp_intra_frames();
15453 if let Err(e) = decode_stream(&stream) {
15454 let msg = e.to_string();
15455 assert!(
15456 msg.contains("unsupported"),
15457 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
15458 attempt {attempt}): {msg}"
15459 );
15460 named_refusals += 1;
15461 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
15462 continue;
15463 }
15464 let tmv = decode::tmv_hits() - before_tmv;
15465 let stamp = crate::motion_field::refstamp_intra_frames().0 - before_stamp.0;
15466 let stamp2 = crate::motion_field::refstamp_intra_frames().1 - before_stamp.1;
15467 // Every frame, hidden ones included, compared in DECODE order.
15468 let (total, hidden) = decode_all_frames_vs_oracle(
15469 &stream,
15470 &format!("{NAME}-{bit_depth}bit-attempt{attempt}"),
15471 );
15472 eprintln!(
15473 "{NAME} ({bit_depth}-bit attempt {attempt}): {total} frames decoded \
15474 ({hidden} hidden), temporal candidates={tmv}, frames with a key/intra \
15475 forward ref={stamp} (two or more: {stamp2})"
15476 );
15477 compared += 1;
15478 tmv_proved += tmv;
15479 stamp_proved += stamp;
15480 stamp2_proved += stamp2;
15481 }
15482 assert!(
15483 compared > 0,
15484 "{NAME} ({bit_depth}-bit): every attempt refused ({named_refusals}) -- gate \
15485 proved nothing"
15486 );
15487 assert!(
15488 tmv_proved > 0,
15489 "{NAME} ({bit_depth}-bit): no compared attempt folded a temporal MV candidate \
15490 into a block's stack -- gate proved nothing"
15491 );
15492 assert!(
15493 stamp_proved > 0,
15494 "{NAME} ({bit_depth}-bit): no compared attempt ever had a forward reference \
15495 holding a key/intra frame ({stamp2_proved} frames had two) -- the ref_stamp \
15496 path this gate exists for never ran"
15497 );
15498 }
15499 }
15500
15501 #[test]
15502 // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter
15503 // residual path IS implemented and reached, but no aomenc recipe swept
15504 // this round produced a stream whose FIRST rect inter block is a 32x16 /
15505 // 16x32 one: real motion content always codes a 16x8/8x16 inter leaf (or
15506 // an intra rect strip) earlier in the tile, and both of those still refuse
15507 // by name, so the decode stops before any 32-level 2:1 strip. The 16x8
15508 // shape additionally needs `default_inter_ext_tx_cdf[2][TX_8X8]` (the
15509 // 12-symbol DTT9_IDTX_1DDCT row, only reachable through a rect
15510 // transform), which this round did not add. See lanes/inter4-r2.report.md.
15511 // Un-ignored 2026-09-04: the intra-rect-strip and 16-level AB/1:4 inter refusals that blocked every attempt are gone and the gate passes.
15512 fn a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact() {
15513 const NAME: &str =
15514 "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact";
15515 let _gate_lock = lock_gate_counters();
15516 if !have_ffmpeg() {
15517 eprintln!("SKIP {NAME}: no ffmpeg");
15518 return;
15519 }
15520 if !have_aomenc() {
15521 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15522 return;
15523 }
15524 let (width, height, frame_count) = (192usize, 128usize, 6usize);
15525 for bit_depth in [8u32, 10u32] {
15526 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
15527 (0u32, 0u32, 0u32, 0u32);
15528 let (mut tu_proved, mut split_proved) = (0usize, 0usize);
15529 for attempt in 0..16u32 {
15530 // Two sources (a translating textured ramp, and testsrc2's
15531 // natural motion) x two quantisers x two tx-size-search arms x
15532 // two motion steps.
15533 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
15534 let cq = [34, 22][(attempt / 2 % 2) as usize];
15535 let natural = attempt / 4 % 2 == 1;
15536 let sp = 3 + (attempt / 8) * 5;
15537 let duration = frame_count as f64 / 25.0;
15538 // Continuous-tone, mid-frequency, translating: a flat or
15539 // banded source makes aomenc code the strips `skip` (r1's
15540 // gate) and its screen-content detector fires on the
15541 // synthetic ramps, stopping the decode at an unrelated intra
15542 // refusal long before any inter strip.
15543 // Structure ALONG one axis is what makes aomenc's RD pick a
15544 // 2:1 rect partition on that axis: horizontal bands drifting
15545 // vertically favour PARTITION_HORZ (32x16 strips), the
15546 // transposed source PARTITION_VERT (16x32).
15547 let lum = if natural {
15548 format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)")
15549 } else {
15550 format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)")
15551 };
15552 let source = format!(
15553 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
15554 geq=lum='{lum}',format=yuv420p"
15555 );
15556 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
15557 let y4m = Command::new("ffmpeg")
15558 .args([
15559 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
15560 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
15561 ])
15562 .stdin(Stdio::null())
15563 .stdout(Stdio::piped())
15564 .stderr(Stdio::piped())
15565 .output()
15566 .expect("ffmpeg failed to run");
15567 assert!(
15568 y4m.status.success(),
15569 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
15570 String::from_utf8_lossy(&y4m.stderr)
15571 );
15572 let cq_arg = format!("--cq-level={cq}");
15573 let depth_arg = format!("--bit-depth={bit_depth}");
15574 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
15575 let tx_arg = format!("--enable-tx-size-search={tx_search}");
15576 let args: Vec<&str> = vec![
15577 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
15578 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
15579 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
15580 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
15581 "--lag-in-frames=0",
15582 // Per-arm overrides go LAST: aomenc keeps the last
15583 // occurrence of a repeated --enable-* flag.
15584 &tx_arg,
15585 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
15586 "--enable-1to4-partitions=0", "--min-partition-size=16",
15587 "--max-partition-size=32",
15588 "--obu", "-o", "-", "-",
15589 ];
15590 let out = run_with_stdin(Command::new(aomenc_path())
15591 .args(&args), &y4m.stdout);
15592 assert!(
15593 out.status.success(),
15594 "aomenc refused the fixture: {}",
15595 String::from_utf8_lossy(&out.stderr)
15596 );
15597 let stream = out.stdout;
15598 let before = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
15599 let frames = match decode_stream(&stream) {
15600 Err(e) => {
15601 let msg = e.to_string();
15602 assert!(
15603 msg.contains("unsupported"),
15604 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
15605 attempt {attempt}): {msg}"
15606 );
15607 named_refusals += 1;
15608 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
15609 continue;
15610 }
15611 Ok(frames) => frames,
15612 };
15613 let after = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
15614 let (tu, split) = (after.0 - before.0, after.1 - before.1);
15615 let ffmpeg_frames = if bit_depth == 10 {
15616 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
15617 } else {
15618 ffmpeg_decode_sequence(&stream, width, height, frame_count)
15619 };
15620 assert_eq!(frames.len(), frame_count);
15621 let mismatched = frames
15622 .iter()
15623 .zip(&ffmpeg_frames)
15624 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
15625 if tu + split == 0 {
15626 out_of_scope += 1;
15627 if mismatched {
15628 oos_mismatch += 1;
15629 eprintln!(
15630 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
15631 coded rect inter transform units -- another shape's defect"
15632 );
15633 }
15634 continue;
15635 }
15636 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15637 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
15638 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
15639 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
15640 }
15641 tu_proved += tu;
15642 split_proved += split;
15643 matched += 1;
15644 }
15645 eprintln!(
15646 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
15647 attempts carrying a coded rect inter residual, whole-block rect TUs={tu_proved}, \
15648 rect trees that split={split_proved}, {out_of_scope} attempts carried none \
15649 ({oos_mismatch} of them mismatched)"
15650 );
15651 assert_eq!(
15652 oos_mismatch, 0,
15653 "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \
15654 mismatched ffmpeg -- a defect of another shape, not a pass"
15655 );
15656 assert!(
15657 tu_proved > 0,
15658 "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever coded a rectangular inter \
15659 residual (tu={tu_proved}, split={split_proved}, {named_refusals} refusals, \
15660 {out_of_scope} out of scope) -- gate proved nothing"
15661 );
15662 }
15663 }
15664
15665 /// lane-intersub8: `PARTITION_SPLIT` below 8x8 on an INTER frame -- four
15666 /// `BLOCK_4X4` inter sub-blocks with one shared 4x4 chroma unit per plane,
15667 /// predicted the sub8x8 way (2x2 chroma piece per luma sub-block mv,
15668 /// `dec_build_inter_predictors`' `is_sub8x8` branch). Reality of the shape
15669 /// was established BEFORE the code (class refusal-from-own-desync): the
15670 /// oracle `aomdec`'s `EC_TRACE` prints `EC_PART_VAL ... bsize=3 value=3`
15671 /// on this recipe's inter frames.
15672 ///
15673 /// Attempts 0..7 run `--enable-rect-partitions=0`, where aomenc can only
15674 /// pick SPLIT below 8x8; attempts 8..15 repeat the schedule with rect on,
15675 /// where it picks HORZ/VERT below 8x8 far more often than SPLIT -- the VERT
15676 /// arm (two `BLOCK_4X8` inter leaves, `decode_inter_sub8_rect2`) is what the
15677 /// `rect_fired` assert pins. The HORZ twin decodes but is refused by name
15678 /// (lane-intersub8 r3: a measured sweep desyncs the block to its right).
15679 #[test]
15680 fn a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact() {
15681 const NAME: &str =
15682 "a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact";
15683 let _gate_lock = lock_gate_counters();
15684 if !have_ffmpeg() {
15685 eprintln!("SKIP {NAME}: no ffmpeg");
15686 return;
15687 }
15688 if !have_aomenc() {
15689 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15690 return;
15691 }
15692 let (width, height, frame_count) = (192usize, 128usize, 6usize);
15693 let mut fired = 0u32;
15694 // lane-intersub8 r3: attempts 8..15 repeat the same schedule with
15695 // `--enable-rect-partitions=1`, where aomenc picks PARTITION_VERT below
15696 // 8x8 (two BLOCK_4X8 inter leaves, one shared 4x4 chroma unit predicted
15697 // from BOTH sub-blocks' mvs). The HORZ twin is still refused by name.
15698 let mut rect_fired = 0u32;
15699 // lane-intersub8 r5: the two rect axes counted apart. Attempts 16..23
15700 // are the same recipe family with the geq source TRANSPOSED (the sine
15701 // that moves runs along Y, not X): measured over a 56-arm sweep
15702 // (~/.cache/intersub8-sweep-r5.log, cq {8,12,14,16,20,26,32} x sp
15703 // {3,6,9,12} x both depths, rect on), aomenc picks PARTITION_HORZ
15704 // below 8x8 on that source and PARTITION_VERT on the untransposed one
15705 // -- neither schedule reaches the other axis, so both are needed.
15706 let (mut horz_fired, mut vert_fired) = (0u32, 0u32);
15707 // Rect (non-square) masked-compound blocks on attempts that DECODED
15708 // and were pixel-compared -- never off a refused stream (class
15709 // counter-from-refused-stream). This is the shape whose
15710 // `compound_type`/`wedge_idx` CDF row lane-intersub8 r4 fixed.
15711 let mut rect_masked = 0usize;
15712 let mut refusals: Vec<String> = Vec::new();
15713 let mut out_of_scope_mismatch = 0u32;
15714 for bit_depth in [8u32, 10u32] {
15715 for attempt in 0..24u32 {
15716 let rect = if attempt >= 16 { 1 } else { attempt / 8 };
15717 let rect_arg = format!("--enable-rect-partitions={rect}");
15718 // lane-intersub8 r2, measured schedule (sweep of cq
15719 // {8,10,12,14,16,18,20} x sp {3,6,9,12} x both depths,
15720 // `decode_probe`'s `sub8_inter_split:` counter vs an ffmpeg
15721 // rawvideo compare): sub-8x8 inter SPLIT groups fire at
15722 // (8-bit, cq 12, sp 3) = 1 group and (10-bit, cq 12, sp 6) =
15723 // 3 groups, both pixel-exact. cq 8 and 10 are NOT used: at
15724 // those quantizers this recipe also carries a CDEF defect of
15725 // another shape -- three luma samples of |d| = 1 on
15726 // decode-order frames 3/4, zero sub-8x8 inter split groups,
15727 // and the identical recipe re-encoded with `--enable-cdef=0`
15728 // decodes all six frames exact. Deferred to a CDEF lane
15729 // rather than hidden: cq 16..20 are all exact, so this gate
15730 // is not selecting quantizers that hide a defect of its own
15731 // shape.
15732 // Attempts 16..23: the (cq, sp) pairs the r5 sweep measured
15733 // as HORZ-firing on the transposed source -- 8-bit
15734 // (14,3)/(20,3)/(32,9), 10-bit (12,3)/(16,3); the rest of the
15735 // eight are non-firing neighbours kept so a schedule that
15736 // stops firing shows up as out-of-scope, not as a silent pass.
15737 const HORZ_SCHEDULE: [(u32, u32); 8] =
15738 [(14, 3), (20, 3), (32, 9), (12, 3), (16, 3), (12, 9), (14, 9), (26, 3)];
15739 let (cq, sp) = if attempt >= 16 {
15740 HORZ_SCHEDULE[(attempt - 16) as usize]
15741 } else {
15742 ([12, 14][(attempt % 2) as usize], 3 + ((attempt % 8) / 2) * 3)
15743 };
15744 let duration = frame_count as f64 / 25.0;
15745 let source = if attempt >= 16 {
15746 format!(
15747 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
15748 geq=lum='128+58*sin((Y+N*{sp})/6)+18*sin(X/23)',format=yuv420p"
15749 )
15750 } else {
15751 format!(
15752 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
15753 geq=lum='128+58*sin((X+N*{sp})/6)+18*sin(Y/23)',format=yuv420p"
15754 )
15755 };
15756 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
15757 let y4m = Command::new("ffmpeg")
15758 .args([
15759 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
15760 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
15761 ])
15762 .stdin(Stdio::null())
15763 .stdout(Stdio::piped())
15764 .stderr(Stdio::piped())
15765 .output()
15766 .expect("ffmpeg failed to run");
15767 assert!(
15768 y4m.status.success(),
15769 "{NAME}: ffmpeg refused the fixture: {}",
15770 String::from_utf8_lossy(&y4m.stderr)
15771 );
15772 let cq_arg = format!("--cq-level={cq}");
15773 let depth_arg = format!("--bit-depth={bit_depth}");
15774 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
15775 let args: Vec<&str> = vec![
15776 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
15777 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
15778 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
15779 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
15780 "--lag-in-frames=0", "--enable-obmc=0", "--enable-tx-size-search=1",
15781 // Per-arm overrides last (aomenc keeps the LAST occurrence).
15782 "--enable-rect-partitions=0", "--enable-ab-partitions=0",
15783 "--enable-1to4-partitions=0", "--min-partition-size=4",
15784 "--max-partition-size=16",
15785 &rect_arg,
15786 "--obu", "-o", "-", "-",
15787 ];
15788 let out = run_with_stdin(Command::new(aomenc_path())
15789 .args(&args), &y4m.stdout);
15790 assert!(
15791 out.status.success(),
15792 "{NAME}: aomenc refused the fixture: {}",
15793 String::from_utf8_lossy(&out.stderr)
15794 );
15795 let stream = out.stdout;
15796 let before = decode::sub8_inter_split_hits();
15797 let before_rect = decode::sub8_inter_rect_hits();
15798 let before_masked = decode::rect_masked_compound_hits();
15799 let frames = match decode_stream(&stream) {
15800 Err(e) => {
15801 let msg = e.to_string();
15802 assert!(
15803 msg.contains("unsupported"),
15804 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
15805 attempt {attempt}): {msg}"
15806 );
15807 refusals.push(format!("{bit_depth}-bit attempt {attempt}: {msg}"));
15808 continue;
15809 }
15810 Ok(frames) => frames,
15811 };
15812 let split_groups = decode::sub8_inter_split_hits() - before;
15813 let rect_now = decode::sub8_inter_rect_hits();
15814 let rect_groups = (rect_now.0 - before_rect.0) + (rect_now.1 - before_rect.1);
15815 let groups = split_groups + rect_groups;
15816 let ffmpeg_frames = if bit_depth == 10 {
15817 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
15818 } else {
15819 ffmpeg_decode_sequence(&stream, width, height, frame_count)
15820 };
15821 assert_eq!(frames.len(), frame_count);
15822 let mismatched = frames
15823 .iter()
15824 .zip(&ffmpeg_frames)
15825 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
15826 if groups == 0 {
15827 // Out of scope: no sub-8x8 inter split in this attempt.
15828 if mismatched {
15829 out_of_scope_mismatch += 1;
15830 eprintln!(
15831 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
15832 sub-8x8 inter group -- another shape's defect"
15833 );
15834 }
15835 refusals.push(format!(
15836 "{bit_depth}-bit attempt {attempt}: decoded, but no sub-8x8 inter split"
15837 ));
15838 continue;
15839 }
15840 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15841 assert_eq!(
15842 got.y, want.y,
15843 "luma frame {i} ({bit_depth}-bit attempt {attempt}, {groups} sub-8x8 \
15844 inter split groups)"
15845 );
15846 assert_eq!(got.u, want.u, "U frame {i} ({bit_depth}-bit attempt {attempt})");
15847 assert_eq!(got.v, want.v, "V frame {i} ({bit_depth}-bit attempt {attempt})");
15848 }
15849 fired += 1;
15850 if rect_groups > 0 {
15851 rect_fired += 1;
15852 }
15853 if rect_now.0 - before_rect.0 > 0 {
15854 horz_fired += 1;
15855 }
15856 if rect_now.1 - before_rect.1 > 0 {
15857 vert_fired += 1;
15858 }
15859 // Only now, past the pixel compare, is this attempt's
15860 // masked-compound count admissible.
15861 rect_masked += decode::rect_masked_compound_hits() - before_masked;
15862 }
15863 }
15864 eprintln!(
15865 "{NAME}: fired={fired} horz={horz_fired} vert={vert_fired} rect_masked={rect_masked}"
15866 );
15867 assert_eq!(
15868 out_of_scope_mismatch, 0,
15869 "{NAME}: attempts mismatched with no sub-8x8 inter group"
15870 );
15871 assert!(
15872 fired >= 2,
15873 "{NAME}: fewer than 2 firing+pixel-exact attempts:\n{}",
15874 refusals.join("\n")
15875 );
15876 assert!(
15877 rect_fired >= 2,
15878 "{NAME}: fewer than 2 firing+pixel-exact attempts with a RECTANGULAR sub-8x8 \
15879 inter leaf (4x8):\n{}",
15880 refusals.join("\n")
15881 );
15882 assert!(
15883 vert_fired >= 2,
15884 "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter VERT \
15885 pair (two BLOCK_4X8 leaves):\n{}",
15886 refusals.join("\n")
15887 );
15888 // lane-intersub8 r5, measured `rect_masked=2` over the 48 attempts:
15889 // the rect masked-compound blocks whose `compound_type`/`wedge_idx`
15890 // CDF row r4 corrected, counted only on pixel-compared attempts.
15891 assert!(
15892 rect_masked >= 1,
15893 "{NAME}: no RECTANGULAR masked-compound block on any pixel-compared attempt -- \
15894 the r4 compound_type/wedge_idx CDF-row fix is unexercised:\n{}",
15895 refusals.join("\n")
15896 );
15897 assert!(
15898 horz_fired >= 2,
15899 "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter HORZ \
15900 pair (two BLOCK_8X4 leaves):\n{}",
15901 refusals.join("\n")
15902 );
15903 }
15904
15905 #[test]
15906 // lane-inter4 r3: the 16x16-level rect INTER leaf -- PARTITION_HORZ /
15907 // PARTITION_VERT at 16x16 on an inter frame, i.e. two 16x8 / 8x16 inter
15908 // blocks, mode info + rectangular residual + prediction. Every decoded
15909 // frame is compared Y/U/V against ffmpeg, refusals are counted and never
15910 // SKIPped, and the gate asserts a pixel-exact attempt for BOTH axes that
15911 // also coded a rectangular inter transform unit (i.e. was not `skip`).
15912 fn a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact() {
15913 const NAME: &str =
15914 "a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact";
15915 let _gate_lock = lock_gate_counters();
15916 if !have_ffmpeg() {
15917 eprintln!("SKIP {NAME}: no ffmpeg");
15918 return;
15919 }
15920 if !have_aomenc() {
15921 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15922 return;
15923 }
15924 let (width, height, frame_count) = (192usize, 128usize, 6usize);
15925 // Coded (non-skip) rect inter transform units, summed over both bit
15926 // depths: at 10 bits this recipe's rect leaves all come out `skip`
15927 // (measured at cq 34/22, 30/26 and 24/12 -- the lower pairs stop
15928 // reaching a rect leaf at all), so the RESIDUAL half of the claim is
15929 // proven by the 8-bit arm while the 10-bit arm proves the mode-info,
15930 // prediction and neighbour halves on both axes.
15931 let mut tu_total = 0usize;
15932 for bit_depth in [8u32, 10u32] {
15933 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
15934 (0u32, 0u32, 0u32, 0u32);
15935 let (mut tu_proved, mut split_proved) = (0usize, 0usize);
15936 let (mut horz_proved, mut vert_proved, mut sub16_split) = (0u32, 0u32, 0usize);
15937 // lane-inter4 r4, measured residue of this recipe family (sweep
15938 // over cq {8,12,16,22} x {both axes} x both depths, tx-size-search
15939 // on, via `decode_probe`'s `rect_inter:` counters): the rect
15940 // var-tx SPLIT arm never fires (txsplit=0 everywhere) and a 10-bit
15941 // rect leaf is always `skip` (tu=0 at every cq that decodes) --
15942 // below cq 22 every attempt stops at another lane's intra refusal
15943 // ("a HORZ/VERT intra strip below 16x16 with a split transform").
15944 // Both are asserted here only where they DO fire (8-bit tu>0);
15945 // shipped-but-unexercised, see lanes/inter4-r4.report.md.
15946 // lane-inter4 r4: attempts 16..32 repeat the same sweep with
15947 // `--enable-obmc=1`. r3 refused OBMC on this shape; r4's
15948 // instrumented-aomdec comparison showed the neighbour list AND
15949 // every pre-filter frame bit-exact, so the arm is a gate now.
15950 let mut obmc_leaf_proved = 0usize;
15951 for attempt in 0..32u32 {
15952 let obmc_arg = if attempt >= 16 { "--enable-obmc=1" } else { "--enable-obmc=0" };
15953 let attempt = attempt % 16;
15954 // Two sources (a translating textured ramp, and testsrc2's
15955 // natural motion) x two quantisers x two tx-size-search arms x
15956 // two motion steps.
15957 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
15958 // A 10-bit encode of the same source spends fewer bits on
15959 // residual at a given cq, so it needs the lower pair to make
15960 // a rect leaf non-skip at all (measured: cq 34/22 gives zero
15961 // coded rect inter TUs in 16 10-bit attempts).
15962 let cq = [34, 22][(attempt / 2 % 2) as usize];
15963 let natural = attempt / 4 % 2 == 1;
15964 let sp = 3 + (attempt / 8) * 5;
15965 let duration = frame_count as f64 / 25.0;
15966 // Continuous-tone, mid-frequency, translating: a flat or
15967 // banded source makes aomenc code the strips `skip` (r1's
15968 // gate) and its screen-content detector fires on the
15969 // synthetic ramps, stopping the decode at an unrelated intra
15970 // refusal long before any inter strip.
15971 // Structure ALONG one axis is what makes aomenc's RD pick a
15972 // 2:1 rect partition on that axis: horizontal bands drifting
15973 // vertically favour PARTITION_HORZ (32x16 strips), the
15974 // transposed source PARTITION_VERT (16x32).
15975 let lum = if natural {
15976 format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)")
15977 } else {
15978 format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)")
15979 };
15980 let source = format!(
15981 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
15982 geq=lum='{lum}',format=yuv420p"
15983 );
15984 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
15985 let y4m = Command::new("ffmpeg")
15986 .args([
15987 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
15988 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
15989 ])
15990 .stdin(Stdio::null())
15991 .stdout(Stdio::piped())
15992 .stderr(Stdio::piped())
15993 .output()
15994 .expect("ffmpeg failed to run");
15995 assert!(
15996 y4m.status.success(),
15997 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
15998 String::from_utf8_lossy(&y4m.stderr)
15999 );
16000 let cq_arg = format!("--cq-level={cq}");
16001 let depth_arg = format!("--bit-depth={bit_depth}");
16002 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
16003 let tx_arg = format!("--enable-tx-size-search={tx_search}");
16004 let args: Vec<&str> = vec![
16005 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
16006 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
16007 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
16008 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
16009 "--lag-in-frames=0",
16010 // Per-arm overrides go LAST: aomenc keeps the last
16011 // occurrence of a repeated --enable-* flag.
16012 &tx_arg,
16013 "--enable-rect-partitions=1", "--enable-ab-partitions=0",
16014 "--enable-1to4-partitions=0", "--min-partition-size=8",
16015 "--max-partition-size=16",
16016 obmc_arg,
16017 "--obu", "-o", "-", "-",
16018 ];
16019 let out = run_with_stdin(Command::new(aomenc_path())
16020 .args(&args), &y4m.stdout);
16021 assert!(
16022 out.status.success(),
16023 "aomenc refused the fixture: {}",
16024 String::from_utf8_lossy(&out.stderr)
16025 );
16026 let stream = out.stdout;
16027 let before = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
16028 let before_obmc_leaf = decode::obmc_rect_leaf_hits();
16029 let before_leaf = (
16030 decode::inter_leaf16_horz_hits(),
16031 decode::inter_leaf16_vert_hits(),
16032 decode::inter_sub16_split_hits(),
16033 );
16034 let frames = match decode_stream(&stream) {
16035 Err(e) => {
16036 let msg = e.to_string();
16037 assert!(
16038 msg.contains("unsupported"),
16039 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
16040 attempt {attempt}): {msg}"
16041 );
16042 named_refusals += 1;
16043 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
16044 continue;
16045 }
16046 Ok(frames) => frames,
16047 };
16048 let after = (decode::rect_inter_tu_hits(), decode::rect_inter_txsplit_hits());
16049 let (tu, split) = (after.0 - before.0, after.1 - before.1);
16050 let obmc_leaf = decode::obmc_rect_leaf_hits() - before_obmc_leaf;
16051 let (horz, vert, splits16) = (
16052 decode::inter_leaf16_horz_hits() - before_leaf.0,
16053 decode::inter_leaf16_vert_hits() - before_leaf.1,
16054 decode::inter_sub16_split_hits() - before_leaf.2,
16055 );
16056 let ffmpeg_frames = if bit_depth == 10 {
16057 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
16058 } else {
16059 ffmpeg_decode_sequence(&stream, width, height, frame_count)
16060 };
16061 assert_eq!(frames.len(), frame_count);
16062 let mismatched = frames
16063 .iter()
16064 .zip(&ffmpeg_frames)
16065 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16066 if horz + vert == 0 {
16067 out_of_scope += 1;
16068 if mismatched {
16069 oos_mismatch += 1;
16070 eprintln!(
16071 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
16072 16-level rect inter leaf -- another shape's defect"
16073 );
16074 }
16075 continue;
16076 }
16077 if mismatched {
16078 // lane-inter4 r3: where, not just that -- a handful of
16079 // 4x4-aligned pixels is a prediction/reconstruction
16080 // defect, a whole band from the first row down is a
16081 // desync.
16082 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16083 let bad: Vec<usize> = (0..got.y.len())
16084 .filter(|&k| got.y[k] != want.y[k])
16085 .collect();
16086 if !bad.is_empty() {
16087 eprintln!(
16088 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
16089 pixels differ, first at ({}, {}), max |delta| {}",
16090 bad.len(),
16091 bad[0] % width,
16092 bad[0] / width,
16093 bad.iter()
16094 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
16095 .max()
16096 .unwrap_or(0)
16097 );
16098 }
16099 }
16100 }
16101 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16102 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
16103 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
16104 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})");
16105 }
16106 tu_proved += tu;
16107 obmc_leaf_proved += obmc_leaf;
16108 split_proved += split;
16109 sub16_split += splits16;
16110 if horz > 0 {
16111 horz_proved += 1;
16112 }
16113 if vert > 0 {
16114 vert_proved += 1;
16115 }
16116 matched += 1;
16117 }
16118 eprintln!(
16119 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
16120 attempts carrying a 16-level rect inter leaf, 16x8-carrying={horz_proved}, \
16121 8x16-carrying={vert_proved}, whole-block rect TUs={tu_proved}, rect trees that \
16122 split={split_proved}, 16x16 SPLITs={sub16_split}, OBMC blends on a rect \
16123 leaf={obmc_leaf_proved}, {out_of_scope} attempts \
16124 carried none ({oos_mismatch} of them mismatched)"
16125 );
16126 assert_eq!(
16127 oos_mismatch, 0,
16128 "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \
16129 mismatched ffmpeg -- a defect of another shape, not a pass"
16130 );
16131 assert!(
16132 horz_proved > 0 && vert_proved > 0,
16133 "{NAME} ({bit_depth}-bit): the 16-level rect inter leaf is not proven on both \
16134 axes (16x8={horz_proved}, 8x16={vert_proved}, tu={tu_proved}, 16x16 \
16135 SPLITs={sub16_split}, {named_refusals} refusals, {out_of_scope} out of \
16136 scope) -- gate proved nothing"
16137 );
16138 assert!(
16139 obmc_leaf_proved > 0,
16140 "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever ran the OBMC blend on a \
16141 16x8/8x16 inter leaf -- the `--enable-obmc=1` arm proved nothing"
16142 );
16143 tu_total += tu_proved;
16144 }
16145 assert!(
16146 tu_total > 0,
16147 "{NAME}: no pixel-exact attempt at either bit depth coded a rectangular inter \
16148 residual on a 16-level leaf -- the residual half of the claim is unproven"
16149 );
16150 }
16151
16152
16153 #[test]
16154 // lane-inter16ab r1: the 16x16-level AB partitions on an INTER frame --
16155 // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter
16156 // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is
16157 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
16158 // out-of-scope mismatches fail the gate, and EACH of the four arms must
16159 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
16160 // proof of four). `--enable-1to4-partitions=0` because the 16-level 1:4
16161 // pair (16x4/4x16 inter strips) is still refused by name.
16162 fn a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact() {
16163 const NAME: &str =
16164 "a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact";
16165 let _gate_lock = lock_gate_counters();
16166 if !have_ffmpeg() {
16167 eprintln!("SKIP {NAME}: no ffmpeg");
16168 return;
16169 }
16170 if !have_aomenc() {
16171 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16172 return;
16173 }
16174 let (width, height, frame_count) = (192usize, 128usize, 6usize);
16175 // Per arm, over both bit depths: how many pixel-exact attempts fired
16176 // it at least once.
16177 let mut arms_total = [0u32; 4];
16178 for bit_depth in [8u32, 10u32] {
16179 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
16180 (0u32, 0u32, 0u32, 0u32);
16181 let mut arms_proved = [0u32; 4];
16182 for attempt in 0..32u32 {
16183 // Two sources (structure along X vs along Y -- an AB
16184 // partition needs an L/T-shaped feature, so both orientations
16185 // are swept), four quantisers, two motion steps, two tiling
16186 // arms. r1 measured (sweep script in the report): a 16-attempt
16187 // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A
16188 // at 8 bits, so the quantiser axis is four wide here; cq 46 on
16189 // the X-structured source is deliberately NOT in the list --
16190 // that stream's decode-order frame 4 desyncs on a defect this
16191 // lane does not own (aomdec's own EC_PART trace reads ZERO
16192 // AB partitions at BLOCK_16X16 anywhere in it, so the AB
16193 // counters it raises are read out of an already-diverged
16194 // stream; see lanes/inter16ab-r1.report.md).
16195 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
16196 // The 10-bit arm swaps cq 40 for 28 on the same sources: at
16197 // cq 40 the X-structured 10-bit stream mismatches ffmpeg with
16198 // ZERO 16-level AB partitions in it (another shape's defect,
16199 // measured r1 -- the gate's own `oos_mismatch` counter is
16200 // what found it, and it is reported, not silenced).
16201 let cq = if bit_depth == 10 {
16202 [18, 22, 34, 28][(attempt / 2 % 4) as usize]
16203 } else {
16204 [18, 22, 34, 40][(attempt / 2 % 4) as usize]
16205 };
16206 let natural = attempt / 8 % 2 == 1;
16207 let group = attempt / 16;
16208 // r1: a `--tile-columns=1` arm of this same sweep PANICS in
16209 // `mc::from_switchable_symbol` (a 4th symbol out of a
16210 // 3-symbol alphabet = someone else's desync, the signature
16211 // the ledger already pins for the below-8x8 inter leaf), not
16212 // in anything this lane added -- so the tiled arm is left out
16213 // rather than turned into a SKIP or a weakened assert.
16214 // Reported as residue in lanes/inter16ab-r1.report.md.
16215 let tile_cols = "0";
16216 let sp = 3 + (group % 2) * 5;
16217 let duration = frame_count as f64 / 25.0;
16218 // Continuous-tone translating texture with a second, coarser
16219 // component on the cross axis: aomenc's RD picks an AB
16220 // partition where one 16x16 quadrant differs from its three
16221 // siblings, which the two sinusoids at different periods
16222 // produce all over the frame.
16223 let lum = if natural {
16224 format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)")
16225 } else {
16226 format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)")
16227 };
16228 let source = format!(
16229 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
16230 geq=lum='{lum}',format=yuv420p"
16231 );
16232 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
16233 let y4m = Command::new("ffmpeg")
16234 .args([
16235 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
16236 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
16237 ])
16238 .stdin(Stdio::null())
16239 .stdout(Stdio::piped())
16240 .stderr(Stdio::piped())
16241 .output()
16242 .expect("ffmpeg failed to run");
16243 assert!(
16244 y4m.status.success(),
16245 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
16246 String::from_utf8_lossy(&y4m.stderr)
16247 );
16248 let cq_arg = format!("--cq-level={cq}");
16249 let depth_arg = format!("--bit-depth={bit_depth}");
16250 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
16251 let tx_arg = format!("--enable-tx-size-search={tx_search}");
16252 let tile_arg = format!("--tile-columns={tile_cols}");
16253 let args: Vec<&str> = vec![
16254 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
16255 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
16256 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
16257 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
16258 "--lag-in-frames=0", "--kf-max-dist=9999", &tile_arg,
16259 // Per-arm overrides go LAST: aomenc keeps the last
16260 // occurrence of a repeated --enable-* flag.
16261 &tx_arg,
16262 "--enable-rect-partitions=1", "--enable-ab-partitions=1",
16263 "--enable-1to4-partitions=0", "--min-partition-size=8",
16264 "--max-partition-size=16",
16265 "--obu", "-o", "-", "-",
16266 ];
16267 let out = run_with_stdin(Command::new(aomenc_path())
16268 .args(&args), &y4m.stdout);
16269 assert!(
16270 out.status.success(),
16271 "aomenc refused the fixture: {}",
16272 String::from_utf8_lossy(&out.stderr)
16273 );
16274 let stream = out.stdout;
16275 let before = decode::ab16_inter_hits_by_arm();
16276 let frames = match decode_stream(&stream) {
16277 Err(e) => {
16278 let msg = e.to_string();
16279 assert!(
16280 msg.contains("unsupported"),
16281 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
16282 attempt {attempt}): {msg}"
16283 );
16284 named_refusals += 1;
16285 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
16286 continue;
16287 }
16288 Ok(frames) => frames,
16289 };
16290 let after = decode::ab16_inter_hits_by_arm();
16291 let fired: Vec<usize> =
16292 (0..4).map(|a| after[a] - before[a]).collect();
16293 let ffmpeg_frames = if bit_depth == 10 {
16294 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
16295 } else {
16296 ffmpeg_decode_sequence(&stream, width, height, frame_count)
16297 };
16298 assert_eq!(frames.len(), frame_count);
16299 let mismatched = frames
16300 .iter()
16301 .zip(&ffmpeg_frames)
16302 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16303 if fired.iter().sum::<usize>() == 0 {
16304 out_of_scope += 1;
16305 if mismatched {
16306 oos_mismatch += 1;
16307 eprintln!(
16308 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
16309 16-level inter AB partition -- another shape's defect"
16310 );
16311 }
16312 continue;
16313 }
16314 if mismatched {
16315 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16316 let bad: Vec<usize> =
16317 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
16318 if !bad.is_empty() {
16319 eprintln!(
16320 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
16321 pixels differ, first at ({}, {}), max |delta| {}",
16322 bad.len(),
16323 bad[0] % width,
16324 bad[0] / width,
16325 bad.iter()
16326 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
16327 .max()
16328 .unwrap_or(0)
16329 );
16330 }
16331 }
16332 }
16333 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16334 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
16335 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
16336 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
16337 }
16338 for a in 0..4 {
16339 if fired[a] > 0 {
16340 arms_proved[a] += 1;
16341 arms_total[a] += 1;
16342 }
16343 }
16344 matched += 1;
16345 }
16346 eprintln!(
16347 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
16348 attempts carrying a 16-level inter AB partition, per-arm attempts \
16349 HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \
16350 none ({oos_mismatch} of them mismatched)"
16351 );
16352 assert_eq!(
16353 oos_mismatch, 0,
16354 "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter AB partition decoded \
16355 but mismatched ffmpeg -- a defect of another shape, not a pass"
16356 );
16357 }
16358 assert!(
16359 arms_total.iter().all(|&n| n > 0),
16360 "{NAME}: not every 16-level inter AB arm fired on a pixel-exact attempt \
16361 (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven"
16362 );
16363 }
16364
16365
16366
16367 #[test]
16368 // lane-inter16ab r2: the 16x16-level 1:4 partitions on an INTER frame --
16369 // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter
16370 // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is
16371 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
16372 // out-of-scope mismatches fail the gate, and EACH of the four arms must
16373 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
16374 // proof of four). `--min-partition-size=4` is what lets aomenc's RD reach
16375 // `PARTITION_HORZ_4`/`_VERT_4` at BLOCK_16X16 (16x4 / 4x16 inter strips);
16376 // the last two counters are the chroma half of the claim -- the odd
16377 // strip's `is_chroma_reference` pair and the pairs whose chroma was built
16378 // from two different strips' motion vectors
16379 // (`build_inter_predictors_sub8x8`).
16380 fn a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact() {
16381 const NAME: &str =
16382 "a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact";
16383 let _gate_lock = lock_gate_counters();
16384 if !have_ffmpeg() {
16385 eprintln!("SKIP {NAME}: no ffmpeg");
16386 return;
16387 }
16388 if !have_aomenc() {
16389 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16390 return;
16391 }
16392 let (width, height, frame_count) = (192usize, 128usize, 6usize);
16393 // Per arm, over both bit depths: how many pixel-exact attempts fired
16394 // it at least once.
16395 let mut arms_total = [0u32; 5];
16396 // lane-inter16ab r5: attempts refused on "a non-skip rectangular
16397 // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding".
16398 let mut rect_residual_refusals = 0u32;
16399 for bit_depth in [8u32, 10u32] {
16400 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
16401 (0u32, 0u32, 0u32, 0u32);
16402 let mut arms_proved = [0u32; 5];
16403 // lane-inter16ab r4: a 4-recipe widening (fine `sin(X/3)` stripes
16404 // at cq 8..14, both depths) was measured and REMOVED again -- every
16405 // extra 1:4 partition it produced is in the KEY frame, and this
16406 // gate's arms count INTER-frame strips. Frame-aware histogram
16407 // script + table in lanes/inter16ab-r4.report.md; the only recipe
16408 // in the whole sweep with an inter-frame `PARTITION_VERT_4` is
16409 // attempt 1's, which refuses on the rect wedge-interintra mask.
16410 for attempt in 0..32u32 {
16411 // Two sources (structure along X vs along Y -- an AB
16412 // partition needs an L/T-shaped feature, so both orientations
16413 // are swept), four quantisers, two motion steps, two tiling
16414 // arms. r1 measured (sweep script in the report): a 16-attempt
16415 // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A
16416 // at 8 bits, so the quantiser axis is four wide here; cq 46 on
16417 // the X-structured source is deliberately NOT in the list --
16418 // that stream's decode-order frame 4 desyncs on a defect this
16419 // lane does not own (aomdec's own EC_PART trace reads ZERO
16420 // AB partitions at BLOCK_16X16 anywhere in it, so the AB
16421 // counters it raises are read out of an already-diverged
16422 // stream; see lanes/inter16ab-r1.report.md).
16423 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
16424 // The 10-bit arm swaps cq 40 for 28 on the same sources: at
16425 // cq 40 the X-structured 10-bit stream mismatches ffmpeg with
16426 // ZERO 16-level AB partitions in it (another shape's defect,
16427 // measured r1 -- the gate's own `oos_mismatch` counter is
16428 // what found it, and it is reported, not silenced).
16429 let cq = if bit_depth == 10 {
16430 [18, 22, 34, 28][(attempt / 2 % 4) as usize]
16431 } else {
16432 [18, 22, 34, 40][(attempt / 2 % 4) as usize]
16433 };
16434 let natural = attempt / 8 % 2 == 1;
16435 let group = attempt / 16;
16436 // r1: a `--tile-columns=1` arm of this same sweep PANICS in
16437 // `mc::from_switchable_symbol` (a 4th symbol out of a
16438 // 3-symbol alphabet = someone else's desync, the signature
16439 // the ledger already pins for the below-8x8 inter leaf), not
16440 // in anything this lane added -- so the tiled arm is left out
16441 // rather than turned into a SKIP or a weakened assert.
16442 // Reported as residue in lanes/inter16ab-r1.report.md.
16443 let tile_cols = "0";
16444 let sp = 3 + (group % 2) * 5;
16445 let duration = frame_count as f64 / 25.0;
16446 // Continuous-tone translating texture with a second, coarser
16447 // component on the cross axis: aomenc's RD picks an AB
16448 // partition where one 16x16 quadrant differs from its three
16449 // siblings, which the two sinusoids at different periods
16450 // produce all over the frame.
16451 let lum = if natural {
16452 format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)")
16453 } else {
16454 format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)")
16455 };
16456 let source = format!(
16457 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
16458 geq=lum='{lum}',format=yuv420p"
16459 );
16460 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
16461 let y4m = Command::new("ffmpeg")
16462 .args([
16463 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
16464 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
16465 ])
16466 .stdin(Stdio::null())
16467 .stdout(Stdio::piped())
16468 .stderr(Stdio::piped())
16469 .output()
16470 .expect("ffmpeg failed to run");
16471 assert!(
16472 y4m.status.success(),
16473 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
16474 String::from_utf8_lossy(&y4m.stderr)
16475 );
16476 let cq_arg = format!("--cq-level={cq}");
16477 let depth_arg = format!("--bit-depth={bit_depth}");
16478 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
16479 let tx_arg = format!("--enable-tx-size-search={tx_search}");
16480 let tile_arg = format!("--tile-columns={tile_cols}");
16481 let args: Vec<&str> = vec![
16482 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
16483 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
16484 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
16485 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
16486 "--lag-in-frames=0", "--kf-max-dist=9999", &tile_arg,
16487 // Per-arm overrides go LAST: aomenc keeps the last
16488 // occurrence of a repeated --enable-* flag.
16489 &tx_arg,
16490 "--enable-rect-partitions=1", "--enable-ab-partitions=1",
16491 "--enable-1to4-partitions=1", "--min-partition-size=4",
16492 "--max-partition-size=16",
16493 "--obu", "-o", "-", "-",
16494 ];
16495 let out = run_with_stdin(Command::new(aomenc_path())
16496 .args(&args), &y4m.stdout);
16497 assert!(
16498 out.status.success(),
16499 "aomenc refused the fixture: {}",
16500 String::from_utf8_lossy(&out.stderr)
16501 );
16502 let stream = out.stdout;
16503 let before = decode::inter16_rect4_counters();
16504 let leaf4_before = crate::stream::vartx_rect_leaf4_hits();
16505 let frames = match decode_stream(&stream) {
16506 Err(e) => {
16507 let msg = e.to_string();
16508 assert!(
16509 msg.contains("unsupported"),
16510 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
16511 attempt {attempt}): {msg}"
16512 );
16513 // lane-inter16ab r5: attempt 1 is the ONLY recipe in
16514 // r4's 100+ stream frame-aware sweep with an
16515 // inter-frame PARTITION_VERT_4. In r4 it refused on
16516 // the rect wedge codebook (lifted this round); it now
16517 // walks further and stops on rect RESIDUAL coding, a
16518 // refusal this lane does not own -- tracked so the
16519 // VERT_4 / split-tx arms can name their blocker
16520 // instead of silently reading 0.
16521 if msg.contains("needs rectangular residual coding") {
16522 rect_residual_refusals += 1;
16523 }
16524 named_refusals += 1;
16525 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
16526 continue;
16527 }
16528 Ok(frames) => frames,
16529 };
16530 let after = decode::inter16_rect4_counters();
16531 let leaf4_after = crate::stream::vartx_rect_leaf4_hits();
16532 // [16x4 strips, 4x16 strips, chroma pairs closed, chroma
16533 // pairs built from two strips' motion vectors].
16534 let fired = [
16535 after.0 - before.0,
16536 after.1 - before.1,
16537 after.2 - before.2,
16538 after.3 - before.3,
16539 // lane-inter16ab r4: the SPLIT-transform arm --
16540 // `sub_tx_size_map[TX_16X4] == TX_8X4`, so a 1:4 strip
16541 // that splits its transform codes 8x4/4x8 RECTANGULAR
16542 // var-tx leaves (`--enable-tx-size-search=1`).
16543 (leaf4_after[0] - leaf4_before[0]) + (leaf4_after[1] - leaf4_before[1]),
16544 ];
16545 let ffmpeg_frames = if bit_depth == 10 {
16546 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
16547 } else {
16548 ffmpeg_decode_sequence(&stream, width, height, frame_count)
16549 };
16550 assert_eq!(frames.len(), frame_count);
16551 let mismatched = frames
16552 .iter()
16553 .zip(&ffmpeg_frames)
16554 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16555 if fired[0] + fired[1] == 0 {
16556 out_of_scope += 1;
16557 if mismatched {
16558 oos_mismatch += 1;
16559 eprintln!(
16560 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
16561 16-level inter AB partition -- another shape's defect"
16562 );
16563 }
16564 continue;
16565 }
16566 if mismatched {
16567 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16568 let bad: Vec<usize> =
16569 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
16570 if !bad.is_empty() {
16571 eprintln!(
16572 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
16573 pixels differ, first at ({}, {}), max |delta| {}",
16574 bad.len(),
16575 bad[0] % width,
16576 bad[0] / width,
16577 bad.iter()
16578 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
16579 .max()
16580 .unwrap_or(0)
16581 );
16582 }
16583 }
16584 }
16585 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16586 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
16587 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
16588 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
16589 }
16590 for a in 0..5 {
16591 if fired[a] > 0 {
16592 arms_proved[a] += 1;
16593 arms_total[a] += 1;
16594 }
16595 }
16596 matched += 1;
16597 }
16598 eprintln!(
16599 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
16600 attempts carrying a 16-level inter 1:4 partition, per-arm attempts \
16601 HORZ_4/VERT_4/chroma-pair/sub8x8-chroma/split-tx-8x4={arms_proved:?}, {out_of_scope} attempts carried \
16602 none ({oos_mismatch} of them mismatched)"
16603 );
16604 assert_eq!(
16605 oos_mismatch, 0,
16606 "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter 1:4 partition decoded \
16607 but mismatched ffmpeg -- a defect of another shape, not a pass"
16608 );
16609 }
16610 // lane-t900 r36 (class [[gate-blind-to-feature]]): this counter was
16611 // incremented and never read. What it was there to prove is that the
16612 // VERT_4 / split-tx arms' blocker is still the rect-residual refusal.
16613 // It no longer is: `decode.rs`'s "a non-skip rectangular
16614 // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding" still
16615 // exists but is narrowed (lane-rectres + lane-inter4 +
16616 // lane-intrarect), and this sweep now reaches it ZERO times at either
16617 // depth -- attempt 1, the one recipe r5 recorded stopping there,
16618 // decodes. So the counter is reported and pinned at 0: a non-zero
16619 // reading means the refusal came back for this shape.
16620 eprintln!("{NAME}: rect-residual refusals over both depths: {rect_residual_refusals}");
16621 assert_eq!(
16622 rect_residual_refusals, 0,
16623 "{NAME}: {rect_residual_refusals} attempt(s) stopped on \"a non-skip rectangular \
16624 (HORZ/VERT/HORZ_B) strip needs rectangular residual coding\" -- that refusal was \
16625 lifted for this shape and must not block the VERT_4 / split-tx arms again"
16626 );
16627 // Arms 1/3/4 (HORZ_4, the odd-strip `is_chroma_reference` pair, the
16628 // `build_inter_predictors_sub8x8` two-mv chroma build) are proven
16629 // outright.
16630 for (a, what) in [
16631 (0usize, "HORZ_4 16x4 strips"),
16632 (2, "odd-strip chroma pairs"),
16633 (3, "sub8x8 two-mv chroma pairs"),
16634 ] {
16635 assert!(
16636 arms_total[a] > 0,
16637 "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \
16638 (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})"
16639 );
16640 }
16641 // lane-inter16ab r5, MEASURED reason for the other two arms: the only
16642 // recipe in r4's 100+ stream frame-aware sweep carrying an
16643 // inter-frame `PARTITION_VERT_4` is attempt 1, and in r4 it refused on
16644 // the rect wedge-interintra codebook. That refusal is LIFTED this
16645 // round -- the stream now walks past it and stops on "a non-skip
16646 // rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual
16647 // coding", a refusal this lane does not own. VERT_4 (and with it the
16648 // split-transform 8x4 leaf it feeds) is blocked on THAT, and the gate
16649 // asserts exactly that -- if rect residual coding lands and the arms
16650 // still read 0, or the blocker changes, this fails.
16651 assert!(
16652 arms_total[1] > 0,
16653 "{NAME}: the VERT_4 arm read 0 \
16654 (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})"
16655 );
16656 // lane-gaterecipe r1 -- the split-transform arm (index 4) is NOT
16657 // asserted, and this is the measured reason, not a weakening. Its old
16658 // escape hatch was "some attempt refused on rectangular residual
16659 // coding"; lane-rectres lifted that refusal, so the hatch closed and
16660 // the arm read 0. A ~40-recipe sweep (192x128 and 384x256, cq 8..50,
16661 // min-partition-size 4/8/16, both source orientations; script and
16662 // table in lanes/gaterecipe-r1.report.md) shows NO 192x128 recipe of
16663 // this shape ever makes aomenc split a 16x4/4x16 strip's transform --
16664 // an aomdec EC_TRACE_COEFF histogram of those streams carries whole
16665 // TX_16X4/TX_4X16 units and no sub-transform. The one recipe that DOES
16666 // split it (384x256 product texture, cq 10, --min-partition-size=8)
16667 // was RE-MEASURED by lane-vartxsplit r2 on the merged tree: that
16668 // stream now decodes PIXEL-EXACT on all six frames and fires ZERO
16669 // rectangular var-tx leaves of any size -- the "6 split-tx 8x4 leaves"
16670 // were counted out of an already-desynced decode (the desync is what
16671 // lane-sub8x4 fixed). r2 also swept THIS gate's own source family at
16672 // cq 46/56/63 (12 streams, both orientations, both motion steps,
16673 // --min-partition-size=4 --enable-tx-size-search=1): zero
16674 // TX_16X4/TX_4X16 split symbols in aomdec's EC_VARTX histogram, all 12
16675 // pixel-exact. What does split a 16x4/4x16 transform is the product
16676 // texture at --min-partition-size=4 (140 + 238 splits at cq 44), and
16677 // every such stream either stops at a refusal our own desync raises or
16678 // mismatches ffmpeg from decode-order frame 1 -- an open defect handed
16679 // off in lanes/vartxsplit-r2.report.md. So the arm stays
16680 // reported-unproven instead of asserted on a stream nobody has decoded
16681 // exactly.
16682 eprintln!(
16683 "{NAME}: split-tx-8x4 arm unproven (arms {arms_total:?}) -- no recipe of this \
16684 sweep produces a split 16x4/4x16 transform; see lanes/gaterecipe-r1.report.md"
16685 );
16686 }
16687
16688
16689 #[test]
16690 // Un-ignored 2026-09-04: the intra 16x4/4x16-in-inter refusal this recipe stopped at is gone and every arm now decodes pixel-exact.
16691 // lane-intra16x4 r1: an INTRA-coded 16x4 / 4x16 strip inside an INTER
16692 // frame's 16x16-level 1:4 partition -- the wall all six of his film cuts
16693 // stopped at once lane-rectres landed. The shape's chroma is the pair's:
16694 // `is_chroma_reference` (av1_common_int.h:1454) is false on the even
16695 // strips (which read no `uv_mode` and code no chroma at all) and the odd
16696 // one codes ONE 8x4 (4x8) chroma unit at the pair's origin -- and when the
16697 // pair mixes an intra and an inter strip, the chroma is predicted per the
16698 // strip that CARRIES it, which is exactly what routing the intra strip
16699 // through the key frame's own proven per-strip body
16700 // (`decode_rect4_16_strip`) gives.
16701 //
16702 // Recipes found by a 24 + 24 run sweep (three sources x cq 16..63 x two
16703 // sizes, `~/.cache/intra16x4-tmp/sweep*.sh`): aomenc only picks an INTRA
16704 // 1:4 strip on an inter frame at HIGH cq over content its MC cannot
16705 // predict -- a per-frame-random bright bar sweeping the frame (HORZ_4
16706 // strips) and a `X*Y` product sinusoid under temporal noise (VERT_4).
16707 // Both sources hash identically twice (report).
16708 fn a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact() {
16709 const NAME: &str =
16710 "a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact";
16711 let _gate_lock = lock_gate_counters();
16712 if !have_ffmpeg() {
16713 eprintln!("SKIP {NAME}: no ffmpeg");
16714 return;
16715 }
16716 if !have_aomenc() {
16717 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16718 return;
16719 }
16720 let frame_count = 6usize;
16721 // (source kind, cq, width, height) -- the four recipes of the 48-run
16722 // sweep (`~/.cache/intra16x4-tmp/sweep*.sh`, table in the report) that
16723 // reach an INTRA 1:4 strip on an inter frame. `bar` is a per-frame
16724 // random bright bar sweeping the frame (its MC failure is what makes
16725 // aomenc's RD pick intra at 16x4), `prod` an `X*Y` product sinusoid
16726 // under temporal noise; `_v` transposes the structure so the RD picks
16727 // PARTITION_VERT_4.
16728 // lane-intra16x4 r2: the last field is `--min-partition-size` -- the
16729 // `bar_h` recipe (a horizontal bar sweeping DOWN the frame) at
16730 // `--min-partition-size=8` is the one recipe of the r2 96-run sweep
16731 // (`~/.cache/intra16x4-tmp/sweep_r2.sh`) that fires intra 16x4 strips
16732 // WITHOUT also carrying the sub-8x8 intra block another lane refuses,
16733 // so it is the arm that can be pixel-compared at all.
16734 const RECIPES: [(&str, u32, usize, usize, u32); 5] = [
16735 ("noise", 60, 128, 128, 4),
16736 ("bar", 60, 192, 128, 4),
16737 ("prod_v", 56, 128, 128, 4),
16738 ("prod", 56, 160, 128, 4),
16739 ("bar_h", 63, 192, 128, 8),
16740 ];
16741 // [16x4 intra strips, 4x16 intra strips, of which chroma-reference]:
16742 // how many pixel-exact attempts fired each, over both bit depths.
16743 let mut arms_total = [0u32; 3];
16744 // Attempts that refused on the sub-8x8 intra block inside an inter
16745 // frame -- a DIFFERENT lane's shape, and the measured blocker of every
16746 // VERT_4-carrying recipe in the sweep.
16747 let mut sub8_intra_refusals = 0u32;
16748 // Every failure the sweep sees, asserted ONCE at the end.
16749 let mut failures: Vec<String> = Vec::new();
16750 // Per bit depth: attempts that decoded at all, and attempts that fired an
16751 // intra 1:4 strip AND compared pixel-exact.
16752 let mut decoded_per_depth = [0u32; 2];
16753 let mut fired_exact_per_depth = [0u32; 2];
16754 for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() {
16755 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
16756 (0u32, 0u32, 0u32, 0u32);
16757 let mut arms_proved = [0u32; 3];
16758 for attempt in 0..RECIPES.len() as u32 {
16759 let (kind, cq, width, height, min_part) = RECIPES[attempt as usize];
16760 let duration = frame_count as f64 / 25.0;
16761 // Both sources are deterministic (two identical y4m hashes,
16762 // report): `random()` here is geq's own indexed PRNG and the
16763 // noise filter carries an explicit `all_seed`.
16764 let (lum, noise) = match kind {
16765 "noise" => (
16766 format!("128+58*sin((X+N*3)/6)+40*sin(Y/11)"),
16767 ",noise=alls=40:allf=t+u:all_seed=7",
16768 ),
16769 "bar" => (
16770 format!(
16771 "if(lt(mod(X+N*37,{width}),24),random(N*100+X+Y)*255,128+50*sin(Y/7))"
16772 ),
16773 "",
16774 ),
16775 "bar_h" => (
16776 format!(
16777 "if(lt(mod(Y+N*37,{height}),24),random(N*100+X+Y)*255,128+50*sin(X/7))"
16778 ),
16779 "",
16780 ),
16781 "prod_v" => (
16782 "128+60*sin((X*Y+N*97)/13)+50*sin((Y+N*11)/5)".to_string(),
16783 ",noise=alls=25:allf=t:all_seed=11",
16784 ),
16785 _ => (
16786 "128+60*sin((X*Y+N*97)/13)+50*sin((X+N*11)/5)".to_string(),
16787 ",noise=alls=25:allf=t:all_seed=11",
16788 ),
16789 };
16790 let source = format!(
16791 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
16792 geq=lum='{lum}',format=yuv420p{noise}"
16793 );
16794 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
16795 let y4m = Command::new("ffmpeg")
16796 .args([
16797 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
16798 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
16799 ])
16800 .stdin(Stdio::null())
16801 .stdout(Stdio::piped())
16802 .stderr(Stdio::piped())
16803 .output()
16804 .expect("ffmpeg failed to run");
16805 assert!(
16806 y4m.status.success(),
16807 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
16808 String::from_utf8_lossy(&y4m.stderr)
16809 );
16810 let cq_arg = format!("--cq-level={cq}");
16811 let min_part_arg = format!("--min-partition-size={min_part}");
16812 let depth_arg = format!("--bit-depth={bit_depth}");
16813 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
16814 let args: Vec<&str> = vec![
16815 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
16816 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
16817 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
16818 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
16819 "--lag-in-frames=0", "--kf-max-dist=9999", "--tile-columns=0",
16820 // Per-arm overrides go LAST (aomenc keeps the last
16821 // occurrence of a repeated --enable-* flag).
16822 "--enable-tx-size-search=1", "--enable-rect-partitions=1",
16823 "--enable-ab-partitions=1", "--enable-1to4-partitions=1",
16824 "--enable-intra-edge-filter=1",
16825 &min_part_arg, "--max-partition-size=16",
16826 "--obu", "-o", "-", "-",
16827 ];
16828 let out = run_with_stdin(Command::new(aomenc_path())
16829 .args(&args), &y4m.stdout);
16830 assert!(
16831 out.status.success(),
16832 "aomenc refused the fixture: {}",
16833 String::from_utf8_lossy(&out.stderr)
16834 );
16835 let stream = out.stdout;
16836 let before = crate::stream::intra16x4_in_inter_hits();
16837 let frames = match decode_stream(&stream) {
16838 Err(e) => {
16839 let msg = e.to_string();
16840 // lane-intra16x4 r3: the ONLY refusals the 120-run sweep
16841 // (`~/.cache/intra16x4-tmp/sweep_r3.sh`, table in the
16842 // report) reaches over these recipes -- each another
16843 // lane's shape. A refusal outside this list is a new wall
16844 // and fails the gate rather than being counted.
16845 const MEASURED_REFUSALS: [&str; 3] = [
16846 "an intra 8x4/4x8 block inside an inter frame's sub-8x8 HORZ/VERT partition",
16847 "an intra 4x4 block inside an inter frame's sub-8x8 split",
16848 "an OBMC neighbour whose switchable interp filter was never recorded",
16849 ];
16850 if !MEASURED_REFUSALS.iter().any(|r| msg.contains(r)) {
16851 failures.push(format!(
16852 "{bit_depth}-bit attempt {attempt}: refusal outside the measured \
16853 list: {msg}"
16854 ));
16855 continue;
16856 }
16857 if msg.contains("sub-8x8") {
16858 sub8_intra_refusals += 1;
16859 }
16860 named_refusals += 1;
16861 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
16862 continue;
16863 }
16864 Ok(frames) => frames,
16865 };
16866 decoded_per_depth[depth_idx] += 1;
16867 let after = crate::stream::intra16x4_in_inter_hits();
16868 let fired = [
16869 (after.0 - before.0) as u32,
16870 (after.1 - before.1) as u32,
16871 (after.2 - before.2) as u32,
16872 ];
16873 let ffmpeg_frames = if bit_depth == 10 {
16874 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
16875 } else {
16876 ffmpeg_decode_sequence(&stream, width, height, frame_count)
16877 };
16878 assert_eq!(frames.len(), frame_count);
16879 let mismatched = frames
16880 .iter()
16881 .zip(&ffmpeg_frames)
16882 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
16883 if fired[0] + fired[1] == 0 {
16884 out_of_scope += 1;
16885 if mismatched {
16886 oos_mismatch += 1;
16887 eprintln!(
16888 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
16889 intra 1:4 strip -- another shape's defect"
16890 );
16891 }
16892 continue;
16893 }
16894 if mismatched {
16895 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16896 let bad: Vec<usize> =
16897 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
16898 if !bad.is_empty() {
16899 eprintln!(
16900 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
16901 pixels differ, first at ({}, {}), max |delta| {}",
16902 bad.len(),
16903 bad[0] % width,
16904 bad[0] / width,
16905 bad.iter()
16906 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
16907 .max()
16908 .unwrap_or(0)
16909 );
16910 }
16911 }
16912 }
16913 // lane-intra16x4 r3: continue-and-sweep -- a mismatching attempt is
16914 // RECORDED and the sweep goes on, so one arm's defect can no longer
16915 // hide every later arm (r2's attempt 0 panicked before arm 4 ran).
16916 // The end-of-sweep assert below fails on any recorded mismatch.
16917 if mismatched {
16918 failures.push(format!(
16919 "{bit_depth}-bit attempt {attempt} (arms {fired:?}) mismatched ffmpeg"
16920 ));
16921 continue;
16922 }
16923 for a in 0..3 {
16924 if fired[a] > 0 {
16925 arms_proved[a] += 1;
16926 arms_total[a] += 1;
16927 }
16928 }
16929 matched += 1;
16930 fired_exact_per_depth[depth_idx] += 1;
16931 }
16932 eprintln!(
16933 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
16934 attempts carrying an intra 1:4 strip, per-arm attempts \
16935 16x4/4x16/chroma-reference={arms_proved:?}, {out_of_scope} attempts carried none \
16936 ({oos_mismatch} of them mismatched)"
16937 );
16938 if oos_mismatch > 0 {
16939 failures.push(format!(
16940 "{bit_depth}-bit: {oos_mismatch} attempt(s) with no intra 1:4 strip decoded \
16941 but mismatched ffmpeg -- another shape's defect, not a pass"
16942 ));
16943 }
16944 }
16945 assert!(
16946 failures.is_empty(),
16947 "{NAME}: {} sweep failure(s): {failures:#?}",
16948 failures.len()
16949 );
16950 // The counter must have fired on a pixel-exact attempt at every bit depth
16951 // the sweep actually decoded at.
16952 for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() {
16953 assert!(
16954 decoded_per_depth[depth_idx] == 0 || fired_exact_per_depth[depth_idx] > 0,
16955 "{NAME}: {bit_depth}-bit decoded {} attempt(s) but none of them fired an intra \
16956 1:4 strip on a pixel-exact compare",
16957 decoded_per_depth[depth_idx]
16958 );
16959 }
16960 // MEASURED (48-run sweep, report table): every recipe that makes
16961 // aomenc pick an intra PARTITION_VERT_4 strip ALSO contains an intra
16962 // 8x4/4x8 or 4x4 block inside a sub-8x8 partition, a refusal this lane
16963 // does not own -- so the 4x16 orientation is blocked on THAT and the
16964 // gate asserts exactly that. If the sub-8x8 lane lands and this arm
16965 // still reads 0, or the blocker changes, this fails.
16966 assert!(
16967 arms_total[1] > 0 || sub8_intra_refusals > 0,
16968 "{NAME}: the 4x16 (PARTITION_VERT_4) arm read 0 \
16969 (16x4/4x16/chroma-reference={arms_total:?}) and NO attempt refused on the sub-8x8 \
16970 intra block -- its documented blocker is gone, so a zero arm is now unexplained"
16971 );
16972 for (a, what) in [
16973 (0usize, "intra 16x4 strips (PARTITION_HORZ_4)"),
16974 (2, "chroma-reference (odd) intra strips carrying the pair's 8x4/4x8 chroma"),
16975 ] {
16976 assert!(
16977 arms_total[a] > 0,
16978 "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \
16979 (16x4/4x16/chroma-reference={arms_total:?}) -- unproven"
16980 );
16981 }
16982 }
16983
16984
16985 #[test]
16986 // lane-sbab r1: the SUPERBLOCK-level (64x64) AB partitions on an INTER
16987 // frame -- PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 64x64, i.e. two
16988 // 32x32 inter squares plus one true 64x32/32x64 inter strip, decoded in
16989 // libaom `decode_partition`'s visit order. Every decode-order frame is
16990 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
16991 // out-of-scope mismatches fail the gate, and EACH of the four arms must
16992 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
16993 // proof of four). `--min-partition-size=32` keeps every AB piece at or
16994 // above 32x32, `--max-partition-size=64` puts the AB symbol at the SB
16995 // root, and `--enable-1to4-partitions=0` because the 64-level 1:4 pair is
16996 // a different lane's shape.
16997 fn a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact() {
16998 const NAME: &str =
16999 "a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact";
17000 let _gate_lock = lock_gate_counters();
17001 if !have_ffmpeg() {
17002 eprintln!("SKIP {NAME}: no ffmpeg");
17003 return;
17004 }
17005 if !have_aomenc() {
17006 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17007 return;
17008 }
17009 let (width, height, frame_count) = (256usize, 192usize, 6usize);
17010 // Per arm, over both bit depths: how many pixel-exact attempts fired
17011 // it at least once.
17012 let mut arms_total = [0u32; 4];
17013 for bit_depth in [8u32, 10u32] {
17014 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
17015 (0u32, 0u32, 0u32, 0u32);
17016 let mut arms_proved = [0u32; 4];
17017 for attempt in 0..20u32 {
17018 // Axes measured live by the r1 sweep
17019 // (~/.cache/sbab-tmp/sweep.sh, table in the report): two
17020 // motion steps x two source orientations x five quantisers x
17021 // a single-tile and a two-tile-column arm. All four arms
17022 // appear in that table at both depths; no single (sp, shape,
17023 // cq) point carries more than three of them, which is why the
17024 // sweep is this wide.
17025 let cq = [18, 26, 34, 45, 55][(attempt % 5) as usize];
17026 let natural = attempt / 5 % 2 == 1;
17027 let sp = if attempt / 10 % 2 == 0 { 3 } else { 8 };
17028 // r1: a `--tile-columns=1` twin of these 20 attempts was run
17029 // and is deliberately NOT in the gate -- its streams PANIC in
17030 // `mc::from_switchable_symbol` (a 4th symbol out of a
17031 // 3-symbol alphabet), the exact signature lane-inter16ab r1
17032 // recorded for its own tiled arm and which the ledger pins to
17033 // the below-8x8 inter leaf, not to anything this lane
17034 // touches. Recorded as open residue in
17035 // lanes/sbab-r1.report.md rather than turned into a SKIP or a
17036 // weakened assert.
17037 let tile_cols = "0";
17038 let duration = frame_count as f64 / 25.0;
17039 // Long-period continuous tone: the 64-level AB partitions
17040 // need the L/T-shaped feature to span 32 px, so the sinusoid
17041 // periods here are ~3x the 16-level gate's.
17042 let lum = if natural {
17043 format!("128+58*sin((Y+N*{sp})/17)+40*sin(X/29)+20*sin((X+Y)/13)")
17044 } else {
17045 format!("128+58*sin((X+N*{sp})/17)+40*sin(Y/29)+20*sin((X-Y)/13)")
17046 };
17047 let source = format!(
17048 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
17049 geq=lum='{lum}',format=yuv420p"
17050 );
17051 let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
17052 let y4m = Command::new("ffmpeg")
17053 .args([
17054 "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
17055 "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
17056 ])
17057 .stdin(Stdio::null())
17058 .stdout(Stdio::piped())
17059 .stderr(Stdio::piped())
17060 .output()
17061 .expect("ffmpeg failed to run");
17062 assert!(
17063 y4m.status.success(),
17064 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
17065 String::from_utf8_lossy(&y4m.stderr)
17066 );
17067 let cq_arg = format!("--cq-level={cq}");
17068 let depth_arg = format!("--bit-depth={bit_depth}");
17069 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
17070 let tile_arg = format!("--tile-columns={tile_cols}");
17071 let args: Vec<&str> = vec![
17072 "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
17073 "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
17074 "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
17075 "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
17076 "--lag-in-frames=0", "--kf-max-dist=9999", &tile_arg,
17077 // Per-arm overrides go LAST: aomenc keeps the last
17078 // occurrence of a repeated --enable-* flag.
17079 "--enable-rect-partitions=1", "--enable-ab-partitions=1",
17080 "--enable-1to4-partitions=0", "--min-partition-size=32",
17081 "--max-partition-size=64",
17082 "--obu", "-o", "-", "-",
17083 ];
17084 let out = run_with_stdin(Command::new(aomenc_path())
17085 .args(&args), &y4m.stdout);
17086 assert!(
17087 out.status.success(),
17088 "aomenc refused the fixture: {}",
17089 String::from_utf8_lossy(&out.stderr)
17090 );
17091 let stream = out.stdout;
17092 let before = decode::sb_ab_inter_hits_by_arm();
17093 let frames = match decode_stream(&stream) {
17094 Err(e) => {
17095 let msg = e.to_string();
17096 assert!(
17097 msg.contains("unsupported"),
17098 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
17099 attempt {attempt}): {msg}"
17100 );
17101 named_refusals += 1;
17102 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
17103 continue;
17104 }
17105 Ok(frames) => frames,
17106 };
17107 let after = decode::sb_ab_inter_hits_by_arm();
17108 let fired: Vec<usize> = (0..4).map(|a| after[a] - before[a]).collect();
17109 let ffmpeg_frames = if bit_depth == 10 {
17110 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
17111 } else {
17112 ffmpeg_decode_sequence(&stream, width, height, frame_count)
17113 };
17114 assert_eq!(frames.len(), frame_count);
17115 let mismatched = frames
17116 .iter()
17117 .zip(&ffmpeg_frames)
17118 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17119 if fired.iter().sum::<usize>() == 0 {
17120 out_of_scope += 1;
17121 if mismatched {
17122 oos_mismatch += 1;
17123 eprintln!(
17124 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
17125 64-level inter AB partition -- another shape's defect"
17126 );
17127 }
17128 continue;
17129 }
17130 if mismatched {
17131 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17132 let bad: Vec<usize> =
17133 (0..got.y.len()).filter(|&k| got.y[k] != want.y[k]).collect();
17134 if !bad.is_empty() {
17135 eprintln!(
17136 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
17137 pixels differ, first at ({}, {}), max |delta| {}",
17138 bad.len(),
17139 bad[0] % width,
17140 bad[0] / width,
17141 bad.iter()
17142 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
17143 .max()
17144 .unwrap_or(0)
17145 );
17146 }
17147 }
17148 }
17149 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17150 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
17151 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
17152 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})");
17153 }
17154 for a in 0..4 {
17155 if fired[a] > 0 {
17156 arms_proved[a] += 1;
17157 arms_total[a] += 1;
17158 }
17159 }
17160 matched += 1;
17161 }
17162 eprintln!(
17163 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
17164 attempts carrying a 64-level inter AB partition, per-arm attempts \
17165 HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \
17166 none ({oos_mismatch} of them mismatched)"
17167 );
17168 assert_eq!(
17169 oos_mismatch, 0,
17170 "{NAME}: {oos_mismatch} attempt(s) with no 64-level inter AB partition decoded \
17171 but mismatched ffmpeg -- a defect of another shape, not a pass"
17172 );
17173 }
17174 assert!(
17175 arms_total.iter().all(|&n| n > 0),
17176 "{NAME}: not every 64-level inter AB arm fired on a pixel-exact attempt \
17177 (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven"
17178 );
17179 }
17180
17181 #[test]
17182 fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() {
17183 if !have_ffmpeg() {
17184 eprintln!(
17185 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no ffmpeg"
17186 );
17187 return;
17188 }
17189 if !have_aomenc() {
17190 eprintln!(
17191 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no aomenc at {}",
17192 aomenc_path().display()
17193 );
17194 return;
17195 }
17196 let (width, height, frame_count) = (64usize, 64usize, 4usize);
17197 let source = gradients_source(42, width, height, "duration=0.16:rate=25");
17198 let y4m = Command::new("ffmpeg")
17199 .args(["-v", "error", "-f", "lavfi", "-i"])
17200 .arg(&source)
17201 .args([
17202 "-pix_fmt",
17203 "yuv420p",
17204 "-f",
17205 "yuv4mpegpipe",
17206 "-",
17207 ])
17208 .stdin(Stdio::null())
17209 .stdout(Stdio::piped())
17210 .stderr(Stdio::piped())
17211 .output()
17212 .expect("ffmpeg failed to run");
17213 assert!(
17214 y4m.status.success(),
17215 "ffmpeg fixture: {}",
17216 String::from_utf8_lossy(&y4m.stderr)
17217 );
17218 let out = run_with_stdin(Command::new(aomenc_path())
17219 .args([
17220 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
17221 // occurrence, so overrides go before the base list).
17222 "--loopfilter-control=1",
17223 "--codec=av1",
17224 "--passes=1",
17225 "--end-usage=q",
17226 "--cq-level=55",
17227 "--cpu-used=0",
17228 "--lag-in-frames=0",
17229 "--auto-alt-ref=0",
17230 "--kf-max-dist=1000",
17231 // Forces `primary_ref_frame = PRIMARY_REF_NONE` on every
17232 // frame (spec 5.9.2): without it a real encoder's inter
17233 // frame loads its initial CDF state from the previous
17234 // frame's *adapted* tables (spec 7.20's `load_cdfs`), which
17235 // this decoder never does -- it always starts each frame's
17236 // `Cdfs` from the spec defaults (`decode.rs`'s
17237 // `Cdfs::new(q_ctx)`, called fresh per frame in
17238 // `decode_stream`). Without this flag the inter frame's
17239 // very first symbol desyncs immediately (traced 2026-08-27:
17240 // no coefficient trace at all before the tile's first
17241 // partition read comes back an out-of-alphabet value). A
17242 // real decoder needs cross-frame CDF forwarding to handle
17243 // that stream; this fixture sidesteps it the same way a
17244 // real broadcast/low-latency encode legitimately can.
17245 "--error-resilient=1",
17246 "--enable-rect-partitions=0",
17247 "--enable-ab-partitions=0",
17248 "--enable-1to4-partitions=0",
17249 "--enable-filter-intra=0",
17250 "--enable-smooth-intra=0",
17251 "--enable-paeth-intra=0",
17252 "--enable-directional-intra=0",
17253 "--enable-angle-delta=0",
17254 "--enable-tx-size-search=0",
17255 "--enable-cdef=0",
17256 // Loop restoration is a named refusal (aomenc's RD picks
17257 // Sgrproj on this kind of content) -- off in every recipe
17258 // whose test targets a different surface.
17259 "--enable-restoration=0",
17260 "--max-partition-size=32",
17261 "--enable-palette=0",
17262 "--enable-intrabc=0",
17263 "--enable-cfl-intra=0",
17264 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
17265 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
17266 "--enable-ref-frame-mvs=0",
17267 "--obu",
17268 "-o",
17269 "-",
17270 "-",
17271 ]), &y4m.stdout);
17272 assert!(
17273 out.status.success(),
17274 "aomenc refused the fixture: {}",
17275 String::from_utf8_lossy(&out.stderr)
17276 );
17277 let stream = out.stdout;
17278 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
17279 std::fs::write(dump, &stream).expect("dump stream");
17280 }
17281 let before = decode::deblock_hits();
17282 let frames = match decode_stream(&stream) {
17283 Ok(frames) => frames,
17284 Err(e) => {
17285 eprintln!(
17286 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: {e}"
17287 );
17288 return;
17289 }
17290 };
17291 assert!(
17292 decode::deblock_hits() > before,
17293 "no deblocking edge fired decoding this sequence -- raise cq-level"
17294 );
17295 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17296 assert_eq!(frames.len(), frame_count);
17297 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17298 // gradients' colors ignore its seed, so this gate encodes fresh
17299 // content every run -- a mismatch here may never reproduce.
17300 // Self-pin the stream before panicking so the failure is
17301 // bisectable (replay: EC_AV1_PIN on scratch_isolate_pinned_mismatch).
17302 let ok = got.y == want.y && got.u == want.u && got.v == want.v;
17303 if !ok {
17304 let pin = std::env::temp_dir().join("ec-av1-deblocking-gate-fail.obu");
17305 let _ = std::fs::write(&pin, &stream);
17306 panic!("frame {i} mismatch vs ffmpeg -- stream pinned at {}", pin.display());
17307 }
17308 }
17309 }
17310
17311 /// The decisive cross-frame CDF forwarding test: identical to
17312 /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`]
17313 /// except it drops `--error-resilient=1`, so aomenc codes every inter
17314 /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`)
17315 /// and expects the decoder to resume from the previous frame's *adapted*
17316 /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding,
17317 /// frame 1's very first tile symbol desyncs (an out-of-alphabet
17318 /// partition read); with it, every frame decodes pixel-exact.
17319 #[test]
17320 fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() {
17321 if !have_ffmpeg() {
17322 eprintln!(
17323 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg"
17324 );
17325 return;
17326 }
17327 if !have_aomenc() {
17328 eprintln!(
17329 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}",
17330 aomenc_path().display()
17331 );
17332 return;
17333 }
17334 let (width, height, frame_count) = (64usize, 64usize, 4usize);
17335 // The fixture's content varies run to run (lavfi gradients ignores its
17336 // seed option for the c0..c7 colors -- they default to "random"), so:
17337 // most encodes of this recipe trip one of the decoder's NAMED round-2
17338 // refusals (a reference other than LAST_FRAME, a sub-16 partition --
17339 // genuine coverage gaps, separately documented), and only some produce
17340 // a stream fully inside this decoder's declared support. So: attempt
17341 // several seeds, and the first stream that DECODES must be pixel-exact
17342 // -- that assertion is what guards the forwarded-CDF state (a wrong
17343 // table decodes plausible-but-wrong pixels; the counter-reset bug this
17344 // gate caught did exactly that). Exhausting every attempt on named
17345 // refusals skips loudly, listing them.
17346 let mut refusals = Vec::new();
17347 for attempt in 0..8u32 {
17348 let seed = 42 + attempt;
17349 let source = gradients_source(seed, 64, 64, "duration=0.16:rate=25");
17350 let y4m = Command::new("ffmpeg")
17351 .args([
17352 "-v",
17353 "error",
17354 "-f",
17355 "lavfi",
17356 "-i",
17357 &source,
17358 "-pix_fmt",
17359 "yuv420p",
17360 "-f",
17361 "yuv4mpegpipe",
17362 "-",
17363 ])
17364 .stdin(Stdio::null())
17365 .stdout(Stdio::piped())
17366 .stderr(Stdio::piped())
17367 .output()
17368 .expect("ffmpeg failed to run");
17369 assert!(
17370 y4m.status.success(),
17371 "ffmpeg fixture: {}",
17372 String::from_utf8_lossy(&y4m.stderr)
17373 );
17374 // lane-cdfflake: hard length check on the y4m fixture itself --
17375 // a truncated/racing ffmpeg write would otherwise surface as a
17376 // downstream pixel mismatch indistinguishable from a real decode
17377 // defect. y4m frames are `FRAME\n` (6 bytes) + raw 4:2:0 payload;
17378 // find the header/frame-data boundary at the first `FRAME` marker
17379 // rather than parsing the header fields (duration/rate can move
17380 // the header text length without moving the frame math).
17381 let marker_at = y4m
17382 .stdout
17383 .windows(5)
17384 .position(|w| w == b"FRAME")
17385 .expect("y4m stream missing FRAME marker");
17386 let frame_420_bytes = width * height * 3 / 2;
17387 assert_eq!(
17388 y4m.stdout.len(),
17389 marker_at + frame_count * (6 + frame_420_bytes),
17390 "y4m fixture length mismatch (seed {seed})"
17391 );
17392 let y4m_hash = fnv1a64(&y4m.stdout);
17393 let out = run_with_stdin(Command::new(aomenc_path())
17394 .args([
17395 "--codec=av1",
17396 "--passes=1",
17397 "--end-usage=q",
17398 "--cq-level=55",
17399 "--cpu-used=0",
17400 "--lag-in-frames=0",
17401 "--auto-alt-ref=0",
17402 "--kf-max-dist=1000",
17403 // `--threads=1` (not the default): a multithreaded RD search
17404 // makes aomenc's screen-content-tools heuristic race (seen
17405 // flaky under `cargo test`'s own parallelism -- the same
17406 // fixture, same seed, occasionally sets
17407 // `allow_screen_content_tools`, a round-2 gap unrelated to
17408 // CDF forwarding), so pin it to one thread for a
17409 // deterministic header.
17410 "--threads=1",
17411 "--row-mt=0",
17412 // `--enable-order-hint=0` kills BWDREF/ALTREF entirely (no
17413 // order hints -> no bidirectional distance weighting) and,
17414 // combined with `--auto-alt-ref=0`/`--lag-in-frames=0`
17415 // above, leaves aomenc's RD search only LAST_FRAME/
17416 // LAST2_FRAME/LAST3_FRAME/GOLDEN_FRAME to pick from --
17417 // GOLDEN itself needs no order hint (it is the keyframe's
17418 // fixed slot, not a distance-weighted reference), so this
17419 // does not suppress GOLDEN selection the way the sibling
17420 // CDF-forwarding gate's own comment worried about; it just
17421 // narrows the pool this gate needs GOLDEN to win out of.
17422 "--enable-order-hint=0",
17423 "--enable-warped-motion=0",
17424 "--enable-obmc=0",
17425 "--enable-masked-comp=0",
17426 "--enable-interintra-comp=0",
17427 "--enable-dist-wtd-comp=0",
17428 "--enable-diff-wtd-comp=0",
17429 "--enable-onesided-comp=0",
17430 "--enable-interintra-wedge=0",
17431 "--enable-smooth-interintra=0",
17432 "--enable-rect-partitions=0",
17433 "--enable-ab-partitions=0",
17434 "--enable-1to4-partitions=0",
17435 "--enable-filter-intra=0",
17436 "--enable-smooth-intra=0",
17437 "--enable-paeth-intra=0",
17438 "--enable-directional-intra=0",
17439 "--enable-angle-delta=0",
17440 "--enable-tx-size-search=0",
17441 "--enable-cdef=0",
17442 // Loop restoration is a named refusal (aomenc's RD picks
17443 // Sgrproj on this kind of content) -- off in every recipe
17444 // whose test targets a different surface.
17445 "--enable-restoration=0",
17446 "--max-partition-size=32",
17447 "--enable-palette=0",
17448 "--enable-intrabc=0",
17449 "--enable-cfl-intra=0",
17450 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
17451 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
17452 "--enable-ref-frame-mvs=0",
17453 "--obu",
17454 "-o",
17455 "-",
17456 "-",
17457 ]), &y4m.stdout);
17458 assert!(
17459 out.status.success(),
17460 "aomenc refused the fixture: {}",
17461 String::from_utf8_lossy(&out.stderr)
17462 );
17463 let stream = out.stdout;
17464 let stream_hash = fnv1a64(&stream);
17465 // A named `unsupported` refusal is a documented coverage gap (each
17466 // one carries its own test debt elsewhere), not a forwarding verdict
17467 // -- try the next seed. Any stream that DECODES must be pixel-exact,
17468 // and any non-refusal error is a hard failure.
17469 let frames = match decode_stream(&stream) {
17470 Err(e) => {
17471 let msg = e.to_string();
17472 assert!(
17473 msg.contains("unsupported"),
17474 "cross-frame CDF forwarding failed outright (seed {seed}): {msg}"
17475 );
17476 refusals.push(format!("seed {seed}: {msg}"));
17477 continue;
17478 }
17479 Ok(frames) => frames,
17480 };
17481 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17482 assert_eq!(frames.len(), frame_count);
17483 // lane-cdfflake: reconstruct ffmpeg's raw reference bytes (the
17484 // three per-frame slices are contiguous chunks of the raw
17485 // `-f rawvideo` output ffmpeg_decode_sequence sliced, so
17486 // concatenating them back is bit-for-bit the same bytes ffmpeg
17487 // actually produced -- no second ffmpeg invocation needed).
17488 let ffmpeg_raw: Vec<u8> = ffmpeg_frames
17489 .iter()
17490 .flat_map(|p| p.y.iter().chain(&p.u).chain(&p.v).map(|&v| v as u8))
17491 .collect();
17492 let ffmpeg_raw_hash = fnv1a64(&ffmpeg_raw);
17493 eprintln!(
17494 "cdfflake attempt seed={seed}: y4m_hash={y4m_hash:016x} \
17495 stream_hash={stream_hash:016x} ffmpeg_raw_hash={ffmpeg_raw_hash:016x}"
17496 );
17497 // lane-av1golden3: pin the exact raw stream on the first mismatch
17498 // so a flaky-looking gate failure becomes a deterministic, static
17499 // fixture to bisect against -- env-gated, no cost on a normal run.
17500 let mismatched = frames
17501 .iter()
17502 .zip(&ffmpeg_frames)
17503 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17504 if mismatched {
17505 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
17506 std::fs::write(&path, &stream).expect("writing pinned stream");
17507 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
17508 }
17509 // lane-cdfflake: unconditional pin on mismatch -- the aomenc
17510 // stream AND ffmpeg's raw reference bytes, so a flake caught
17511 // under load names the liar (stream bytes differ from a
17512 // clean rerun -> subprocess instability; reference bytes
17513 // differ -> ffmpeg instability; both stable -> real decode
17514 // defect) without relying on the env var being set.
17515 // The pin goes to `fixtures/`, which outlives the session: an
17516 // earlier version wrote to a session scratchpad, so once tmpfs
17517 // reaped it a real mismatch aborted on the write instead of
17518 // reporting itself. A failed write must not mask the assert
17519 // below either, so it warns rather than panicking.
17520 let sp = pin_dir();
17521 let stream_pin = sp.join(format!("cdfflake-stream-seed{seed}.bin"));
17522 let ref_pin = sp.join(format!("cdfflake-ffmpeg-raw-seed{seed}.bin"));
17523 for (path, bytes) in [(&stream_pin, &stream), (&ref_pin, &ffmpeg_raw)] {
17524 if let Err(e) = std::fs::write(path, bytes) {
17525 eprintln!("cdfflake: could not pin to {}: {e}", path.display());
17526 }
17527 }
17528 eprintln!(
17529 "cdfflake MISMATCH seed={seed}: pinned stream + ffmpeg reference to {}",
17530 sp.display()
17531 );
17532 }
17533 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17534 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
17535 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
17536 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
17537 }
17538 return;
17539 }
17540 eprintln!(
17541 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: every \
17542 attempt hit a named refusal:\n{}",
17543 refusals.join("\n")
17544 );
17545 }
17546
17547 /// lane-av1golden3: reproduces the pinned mismatch bytes captured by
17548 /// `EC_AV1_GATE_DUMP=$SP/golden3-pin.obu` off
17549 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
17550 /// (seed 47, frame 1 U). Deterministic and static -- no aomenc/ffmpeg
17551 /// re-encode involved, only re-decodes the fixed bytes on disk, so it is
17552 /// `#[ignore]`d (the file only exists on this machine's scratchpad) but
17553 /// gives a fast red/green loop for the actual fix.
17554 #[test]
17555 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
17556 fn pinned_golden3_stream_decodes_pixel_exact() {
17557 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
17558 .map(std::path::PathBuf::from)
17559 .unwrap_or_else(|_| pin_dir().join("golden3-pin.obu"));
17560 let Ok(stream) = std::fs::read(&path) else {
17561 eprintln!(
17562 "SKIP pinned_golden3_stream_decodes_pixel_exact: no pinned bytes at {} \
17563 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
17564 path.display()
17565 );
17566 return;
17567 };
17568 if !have_ffmpeg() {
17569 eprintln!("SKIP pinned_golden3_stream_decodes_pixel_exact: no ffmpeg");
17570 return;
17571 }
17572 let frames = decode_stream(&stream).expect("pinned stream must decode");
17573 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
17574 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17575 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
17576 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
17577 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
17578 }
17579 }
17580
17581 /// lane-av1golden4: reproduces the pinned mismatch bytes captured by
17582 /// `EC_AV1_GATE_DUMP=$SP/golden4-pin.obu` off
17583 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
17584 /// (seed 43, frame 3 luma) the round the GOLDEN mask lifted. Deterministic
17585 /// and static -- `#[ignore]`d, run manually.
17586 #[test]
17587 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
17588 fn pinned_golden4_stream_decodes_pixel_exact() {
17589 use crate::decode::non_last_ref_hits;
17590 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
17591 .map(std::path::PathBuf::from)
17592 .unwrap_or_else(|_| pin_dir().join("golden4-pin.obu"));
17593 let Ok(stream) = std::fs::read(&path) else {
17594 eprintln!(
17595 "SKIP pinned_golden4_stream_decodes_pixel_exact: no pinned bytes at {} \
17596 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
17597 path.display()
17598 );
17599 return;
17600 };
17601 if !have_ffmpeg() {
17602 eprintln!("SKIP pinned_golden4_stream_decodes_pixel_exact: no ffmpeg");
17603 return;
17604 }
17605 let before = non_last_ref_hits();
17606 let frames = decode_stream(&stream).expect("pinned stream must decode");
17607 eprintln!(
17608 "non_last_ref_hits before={before} after={}",
17609 non_last_ref_hits()
17610 );
17611 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
17612 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17613 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
17614 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
17615 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
17616 }
17617 }
17618
17619 /// lane-av1golden7 round 9: pins the residual GOLDEN_FRAME MC bug found
17620 /// by the forwarding gate once film grain is out of the way (1/20 real
17621 /// aomenc streams, frame 3 luma, apply_grain=false, `non_last_ref_hits`
17622 /// delta=2). `GOLDEN_FRAME` refuses by name until this decodes exact.
17623 #[test]
17624 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
17625 fn pinned_golden7_stream_decodes_pixel_exact() {
17626 use crate::decode::non_last_ref_hits;
17627 let path = concat!(
17628 env!("CARGO_MANIFEST_DIR"),
17629 "/../../fixtures/golden7-forwarding-mismatch.obu"
17630 );
17631 let stream = std::fs::read(path).expect("reading pinned stream");
17632 if !have_ffmpeg() {
17633 eprintln!("SKIP pinned_golden7_stream_decodes_pixel_exact: no ffmpeg");
17634 return;
17635 }
17636 let before = non_last_ref_hits();
17637 let frames = decode_stream(&stream).expect("pinned stream must decode");
17638 eprintln!(
17639 "non_last_ref_hits before={before} after={}",
17640 non_last_ref_hits()
17641 );
17642 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
17643 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17644 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
17645 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
17646 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
17647 }
17648 }
17649
17650 /// lane-av1refs's decisive single-non-LAST-reference gate: identical
17651 /// recipe to
17652 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
17653 /// except `--enable-order-hint=0` is DROPPED (that flag's own comment on
17654 /// the sibling test names it as exactly what suppresses aomenc's RD from
17655 /// ever picking `GOLDEN_FRAME`) and the sequence runs 8 frames, not 4 --
17656 /// more chances for the RD search to reach past the first GOP's initial
17657 /// key frame. `--auto-alt-ref=0` stays: this decoder only supports
17658 /// `LAST_FRAME`/`GOLDEN_FRAME` so far, and alt-ref/backward references
17659 /// are still a named refusal, not this gate's target. A stream that
17660 /// decodes without firing [`decode::non_last_ref_hits`] is not a
17661 /// coverage win for this round -- SKIP it as a genuine, named miss
17662 /// rather than pass silently on untested ground.
17663 #[test]
17664 fn a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact() {
17665 if !have_ffmpeg() {
17666 eprintln!(
17667 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no ffmpeg"
17668 );
17669 return;
17670 }
17671 if !have_aomenc() {
17672 eprintln!(
17673 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no aomenc at {}",
17674 aomenc_path().display()
17675 );
17676 return;
17677 }
17678 let (width, height, frame_count) = (64usize, 64usize, 8usize);
17679 let mut refusals = Vec::new();
17680 let mut never_fired = 0u32;
17681 // aomenc's own RD search is nondeterministic run-to-run even at
17682 // `--threads=1` (confirmed live: identical CLI args, identical
17683 // input, two different output byte streams) -- so beyond varying
17684 // the fixture's seed, each attempt is its own independent coin
17685 // flip against every named refusal below. 120 attempts (not 40)
17686 // to give that coin flip enough tries to land on a stream this
17687 // decoder both accepts and that fires GOLDEN_FRAME. `duration=0.32`
17688 // at `rate=25` (not `0.24`) matches every sibling gate's own
17689 // frame-count fixture exactly -- a shorter duration here once
17690 // produced a frame-0 (keyframe, no reference at all) luma mismatch
17691 // against ffmpeg, i.e. a source-frame-count rounding artifact of
17692 // this recipe's own choosing, not a decoder bug.
17693 for attempt in 0..120u32 {
17694 let seed = 42 + attempt % 40;
17695 let source = gradients_source(seed, 64, 64, "duration=0.32:rate=25");
17696 let y4m = Command::new("ffmpeg")
17697 .args([
17698 "-v",
17699 "error",
17700 "-f",
17701 "lavfi",
17702 "-i",
17703 &source,
17704 "-pix_fmt",
17705 "yuv420p",
17706 "-f",
17707 "yuv4mpegpipe",
17708 "-",
17709 ])
17710 .stdin(Stdio::null())
17711 .stdout(Stdio::piped())
17712 .stderr(Stdio::piped())
17713 .output()
17714 .expect("ffmpeg failed to run");
17715 assert!(
17716 y4m.status.success(),
17717 "ffmpeg fixture: {}",
17718 String::from_utf8_lossy(&y4m.stderr)
17719 );
17720 let out = run_with_stdin(Command::new(aomenc_path())
17721 .args([
17722 "--codec=av1",
17723 "--passes=1",
17724 "--end-usage=q",
17725 "--cq-level=55",
17726 "--cpu-used=0",
17727 "--lag-in-frames=0",
17728 "--auto-alt-ref=0",
17729 "--kf-max-dist=1000",
17730 "--threads=1",
17731 "--row-mt=0",
17732 // Narrows the RD search's reference alphabet toward
17733 // LAST_FRAME/GOLDEN_FRAME -- without this, aomenc's RD is
17734 // just as likely to pick LAST2/LAST3/BWDREF/ALTREF2/
17735 // ALTREF (this decoder's already-documented, still-open
17736 // refusals), starving this gate of the one reference it
17737 // targets.
17738 "--max-reference-frames=3",
17739 "--reduced-reference-set=1",
17740 "--enable-warped-motion=0",
17741 "--enable-obmc=0",
17742 "--enable-masked-comp=0",
17743 "--enable-interintra-comp=0",
17744 "--enable-dist-wtd-comp=0",
17745 "--enable-diff-wtd-comp=0",
17746 "--enable-onesided-comp=0",
17747 "--enable-interintra-wedge=0",
17748 "--enable-smooth-interintra=0",
17749 "--enable-rect-partitions=0",
17750 "--enable-ab-partitions=0",
17751 "--enable-1to4-partitions=0",
17752 "--enable-filter-intra=0",
17753 "--enable-smooth-intra=0",
17754 "--enable-paeth-intra=0",
17755 "--enable-directional-intra=0",
17756 "--enable-angle-delta=0",
17757 "--enable-tx-size-search=0",
17758 "--enable-cdef=0",
17759 "--enable-restoration=0",
17760 // `min == max == 32` forces PARTITION_NONE for every
17761 // 32x32 block, not just biases toward it -- with
17762 // `--min-partition-size=16` alone aomenc's exhaustive
17763 // `cpu-used=0` RD search still occasionally read HORZ/
17764 // VERT/SPLIT partitions below 32x32 despite
17765 // `--enable-rect-partitions=0`/`--enable-ab-partitions=0`/
17766 // `--enable-1to4-partitions=0` all being off (two
17767 // separate, already-documented round-2 gaps: "a
17768 // partition below 16x16", "a partition type this encoder
17769 // never writes"), starving this gate's already-narrow
17770 // seed pool. Locking both bounds to 32 removes any
17771 // partition-depth choice from the search entirely, so
17772 // this gate can isolate GOLDEN_FRAME selection alone.
17773 "--max-partition-size=32",
17774 "--min-partition-size=32",
17775 "--enable-palette=0",
17776 "--enable-intrabc=0",
17777 "--enable-cfl-intra=0",
17778 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
17779 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
17780 "--enable-ref-frame-mvs=0",
17781 // `--tune-content=film` was dropped: on this box it
17782 // makes aomenc emit `apply_grain` almost every attempt
17783 // (lane-av1golden8 round 10 measurement, live: 120/120
17784 // real attempts hit a named refusal, 0 ever fired
17785 // GOLDEN_FRAME -- mostly `apply_grain`, dominated by its
17786 // own recipe flag) -- film grain synthesis has its own
17787 // dedicated refusal test and must not starve this gate
17788 // of the GOLDEN_FRAME draws it exists to prove. Default
17789 // content tuning still occasionally flips
17790 // `allow_screen_content_tools` on for this synthetic
17791 // gradient content (a separate, already-documented open
17792 // refusal), which the 120-attempt coin flip below
17793 // tolerates the same way.
17794 "--obu",
17795 "-o",
17796 "-",
17797 "-",
17798 ]), &y4m.stdout);
17799 assert!(
17800 out.status.success(),
17801 "aomenc refused the fixture: {}",
17802 String::from_utf8_lossy(&out.stderr)
17803 );
17804 let stream = out.stdout;
17805 let before = decode::non_last_ref_hits();
17806 let frames = match decode_stream(&stream) {
17807 Err(e) => {
17808 let msg = e.to_string();
17809 assert!(
17810 msg.contains("unsupported"),
17811 "a golden-reference stream failed outright (seed {seed}): {msg}"
17812 );
17813 refusals.push(format!("seed {seed}: {msg}"));
17814 continue;
17815 }
17816 Ok(frames) => frames,
17817 };
17818 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
17819 // is ALWAYS pixel-compared below; the hit counter only decides whether
17820 // the attempt counts toward the firing total.
17821 // This seed's RD search may never have picked GOLDEN_FRAME -- a
17822 // genuine miss, not a refusal, and not a reason to skip the pixels.
17823 let counted = decode::non_last_ref_hits() != before;
17824 if !counted {
17825 never_fired += 1;
17826 }
17827 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17828 assert_eq!(frames.len(), frame_count);
17829 // Same pin-on-mismatch pattern as the CDF forwarding gate above:
17830 // env-gated, no cost on a normal run.
17831 let mismatched = frames
17832 .iter()
17833 .zip(&ffmpeg_frames)
17834 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17835 if mismatched {
17836 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
17837 std::fs::write(&path, &stream).expect("writing pinned stream");
17838 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
17839 }
17840 }
17841 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17842 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
17843 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
17844 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
17845 }
17846 if counted {
17847 eprintln!(
17848 "FIRING seed {seed}: non_last_ref_hits advanced by {}",
17849 decode::non_last_ref_hits() - before
17850 );
17851 gate_buckets(
17852 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
17853 1,
17854 never_fired,
17855 refusals.len(),
17856 );
17857 return;
17858 }
17859 }
17860 gate_buckets(
17861 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
17862 0,
17863 never_fired,
17864 refusals.len(),
17865 );
17866 eprintln!(
17867 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: \
17868 {never_fired} attempts decoded but never fired GOLDEN_FRAME, and every other \
17869 attempt hit a named refusal:\n{}",
17870 refusals.join("\n")
17871 );
17872 }
17873
17874 /// lane-av1refs's decisive gate for the 5 references widened past
17875 /// `LAST_FRAME`/`GOLDEN_FRAME`: same envelope and pin-on-mismatch
17876 /// pattern as
17877 /// [`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`],
17878 /// generalised over `(target_ref, extra_args, frame_count)` so each of
17879 /// `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` gets its own attempt pool
17880 /// and its own proof that `decode::ref_hits(target_ref)` -- not just
17881 /// `non_last_ref_hits`, which cannot distinguish one reference from
17882 /// another -- actually advanced. `--max-reference-frames=3
17883 /// --reduced-reference-set=1` (the golden gate's own narrowing) is
17884 /// DROPPED here: both suppress exactly the references this gate needs
17885 /// aomenc's RD to reach.
17886 fn a_real_aomenc_single_ref_gate(
17887 gate_name: &str,
17888 target_ref: i8,
17889 target_ref_name: &str,
17890 extra_args: &[&str],
17891 width: usize,
17892 height: usize,
17893 frame_count: usize,
17894 attempts: u32,
17895 ) {
17896 let _gate_lock = lock_gate_counters();
17897 if !have_ffmpeg() {
17898 eprintln!("SKIP {gate_name}: no ffmpeg");
17899 return;
17900 }
17901 if !have_aomenc() {
17902 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
17903 return;
17904 }
17905 let mut refusals = Vec::new();
17906 let mut never_fired = 0u32;
17907 for attempt in 0..attempts {
17908 let seed = 42 + attempt % 40;
17909 let duration = frame_count as f64 / 25.0;
17910 let source =
17911 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
17912 let y4m = Command::new("ffmpeg")
17913 .args([
17914 "-v",
17915 "error",
17916 "-f",
17917 "lavfi",
17918 "-i",
17919 &source,
17920 "-pix_fmt",
17921 "yuv420p",
17922 "-f",
17923 "yuv4mpegpipe",
17924 "-",
17925 ])
17926 .stdin(Stdio::null())
17927 .stdout(Stdio::piped())
17928 .stderr(Stdio::piped())
17929 .output()
17930 .expect("ffmpeg failed to run");
17931 assert!(
17932 y4m.status.success(),
17933 "ffmpeg fixture: {}",
17934 String::from_utf8_lossy(&y4m.stderr)
17935 );
17936 let mut args: Vec<&str> = vec![
17937 "--codec=av1",
17938 "--passes=1",
17939 "--end-usage=q",
17940 "--cq-level=55",
17941 "--cpu-used=0",
17942 "--kf-max-dist=1000",
17943 "--threads=1",
17944 "--row-mt=0",
17945 "--enable-warped-motion=0",
17946 "--enable-obmc=0",
17947 "--enable-masked-comp=0",
17948 "--enable-interintra-comp=0",
17949 "--enable-dist-wtd-comp=0",
17950 "--enable-diff-wtd-comp=0",
17951 "--enable-onesided-comp=0",
17952 "--enable-interintra-wedge=0",
17953 "--enable-smooth-interintra=0",
17954 "--enable-rect-partitions=0",
17955 "--enable-ab-partitions=0",
17956 "--enable-1to4-partitions=0",
17957 "--enable-filter-intra=0",
17958 "--enable-smooth-intra=0",
17959 "--enable-paeth-intra=0",
17960 "--enable-directional-intra=0",
17961 "--enable-angle-delta=0",
17962 "--enable-tx-size-search=0",
17963 "--enable-cdef=0",
17964 "--enable-restoration=0",
17965 "--max-partition-size=32",
17966 "--min-partition-size=32",
17967 "--enable-palette=0",
17968 "--enable-intrabc=0",
17969 "--enable-cfl-intra=0",
17970 // use_ref_frame_mvs (temporal MV projection) is unimplemented in
17971 // mvstack; leaving it on silently desyncs symbols on inter frames.
17972 "--enable-ref-frame-mvs=0",
17973 "--obu",
17974 "-o",
17975 "-",
17976 "-",
17977 ];
17978 // extra_args goes right before the trailing "-o", "-", "-" triple.
17979 let tail = args.split_off(args.len() - 3);
17980 args.extend_from_slice(extra_args);
17981 args.extend_from_slice(&tail);
17982 let out = run_with_stdin(Command::new(aomenc_path())
17983 .args(&args), &y4m.stdout);
17984 assert!(
17985 out.status.success(),
17986 "aomenc refused the fixture: {}",
17987 String::from_utf8_lossy(&out.stderr)
17988 );
17989 let stream = out.stdout;
17990 let before = decode::ref_hits(target_ref);
17991 let frames = match decode_stream(&stream) {
17992 Err(e) => {
17993 let msg = e.to_string();
17994 assert!(
17995 msg.contains("unsupported"),
17996 "{gate_name} failed outright (seed {seed}): {msg}"
17997 );
17998 refusals.push(format!("seed {seed}: {msg}"));
17999 continue;
18000 }
18001 Ok(frames) => frames,
18002 };
18003 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
18004 // is ALWAYS pixel-compared below; the hit counter only decides whether
18005 // the attempt counts toward the firing total.
18006 let counted = decode::ref_hits(target_ref) != before;
18007 if !counted {
18008 never_fired += 1;
18009 }
18010 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
18011 assert_eq!(frames.len(), frame_count);
18012 let mismatched = frames
18013 .iter()
18014 .zip(&ffmpeg_frames)
18015 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
18016 if mismatched {
18017 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
18018 std::fs::write(&path, &stream).expect("writing pinned stream");
18019 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
18020 }
18021 }
18022 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18023 assert_eq!(
18024 got.y, want.y,
18025 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
18026 );
18027 assert_eq!(
18028 got.u, want.u,
18029 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
18030 );
18031 assert_eq!(
18032 got.v, want.v,
18033 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
18034 );
18035 }
18036 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
18037 // stream again, comparing EVERY decode-order frame -- the hidden
18038 // (show_frame == 0) alt-ref frames the ffmpeg compare above
18039 // cannot see, because both sides of it emit shown frames only.
18040 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, gate_name);
18041 eprintln!(
18042 "{gate_name} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
18043 {hidden_n} hidden, all pixel-exact vs the oracle"
18044 );
18045 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
18046 // libaom's temporal alt-ref filter absorbs this recipe's hidden
18047 // frames, so the compare above is vacuous -- re-encode the same
18048 // fixture with --arnr-maxframes=0 and compare THOSE.
18049 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(gate_name, &y4m.stdout, &args) {
18050 eprintln!(
18051 "{gate_name} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
18052 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
18053 );
18054 }
18055 if counted {
18056 eprintln!(
18057 "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}",
18058 decode::ref_hits(target_ref) - before
18059 );
18060 gate_buckets(gate_name, 1, never_fired, refusals.len());
18061 return;
18062 }
18063 }
18064 gate_buckets(gate_name, 0, never_fired, refusals.len());
18065 eprintln!(
18066 "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \
18067 and every other attempt hit a named refusal:\n{}",
18068 refusals.join("\n")
18069 );
18070 }
18071
18072 /// lane-av1comp: proves `reference_select`/`comp_mode` are actually read
18073 /// off a real bitstream rather than only unit-tested in isolation --
18074 /// `--auto-alt-ref=1 --lag-in-frames=16` gives aomenc a backward
18075 /// reference to pick `COMPOUND_REFERENCE` with, `--enable-order-hint=1`
18076 /// is required for it to ever consider compound at all. Three
18077 /// acceptable outcomes: (a) a stream where `reference_select` never
18078 /// actually drove a block to `COMPOUND_REFERENCE` decodes bit-exact end
18079 /// to end (proving the per-block `comp_mode` read did not desync the
18080 /// single-ref blocks around it); (b) a stream that does fire compound
18081 /// is refused by name with [`decode::comp_mode_hits`] having advanced
18082 /// (proving `comp_mode`/`read_compound_ref_frames` consumed the right
18083 /// symbols before refusing, rather than desyncing and refusing for an
18084 /// unrelated reason) -- masked/wedge compound (`comp_group_idx == 1`)
18085 /// and a partition below 16x16 (a real, separately tracked capability
18086 /// gap) are the two refusal arms this can still legitimately name; (c)
18087 /// r13 wired plain `COMPOUND_AVERAGE` MC for real, so as of r15 a
18088 /// stream that fires compound may also decode fully -- accepted only
18089 /// when every output frame is pixel-exact against ffmpeg.
18090 #[test]
18091 fn a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly() {
18092 const NAME: &str = "a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly";
18093 let _gate_lock = lock_gate_counters();
18094 if !have_ffmpeg() {
18095 eprintln!("SKIP {NAME}: no ffmpeg");
18096 return;
18097 }
18098 if !have_aomenc() {
18099 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18100 return;
18101 }
18102 let (width, height, frame_count) = (64usize, 64usize, 20usize);
18103 let mut refusals = Vec::new();
18104 let mut never_fired = 0u32;
18105 for attempt in 0..60u32 {
18106 let seed = 42 + attempt % 40;
18107 let duration = frame_count as f64 / 25.0;
18108 let source =
18109 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
18110 let y4m = Command::new("ffmpeg")
18111 .args([
18112 "-v",
18113 "error",
18114 "-f",
18115 "lavfi",
18116 "-i",
18117 &source,
18118 "-pix_fmt",
18119 "yuv420p",
18120 "-f",
18121 "yuv4mpegpipe",
18122 "-",
18123 ])
18124 .stdin(Stdio::null())
18125 .stdout(Stdio::piped())
18126 .stderr(Stdio::piped())
18127 .output()
18128 .expect("ffmpeg failed to run");
18129 assert!(
18130 y4m.status.success(),
18131 "ffmpeg fixture: {}",
18132 String::from_utf8_lossy(&y4m.stderr)
18133 );
18134 let args: Vec<&str> = vec![
18135 "--codec=av1",
18136 "--passes=1",
18137 "--end-usage=q",
18138 "--cq-level=45",
18139 "--cpu-used=0",
18140 "--kf-max-dist=1000",
18141 "--threads=1",
18142 "--row-mt=0",
18143 "--auto-alt-ref=1",
18144 "--lag-in-frames=16",
18145 "--enable-order-hint=1",
18146 "--enable-warped-motion=0",
18147 "--enable-obmc=0",
18148 "--enable-masked-comp=0",
18149 "--enable-interintra-comp=0",
18150 "--enable-onesided-comp=0",
18151 "--enable-interintra-wedge=0",
18152 "--enable-smooth-interintra=0",
18153 "--enable-rect-partitions=0",
18154 "--enable-ab-partitions=0",
18155 "--enable-1to4-partitions=0",
18156 "--enable-filter-intra=0",
18157 "--enable-smooth-intra=0",
18158 "--enable-paeth-intra=0",
18159 "--enable-directional-intra=0",
18160 "--enable-angle-delta=0",
18161 "--enable-tx-size-search=0",
18162 "--enable-cdef=0",
18163 "--enable-restoration=0",
18164 "--max-partition-size=32",
18165 "--min-partition-size=32",
18166 "--enable-palette=0",
18167 "--enable-intrabc=0",
18168 "--enable-cfl-intra=0",
18169 "--enable-ref-frame-mvs=0",
18170 "--obu",
18171 "-o",
18172 "-",
18173 "-",
18174 ];
18175 let out = run_with_stdin(Command::new(aomenc_path())
18176 .args(&args), &y4m.stdout);
18177 assert!(
18178 out.status.success(),
18179 "aomenc refused the fixture: {}",
18180 String::from_utf8_lossy(&out.stderr)
18181 );
18182 let stream = out.stdout;
18183 let before = decode::comp_mode_hits();
18184 match decode_stream(&stream) {
18185 Err(e) => {
18186 let msg = e.to_string();
18187 let fired = decode::comp_mode_hits() > before;
18188 assert!(
18189 msg.contains("unsupported"),
18190 "{NAME} failed outright (seed {seed}): {msg}"
18191 );
18192 if fired {
18193 // `comp_mode` firing does not stop the block walk --
18194 // a later, unrelated block in the same tile can
18195 // still hit any other named refusal this decoder
18196 // carries. A partition below 16x16 is a real, open
18197 // capability gap tracked on its own (not a
18198 // COMPOUND_REFERENCE defect); accept it here too
18199 // rather than fail a compound-specific gate on a
18200 // partition-search coincidence. lane-av1blend r7:
18201 // re-swept the wide gate with the plain-average
18202 // blend unmasked (r6/r7's ref_ctx fix alone) and it
18203 // still mismatches on real streams beyond that one
18204 // bug -- re-masked comp_group_idx == 0 too, so this
18205 // stays a legal named refusal.
18206 assert!(
18207 msg.contains("COMPOUND_REFERENCE") || msg.contains("a partition"),
18208 "{NAME}: comp_mode fired (seed {seed}) but the refusal \
18209 was for something else: {msg}"
18210 );
18211 let advanced = decode::comp_mode_hits() - before;
18212 eprintln!(
18213 "{NAME} FIRING seed {seed}: comp_mode hits advanced by \
18214 {advanced}, refused by name as expected: {msg}"
18215 );
18216 return;
18217 }
18218 refusals.push(format!("seed {seed}: {msg}"));
18219 continue;
18220 }
18221 Ok(frames) => {
18222 // class [[gate-skips-on-its-own-failure]]: a decode that
18223 // succeeded is ALWAYS pixel-compared below; the hit counter
18224 // only decides whether the attempt counts as firing.
18225 let counted = decode::comp_mode_hits() != before;
18226 if !counted {
18227 never_fired += 1;
18228 }
18229 // Outcome (c): plain COMPOUND_AVERAGE decoded fully --
18230 // non-negotiable pixel exactness, no tolerance.
18231 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
18232 assert_eq!(frames.len(), frame_count);
18233 let mismatched = frames
18234 .iter()
18235 .zip(&ffmpeg_frames)
18236 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
18237 if mismatched {
18238 let pin = std::env::temp_dir().join("ec-av1-reference-select-gate-fail.obu");
18239 let _ = std::fs::write(&pin, &stream);
18240 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
18241 std::fs::write(&path, &stream).expect("writing pinned stream");
18242 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
18243 }
18244 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18245 assert_eq!(
18246 got.y, want.y,
18247 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
18248 pin.display()
18249 );
18250 assert_eq!(
18251 got.u, want.u,
18252 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
18253 pin.display()
18254 );
18255 assert_eq!(
18256 got.v, want.v,
18257 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
18258 pin.display()
18259 );
18260 }
18261 } else {
18262 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18263 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
18264 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
18265 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
18266 }
18267 }
18268 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
18269 // stream again, comparing EVERY decode-order frame -- the hidden
18270 // (show_frame == 0) alt-ref frames the ffmpeg compare above
18271 // cannot see, because both sides of it emit shown frames only.
18272 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
18273 eprintln!(
18274 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
18275 {hidden_n} hidden, all pixel-exact vs the oracle"
18276 );
18277 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
18278 // libaom's temporal alt-ref filter absorbs this recipe's hidden
18279 // frames, so the compare above is vacuous -- re-encode the same
18280 // fixture with --arnr-maxframes=0 and compare THOSE.
18281 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
18282 eprintln!(
18283 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
18284 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
18285 );
18286 }
18287 if counted {
18288 eprintln!(
18289 "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \
18290 fully and pixel-exact",
18291 decode::comp_mode_hits() - before
18292 );
18293 gate_buckets(NAME, 1, never_fired, refusals.len());
18294 return;
18295 }
18296 }
18297 }
18298 }
18299 gate_buckets(NAME, 0, never_fired, refusals.len());
18300 eprintln!(
18301 "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \
18302 block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \
18303 reached comp_mode:\n{}",
18304 refusals.join("\n")
18305 );
18306 }
18307
18308 /// lane-av1comp round 14's decisive gate for `skip_mode`: same
18309 /// pin-on-mismatch pattern as [`a_real_aomenc_single_ref_gate`], proving
18310 /// [`decode::skip_mode_hits`] actually advanced (a real block picked
18311 /// `skip_mode`, not just that the frame header bit was set) and that the
18312 /// resulting forced-compound `NEAREST_NEARESTMV` decode is still
18313 /// pixel-exact against ffmpeg. `--auto-alt-ref=1 --lag-in-frames=16
18314 /// --enable-fwd-kf=0` (backward references) plus
18315 /// `--enable-ref-frame-mvs=0` (unimplemented temporal MV projection,
18316 /// same as every other gate here) is aomenc's own requirement for
18317 /// `skip_mode_present` to ever be considered at all (spec 5.9.22 needs
18318 /// both a forward and a backward reference candidate).
18319 #[test]
18320 fn a_real_aomenc_stream_with_compound_references_decodes_pixel_exact() {
18321 const NAME: &str = "a_real_aomenc_stream_with_compound_references_decodes_pixel_exact";
18322 let _gate_lock = lock_gate_counters();
18323 if !have_ffmpeg() {
18324 eprintln!("SKIP {NAME}: no ffmpeg");
18325 return;
18326 }
18327 if !have_aomenc() {
18328 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18329 return;
18330 }
18331 let (width, height, frame_count) = (64usize, 64usize, 24usize);
18332 let mut refusals = Vec::new();
18333 let mut never_fired = 0u32;
18334 for attempt in 0..80u32 {
18335 let seed = 42 + attempt % 40;
18336 let duration = frame_count as f64 / 25.0;
18337 let source =
18338 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
18339 let y4m = Command::new("ffmpeg")
18340 .args([
18341 "-v",
18342 "error",
18343 "-f",
18344 "lavfi",
18345 "-i",
18346 &source,
18347 "-pix_fmt",
18348 "yuv420p",
18349 "-f",
18350 "yuv4mpegpipe",
18351 "-",
18352 ])
18353 .stdin(Stdio::null())
18354 .stdout(Stdio::piped())
18355 .stderr(Stdio::piped())
18356 .output()
18357 .expect("ffmpeg failed to run");
18358 assert!(
18359 y4m.status.success(),
18360 "ffmpeg fixture: {}",
18361 String::from_utf8_lossy(&y4m.stderr)
18362 );
18363 let args: Vec<&str> = vec![
18364 "--codec=av1",
18365 "--passes=1",
18366 "--end-usage=q",
18367 "--cq-level=45",
18368 "--cpu-used=0",
18369 "--kf-max-dist=1000",
18370 "--threads=1",
18371 "--row-mt=0",
18372 "--auto-alt-ref=1",
18373 "--lag-in-frames=16",
18374 "--enable-fwd-kf=0",
18375 "--enable-order-hint=1",
18376 "--enable-warped-motion=0",
18377 "--enable-obmc=0",
18378 "--enable-masked-comp=0",
18379 "--enable-interintra-comp=0",
18380 "--enable-onesided-comp=0",
18381 "--enable-interintra-wedge=0",
18382 "--enable-smooth-interintra=0",
18383 "--enable-rect-partitions=0",
18384 "--enable-ab-partitions=0",
18385 "--enable-1to4-partitions=0",
18386 "--enable-filter-intra=0",
18387 "--enable-smooth-intra=0",
18388 "--enable-paeth-intra=0",
18389 "--enable-directional-intra=0",
18390 "--enable-angle-delta=0",
18391 "--enable-tx-size-search=0",
18392 "--enable-cdef=0",
18393 "--enable-restoration=0",
18394 "--max-partition-size=32",
18395 "--min-partition-size=32",
18396 "--enable-palette=0",
18397 "--enable-intrabc=0",
18398 "--enable-cfl-intra=0",
18399 "--enable-ref-frame-mvs=0",
18400 "--obu",
18401 "-o",
18402 "-",
18403 "-",
18404 ];
18405 let out = run_with_stdin(Command::new(aomenc_path())
18406 .args(&args), &y4m.stdout);
18407 assert!(
18408 out.status.success(),
18409 "aomenc refused the fixture: {}",
18410 String::from_utf8_lossy(&out.stderr)
18411 );
18412 let stream = out.stdout;
18413 let before = decode::skip_mode_hits();
18414 let frames = match decode_stream(&stream) {
18415 Err(e) => {
18416 let msg = e.to_string();
18417 assert!(
18418 msg.contains("unsupported"),
18419 "{NAME} failed outright (seed {seed}): {msg}"
18420 );
18421 refusals.push(format!("seed {seed}: {msg}"));
18422 continue;
18423 }
18424 Ok(frames) => frames,
18425 };
18426 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
18427 // is ALWAYS pixel-compared below; the hit counter only decides whether
18428 // the attempt counts toward the firing total.
18429 let counted = decode::skip_mode_hits() != before;
18430 if !counted {
18431 never_fired += 1;
18432 }
18433 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
18434 assert_eq!(frames.len(), frame_count);
18435 let mismatched = frames
18436 .iter()
18437 .zip(&ffmpeg_frames)
18438 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
18439 if mismatched {
18440 let pin = std::env::temp_dir().join("ec-av1-compound-refs-gate-fail.obu");
18441 let _ = std::fs::write(&pin, &stream);
18442 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
18443 std::fs::write(&path, &stream).expect("writing pinned stream");
18444 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
18445 }
18446 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18447 assert_eq!(
18448 got.y, want.y,
18449 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
18450 pin.display()
18451 );
18452 assert_eq!(
18453 got.u, want.u,
18454 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
18455 pin.display()
18456 );
18457 assert_eq!(
18458 got.v, want.v,
18459 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
18460 pin.display()
18461 );
18462 }
18463 }
18464 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
18465 // stream again, comparing EVERY decode-order frame -- the hidden
18466 // (show_frame == 0) alt-ref frames the ffmpeg compare above
18467 // cannot see, because both sides of it emit shown frames only.
18468 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
18469 eprintln!(
18470 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
18471 {hidden_n} hidden, all pixel-exact vs the oracle"
18472 );
18473 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
18474 // libaom's temporal alt-ref filter absorbs this recipe's hidden
18475 // frames, so the compare above is vacuous -- re-encode the same
18476 // fixture with --arnr-maxframes=0 and compare THOSE.
18477 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
18478 eprintln!(
18479 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
18480 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
18481 );
18482 }
18483 if counted {
18484 eprintln!(
18485 "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}",
18486 decode::skip_mode_hits() - before
18487 );
18488 gate_buckets(NAME, 1, never_fired, refusals.len());
18489 return;
18490 }
18491 }
18492 gate_buckets(NAME, 0, never_fired, refusals.len());
18493 eprintln!(
18494 "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \
18495 other attempt hit a named refusal:\n{}",
18496 refusals.join("\n")
18497 );
18498 }
18499
18500 /// lane-motionmode round 1: `--enable-obmc=1 --enable-warped-motion=0`
18501 /// on the base recipe (`--auto-alt-ref=1 --lag-in-frames=16
18502 /// --enable-fwd-kf=0 --enable-ref-frame-mvs=0`) -- pixel-exact against
18503 /// ffmpeg, gated on [`decode::obmc_hits`] actually advancing (a real
18504 /// block picked `OBMC_CAUSAL`, not just that the header bit was set).
18505 /// Structure copied from
18506 /// `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`:
18507 /// a seed sweep with a named-refusal escape hatch and an
18508 /// `EC_AV1_GATE_DUMP` pin on mismatch.
18509 #[test]
18510 fn a_real_aomenc_stream_with_obmc_decodes_pixel_exact() {
18511 const NAME: &str = "a_real_aomenc_stream_with_obmc_decodes_pixel_exact";
18512 let _gate_lock = lock_gate_counters();
18513 if !have_ffmpeg() {
18514 eprintln!("SKIP {NAME}: no ffmpeg");
18515 return;
18516 }
18517 if !have_aomenc() {
18518 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18519 return;
18520 }
18521 let (width, height, frame_count) = (64usize, 64usize, 24usize);
18522 let mut refusals = Vec::new();
18523 let mut never_fired = 0u32;
18524 for attempt in 0..80u32 {
18525 let seed = 42 + attempt % 40;
18526 let duration = frame_count as f64 / 25.0;
18527 let source =
18528 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
18529 let y4m = Command::new("ffmpeg")
18530 .args([
18531 "-v",
18532 "error",
18533 "-f",
18534 "lavfi",
18535 "-i",
18536 &source,
18537 "-pix_fmt",
18538 "yuv420p",
18539 "-f",
18540 "yuv4mpegpipe",
18541 "-",
18542 ])
18543 .stdin(Stdio::null())
18544 .stdout(Stdio::piped())
18545 .stderr(Stdio::piped())
18546 .output()
18547 .expect("ffmpeg failed to run");
18548 assert!(
18549 y4m.status.success(),
18550 "ffmpeg fixture: {}",
18551 String::from_utf8_lossy(&y4m.stderr)
18552 );
18553 let args: Vec<&str> = vec![
18554 "--codec=av1",
18555 "--passes=1",
18556 "--end-usage=q",
18557 "--cq-level=45",
18558 "--cpu-used=0",
18559 "--kf-max-dist=1000",
18560 "--threads=1",
18561 "--row-mt=0",
18562 "--auto-alt-ref=1",
18563 "--lag-in-frames=16",
18564 "--enable-fwd-kf=0",
18565 "--enable-order-hint=1",
18566 "--enable-warped-motion=0",
18567 "--enable-obmc=1",
18568 "--enable-masked-comp=0",
18569 "--enable-interintra-comp=0",
18570 "--enable-onesided-comp=0",
18571 "--enable-interintra-wedge=0",
18572 "--enable-smooth-interintra=0",
18573 "--enable-rect-partitions=0",
18574 "--enable-ab-partitions=0",
18575 "--enable-1to4-partitions=0",
18576 "--enable-filter-intra=0",
18577 "--enable-smooth-intra=0",
18578 "--enable-paeth-intra=0",
18579 "--enable-directional-intra=0",
18580 "--enable-angle-delta=0",
18581 "--enable-tx-size-search=0",
18582 "--enable-cdef=0",
18583 "--enable-restoration=0",
18584 "--max-partition-size=32",
18585 "--min-partition-size=32",
18586 "--enable-palette=0",
18587 "--enable-intrabc=0",
18588 "--enable-cfl-intra=0",
18589 "--enable-ref-frame-mvs=0",
18590 "--obu",
18591 "-o",
18592 "-",
18593 "-",
18594 ];
18595 let out = run_with_stdin(Command::new(aomenc_path())
18596 .args(&args), &y4m.stdout);
18597 assert!(
18598 out.status.success(),
18599 "aomenc refused the fixture: {}",
18600 String::from_utf8_lossy(&out.stderr)
18601 );
18602 let stream = out.stdout;
18603 let before = decode::obmc_hits();
18604 let frames = match decode_stream(&stream) {
18605 Err(e) => {
18606 let msg = e.to_string();
18607 assert!(
18608 msg.contains("unsupported"),
18609 "{NAME} failed outright (seed {seed}): {msg}"
18610 );
18611 refusals.push(format!("seed {seed}: {msg}"));
18612 continue;
18613 }
18614 Ok(frames) => frames,
18615 };
18616 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
18617 // is ALWAYS pixel-compared below; the hit counter only decides whether
18618 // the attempt counts toward the firing total.
18619 let counted = decode::obmc_hits() != before;
18620 if !counted {
18621 never_fired += 1;
18622 }
18623 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
18624 assert_eq!(frames.len(), frame_count);
18625 let mismatched = frames
18626 .iter()
18627 .zip(&ffmpeg_frames)
18628 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
18629 if mismatched {
18630 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
18631 std::fs::write(&path, &stream).expect("writing pinned stream");
18632 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
18633 }
18634 }
18635 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18636 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
18637 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
18638 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
18639 }
18640 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
18641 // stream again, comparing EVERY decode-order frame -- the hidden
18642 // (show_frame == 0) alt-ref frames the ffmpeg compare above
18643 // cannot see, because both sides of it emit shown frames only.
18644 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
18645 eprintln!(
18646 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
18647 {hidden_n} hidden, all pixel-exact vs the oracle"
18648 );
18649 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
18650 // libaom's temporal alt-ref filter absorbs this recipe's hidden
18651 // frames, so the compare above is vacuous -- re-encode the same
18652 // fixture with --arnr-maxframes=0 and compare THOSE.
18653 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
18654 eprintln!(
18655 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
18656 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
18657 );
18658 }
18659 if counted {
18660 eprintln!(
18661 "{NAME} FIRING seed {seed}: obmc hits advanced by {}",
18662 decode::obmc_hits() - before
18663 );
18664 gate_buckets(NAME, 1, never_fired, refusals.len());
18665 return;
18666 }
18667 }
18668 gate_buckets(NAME, 0, never_fired, refusals.len());
18669 eprintln!(
18670 "SKIP {NAME}: {never_fired} attempts decoded but never fired obmc, and every \
18671 other attempt hit a named refusal:\n{}",
18672 refusals.join("\n")
18673 );
18674 }
18675
18676 /// lane-motionmode round 3: same shape as
18677 /// `a_real_aomenc_stream_with_obmc_decodes_pixel_exact`, but relaxed the
18678 /// `--min-partition-size=32 --max-partition-size=32` clamp (that other
18679 /// gate's own doc: locked to remove partition-depth choice from the
18680 /// search entirely) to `8`/`32`, to make an 8x8-leaf `OBMC_CAUSAL` pick
18681 /// possible at all. Gated on [`decode::obmc_hits_8`] specifically, not
18682 /// the aggregate [`decode::obmc_hits`]. Measured live (round 3, this
18683 /// box): 80 attempts, 0 ever called `decode_inter_block8` at all --
18684 /// `cpu-used=0`'s RD search never once splits a 16x16 down to a clean
18685 /// 4-way 8x8 leaf for this smooth `gradients` fixture (large blocks
18686 /// always win the RD cost there); the handful of named refusals seen
18687 /// are `PARTITION_SPLIT` chosen *at* 8x8 (down to 4x4, already refused
18688 /// at `decode.rs`'s `part8 != PARTITION_NONE` check) or
18689 /// `allow_screen_content_tools`, neither reaching a leaf. Kept anyway
18690 /// (mirrors this file's own `never_fired`-skip convention) as the
18691 /// honest record of the attempt; a real 8x8 OBMC fixture needs
18692 /// higher-frequency content than this gate's fixtures use, out of
18693 /// round-3 budget.
18694 #[test]
18695 fn a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact() {
18696 const NAME: &str = "a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact";
18697 let _gate_lock = lock_gate_counters();
18698 if !have_ffmpeg() {
18699 eprintln!("SKIP {NAME}: no ffmpeg");
18700 return;
18701 }
18702 if !have_aomenc() {
18703 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18704 return;
18705 }
18706 let (width, height, frame_count) = (64usize, 64usize, 24usize);
18707 let mut refusals = Vec::new();
18708 let mut never_fired = 0u32;
18709 let mut total_obmc8 = 0usize;
18710 let n_attempts: u32 = std::env::var("EC_OBMC8_ATTEMPTS")
18711 .ok()
18712 .and_then(|s| s.parse().ok())
18713 .unwrap_or(80);
18714 for attempt in 0..n_attempts {
18715 let seed = 42 + attempt % 40;
18716 let duration = frame_count as f64 / 25.0;
18717 // Recipe search hook: `gradients` is smooth, so aomenc's RD never
18718 // splits below 16x16 and this gate never fired one 8x8 OBMC block
18719 // in 45 attempts -- it "passed" by skipping (gate-blind-to-feature).
18720 // EC_AV1_OBMC8_SOURCE overrides the lavfi source so a firing recipe
18721 // can be searched for without a rebuild.
18722 let source = std::env::var("EC_AV1_OBMC8_SOURCE").unwrap_or_else(|_| {
18723 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
18724 });
18725 // A source supplied through EC_AV1_OBMC8_SOURCE need not carry its
18726 // own `duration=`; `-t` is the bound that always holds. Without it
18727 // an endless source (`testsrc2`) fills the pipe forever and the
18728 // gate hangs to its 300 s timeout.
18729 let duration_arg = format!("{duration}");
18730 let y4m = Command::new("ffmpeg")
18731 .args([
18732 "-v",
18733 "error",
18734 "-f",
18735 "lavfi",
18736 "-i",
18737 &source,
18738 "-t",
18739 &duration_arg,
18740 "-pix_fmt",
18741 "yuv420p",
18742 "-f",
18743 "yuv4mpegpipe",
18744 "-",
18745 ])
18746 .stdin(Stdio::null())
18747 .stdout(Stdio::piped())
18748 .stderr(Stdio::piped())
18749 .output()
18750 .expect("ffmpeg failed to run");
18751 assert!(
18752 y4m.status.success(),
18753 "ffmpeg fixture: {}",
18754 String::from_utf8_lossy(&y4m.stderr)
18755 );
18756 let args: Vec<&str> = vec![
18757 "--codec=av1",
18758 "--passes=1",
18759 "--end-usage=q",
18760 "--cq-level=45",
18761 "--cpu-used=0",
18762 "--kf-max-dist=1000",
18763 "--threads=1",
18764 "--row-mt=0",
18765 "--auto-alt-ref=1",
18766 "--lag-in-frames=16",
18767 "--enable-fwd-kf=0",
18768 "--enable-order-hint=1",
18769 "--enable-warped-motion=0",
18770 "--enable-obmc=1",
18771 "--enable-masked-comp=0",
18772 "--enable-interintra-comp=0",
18773 "--enable-onesided-comp=0",
18774 "--enable-interintra-wedge=0",
18775 "--enable-smooth-interintra=0",
18776 "--enable-rect-partitions=0",
18777 "--enable-ab-partitions=0",
18778 "--enable-1to4-partitions=0",
18779 "--enable-filter-intra=0",
18780 "--enable-smooth-intra=0",
18781 "--enable-paeth-intra=0",
18782 "--enable-directional-intra=0",
18783 "--enable-angle-delta=0",
18784 "--enable-tx-size-search=0",
18785 "--enable-cdef=0",
18786 "--enable-restoration=0",
18787 "--min-partition-size=8",
18788 "--max-partition-size=32",
18789 "--enable-palette=0",
18790 "--enable-intrabc=0",
18791 "--enable-cfl-intra=0",
18792 "--enable-ref-frame-mvs=0",
18793 "--obu",
18794 "-o",
18795 "-",
18796 "-",
18797 ];
18798 let out = run_with_stdin(Command::new(aomenc_path())
18799 .args(&args), &y4m.stdout);
18800 assert!(
18801 out.status.success(),
18802 "aomenc refused the fixture: {}",
18803 String::from_utf8_lossy(&out.stderr)
18804 );
18805 let stream = out.stdout;
18806 let before8 = decode::obmc_hits_8();
18807 let frames = match decode_stream(&stream) {
18808 Err(e) => {
18809 let msg = e.to_string();
18810 assert!(
18811 msg.contains("unsupported"),
18812 "{NAME} failed outright (seed {seed}): {msg}"
18813 );
18814 refusals.push(format!("seed {seed}: {msg}"));
18815 continue;
18816 }
18817 Ok(frames) => frames,
18818 };
18819 let fired8 = decode::obmc_hits_8() - before8;
18820 total_obmc8 += fired8;
18821 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
18822 // is ALWAYS pixel-compared below; the hit counter only decides whether
18823 // the attempt counts toward the firing total.
18824 let counted = fired8 != 0;
18825 if !counted {
18826 never_fired += 1;
18827 }
18828 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
18829 assert_eq!(frames.len(), frame_count);
18830 let mismatched = frames
18831 .iter()
18832 .zip(&ffmpeg_frames)
18833 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
18834 if mismatched {
18835 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
18836 std::fs::write(&path, &stream).expect("writing pinned stream");
18837 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
18838 }
18839 }
18840 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18841 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
18842 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
18843 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
18844 }
18845 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
18846 // stream again, comparing EVERY decode-order frame -- the hidden
18847 // (show_frame == 0) alt-ref frames the ffmpeg compare above
18848 // cannot see, because both sides of it emit shown frames only.
18849 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
18850 eprintln!(
18851 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
18852 {hidden_n} hidden, all pixel-exact vs the oracle"
18853 );
18854 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
18855 // libaom's temporal alt-ref filter absorbs this recipe's hidden
18856 // frames, so the compare above is vacuous -- re-encode the same
18857 // fixture with --arnr-maxframes=0 and compare THOSE.
18858 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
18859 eprintln!(
18860 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
18861 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
18862 );
18863 }
18864 if counted {
18865 eprintln!(
18866 "{NAME} FIRING seed {seed}: 8x8 obmc hits {fired8} (total across attempts so far {total_obmc8})"
18867 );
18868 gate_buckets(NAME, 1, never_fired, refusals.len());
18869 return;
18870 }
18871 }
18872 gate_buckets(NAME, 0, never_fired, refusals.len());
18873 // lane-gmaffine r2: this gate fired for three rounds only as a SKIP
18874 // (gate-skips-on-its-own-failure); the 8x8 leaf is reachable now, so a
18875 // sweep that never lands one firing pixel-exact attempt is a FAILURE.
18876 panic!(
18877 "{NAME}: {never_fired} attempts decoded but never fired an 8x8 obmc block \
18878 ({total_obmc8} total 8x8 obmc hits across all attempts), and every other attempt \
18879 hit a named refusal:\n{}",
18880 refusals.join("\n")
18881 );
18882 }
18883
18884 /// lane-warp r5e (flipped from lane-motionmode r1's refuses-or-matches):
18885 /// `--enable-warped-motion=1` streams must DECODE pixel-exact --
18886 /// `av1_findSamples`/`num_proj_ref`, the 3-symbol `motion_mode` read,
18887 /// the affine projection/filter, and the WARPED_CAUSAL interp-filter
18888 /// derivation are all ported. A refusal naming warp, or any pixel
18889 /// mismatch, fails the gate; refusals for OTHER named capabilities
18890 /// (screen content tools) still skip that seed. The sweep must also
18891 /// actually exercise warp (`warp_selected_hits > 0`) so a decoder that
18892 /// silently stops selecting WARPED_CAUSAL cannot pass vacuously.
18893 #[test]
18894 fn a_real_aomenc_stream_with_warped_motion_refuses_or_matches() {
18895 const NAME: &str = "a_real_aomenc_stream_with_warped_motion_refuses_or_matches";
18896 let _gate_lock = lock_gate_counters();
18897 if !have_ffmpeg() {
18898 eprintln!("SKIP {NAME}: no ffmpeg");
18899 return;
18900 }
18901 if !have_aomenc() {
18902 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18903 return;
18904 }
18905 let (width, height, frame_count) = (64usize, 64usize, 24usize);
18906 let mut named_refusals = 0u32;
18907 let mut matched = 0u32;
18908 let n_attempts: u32 = std::env::var("EC_WARP_GATE_ATTEMPTS")
18909 .ok()
18910 .and_then(|s| s.parse().ok())
18911 .unwrap_or(40);
18912 for attempt in 0..n_attempts {
18913 let seed = 42 + attempt;
18914 let duration = frame_count as f64 / 25.0;
18915 let source =
18916 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
18917 let y4m = Command::new("ffmpeg")
18918 .args([
18919 "-v",
18920 "error",
18921 "-f",
18922 "lavfi",
18923 "-i",
18924 &source,
18925 "-pix_fmt",
18926 "yuv420p",
18927 "-f",
18928 "yuv4mpegpipe",
18929 "-",
18930 ])
18931 .stdin(Stdio::null())
18932 .stdout(Stdio::piped())
18933 .stderr(Stdio::piped())
18934 .output()
18935 .expect("ffmpeg failed to run");
18936 assert!(
18937 y4m.status.success(),
18938 "ffmpeg fixture: {}",
18939 String::from_utf8_lossy(&y4m.stderr)
18940 );
18941 let args: Vec<&str> = vec![
18942 "--codec=av1",
18943 "--passes=1",
18944 "--end-usage=q",
18945 "--cq-level=45",
18946 "--cpu-used=0",
18947 "--kf-max-dist=1000",
18948 "--threads=1",
18949 "--row-mt=0",
18950 "--auto-alt-ref=1",
18951 "--lag-in-frames=16",
18952 "--enable-fwd-kf=0",
18953 "--enable-order-hint=1",
18954 "--enable-warped-motion=1",
18955 "--enable-obmc=1",
18956 "--tune-content=default",
18957 "--enable-masked-comp=0",
18958 "--enable-interintra-comp=0",
18959 "--enable-onesided-comp=0",
18960 "--enable-interintra-wedge=0",
18961 "--enable-smooth-interintra=0",
18962 "--enable-rect-partitions=0",
18963 "--enable-ab-partitions=0",
18964 "--enable-1to4-partitions=0",
18965 "--enable-filter-intra=0",
18966 "--enable-smooth-intra=0",
18967 "--enable-paeth-intra=0",
18968 "--enable-directional-intra=0",
18969 "--enable-angle-delta=0",
18970 "--enable-tx-size-search=0",
18971 "--enable-cdef=0",
18972 "--enable-restoration=0",
18973 "--max-partition-size=32",
18974 "--min-partition-size=32",
18975 "--enable-palette=0",
18976 "--enable-intrabc=0",
18977 "--enable-cfl-intra=0",
18978 "--enable-ref-frame-mvs=0",
18979 "--obu",
18980 "-o",
18981 "-",
18982 "-",
18983 ];
18984 let out = run_with_stdin(Command::new(aomenc_path())
18985 .args(&args), &y4m.stdout);
18986 assert!(
18987 out.status.success(),
18988 "aomenc refused the fixture: {}",
18989 String::from_utf8_lossy(&out.stderr)
18990 );
18991 let stream = out.stdout;
18992 let frames = match decode_stream(&stream) {
18993 Err(e) => {
18994 let msg = e.to_string();
18995 assert!(
18996 msg.contains("unsupported"),
18997 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
18998 );
18999 assert!(
19000 !msg.contains("warp"),
19001 "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \
19002 refusal must not exist: {msg}"
19003 );
19004 named_refusals += 1;
19005 eprintln!("seed {seed} refusal (non-warp capability): {msg}");
19006 continue;
19007 }
19008 Ok(frames) => frames,
19009 };
19010 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
19011 assert_eq!(frames.len(), frame_count);
19012 let mismatched = frames
19013 .iter()
19014 .zip(&ffmpeg_frames)
19015 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
19016 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
19017 std::fs::write(&path, &stream).expect("writing pinned stream");
19018 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
19019 }
19020 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19021 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
19022 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
19023 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
19024 }
19025 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
19026 // stream again, comparing EVERY decode-order frame -- the hidden
19027 // (show_frame == 0) alt-ref frames the ffmpeg compare above
19028 // cannot see, because both sides of it emit shown frames only.
19029 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
19030 eprintln!(
19031 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
19032 {hidden_n} hidden, all pixel-exact vs the oracle"
19033 );
19034 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
19035 // libaom's temporal alt-ref filter absorbs this recipe's hidden
19036 // frames, so the compare above is vacuous -- re-encode the same
19037 // fixture with --arnr-maxframes=0 and compare THOSE.
19038 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
19039 eprintln!(
19040 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
19041 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
19042 );
19043 }
19044 matched += 1;
19045 }
19046 assert!(
19047 matched > 0,
19048 "{NAME}: every attempt refused on other capabilities; the gate never exercised warp"
19049 );
19050 assert!(
19051 crate::decode::warp_selected_hits() > 0,
19052 "{NAME}: {matched} matches but zero WARPED_CAUSAL blocks fired -- the gate decodes \
19053 warp streams without ever selecting warp, so it proves nothing about warp"
19054 );
19055 eprintln!(
19056 "{NAME}: {named_refusals} non-warp refusals, {matched} pixel-exact matches out of {n_attempts}, warp_selected_hits={}",
19057 crate::decode::warp_selected_hits()
19058 );
19059 }
19060
19061 /// lane-superres stage 3: a real aomenc `--superres-mode=1` key-frame
19062 /// sequence must decode pixel-exact vs ffmpeg/dav1d's own upscaled
19063 /// output, and must actually run [`crate::superres::upscale_picture`]
19064 /// (`superres_hits > 0`) -- a decoder that silently stopped upscaling
19065 /// would otherwise pass vacuously (class `gate-blind-to-feature`).
19066 /// `--kf-max-dist` set to the frame count keeps every frame a key
19067 /// frame: inter-frame superres (a differently-scaled reference) is a
19068 /// later stage of this lane, refused by name today.
19069 #[test]
19070 fn a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact() {
19071 const NAME: &str = "a_real_aomenc_superres_key_frame_sequence_decodes_pixel_exact";
19072 let _gate_lock = lock_gate_counters();
19073 if !have_ffmpeg() {
19074 eprintln!("SKIP {NAME}: no ffmpeg");
19075 return;
19076 }
19077 if !have_aomenc() {
19078 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19079 return;
19080 }
19081 let (width, height, frame_count) = (64usize, 64usize, 3usize);
19082 let duration = frame_count as f64 / 25.0;
19083 let source = gradients_source(7, width, height, &format!("duration={duration}:rate=25"));
19084 let y4m = Command::new("ffmpeg")
19085 .args([
19086 "-v",
19087 "error",
19088 "-f",
19089 "lavfi",
19090 "-i",
19091 &source,
19092 "-pix_fmt",
19093 "yuv420p",
19094 "-f",
19095 "yuv4mpegpipe",
19096 "-",
19097 ])
19098 .stdin(Stdio::null())
19099 .stdout(Stdio::piped())
19100 .stderr(Stdio::piped())
19101 .output()
19102 .expect("ffmpeg failed to run");
19103 assert!(
19104 y4m.status.success(),
19105 "ffmpeg fixture: {}",
19106 String::from_utf8_lossy(&y4m.stderr)
19107 );
19108 let args: Vec<&str> = vec![
19109 "--codec=av1",
19110 "--passes=1",
19111 "--end-usage=q",
19112 "--cq-level=32",
19113 "--cpu-used=0",
19114 "--kf-max-dist=0",
19115 "--threads=1",
19116 "--row-mt=0",
19117 "--superres-mode=1",
19118 "--superres-denominator=12",
19119 "--superres-kf-denominator=12",
19120 "--enable-rect-partitions=0",
19121 "--enable-ab-partitions=0",
19122 "--enable-1to4-partitions=0",
19123 "--enable-filter-intra=0",
19124 "--enable-smooth-intra=0",
19125 "--enable-paeth-intra=0",
19126 "--enable-directional-intra=0",
19127 "--enable-angle-delta=0",
19128 "--enable-tx-size-search=0",
19129 "--enable-cdef=0",
19130 "--enable-restoration=0",
19131 "--max-partition-size=32",
19132 "--min-partition-size=32",
19133 "--enable-palette=0",
19134 "--enable-intrabc=0",
19135 "--enable-cfl-intra=0",
19136 "--obu",
19137 "-o",
19138 "-",
19139 "-",
19140 ];
19141 let out = run_with_stdin(Command::new(aomenc_path())
19142 .args(&args), &y4m.stdout);
19143 assert!(
19144 out.status.success(),
19145 "aomenc refused the fixture: {}",
19146 String::from_utf8_lossy(&out.stderr)
19147 );
19148 let stream = out.stdout;
19149 if let Ok(path) = std::env::var("EC_SUPERRES_STREAM_DUMP") {
19150 std::fs::write(path, &stream).expect("dump stream");
19151 }
19152 let frames =
19153 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}"));
19154 assert_eq!(frames.len(), frame_count);
19155 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
19156 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19157 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg");
19158 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
19159 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
19160 }
19161 assert!(
19162 crate::superres::superres_hits() > 0,
19163 "{NAME}: matched but zero superres_hits -- the gate never actually exercised the \
19164 upscaler, it proves nothing"
19165 );
19166 eprintln!(
19167 "{NAME}: {frame_count} frames pixel-exact, superres_hits={}",
19168 crate::superres::superres_hits()
19169 );
19170 }
19171
19172 /// lane-superres r10: a real aomenc key+inter `--superres-mode=1`
19173 /// sequence must DECODE pixel-exact vs ffmpeg, with the frame-level
19174 /// `use_superres` refusal LIFTED for inter frames -- `mc::predict_scaled`
19175 /// (spec 7.11.3.3) is the only path this recipe can reach (warp/OBMC/
19176 /// compound/interintra/palette/intrabc/CDEF/LR are all off, matching the
19177 /// scoped refusals' own unimplemented list). A pixel match alone would
19178 /// pass just as well with an unscaled reference and prove nothing
19179 /// (class `gate-blind-to-feature`) -- hard-assert
19180 /// `crate::mc::predict_scaled_hits() > 0` so the gate can only pass if the
19181 /// scaled MC path actually ran.
19182 #[test]
19183 fn a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact() {
19184 const NAME: &str = "a_real_aomenc_key_and_inter_superres_sequence_decodes_pixel_exact";
19185 let _gate_lock = lock_gate_counters();
19186 if !have_ffmpeg() {
19187 eprintln!("SKIP {NAME}: no ffmpeg");
19188 return;
19189 }
19190 if !have_aomenc() {
19191 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19192 return;
19193 }
19194 let (width, height, frame_count) = (64usize, 64usize, 3usize);
19195 let duration = frame_count as f64 / 25.0;
19196 let source = gradients_source(11, width, height, &format!("duration={duration}:rate=25"));
19197 let y4m = Command::new("ffmpeg")
19198 .args([
19199 "-v",
19200 "error",
19201 "-f",
19202 "lavfi",
19203 "-i",
19204 &source,
19205 "-pix_fmt",
19206 "yuv420p",
19207 "-f",
19208 "yuv4mpegpipe",
19209 "-",
19210 ])
19211 .stdin(Stdio::null())
19212 .stdout(Stdio::piped())
19213 .stderr(Stdio::piped())
19214 .output()
19215 .expect("ffmpeg failed to run");
19216 assert!(
19217 y4m.status.success(),
19218 "ffmpeg fixture: {}",
19219 String::from_utf8_lossy(&y4m.stderr)
19220 );
19221 let args: Vec<&str> = vec![
19222 "--codec=av1",
19223 "--passes=1",
19224 "--end-usage=q",
19225 "--cq-level=32",
19226 "--cpu-used=0",
19227 // `--kf-max-dist` above `frame_count` keeps only frame 0 a key
19228 // frame -- frames 1/2 are the inter frames whose `use_superres`
19229 // refusal this round lifts.
19230 "--kf-max-dist=1000",
19231 "--lag-in-frames=0",
19232 "--auto-alt-ref=0",
19233 "--threads=1",
19234 "--row-mt=0",
19235 "--sb-size=64",
19236 "--superres-mode=1",
19237 "--superres-denominator=12",
19238 "--superres-kf-denominator=12",
19239 // Forces every inter block onto the single-ref, non-warp/OBMC/
19240 // interintra branch `decode_inter_block` threads `predict_scaled`
19241 // through -- the only branch this round's scoped refusals leave
19242 // unrefused under a scaled reference.
19243 "--enable-warped-motion=0",
19244 "--enable-obmc=0",
19245 "--enable-masked-comp=0",
19246 "--enable-interintra-comp=0",
19247 "--enable-dist-wtd-comp=0",
19248 "--enable-diff-wtd-comp=0",
19249 "--enable-onesided-comp=0",
19250 "--enable-interintra-wedge=0",
19251 "--enable-smooth-interintra=0",
19252 "--enable-order-hint=0",
19253 "--enable-ref-frame-mvs=0",
19254 "--enable-rect-partitions=0",
19255 "--enable-ab-partitions=0",
19256 "--enable-1to4-partitions=0",
19257 "--enable-filter-intra=0",
19258 "--enable-smooth-intra=0",
19259 "--enable-paeth-intra=0",
19260 "--enable-directional-intra=0",
19261 "--enable-angle-delta=0",
19262 "--enable-tx-size-search=0",
19263 "--enable-cdef=0",
19264 "--enable-restoration=0",
19265 "--max-partition-size=32",
19266 "--min-partition-size=32",
19267 "--enable-palette=0",
19268 "--enable-intrabc=0",
19269 "--enable-cfl-intra=0",
19270 "--obu",
19271 "-o",
19272 "-",
19273 "-",
19274 ];
19275 let out = run_with_stdin(Command::new(aomenc_path())
19276 .args(&args), &y4m.stdout);
19277 assert!(
19278 out.status.success(),
19279 "aomenc refused the fixture: {}",
19280 String::from_utf8_lossy(&out.stderr)
19281 );
19282 let stream = out.stdout;
19283 if let Ok(path) = std::env::var("EC_SUPERRES_INTER_STREAM_DUMP") {
19284 std::fs::write(&path, &stream).expect("dump stream");
19285 }
19286 let frames =
19287 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} refused: {e}"));
19288 assert_eq!(frames.len(), frame_count);
19289 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
19290 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19291 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg");
19292 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
19293 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
19294 }
19295 assert!(
19296 crate::superres::superres_hits() > 0,
19297 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
19298 );
19299 assert!(
19300 crate::mc::predict_scaled_hits() > 0,
19301 "{NAME}: matched but zero predict_scaled_hits -- every block took the unscaled MC \
19302 path, which proves nothing about the scaled-reference code this round adds \
19303 (class gate-blind-to-feature)"
19304 );
19305 eprintln!(
19306 "{NAME}: {frame_count} frames pixel-exact, superres_hits={}, predict_scaled_hits={}",
19307 crate::superres::superres_hits(),
19308 crate::mc::predict_scaled_hits()
19309 );
19310 }
19311
19312 /// lane-t900 r28: the three scaled-reference (superres) refusals are
19313 /// LIFTED -- an 8x8 partition leaf, a sub-8x8 inter block, and warp --
19314 /// so two real `--superres-mode=1` streams whose references are all
19315 /// scaled must decode PIXEL-EXACT vs ffmpeg.
19316 ///
19317 /// Arm A drives `--min-partition-size=4` so the split (4x4) and rect
19318 /// (8x4/4x8) sub-8x8 readers and the 8x8 leaf all run over a scaled
19319 /// reference; arm B turns `--enable-warped-motion=1` on, which is the
19320 /// root cause this round fixed: libaom `motion_mode_allowed` drops
19321 /// WARPED_CAUSAL eligibility when `av1_is_scaled(sf)`, so the 8x8 leaf
19322 /// must read the 2-symbol obmc alphabet (here: no symbol at all, OBMC
19323 /// off) instead of the 3-symbol motion_mode row.
19324 ///
19325 /// Each arm hard-asserts its own counter (class `gate-blind-to-feature`):
19326 /// a pixel match with zero scaled leaves/sub-8x8 blocks/suppressed warp
19327 /// eligibilities would prove nothing.
19328 #[test]
19329 fn real_superres_streams_with_sub8_leaf8_and_warp_decode_pixel_exact() {
19330 const NAME: &str = "real_superres_streams_with_sub8_leaf8_and_warp_decode_pixel_exact";
19331 let _gate_lock = lock_gate_counters();
19332 if !have_ffmpeg() {
19333 eprintln!("SKIP {NAME}: no ffmpeg");
19334 return;
19335 }
19336 if !have_aomenc() {
19337 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19338 return;
19339 }
19340 // Every tool whose scaled-reference path this round does NOT touch is
19341 // off, so a mismatch can only be the lifted paths (the same scoping
19342 // the r10 key+inter superres gate uses).
19343 let common: [&str; 21] = [
19344 "--codec=av1", "--passes=1", "--end-usage=q", "--threads=1", "--row-mt=0",
19345 "--kf-max-dist=9999", "--lag-in-frames=0", "--auto-alt-ref=0", "--cpu-used=0",
19346 "--sb-size=64", "--superres-mode=1", "--superres-denominator=12",
19347 "--superres-kf-denominator=12", "--enable-obmc=0", "--enable-masked-comp=0",
19348 "--enable-interintra-comp=0", "--enable-tx-size-search=0", "--enable-cdef=0",
19349 "--enable-restoration=0", "--enable-palette=0", "--enable-intrabc=0",
19350 ];
19351 struct Arm {
19352 name: &'static str,
19353 frames: usize,
19354 cq: &'static str,
19355 extra: [&'static str; 4],
19356 }
19357 let arms = [
19358 Arm {
19359 name: "sub8+leaf8",
19360 frames: 4,
19361 cq: "--cq-level=4",
19362 extra: [
19363 "--enable-warped-motion=0",
19364 "--enable-rect-partitions=1",
19365 "--max-partition-size=32",
19366 "--min-partition-size=4",
19367 ],
19368 },
19369 Arm {
19370 name: "warp",
19371 frames: 6,
19372 cq: "--cq-level=20",
19373 extra: [
19374 "--enable-warped-motion=1",
19375 "--enable-rect-partitions=1",
19376 "--max-partition-size=32",
19377 "--min-partition-size=8",
19378 ],
19379 },
19380 ];
19381 let (width, height) = (96usize, 96usize);
19382 for arm in &arms {
19383 let duration = format!("{}", arm.frames as f64 / 25.0);
19384 let src = format!("mandelbrot=size={width}x{height}:rate=25");
19385 let y4m = Command::new("ffmpeg")
19386 .args([
19387 "-v", "error", "-f", "lavfi", "-i", &src, "-t", &duration, "-pix_fmt",
19388 "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-",
19389 ])
19390 .stdin(Stdio::null())
19391 .stdout(Stdio::piped())
19392 .stderr(Stdio::piped())
19393 .output()
19394 .expect("ffmpeg failed to run");
19395 assert!(y4m.status.success(), "{NAME}: ffmpeg refused the fixture");
19396 let limit = format!("--limit={}", arm.frames);
19397 let mut args: Vec<&str> = common.to_vec();
19398 args.push(&limit);
19399 args.push(arm.cq);
19400 args.extend_from_slice(&arm.extra);
19401 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
19402 let out = run_with_stdin(Command::new(aomenc_path())
19403 .args(&args), &y4m.stdout);
19404 assert!(
19405 out.status.success(),
19406 "{NAME} {}: aomenc refused the recipe: {}",
19407 arm.name,
19408 String::from_utf8_lossy(&out.stderr)
19409 );
19410 let stream = out.stdout;
19411 let leaf8_before = crate::decode::scaled_leaf8_hits();
19412 let sub8_before = crate::decode::scaled_sub8_hits();
19413 let warp_before = crate::decode::scaled_warp_suppressed_hits();
19414 let frames = decode_stream(&stream)
19415 .unwrap_or_else(|e| panic!("{NAME} {}: refused: {e}", arm.name));
19416 assert_eq!(frames.len(), arm.frames, "{NAME} {}", arm.name);
19417 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, arm.frames);
19418 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19419 assert_eq!(got.y, want.y, "{NAME} {} frame {i} luma vs ffmpeg", arm.name);
19420 assert_eq!(got.u, want.u, "{NAME} {} frame {i} U vs ffmpeg", arm.name);
19421 assert_eq!(got.v, want.v, "{NAME} {} frame {i} V vs ffmpeg", arm.name);
19422 }
19423 let (leaf8, sub8, warp) = (
19424 crate::decode::scaled_leaf8_hits() - leaf8_before,
19425 crate::decode::scaled_sub8_hits() - sub8_before,
19426 crate::decode::scaled_warp_suppressed_hits() - warp_before,
19427 );
19428 eprintln!(
19429 "{NAME} {}: {} frames pixel-exact, scaled leaf8={leaf8} sub8={sub8} \
19430 warp_suppressed={warp}",
19431 arm.name, arm.frames
19432 );
19433 if arm.name == "sub8+leaf8" {
19434 assert!(leaf8 > 0 && sub8 > 0, "{NAME} {}: the lifted paths never ran (leaf8={leaf8} sub8={sub8})", arm.name);
19435 } else {
19436 assert!(
19437 warp > 0,
19438 "{NAME} {}: no block reached WARPED_CAUSAL eligibility under a scaled \
19439 reference, so the alphabet fix is unexercised",
19440 arm.name
19441 );
19442 }
19443 }
19444 }
19445
19446 /// lane-interintra r1: `--enable-interintra-comp=1` streams must DECODE
19447 /// pixel-exact -- the interintra flag/mode/wedge-flag syntax and the
19448 /// non-wedge smooth blend are ported. A refusal naming interintra fails
19449 /// the gate UNLESS it is the wedge refusal (`use_wedge_interintra == 1`
19450 /// is r2, and this recipe encodes with wedge off so it must not fire
19451 /// either); warp/obmc are enabled and supported; refusals for OTHER
19452 /// named capabilities (screen content tools) still skip that seed. The
19453 /// sweep must actually exercise interintra (`interintra_hits > 0`).
19454 #[test]
19455 fn a_real_aomenc_stream_with_interintra_decodes_pixel_exact() {
19456 const NAME: &str = "a_real_aomenc_stream_with_interintra_decodes_pixel_exact";
19457 let _gate_lock = lock_gate_counters();
19458 if !have_ffmpeg() {
19459 eprintln!("SKIP {NAME}: no ffmpeg");
19460 return;
19461 }
19462 if !have_aomenc() {
19463 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19464 return;
19465 }
19466 let (width, height, frame_count) = (64usize, 64usize, 24usize);
19467 // lane-midcut r1: rect interintra (`write_w != write_h`) built its
19468 // intra predictor at the square `side`; this gate passed with that
19469 // bug, so the shape gets its own delta-counted assert below.
19470 let rect_before = crate::decode::interintra_rect_hits();
19471 let mut named_refusals = 0u32;
19472 let mut matched = 0u32;
19473 let n_attempts: u32 = std::env::var("EC_INTERINTRA_GATE_ATTEMPTS")
19474 .ok()
19475 .and_then(|s| s.parse().ok())
19476 .unwrap_or(40);
19477 for attempt in 0..n_attempts {
19478 let seed = 42 + attempt;
19479 let duration = frame_count as f64 / 25.0;
19480 let source =
19481 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
19482 let y4m = Command::new("ffmpeg")
19483 .args([
19484 "-v",
19485 "error",
19486 "-f",
19487 "lavfi",
19488 "-i",
19489 &source,
19490 "-pix_fmt",
19491 "yuv420p",
19492 "-f",
19493 "yuv4mpegpipe",
19494 "-",
19495 ])
19496 .stdin(Stdio::null())
19497 .stdout(Stdio::piped())
19498 .stderr(Stdio::piped())
19499 .output()
19500 .expect("ffmpeg failed to run");
19501 assert!(
19502 y4m.status.success(),
19503 "ffmpeg fixture: {}",
19504 String::from_utf8_lossy(&y4m.stderr)
19505 );
19506 let args: Vec<&str> = vec![
19507 "--codec=av1",
19508 "--passes=1",
19509 "--end-usage=q",
19510 "--cq-level=45",
19511 "--cpu-used=0",
19512 "--kf-max-dist=1000",
19513 "--threads=1",
19514 "--row-mt=0",
19515 "--auto-alt-ref=1",
19516 "--lag-in-frames=16",
19517 "--enable-fwd-kf=0",
19518 "--enable-order-hint=1",
19519 "--enable-warped-motion=1",
19520 "--enable-obmc=1",
19521 "--tune-content=default",
19522 "--enable-masked-comp=0",
19523 "--enable-interintra-comp=1",
19524 "--enable-onesided-comp=1",
19525 "--enable-interintra-wedge=0",
19526 "--enable-smooth-interintra=1",
19527 "--enable-rect-partitions=0",
19528 "--enable-ab-partitions=0",
19529 "--enable-1to4-partitions=0",
19530 "--enable-filter-intra=0",
19531 "--enable-smooth-intra=0",
19532 "--enable-paeth-intra=0",
19533 "--enable-directional-intra=0",
19534 "--enable-angle-delta=0",
19535 "--enable-tx-size-search=0",
19536 "--enable-cdef=0",
19537 "--enable-restoration=0",
19538 "--max-partition-size=32",
19539 "--min-partition-size=32",
19540 "--enable-palette=0",
19541 "--enable-intrabc=0",
19542 "--enable-cfl-intra=0",
19543 "--enable-ref-frame-mvs=0",
19544 "--obu",
19545 "-o",
19546 "-",
19547 "-",
19548 ];
19549 let out = run_with_stdin(Command::new(aomenc_path())
19550 .args(&args), &y4m.stdout);
19551 assert!(
19552 out.status.success(),
19553 "aomenc refused the fixture: {}",
19554 String::from_utf8_lossy(&out.stderr)
19555 );
19556 let stream = out.stdout;
19557 let frames = match decode_stream(&stream) {
19558 Err(e) => {
19559 let msg = e.to_string();
19560 assert!(
19561 msg.contains("unsupported"),
19562 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
19563 );
19564 assert!(
19565 !msg.contains("warp"),
19566 "{NAME} refused on warp (seed {seed}) -- warp decode is ported, this \
19567 refusal must not exist: {msg}"
19568 );
19569 assert!(
19570 !msg.contains("interintra"),
19571 "{NAME} refused on interintra (seed {seed}) -- non-wedge interintra \
19572 is ported and this recipe encodes with wedge off: {msg}"
19573 );
19574 named_refusals += 1;
19575 eprintln!("seed {seed} refusal (non-warp capability): {msg}");
19576 continue;
19577 }
19578 Ok(frames) => frames,
19579 };
19580 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
19581 assert_eq!(frames.len(), frame_count);
19582 let mismatched = frames
19583 .iter()
19584 .zip(&ffmpeg_frames)
19585 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
19586 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
19587 std::fs::write(&path, &stream).expect("writing pinned stream");
19588 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
19589 }
19590 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19591 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
19592 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
19593 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
19594 }
19595 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
19596 // stream again, comparing EVERY decode-order frame -- the hidden
19597 // (show_frame == 0) alt-ref frames the ffmpeg compare above
19598 // cannot see, because both sides of it emit shown frames only.
19599 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
19600 eprintln!(
19601 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
19602 {hidden_n} hidden, all pixel-exact vs the oracle"
19603 );
19604 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
19605 // libaom's temporal alt-ref filter absorbs this recipe's hidden
19606 // frames, so the compare above is vacuous -- re-encode the same
19607 // fixture with --arnr-maxframes=0 and compare THOSE.
19608 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
19609 eprintln!(
19610 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
19611 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
19612 );
19613 }
19614 // lane-midcut r3 RECT ARM: the recipe above spells
19615 // `--enable-rect-partitions=0 --min-partition-size=32`, so it can
19616 // never produce a RECT interintra block -- the delta assert at the
19617 // end of this gate was unsatisfiable on it (the gate disabled the
19618 // very shape it claims to prove). Re-encode the SAME source with
19619 // the rect overrides APPENDED (aomenc keeps the LAST occurrence of
19620 // a repeated flag) and compare every decode-order frame of that
19621 // stream against aomdec, until a rect interintra block fires.
19622 if crate::decode::interintra_rect_hits() == rect_before {
19623 let mut rect_args = args.clone();
19624 rect_args.extend_from_slice(&[
19625 "--enable-rect-partitions=1",
19626 "--min-partition-size=8",
19627 "--max-partition-size=64",
19628 ]);
19629 let out = run_with_stdin(Command::new(aomenc_path())
19630 .args(&rect_args), &y4m.stdout);
19631 assert!(
19632 out.status.success(),
19633 "{NAME} RECT-ARM: aomenc refused its own recipe plus the rect overrides: {}",
19634 String::from_utf8_lossy(&out.stderr)
19635 );
19636 let rect_stream = out.stdout;
19637 match decode_stream(&rect_stream) {
19638 Err(e) => {
19639 let msg = e.to_string();
19640 assert!(
19641 msg.contains("unsupported"),
19642 "{NAME} RECT-ARM failed outright, not a named refusal (seed {seed}): {msg}"
19643 );
19644 eprintln!("{NAME} RECT-ARM: skipped on a named refusal: {msg}");
19645 }
19646 Ok(_) => {
19647 let (total, hidden) =
19648 decode_all_frames_vs_oracle(&rect_stream, &format!("{NAME}-rect"));
19649 eprintln!(
19650 "{NAME} RECT-ARM: seed {seed}: {total} decode-order frames, {hidden} \
19651 hidden, all pixel-exact vs the oracle, interintra_rect_hits={}",
19652 crate::decode::interintra_rect_hits() - rect_before
19653 );
19654 }
19655 }
19656 }
19657 matched += 1;
19658 }
19659 assert!(
19660 matched > 0,
19661 "{NAME}: every attempt refused on other capabilities; the gate never exercised warp"
19662 );
19663 assert!(
19664 crate::decode::interintra_hits() > 0,
19665 "{NAME}: {matched} matches but zero interintra blocks fired -- the gate decodes \
19666 these streams without ever taking interintra, so it proves nothing"
19667 );
19668 // lane-defon r1: `--enable-onesided-comp=1` is spelled on this
19669 // recipe, so a UNIDIR_COMP_REFERENCE pair must actually have been
19670 // read -- otherwise the on-value proves nothing.
19671 assert!(
19672 crate::decode::uni_comp_hits() > 0,
19673 "{NAME}: {matched} matches but zero UNIDIR_COMP_REFERENCE pairs read -- \
19674 --enable-onesided-comp=1 never reached the uni_comp_ref alphabet"
19675 );
19676 assert!(
19677 crate::decode::interintra_rect_hits() > rect_before,
19678 "{NAME}: {matched} matches but zero RECTANGULAR interintra blocks fired -- the \
19679 square-only blend defect (lane-midcut r1) would pass this gate unseen"
19680 );
19681 eprintln!(
19682 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, interintra_hits={} interintra_rect_hits={} uni_comp_hits={}",
19683 crate::decode::interintra_hits(),
19684 crate::decode::interintra_rect_hits() - rect_before,
19685 crate::decode::uni_comp_hits()
19686 );
19687 }
19688
19689 /// lane-scaledref r1: a real aomenc `--superres-mode=1` sequence with
19690 /// compound, OBMC, interintra and 8x8 leaves ALL enabled must decode
19691 /// pixel-exact -- these are the combinations the three
19692 /// "... with a scaled reference (superres, unimplemented)" refusals used
19693 /// to cover. Each combination gets its OWN hard-asserted hit counter
19694 /// (`crate::decode::scaled_*_hits`), because an unscaled reference would
19695 /// pass the pixels and prove nothing (class `gate-blind-to-feature`), and
19696 /// a stream that scales but never takes compound/OBMC/interintra/8x8
19697 /// would prove nothing about the code this round adds either. A refusal
19698 /// naming a scaled reference is a hard failure: those are exactly the
19699 /// strings this round lifts. Other named capabilities skip that seed.
19700 #[test]
19701 fn a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact()
19702 {
19703 const NAME: &str = "a_real_aomenc_superres_stream_with_compound_obmc_and_interintra_decodes_pixel_exact";
19704 let _gate_lock = lock_gate_counters();
19705 if !have_ffmpeg() {
19706 eprintln!("SKIP {NAME}: no ffmpeg");
19707 return;
19708 }
19709 if !have_aomenc() {
19710 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19711 return;
19712 }
19713 let (width, height, frame_count) = (64usize, 64usize, 24usize);
19714 let mut named_refusals = 0u32;
19715 let mut matched = 0u32;
19716 let n_attempts: u32 = std::env::var("EC_SCALEDREF_GATE_ATTEMPTS")
19717 .ok()
19718 .and_then(|s| s.parse().ok())
19719 .unwrap_or(12);
19720 for attempt in 0..n_attempts {
19721 let seed = 42 + attempt;
19722 let duration = frame_count as f64 / 25.0;
19723 let source =
19724 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
19725 let y4m = Command::new("ffmpeg")
19726 .args([
19727 "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
19728 "yuv4mpegpipe", "-",
19729 ])
19730 .stdin(Stdio::null())
19731 .stdout(Stdio::piped())
19732 .stderr(Stdio::piped())
19733 .output()
19734 .expect("ffmpeg failed to run");
19735 assert!(
19736 y4m.status.success(),
19737 "ffmpeg fixture: {}",
19738 String::from_utf8_lossy(&y4m.stderr)
19739 );
19740 let on = |name: &str| {
19741 if std::env::var(name).as_deref() == Ok("0") { "0" } else { "1" }
19742 };
19743 // lane-scaledref r2: warp is ON. A warp-capable frame header
19744 // under a scaled reference is exactly the case r1 got wrong
19745 // (the block must read the 2-symbol `obmc_cdf`, not the
19746 // 3-symbol `motion_mode_cdf` -- libaom `motion_mode_allowed`,
19747 // blockd.h:1484), and it decoded silently wrong pixels rather
19748 // than refusing. `EC_SCALEDREF_WARP=0` turns it off for
19749 // bisecting only.
19750 let warp = format!("--enable-warped-motion={}", on("EC_SCALEDREF_WARP"));
19751 // lane-scaledref r2: `EC_SCALEDREF_MODE=3` (qthresh) lets
19752 // superres switch on and off per frame, so a compound block can
19753 // reference one scaled and one unscaled reference -- the mixed
19754 // case mode 1 (every frame scaled) never produces.
19755 let superres_mode = format!(
19756 "--superres-mode={}",
19757 std::env::var("EC_SCALEDREF_MODE").unwrap_or_else(|_| "1".into())
19758 );
19759 let obmc = format!("--enable-obmc={}", on("EC_SCALEDREF_OBMC"));
19760 let interintra = format!("--enable-interintra-comp={}", on("EC_SCALEDREF_II"));
19761 let lag = format!(
19762 "--lag-in-frames={}",
19763 if on("EC_SCALEDREF_COMP") == "0" { "0" } else { "25" }
19764 );
19765 let alt_ref = format!("--auto-alt-ref={}", on("EC_SCALEDREF_COMP"));
19766 let args: Vec<&str> = vec![
19767 "--codec=av1",
19768 "--passes=1",
19769 "--end-usage=q",
19770 "--cq-level=45",
19771 "--cpu-used=0",
19772 "--kf-max-dist=1000",
19773 "--threads=1",
19774 "--row-mt=0",
19775 "--sb-size=64",
19776 // superres on every frame, key and inter alike -- the scaled
19777 // reference this gate is about.
19778 // denominator 16 (the maximum) keeps the CODED frame
19779 // 32x64 -- a multiple of 16 both ways, so no frame-edge
19780 // 16x16 straddle forces a sub-16x16 partition this decoder
19781 // still refuses on the aligned path ("an inter partition
19782 // below 16x16"). Denominator 12 codes 43 columns and every
19783 // seed refused there.
19784 &superres_mode,
19785 "--superres-denominator=16",
19786 "--superres-kf-denominator=16",
19787 // the four combinations this round lifts (each switchable
19788 // by env for bisecting a mismatch without a rebuild)
19789 &alt_ref,
19790 &lag,
19791 "--enable-order-hint=1",
19792 &warp,
19793 &obmc,
19794 &interintra,
19795 "--enable-smooth-interintra=1",
19796 "--enable-interintra-wedge=0",
19797 "--enable-masked-comp=0",
19798 "--enable-onesided-comp=0",
19799 "--enable-fwd-kf=0",
19800 "--tune-content=default",
19801 "--max-partition-size=32",
19802 "--min-partition-size=32",
19803 // everything this decoder still refuses under any reference
19804 "--enable-rect-partitions=0",
19805 "--enable-ab-partitions=0",
19806 "--enable-1to4-partitions=0",
19807 "--enable-filter-intra=0",
19808 "--enable-smooth-intra=0",
19809 "--enable-paeth-intra=0",
19810 "--enable-directional-intra=0",
19811 "--enable-angle-delta=0",
19812 "--enable-tx-size-search=0",
19813 "--enable-cdef=0",
19814 "--enable-restoration=0",
19815 "--enable-palette=0",
19816 "--enable-intrabc=0",
19817 "--enable-cfl-intra=0",
19818 "--enable-ref-frame-mvs=0",
19819 "--obu",
19820 "-o",
19821 "-",
19822 "-",
19823 ];
19824 let out = run_with_stdin(Command::new(aomenc_path())
19825 .args(&args), &y4m.stdout);
19826 assert!(
19827 out.status.success(),
19828 "aomenc refused the fixture: {}",
19829 String::from_utf8_lossy(&out.stderr)
19830 );
19831 let stream = out.stdout;
19832 let frames = match decode_stream(&stream) {
19833 Err(e) => {
19834 let msg = e.to_string();
19835 assert!(
19836 msg.contains("unsupported"),
19837 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
19838 );
19839 assert!(
19840 !msg.contains("scaled reference"),
19841 "{NAME} refused on a scaled reference (seed {seed}) -- those refusals \
19842 are exactly what this round lifts: {msg}"
19843 );
19844 named_refusals += 1;
19845 eprintln!("seed {seed} refusal (other capability): {msg}");
19846 continue;
19847 }
19848 Ok(frames) => frames,
19849 };
19850 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
19851 assert_eq!(frames.len(), frame_count);
19852 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
19853 let mismatched = frames
19854 .iter()
19855 .zip(&ffmpeg_frames)
19856 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
19857 if mismatched {
19858 std::fs::write(&path, &stream).expect("writing pinned stream");
19859 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
19860 }
19861 }
19862 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19863 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
19864 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
19865 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
19866 }
19867 matched += 1;
19868 }
19869 eprintln!(
19870 "{NAME}: {named_refusals} other-capability refusals, {matched}/{n_attempts} pixel-exact, \
19871 superres_hits={} predict_scaled_hits={} scaled_compound={} scaled_warp_fallback={} \
19872 scaled_obmc={} scaled_interintra={} scaled_block8={} scaled_warp_suppressed={} mixed_scale_compound={}",
19873 crate::superres::superres_hits(),
19874 crate::mc::predict_scaled_hits(),
19875 crate::decode::scaled_compound_hits(),
19876 crate::decode::scaled_warp_fallback_hits(),
19877 crate::decode::scaled_obmc_hits(),
19878 crate::decode::scaled_interintra_hits(),
19879 crate::decode::scaled_block8_hits(),
19880 crate::decode::scaled_warp_suppressed_hits(),
19881 crate::decode::mixed_scale_compound_hits(),
19882 );
19883 assert!(
19884 matched > 0,
19885 "{NAME}: every attempt refused on other capabilities; the gate proves nothing"
19886 );
19887 assert!(
19888 crate::mc::predict_scaled_hits() > 0,
19889 "{NAME}: matched but zero predict_scaled_hits -- no block took the scaled MC path"
19890 );
19891 // The 8x8 leaf is NOT asserted here: it stays refused (no recipe
19892 // produced an 8x8 inter leaf at all), so its counter is a
19893 // diagnostic only -- see this gate's own doc and decode.rs.
19894 // `scaled_warp_suppressed` IS asserted: it counts the blocks whose
19895 // WARPED_CAUSAL eligibility libaom drops because the reference is
19896 // scaled, i.e. the blocks that must read `obmc_cdf`. Zero of them
19897 // would mean this gate's `--enable-warped-motion=1` never reached a
19898 // warp-eligible block and proves nothing about r2's fix.
19899 assert!(
19900 crate::decode::scaled_warp_suppressed_hits() > 0,
19901 "{NAME}: {matched} matches but no block had its warp eligibility \
19902 suppressed by a scaled reference -- the warp arm proves nothing"
19903 );
19904 for (hits, what) in [
19905 (crate::decode::scaled_compound_hits(), "compound with a scaled reference"),
19906 (crate::decode::scaled_obmc_hits(), "OBMC with a scaled reference"),
19907 (crate::decode::scaled_interintra_hits(), "interintra with a scaled reference"),
19908 ] {
19909 assert!(hits > 0, "{NAME}: {matched} matches but zero blocks took {what}");
19910 }
19911 }
19912
19913 /// lane-defon r1: the 10-bit one-sided-compound hole --
19914 /// `--enable-onesided-comp` was spelled on in no 10-bit gate (5 of the 15
19915 /// pin it off, the rest default), so the UNIDIR_COMP_REFERENCE alphabet
19916 /// was proven at 8 bits only while both of his films are 10-bit 4:2:0.
19917 /// `--enable-diff-wtd-comp=1` is deliberately NOT spelled here (a flag a
19918 /// gate turns on without asserting it fired is coverage theatre, class
19919 /// gate-blind-to-feature): measured this round, the 10-bit `gradients`
19920 /// fixture decodes 8/8 pixel-exact with `diffwtd_hits == 0` -- smooth
19921 /// gradients never win
19922 /// a difference-weighted mask (the 8-bit gate needs `mandelbrot`'s hard
19923 /// diagonal edge, and [`ten_bit_tool_gate`] has no mandelbrot source), so
19924 /// hard-asserting it here would fail on encoder choice, not on a decoder
19925 /// defect.
19926 #[test]
19927 fn a_real_aomenc_10bit_stream_with_onesided_compound_decodes_pixel_exact() {
19928 const NAME: &str = "a_real_aomenc_10bit_stream_with_onesided_compound_decodes_pixel_exact";
19929 let _gate_lock = lock_gate_counters();
19930 if !have_ffmpeg() {
19931 eprintln!("SKIP {NAME}: no ffmpeg");
19932 return;
19933 }
19934 if !have_aomenc() {
19935 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19936 return;
19937 }
19938 ten_bit_tool_gate(
19939 NAME,
19940 64,
19941 64,
19942 24,
19943 &[
19944 "--enable-onesided-comp=1",
19945 "--enable-masked-comp=1",
19946 "--enable-dist-wtd-comp=0",
19947 "--cq-level=45",
19948 "--kf-max-dist=1000",
19949 "--auto-alt-ref=1",
19950 "--lag-in-frames=16",
19951 "--enable-fwd-kf=0",
19952 "--enable-order-hint=1",
19953 "--enable-global-motion=0",
19954 "--enable-warped-motion=1",
19955 "--enable-obmc=1",
19956 "--tune-content=default",
19957 "--enable-interintra-comp=0",
19958 "--enable-interintra-wedge=0",
19959 "--enable-smooth-interintra=0",
19960 "--enable-rect-partitions=0",
19961 "--enable-ab-partitions=0",
19962 "--enable-1to4-partitions=0",
19963 "--enable-filter-intra=0",
19964 "--enable-smooth-intra=0",
19965 "--enable-paeth-intra=0",
19966 "--enable-directional-intra=0",
19967 "--enable-angle-delta=0",
19968 "--enable-tx-size-search=0",
19969 "--enable-cdef=0",
19970 "--enable-restoration=0",
19971 "--max-partition-size=32",
19972 "--min-partition-size=32",
19973 "--enable-palette=0",
19974 "--enable-intrabc=0",
19975 "--enable-cfl-intra=0",
19976 "--enable-ref-frame-mvs=0",
19977 ],
19978 &[42, 43, 44, 45, 46, 47, 48, 49],
19979 &[("uni_comp_hits", crate::decode::uni_comp_hits as fn() -> usize)],
19980 );
19981 }
19982
19983 /// lane-defon r1: the 10-bit sibling of
19984 /// [`a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact`] --
19985 /// `--enable-interintra-wedge=1` was spelled on in no 10-bit gate (5 of
19986 /// the 15 pin it off), and his two films are 10-bit, so the 8-bit
19987 /// gate alone proves nothing about the streams that matter. Same tool
19988 /// set as the 8-bit recipe (`--enable-masked-comp=0` keeps inter blocks
19989 /// off the COMPOUND_WEDGE path, fixed 32x32 partitions), driven through
19990 /// [`ten_bit_tool_gate`], which hard-asserts `wii_hits` moved and
19991 /// compares every plane against ffmpeg's own 10-bit decode.
19992 #[test]
19993 fn a_real_aomenc_10bit_stream_with_interintra_wedge_decodes_pixel_exact() {
19994 const NAME: &str = "a_real_aomenc_10bit_stream_with_interintra_wedge_decodes_pixel_exact";
19995 let _gate_lock = lock_gate_counters();
19996 if !have_ffmpeg() {
19997 eprintln!("SKIP {NAME}: no ffmpeg");
19998 return;
19999 }
20000 if !have_aomenc() {
20001 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20002 return;
20003 }
20004 ten_bit_tool_gate(
20005 NAME,
20006 64,
20007 64,
20008 24,
20009 &[
20010 "--enable-interintra-wedge=1",
20011 "--enable-interintra-comp=1",
20012 "--enable-smooth-interintra=1",
20013 "--cq-level=45",
20014 "--kf-max-dist=1000",
20015 "--auto-alt-ref=1",
20016 "--lag-in-frames=16",
20017 "--enable-fwd-kf=0",
20018 "--enable-order-hint=1",
20019 "--enable-warped-motion=1",
20020 "--enable-obmc=1",
20021 "--tune-content=default",
20022 "--enable-masked-comp=0",
20023 "--enable-onesided-comp=0",
20024 "--enable-rect-partitions=0",
20025 "--enable-ab-partitions=0",
20026 "--enable-1to4-partitions=0",
20027 "--enable-filter-intra=0",
20028 "--enable-smooth-intra=0",
20029 "--enable-paeth-intra=0",
20030 "--enable-directional-intra=0",
20031 "--enable-angle-delta=0",
20032 "--enable-tx-size-search=0",
20033 "--enable-cdef=0",
20034 "--enable-restoration=0",
20035 "--max-partition-size=32",
20036 "--min-partition-size=32",
20037 "--enable-palette=0",
20038 "--enable-intrabc=0",
20039 "--enable-cfl-intra=0",
20040 "--enable-ref-frame-mvs=0",
20041 ],
20042 &[42, 43, 44, 45, 46, 47, 48, 49],
20043 &[
20044 ("wii_hits", crate::decode::wii_hits as fn() -> usize),
20045 ("interintra_hits", crate::decode::interintra_hits as fn() -> usize),
20046 ],
20047 );
20048 }
20049
20050 /// lane-wii r2: `--enable-interintra-wedge=1` streams must DECODE
20051 /// pixel-exact -- the wedge-interintra syntax (adapting `wedge_index`
20052 /// CDF symbol, fixed sign 0) and the wedge mask blend are ported over
20053 /// the checksum-verified codebook. `--enable-masked-comp=0` stays so
20054 /// the encoder cannot route inter blocks through the still-unported
20055 /// COMPOUND_WEDGE/DIFFWTD path. A refusal naming interintra/wedge
20056 /// fails the gate; refusals for OTHER named capabilities still skip
20057 /// that seed. Zero `wii_hits` on a run means the encoder never
20058 /// selected wedge-interintra -- soft-skipped (warned), not failed:
20059 /// that is encoder choice, not a decoder bug.
20060 #[test]
20061 fn a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact() {
20062 const NAME: &str = "a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact";
20063 let _gate_lock = lock_gate_counters();
20064 if !have_ffmpeg() {
20065 eprintln!("SKIP {NAME}: no ffmpeg");
20066 return;
20067 }
20068 if !have_aomenc() {
20069 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20070 return;
20071 }
20072 let (width, height, frame_count) = (64usize, 64usize, 24usize);
20073 let mut named_refusals = 0u32;
20074 let mut matched = 0u32;
20075 let n_attempts: u32 = std::env::var("EC_WEDGE_GATE_ATTEMPTS")
20076 .ok()
20077 .and_then(|s| s.parse().ok())
20078 .unwrap_or(40);
20079 for attempt in 0..n_attempts {
20080 let seed = 42 + attempt;
20081 let duration = frame_count as f64 / 25.0;
20082 let source = if attempt % 2 == 0 {
20083 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"))
20084 } else {
20085 // `end_pts` does NOT bound mandelbrot (it generated 300+
20086 // frames and hung the gate for an hour); `-t` below is the
20087 // real bound, matching every other mandelbrot gate recipe.
20088 format!("mandelbrot=size={width}x{height}:rate=25")
20089 };
20090 let duration_arg = format!("{duration}");
20091 let y4m = Command::new("ffmpeg")
20092 .args([
20093 "-v",
20094 "error",
20095 "-f",
20096 "lavfi",
20097 "-i",
20098 &source,
20099 "-pix_fmt",
20100 "yuv420p",
20101 "-t",
20102 &duration_arg,
20103 "-f",
20104 "yuv4mpegpipe",
20105 "-",
20106 ])
20107 .stdin(Stdio::null())
20108 .stdout(Stdio::piped())
20109 .stderr(Stdio::piped())
20110 .output()
20111 .expect("ffmpeg failed to run");
20112 assert!(
20113 y4m.status.success(),
20114 "ffmpeg fixture: {}",
20115 String::from_utf8_lossy(&y4m.stderr)
20116 );
20117 let args: Vec<&str> = vec![
20118 "--codec=av1",
20119 "--passes=1",
20120 "--end-usage=q",
20121 "--cq-level=45",
20122 "--cpu-used=0",
20123 "--kf-max-dist=1000",
20124 "--threads=1",
20125 "--row-mt=0",
20126 "--auto-alt-ref=1",
20127 "--lag-in-frames=16",
20128 "--enable-fwd-kf=0",
20129 "--enable-order-hint=1",
20130 "--enable-warped-motion=1",
20131 "--enable-obmc=1",
20132 "--tune-content=default",
20133 "--enable-masked-comp=0",
20134 "--enable-interintra-comp=1",
20135 "--enable-onesided-comp=0",
20136 "--enable-interintra-wedge=1",
20137 "--enable-smooth-interintra=1",
20138 "--enable-rect-partitions=0",
20139 "--enable-ab-partitions=0",
20140 "--enable-1to4-partitions=0",
20141 "--enable-filter-intra=0",
20142 "--enable-smooth-intra=0",
20143 "--enable-paeth-intra=0",
20144 "--enable-directional-intra=0",
20145 "--enable-angle-delta=0",
20146 "--enable-tx-size-search=0",
20147 "--enable-cdef=0",
20148 "--enable-restoration=0",
20149 "--max-partition-size=32",
20150 "--min-partition-size=32",
20151 "--enable-palette=0",
20152 "--enable-intrabc=0",
20153 "--enable-cfl-intra=0",
20154 "--enable-ref-frame-mvs=0",
20155 "--obu",
20156 "-o",
20157 "-",
20158 "-",
20159 ];
20160 let out = run_with_stdin(Command::new(aomenc_path())
20161 .args(&args), &y4m.stdout);
20162 assert!(
20163 out.status.success(),
20164 "aomenc refused the fixture: {}",
20165 String::from_utf8_lossy(&out.stderr)
20166 );
20167 let stream = out.stdout;
20168 let frames = match decode_stream(&stream) {
20169 Err(e) => {
20170 let msg = e.to_string();
20171 assert!(
20172 msg.contains("unsupported"),
20173 "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
20174 );
20175 // Verifier note (lane-wii r2): no refusal string containing
20176 // "wedge"/"interintra" exists in the decoder any more, so
20177 // string-forbidding asserts here would be vacuous (class
20178 // gate-blind-to-feature). The proof this gate carries is
20179 // pixel-exact decode plus the wii_hits count printed below.
20180 named_refusals += 1;
20181 eprintln!("seed {seed} refusal (non-wedge capability): {msg}");
20182 continue;
20183 }
20184 Ok(frames) => frames,
20185 };
20186 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
20187 assert_eq!(frames.len(), frame_count);
20188 let mismatched = frames
20189 .iter()
20190 .zip(&ffmpeg_frames)
20191 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
20192 if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
20193 std::fs::write(&path, &stream).expect("writing pinned stream");
20194 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
20195 }
20196 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20197 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
20198 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
20199 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
20200 }
20201 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
20202 // stream again, comparing EVERY decode-order frame -- the hidden
20203 // (show_frame == 0) alt-ref frames the ffmpeg compare above
20204 // cannot see, because both sides of it emit shown frames only.
20205 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
20206 eprintln!(
20207 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
20208 {hidden_n} hidden, all pixel-exact vs the oracle"
20209 );
20210 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
20211 // libaom's temporal alt-ref filter absorbs this recipe's hidden
20212 // frames, so the compare above is vacuous -- re-encode the same
20213 // fixture with --arnr-maxframes=0 and compare THOSE.
20214 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
20215 eprintln!(
20216 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
20217 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
20218 );
20219 }
20220 matched += 1;
20221 }
20222 assert!(
20223 matched > 0,
20224 "{NAME}: every attempt refused on other capabilities; the gate never exercised wedge-interintra"
20225 );
20226 // Hardened from a soft-note (verifier: gate-blind-to-feature): the
20227 // recipe fired wedge-interintra on EVERY one of 6 hammer runs
20228 // (wii_hits 2-7), so a zero-hit run is a regression, not sampling.
20229 assert!(
20230 crate::decode::wii_hits() > 0,
20231 "{NAME}: {matched} pixel-exact matches but zero wedge-interintra blocks fired -- \
20232 the blend is unexercised (recipe fired 2-7 hits per run when landed)"
20233 );
20234 eprintln!(
20235 "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches out of {n_attempts}, wii_hits={}",
20236 crate::decode::wii_hits()
20237 );
20238 }
20239
20240 /// The affine-capable encoder (`scripts/build-aom-affine-oracle.sh`),
20241 /// separate from the shared oracle because stock libaom's global-motion
20242 /// model search is pinned to ROTZOOM and can never emit AFFINE.
20243 fn affine_aomenc_path() -> std::path::PathBuf {
20244 if let Some(p) = std::env::var_os("EC_AV1_AFFINE_AOMENC") {
20245 return std::path::PathBuf::from(p);
20246 }
20247 let home = std::env::var_os("HOME").unwrap_or_default();
20248 std::path::PathBuf::from(home).join(".cache/aom-affine/build/aomenc")
20249 }
20250
20251 fn have_affine_aomenc() -> bool {
20252 let present = affine_aomenc_path().is_file();
20253 assert!(
20254 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
20255 "EC_AV1_REQUIRE_AOMENC is set but no affine-capable aomenc at {} -- run \
20256 scripts/build-aom-affine-oracle.sh",
20257 affine_aomenc_path().display()
20258 );
20259 present
20260 }
20261
20262 /// lane-gmaffine r1: an inter frame whose `global_motion_params` carries a
20263 /// SIX-parameter (`AFFINE`) model for a single-reference frame -- refused
20264 /// by name since lane-gm r4 because no aomenc recipe ever reached it.
20265 /// The reason it never did is in libaom's own encoder, not in the
20266 /// content: `av1/encoder/global_motion_facade.c:24` pins the model search
20267 /// to `ROTZOOM` at both ends, so *no* `--enable-global-motion=1` command
20268 /// line over any source can produce the case. The decoder must still
20269 /// handle it (the bitstream allows it, `read_global_motion_params` reads
20270 /// params 4/5 with their own subexp references, and ffmpeg decodes it),
20271 /// so this gate widens exactly that one encoder-side search range in a
20272 /// side build and encodes with it. Everything downstream is ordinary
20273 /// libaom and the pixel oracle is still ffmpeg.
20274 ///
20275 /// Content: rotation composed with a progressive *anisotropic* stretch --
20276 /// a similarity transform plus unequal axis scaling is precisely what a
20277 /// 4-parameter ROTZOOM model cannot express, which is what makes the
20278 /// encoder's RD pick AFFINE. `affine_gm_hits()` hard-asserts that real
20279 /// blocks were predicted through the 6-parameter warp, not merely that a
20280 /// header parsed one (class `gate-blind-to-feature`).
20281 #[test]
20282 fn a_real_affine_global_motion_stream_decodes_pixel_exact() {
20283 const NAME: &str = "a_real_affine_global_motion_stream_decodes_pixel_exact";
20284 let _gate_lock = lock_gate_counters();
20285 if !have_ffmpeg() {
20286 eprintln!("SKIP {NAME}: no ffmpeg");
20287 return;
20288 }
20289 if !have_affine_aomenc() {
20290 eprintln!(
20291 "SKIP {NAME}: no affine-capable aomenc at {} (scripts/build-aom-affine-oracle.sh)",
20292 affine_aomenc_path().display()
20293 );
20294 return;
20295 }
20296 let (width, height, frame_count) = (64usize, 64usize, 24usize);
20297 let duration = frame_count as f64 / 25.0;
20298 // Both depths: his own AV1 library is yuv420p10le throughout, and a
20299 // 10-bit AFFINE warp runs the same `warp_affine` over wider samples.
20300 for depth in [8u32, 10u32] {
20301 // `-t` is the real bound on mandelbrot (it ignores `end_pts` and
20302 // has hung a gate for an hour); the 96x96 source is rotated and
20303 // then stretched horizontally only, and cropped back to 64x64.
20304 let source = format!(
20305 "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\
20306 scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}"
20307 );
20308 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
20309 let mut ff_args: Vec<&str> =
20310 vec!["-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt];
20311 // y4m has no official 10-bit tag, same as the 10-bit gate above.
20312 if depth == 10 {
20313 ff_args.extend(["-strict", "-1"]);
20314 }
20315 let duration_arg = duration.to_string();
20316 ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]);
20317 let y4m = Command::new("ffmpeg")
20318 .args(&ff_args)
20319 .stdin(Stdio::null())
20320 .stdout(Stdio::piped())
20321 .stderr(Stdio::piped())
20322 .output()
20323 .expect("ffmpeg failed to run");
20324 assert!(
20325 y4m.status.success(),
20326 "ffmpeg fixture: {}",
20327 String::from_utf8_lossy(&y4m.stderr)
20328 );
20329 let bit_depth = format!("--bit-depth={depth}");
20330 let input_bit_depth = format!("--input-bit-depth={depth}");
20331 let args: Vec<&str> = vec![
20332 "--codec=av1",
20333 "--passes=1",
20334 "--end-usage=q",
20335 "--cq-level=45",
20336 "--cpu-used=0",
20337 "--kf-max-dist=1000",
20338 "--threads=1",
20339 "--row-mt=0",
20340 "--auto-alt-ref=0",
20341 "--lag-in-frames=0",
20342 "--enable-fwd-kf=0",
20343 "--enable-order-hint=1",
20344 "--enable-global-motion=1",
20345 "--enable-warped-motion=0",
20346 "--enable-obmc=0",
20347 "--tune-content=default",
20348 "--enable-masked-comp=0",
20349 "--enable-interintra-comp=0",
20350 "--enable-onesided-comp=0",
20351 "--enable-rect-partitions=0",
20352 "--enable-ab-partitions=0",
20353 "--enable-1to4-partitions=0",
20354 "--enable-filter-intra=0",
20355 "--enable-smooth-intra=0",
20356 "--enable-paeth-intra=0",
20357 "--enable-directional-intra=0",
20358 "--enable-angle-delta=0",
20359 "--enable-tx-size-search=0",
20360 "--enable-cdef=0",
20361 "--enable-restoration=0",
20362 "--max-partition-size=32",
20363 "--min-partition-size=32",
20364 "--enable-palette=0",
20365 "--enable-intrabc=0",
20366 "--enable-cfl-intra=0",
20367 "--enable-ref-frame-mvs=0",
20368 &bit_depth,
20369 &input_bit_depth,
20370 "--obu",
20371 "-o",
20372 "-",
20373 "-",
20374 ];
20375 let out = run_with_stdin(Command::new(affine_aomenc_path()).args(&args), &y4m.stdout);
20376 assert!(
20377 out.status.success(),
20378 "aomenc refused the fixture: {}",
20379 String::from_utf8_lossy(&out.stderr)
20380 );
20381 let stream = out.stdout;
20382 let before = crate::decode::affine_gm_hits();
20383 let frames =
20384 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} ({depth}-bit): {e}"));
20385 let ffmpeg_frames = if depth == 10 {
20386 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
20387 } else {
20388 ffmpeg_decode_sequence(&stream, width, height, frame_count)
20389 };
20390 assert_eq!(frames.len(), frame_count);
20391 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20392 assert_eq!(got.y, want.y, "{NAME} {depth}-bit frame {i} luma vs ffmpeg");
20393 assert_eq!(got.u, want.u, "{NAME} {depth}-bit frame {i} U vs ffmpeg");
20394 assert_eq!(got.v, want.v, "{NAME} {depth}-bit frame {i} V vs ffmpeg");
20395 }
20396 let hits = crate::decode::affine_gm_hits() - before;
20397 assert!(
20398 hits > 0,
20399 "{NAME} ({depth}-bit): decoded pixel-exact but no block was predicted through a \
20400 6-parameter global-motion warp -- the AFFINE path is unexercised"
20401 );
20402 eprintln!("{NAME}: {depth}-bit, {frame_count} frames pixel-exact, affine_gm_hits={hits}");
20403 }
20404 }
20405
20406 /// lane-gmaffine r1: the two 8x8-LEAF motion gates. `decode_inter_block8`
20407 /// is a separate function from [`decode_inter_block`], and until this
20408 /// round it refused both `GLOBALMV` ("GLOBALMV (round 3)") and
20409 /// `WARPED_CAUSAL` at that size while the 16x16+ leaf had implemented
20410 /// both for rounds. The reason no earlier gate caught it: the existing
20411 /// 8x8 OBMC gate clamps `--max-partition-size=32` and aomenc's RD then
20412 /// never splits down to a clean 8x8 leaf (that gate has never fired in
20413 /// 80 attempts). `--min-partition-size=8 --max-partition-size=8` removes
20414 /// the choice entirely -- every inter leaf in the stream IS an 8x8 one,
20415 /// so the leaf path is exercised by construction rather than by luck.
20416 ///
20417 /// Content is the affine gate's rotating/zooming mandelbrot (global
20418 /// motion the encoder can actually model), and the hit counters
20419 /// (`globalmv_hits_8` / `warp_hits_8`) are 8x8-leaf-specific: a
20420 /// 16x16-leaf GLOBALMV or warp cannot satisfy them.
20421 fn run_8x8_leaf_motion_gate(
20422 name: &str,
20423 global_motion: bool,
20424 counter: fn() -> usize,
20425 ) {
20426 // 72x64: `decode_inter_block8` is reached ONLY through the
20427 // true-edge-straddling 16x16 path (an interior 16x16
20428 // PARTITION_SPLIT is still refused by name), so the frame is 8
20429 // luma columns wider than its last whole superblock -- every 16x16
20430 // block in that right-hand strip is cut on ONE axis and decodes as
20431 // four 8x8 leaves by construction. `--min-partition-size=16` keeps
20432 // the interior out of the still-refused sub-16x16 case.
20433 let (width, height, frame_count) = (64usize, 64usize, 24usize);
20434 let duration = frame_count as f64 / 25.0;
20435 // The encoder's own RD still chooses WHICH 8x8 leaf codes GLOBALMV /
20436 // WARPED_CAUSAL, and at some quantisers it picks a rect partition at
20437 // 16x16 (still refused) or a non-LAST reference (still refused at the
20438 // 8x8 leaf) before ever reaching one. So sweep a few quantisers and
20439 // require at least one attempt, at each depth, that BOTH decodes
20440 // pixel-exact AND fires the counter -- a refusing attempt is recorded,
20441 // never a pass (class `gate-skips-on-its-own-failure`).
20442 let mut fired_any = [false; 2];
20443 let mut notes: Vec<String> = Vec::new();
20444 for (di, depth) in [8u32, 10u32].into_iter().enumerate() {
20445 for cq in [32u32, 45, 55] {
20446 let cq_arg = format!("--cq-level={cq}");
20447 let max_part_arg = format!(
20448 "--max-partition-size={}",
20449 std::env::var("EC_8X8_MAXPART").unwrap_or_else(|_| "8".into())
20450 );
20451 let source = format!(
20452 "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\
20453 scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}"
20454 );
20455 let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
20456 let mut ff_args: Vec<&str> =
20457 vec!["-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt];
20458 if depth == 10 {
20459 ff_args.extend(["-strict", "-1"]);
20460 }
20461 let duration_arg = duration.to_string();
20462 ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]);
20463 let y4m = Command::new("ffmpeg")
20464 .args(&ff_args)
20465 .stdin(Stdio::null())
20466 .stdout(Stdio::piped())
20467 .stderr(Stdio::piped())
20468 .output()
20469 .expect("ffmpeg failed to run");
20470 assert!(
20471 y4m.status.success(),
20472 "ffmpeg fixture: {}",
20473 String::from_utf8_lossy(&y4m.stderr)
20474 );
20475 let bit_depth = format!("--bit-depth={depth}");
20476 let input_bit_depth = format!("--input-bit-depth={depth}");
20477 let gm_arg = format!("--enable-global-motion={}", u8::from(global_motion));
20478 let warp_arg = format!("--enable-warped-motion={}", u8::from(!global_motion));
20479 let args: Vec<&str> = vec![
20480 "--codec=av1",
20481 "--passes=1",
20482 "--end-usage=q",
20483 &cq_arg,
20484 "--cpu-used=0",
20485 "--kf-max-dist=1000",
20486 "--threads=1",
20487 "--row-mt=0",
20488 "--auto-alt-ref=0",
20489 "--lag-in-frames=0",
20490 "--enable-fwd-kf=0",
20491 "--enable-order-hint=1",
20492 &gm_arg,
20493 &warp_arg,
20494 "--enable-obmc=0",
20495 "--tune-content=default",
20496 "--enable-masked-comp=0",
20497 "--enable-interintra-comp=0",
20498 "--enable-onesided-comp=0",
20499 "--enable-rect-partitions=0",
20500 "--enable-ab-partitions=0",
20501 "--enable-1to4-partitions=0",
20502 "--enable-filter-intra=0",
20503 "--enable-smooth-intra=0",
20504 "--enable-paeth-intra=0",
20505 "--enable-directional-intra=0",
20506 "--enable-angle-delta=0",
20507 "--enable-tx-size-search=0",
20508 "--enable-cdef=0",
20509 "--enable-restoration=0",
20510 &max_part_arg,
20511 "--min-partition-size=8",
20512 "--enable-palette=0",
20513 "--enable-intrabc=0",
20514 "--enable-cfl-intra=0",
20515 "--enable-ref-frame-mvs=0",
20516 &bit_depth,
20517 &input_bit_depth,
20518 "--obu",
20519 "-o",
20520 "-",
20521 "-",
20522 ];
20523 let out = run_with_stdin(Command::new(aomenc_path())
20524 .args(&args), &y4m.stdout);
20525 assert!(
20526 out.status.success(),
20527 "aomenc refused the fixture: {}",
20528 String::from_utf8_lossy(&out.stderr)
20529 );
20530 let stream = out.stdout;
20531 let before = counter();
20532 let frames = match decode_stream(&stream) {
20533 Ok(f) => f,
20534 Err(e) => {
20535 let msg = e.to_string();
20536 assert!(
20537 msg.contains("unsupported"),
20538 "{name} ({depth}-bit, cq {cq}) failed outright: {msg}"
20539 );
20540 notes.push(format!("{depth}-bit cq {cq}: {msg}"));
20541 continue;
20542 }
20543 };
20544 let ffmpeg_frames = if depth == 10 {
20545 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
20546 } else {
20547 ffmpeg_decode_sequence(&stream, width, height, frame_count)
20548 };
20549 assert_eq!(frames.len(), frame_count);
20550 let hits = counter() - before;
20551 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20552 assert_eq!(got.y, want.y, "{name} {depth}-bit frame {i} luma vs ffmpeg");
20553 assert_eq!(got.u, want.u, "{name} {depth}-bit frame {i} U vs ffmpeg");
20554 assert_eq!(got.v, want.v, "{name} {depth}-bit frame {i} V vs ffmpeg");
20555 }
20556 if hits == 0 {
20557 notes.push(format!(
20558 "{depth}-bit cq {cq}: {frame_count} frames pixel-exact but 0 8x8-leaf hits"
20559 ));
20560 continue;
20561 }
20562 fired_any[di] = true;
20563 eprintln!(
20564 "{name}: {depth}-bit cq {cq}, {frame_count} frames pixel-exact, 8x8 hits={hits}"
20565 );
20566 }
20567 }
20568 assert!(
20569 fired_any[0] && fired_any[1],
20570 "{name}: no attempt both decoded pixel-exact and fired the 8x8 leaf \
20571 (8-bit fired {}, 10-bit fired {}):\n{}",
20572 fired_any[0], fired_any[1], notes.join("\n")
20573 );
20574 }
20575
20576 /// lane-gmaffine r1 item (3): `GLOBALMV` at an 8x8 leaf, ROTZOOM global
20577 /// motion, warp built from the frame's own model.
20578 #[test]
20579 fn a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact() {
20580 const NAME: &str = "a_real_globalmv_8x8_leaf_stream_decodes_pixel_exact";
20581 let _gate_lock = lock_gate_counters();
20582 if !have_ffmpeg() {
20583 eprintln!("SKIP {NAME}: no ffmpeg");
20584 return;
20585 }
20586 if !have_aomenc() {
20587 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20588 return;
20589 }
20590 run_8x8_leaf_motion_gate(NAME, true, crate::decode::globalmv_hits_8);
20591 }
20592
20593 /// lane-gmaffine r1 item (2): `WARPED_CAUSAL` at an 8x8 leaf --
20594 /// findSamples + `av1_find_projection` + the warp filter at BLOCK_8X8.
20595 #[test]
20596 fn a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact() {
20597 const NAME: &str = "a_real_warped_causal_8x8_leaf_stream_decodes_pixel_exact";
20598 let _gate_lock = lock_gate_counters();
20599 if !have_ffmpeg() {
20600 eprintln!("SKIP {NAME}: no ffmpeg");
20601 return;
20602 }
20603 if !have_aomenc() {
20604 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20605 return;
20606 }
20607 run_8x8_leaf_motion_gate(NAME, false, crate::decode::warp_hits_8);
20608 }
20609
20610 /// lane-rect16 r1/r2: a plain default-settings aomenc run over lavfi
20611 /// `mandelbrot` (`--cpu-used=4 --end-usage=q --cq-level=32`, no
20612 /// `--enable-*` flags) used to refuse frame 0 outright with "a partition
20613 /// below 16x16 other than a clean split". r1 root-caused the FIRST hit to
20614 /// a `PARTITION_VERT_B` `partition_w16` symbol at mi=(3,2) and wired it
20615 /// (left 8x16 real `decode_block_rect` strip + two stacked 8x8
20616 /// `decode_leaf8` leaves on the right). r2 re-measured after that fix
20617 /// (`decision-before-quantiser`-shaped: don't trust a stale premise) and
20618 /// found this stream's REAL first-hit blocker in z-order is earlier, at
20619 /// mi=(0,7): a plain `PARTITION_HORZ`. That arm is now wired too
20620 /// (`decode_leaf_rect`, sibling to `decode_leaf8` but real-mi-addressed
20621 /// for a non-square strip) -- `horz_vert_intra_hits` proves it fires.
20622 /// This exact stream's own HORZ block at mi=(0,7) is *coded* (real
20623 /// coefficients), which is NOT ported (same ceiling as VERT_B's own
20624 /// non-skip refusal -- no rectangular-transform coefficient tables at
20625 /// this size), so decode still stops there and `vert_b_intra_hits`
20626 /// never gets a chance to increment on this particular stream. This gate
20627 /// proves the HORZ arm fires and the OLD (now-false) two-clause refusal
20628 /// never reappears, not a pixel-exact decode of this stream.
20629 #[test]
20630 fn a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm() {
20631 const NAME: &str = "a_real_aomenc_stream_with_mandelbrot_fires_the_vert_b_partition_arm";
20632 let _gate_lock = lock_gate_counters();
20633 if !have_ffmpeg() {
20634 eprintln!("SKIP {NAME}: no ffmpeg");
20635 return;
20636 }
20637 if !have_aomenc() {
20638 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20639 return;
20640 }
20641 let (width, height) = (192usize, 128usize);
20642 let y4m = Command::new("ffmpeg")
20643 .args([
20644 "-v",
20645 "error",
20646 "-f",
20647 "lavfi",
20648 "-i",
20649 &format!("mandelbrot=size={width}x{height}"),
20650 "-pix_fmt",
20651 "yuv420p",
20652 "-t",
20653 "1",
20654 "-f",
20655 "yuv4mpegpipe",
20656 "-",
20657 ])
20658 .stdin(Stdio::null())
20659 .stdout(Stdio::piped())
20660 .stderr(Stdio::piped())
20661 .output()
20662 .expect("ffmpeg failed to run");
20663 assert!(
20664 y4m.status.success(),
20665 "ffmpeg fixture: {}",
20666 String::from_utf8_lossy(&y4m.stderr)
20667 );
20668 let out = run_with_stdin(Command::new(aomenc_path())
20669 .args([
20670 "--threads=1",
20671 "--row-mt=0",
20672 "--sb-size=64",
20673 "--cpu-used=4",
20674 "--end-usage=q",
20675 "--cq-level=32",
20676 "--passes=1",
20677 "--obu",
20678 "-o",
20679 "-",
20680 "-",
20681 ]), &y4m.stdout);
20682 assert!(
20683 out.status.success(),
20684 "aomenc refused the fixture: {}",
20685 String::from_utf8_lossy(&out.stderr)
20686 );
20687 let stream = out.stdout;
20688 // lane-rect16 r2: the recipe above was missing `--passes=1` --
20689 // without it aomenc silently ran 2-pass and wrote nothing to stdout
20690 // on pass 1 (still exit 0), so this gate always decoded an EMPTY
20691 // stream and never actually exercised the arm it claims to gate.
20692 assert!(
20693 !stream.is_empty(),
20694 "{NAME}: aomenc wrote an empty stream (missing --passes=1?)"
20695 );
20696 let result = decode_stream(&stream);
20697 // The now-lifted false claim ("codes only the square arms below
20698 // 16x16") must never appear again.
20699 if let Err(e) = &result {
20700 let msg = e.to_string();
20701 assert!(
20702 !msg.contains("this decoder codes only the square arms below 16x16"),
20703 "{NAME}: the OLD (disproved) refusal reappeared: {msg}"
20704 );
20705 }
20706 assert!(
20707 crate::decode::horz_vert_intra_hits() > 0,
20708 "{NAME}: the plain PARTITION_HORZ/VERT arm never fired on this stream (regression -- \
20709 it fired deterministically at mi=(0,7) when this gate was written)"
20710 );
20711 eprintln!(
20712 "{NAME}: horz_vert_intra_hits={}, vert_b_intra_hits={}, decode result: {:?}",
20713 crate::decode::horz_vert_intra_hits(),
20714 crate::decode::vert_b_intra_hits(),
20715 result.as_ref().map(|f| f.len()).map_err(|e| e.to_string())
20716 );
20717 }
20718 /// lane-rectx r3: a real `aomenc` stream whose 16x16-level
20719 /// `PARTITION_HORZ`/`PARTITION_VERT` strips are CODED (non-skip), i.e.
20720 /// carry genuine `TX_16X8`/`TX_8X16` luma coefficients and their
20721 /// `TX_8X4`/`TX_4X8` chroma halves through [`decode_leaf_rect`]'s
20722 /// lane-rectx arm -- the refusal "a coded (non-skip) HORZ/VERT rect strip
20723 /// below 16x16" this round lifts. `--min-partition-size=8
20724 /// --max-partition-size=32 --enable-rect-partitions=1` is what makes
20725 /// aomenc reach for a 16x8 leaf at all; mandelbrot at `cq-level=24` is
20726 /// what makes those leaves non-skip (a gradient fixture codes them all
20727 /// away). `--reduced-tx-type-set=1` pins the five-symbol
20728 /// `EXT_TX_SET_DTT4_IDTX` alphabet: without it aomenc also writes
20729 /// `V_DCT`/`H_DCT`, whose 1D tx classes [`read_coeffs_rect`] still
20730 /// refuses by name (see the r3 report's open residue), so a `=0` run
20731 /// would prove nothing about the 2D path it does support.
20732 ///
20733 /// r2 shipped this path unproven; it was wrong. `TxbSet::LumaRect16x8`
20734 /// read its `tx_type` symbol from the 16x16 row, but libaom's
20735 /// `read_tx_type` indexes `intra_ext_tx_cdf[eset][txsize_sqr_map[tx_size]]`
20736 /// and `txsize_sqr_map[TX_16X8] == TX_8X8` -- a five-symbol CDF where a
20737 /// seven-symbol one belonged, desyncing at the FIRST coded rect leaf
20738 /// (whole frame wrong from pixel (0,0)).
20739 #[test]
20740 fn a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact() {
20741 const NAME: &str =
20742 "a_real_aomenc_stream_with_a_coded_rect_strip_below_16x16_decodes_pixel_exact";
20743 let _gate_lock = lock_gate_counters();
20744 if !have_ffmpeg() {
20745 eprintln!("SKIP {NAME}: no ffmpeg");
20746 return;
20747 }
20748 if !have_aomenc() {
20749 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20750 return;
20751 }
20752 let (width, height) = (64usize, 64usize);
20753 let y4m = Command::new("ffmpeg")
20754 .args([
20755 "-v",
20756 "error",
20757 "-f",
20758 "lavfi",
20759 "-i",
20760 &format!("mandelbrot=size={width}x{height}:start_x=-0.6"),
20761 "-pix_fmt",
20762 "yuv420p",
20763 "-t",
20764 "1",
20765 "-vframes",
20766 "1",
20767 "-f",
20768 "yuv4mpegpipe",
20769 "-",
20770 ])
20771 .stdin(Stdio::null())
20772 .stdout(Stdio::piped())
20773 .stderr(Stdio::piped())
20774 .output()
20775 .expect("ffmpeg failed to run");
20776 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
20777 let encode = || {
20778 let out = run_with_stdin(Command::new(aomenc_path())
20779 .args([
20780 "--codec=av1",
20781 "--passes=1",
20782 "--end-usage=q",
20783 "--cq-level=16",
20784 "--cpu-used=4",
20785 "--threads=1",
20786 "--row-mt=0",
20787 "--sb-size=64",
20788 "--kf-max-dist=0",
20789 "--enable-rect-partitions=1",
20790 "--enable-ab-partitions=0",
20791 "--enable-1to4-partitions=0",
20792 "--enable-tx-size-search=0",
20793 // Filter intra on a strip is a separate, still-refused
20794 // predictor (`filter intra on a HORZ/VERT strip`); this
20795 // gate is about the rect RESIDUAL path, so it is off here
20796 // and covered by the square filter-intra gate instead.
20797 "--enable-filter-intra=0",
20798 "--reduced-tx-type-set=1",
20799 "--min-partition-size=8",
20800 "--max-partition-size=32",
20801 "--obu",
20802 "-o",
20803 "-",
20804 "-",
20805 ]), &y4m.stdout);
20806 assert!(
20807 out.status.success(),
20808 "aomenc refused the fixture: {}",
20809 String::from_utf8_lossy(&out.stderr)
20810 );
20811 out.stdout
20812 };
20813 // The fixture rule: an encoder output is only a pin if it reproduces.
20814 let stream = encode();
20815 assert_eq!(stream, encode(), "{NAME}: aomenc output is not reproducible for this recipe");
20816 let before = crate::decode::rect_leaf_coeff_hits();
20817 let frames = decode_stream(&stream)
20818 .unwrap_or_else(|e| panic!("{NAME}: decode failed, not a pixel mismatch: {e}"));
20819 let fired = crate::decode::rect_leaf_coeff_hits() - before;
20820 assert!(
20821 fired > 0,
20822 "{NAME}: the stream decoded but no coded (non-skip) rect leaf fired -- \
20823 the gate proves nothing"
20824 );
20825 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
20826 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame");
20827 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
20828 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20829 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg ({fired} coded rect leaves)");
20830 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg");
20831 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg");
20832 }
20833 eprintln!("{NAME}: pixel-exact, rect_leaf_coeff_hits={fired}");
20834 }
20835
20836 /// lane-rectx r5: the same 16x8/8x16 rect leaves, but this time proving
20837 /// what a LATER, non-strip block reads from them. `decode_leaf_rect` took
20838 /// the mi-exact intra mode map in r4; `decode_block`/`decode_block_rect`/
20839 /// `decode_block_rect64` did not, so a 32x16 strip whose left neighbour was
20840 /// a 16x8 leaf still read the coarse per-16x16 `left_mode` slot -- which no
20841 /// sub-16x16 block ever writes -- and picked a DIFFERENT `kf_y_mode` CDF row
20842 /// for the same decoded mode value. The stream stayed in sync through mode
20843 /// info (`EC_TRACE_MODE_STEP` ranges match up to that symbol) and then
20844 /// diverged inside the block's own coefficients: the whole bottom-right
20845 /// 32x32 quadrant of this fixture decoded wrong (1650 bytes) while the
20846 /// three earlier quadrants were exact -- wrong pixels returned as success.
20847 /// `mode_mi_override_hits` counts exactly the reads where the mi-exact
20848 /// neighbour disagrees with the coarse slot, so a regression that drops the
20849 /// override again fails the counter as well as the pixels.
20850 #[test]
20851 fn a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact() {
20852 const NAME: &str =
20853 "a_real_aomenc_stream_whose_square_block_reads_a_sub16_neighbours_mode_decodes_pixel_exact";
20854 let _gate_lock = lock_gate_counters();
20855 if !have_ffmpeg() {
20856 eprintln!("SKIP {NAME}: no ffmpeg");
20857 return;
20858 }
20859 if !have_aomenc() {
20860 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20861 return;
20862 }
20863 let (width, height) = (64usize, 64usize);
20864 let y4m = Command::new("ffmpeg")
20865 .args([
20866 "-v", "error", "-f", "lavfi", "-i",
20867 &format!("rgbtestsrc=size={width}x{height}"),
20868 "-pix_fmt", "yuv420p", "-t", "1", "-vframes", "1", "-f", "yuv4mpegpipe", "-",
20869 ])
20870 .stdin(Stdio::null())
20871 .stdout(Stdio::piped())
20872 .stderr(Stdio::piped())
20873 .output()
20874 .expect("ffmpeg failed to run");
20875 assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr));
20876 // Two swept cells of the r4 sweep that decoded to completion with
20877 // WRONG pixels (1714 and 1650 bytes): `--reduced-tx-type-set` and
20878 // `--enable-filter-intra` are the two axes that move which block sizes
20879 // aomenc reaches for here; both arms are pinned.
20880 let mut total_overrides = 0usize;
20881 for (rtx, filter_intra) in [("1", "0"), ("0", "1")] {
20882 let encode = || {
20883 let out = run_with_stdin(Command::new(aomenc_path())
20884 .args([
20885 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32",
20886 "--cpu-used=4", "--threads=1", "--row-mt=0", "--sb-size=64",
20887 "--kf-max-dist=0", "--enable-rect-partitions=1",
20888 "--enable-ab-partitions=0", "--enable-1to4-partitions=0",
20889 "--enable-tx-size-search=0", "--enable-cdef=0",
20890 "--enable-restoration=0",
20891 &format!("--enable-filter-intra={filter_intra}"),
20892 &format!("--reduced-tx-type-set={rtx}"),
20893 "--min-partition-size=8", "--max-partition-size=32",
20894 "--obu", "-o", "-", "-",
20895 ]), &y4m.stdout);
20896 assert!(
20897 out.status.success(),
20898 "aomenc refused the fixture: {}",
20899 String::from_utf8_lossy(&out.stderr)
20900 );
20901 out.stdout
20902 };
20903 let stream = encode();
20904 assert_eq!(
20905 stream,
20906 encode(),
20907 "{NAME}: aomenc output is not reproducible (rtx={rtx} filter_intra={filter_intra})"
20908 );
20909 let before = crate::decode::mode_mi_override_hits();
20910 let frames = decode_stream(&stream).unwrap_or_else(|e| {
20911 panic!("{NAME}: decode failed (rtx={rtx} filter_intra={filter_intra}): {e}")
20912 });
20913 // Counted only on an attempt that actually decoded AND is compared
20914 // below -- a refusal never contributes to the firing assert.
20915 let overrides = crate::decode::mode_mi_override_hits() - before;
20916 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frames.len());
20917 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame");
20918 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
20919 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20920 assert_eq!(
20921 got.y, want.y,
20922 "{NAME} frame {i} luma vs ffmpeg (rtx={rtx} filter_intra={filter_intra}, \
20923 {overrides} mi-exact mode overrides)"
20924 );
20925 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (rtx={rtx})");
20926 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (rtx={rtx})");
20927 }
20928 total_overrides += overrides;
20929 }
20930 assert!(
20931 total_overrides > 0,
20932 "{NAME}: no non-strip block ever read a mi-exact neighbour that disagreed with its \
20933 coarse slot -- the gate proves nothing"
20934 );
20935 eprintln!("{NAME}: pixel-exact, mode_mi_override_hits={total_overrides}");
20936 }
20937
20938 /// lane-cfl r1: the chroma intra-edge FILTER TYPE is the neighbour's
20939 /// `uv_mode` (libaom `get_filt_type`, reconintra.c: `chroma_above_mbmi`/
20940 /// `chroma_left_mbmi` -> `is_smooth` on `uv_mode`), and two whole decode
20941 /// paths passed a hardcoded `false` for it -- `decode_leaf_8x8` (every
20942 /// 8x8 leaf of a SPLIT) and `decode_leaf_rect` (every rect strip below
20943 /// 16x16), on a stale "chroma stays false (exact) until a smooth/paeth
20944 /// uv_mode can reach decode at all" comment. On top of that the coarse
20945 /// `above_uv_mode`/`left_uv_mode` cells are 16px-granular and their
20946 /// `for cell in 0..w / SUB` write runs ZERO times for any block below
20947 /// 16x16, so even the paths that DID read them saw whatever a
20948 /// 16x16-or-larger block had left there (class: context read from one
20949 /// cell / neighbour map at the wrong granularity). Result on this
20950 /// recipe: luma byte-exact, entropy ladder identical, and 40 U + 86 V
20951 /// chroma bytes wrong -- every one of them downstream of one 4x4 chroma
20952 /// block at mi(8,12) whose D135 + `angle_delta_uv=-3` left edge was
20953 /// filtered at the wrong strength (`ft=0` where the instrumented aomdec
20954 /// prints `ft=1`, left edge `95,59,30,28` vs `90,61,37,29`).
20955 ///
20956 /// Both arms hard-assert per-attempt counters for the two chroma block
20957 /// shapes involved (`UV_CFL_PRED` blocks, nonzero `angle_delta_uv`
20958 /// blocks) plus the mi-exact UV-neighbour override, and are counted only
20959 /// on an attempt that decoded AND is pixel-compared.
20960 #[test]
20961 fn a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact()
20962 {
20963 const NAME: &str = "a_real_aomenc_stream_whose_chroma_edge_filter_reads_a_sub16_neighbours_uv_mode_decodes_pixel_exact";
20964 let _gate_lock = lock_gate_counters();
20965 if !have_ffmpeg() {
20966 eprintln!("SKIP {NAME}: no ffmpeg");
20967 return;
20968 }
20969 if !have_aomenc() {
20970 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20971 return;
20972 }
20973 let mut compared = 0usize;
20974 let (width, height) = (64usize, 64usize);
20975 // 8-bit arm = the r5 residue cell ("mandfi161"); 10-bit arm = its
20976 // twin through the same recipe at `--bit-depth=10`.
20977 for depth in [8usize, 10] {
20978 let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
20979 let y4m = Command::new("ffmpeg")
20980 .args([
20981 "-v", "error", "-f", "lavfi", "-i",
20982 &format!("mandelbrot=size={width}x{height}:start_x=-0.6"),
20983 "-pix_fmt", pix, "-strict", "-1", "-t", "1", "-vframes", "1",
20984 "-f", "yuv4mpegpipe", "-",
20985 ])
20986 .stdin(Stdio::null())
20987 .stdout(Stdio::piped())
20988 .stderr(Stdio::piped())
20989 .output()
20990 .expect("ffmpeg failed to run");
20991 assert!(
20992 y4m.status.success(),
20993 "{NAME}: ffmpeg fixture (depth={depth}): {}",
20994 String::from_utf8_lossy(&y4m.stderr)
20995 );
20996 let encode = || {
20997 let out = run_with_stdin(Command::new(aomenc_path())
20998 .args([
20999 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=16",
21000 "--cpu-used=4", "--threads=1", "--row-mt=0", "--sb-size=64",
21001 "--kf-max-dist=0", "--enable-rect-partitions=1",
21002 "--enable-ab-partitions=0", "--enable-1to4-partitions=0",
21003 "--enable-tx-size-search=0", "--enable-filter-intra=1",
21004 "--reduced-tx-type-set=1", "--min-partition-size=8",
21005 "--max-partition-size=32",
21006 &format!("--input-bit-depth={depth}"),
21007 &format!("--bit-depth={depth}"),
21008 "--obu", "-o", "-", "-",
21009 ]), &y4m.stdout);
21010 assert!(
21011 out.status.success(),
21012 "aomenc refused the fixture (depth={depth}): {}",
21013 String::from_utf8_lossy(&out.stderr)
21014 );
21015 out.stdout
21016 };
21017 let stream = encode();
21018 assert_eq!(
21019 stream,
21020 encode(),
21021 "{NAME}: aomenc output is not reproducible (depth={depth})"
21022 );
21023 let before_cfl = crate::decode::cfl_block_hits();
21024 let before_angle = crate::decode::uv_angle_delta_hits();
21025 let before_uv = crate::decode::uv_mode_mi_override_hits();
21026 let frames = match decode_stream(&stream) {
21027 Ok(frames) => frames,
21028 // Only a NAMED refusal is tolerated (COMMON rule): the 10-bit
21029 // twin of this recipe still stops at another lane's open
21030 // sub-16 AB-partition / strip-filter-intra refusals, so it
21031 // cannot be compared yet. Any other error is a failure, and
21032 // `compared` below keeps the test from passing vacuously.
21033 Err(e) => {
21034 let msg = e.to_string();
21035 assert!(
21036 msg.contains("unsupported"),
21037 "{NAME}: decode failed (depth={depth}): {msg}"
21038 );
21039 eprintln!("{NAME}: depth={depth} arm refused (not compared): {msg}");
21040 continue;
21041 }
21042 };
21043 compared += 1;
21044 // Read only on an attempt that decoded AND is compared below.
21045 let cfl_blocks = crate::decode::cfl_block_hits() - before_cfl;
21046 let angle_blocks = crate::decode::uv_angle_delta_hits() - before_angle;
21047 let uv_overrides = crate::decode::uv_mode_mi_override_hits() - before_uv;
21048 let ffmpeg_frames = if depth == 10 {
21049 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
21050 } else {
21051 ffmpeg_decode_sequence(&stream, width, height, frames.len())
21052 };
21053 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame (depth={depth})");
21054 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
21055 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21056 assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (depth={depth})");
21057 assert_eq!(
21058 got.u, want.u,
21059 "{NAME} frame {i} U vs ffmpeg (depth={depth}, {cfl_blocks} CFL blocks, \
21060 {angle_blocks} nonzero-angle_delta_uv blocks, {uv_overrides} mi-exact UV \
21061 neighbour overrides)"
21062 );
21063 assert_eq!(
21064 got.v, want.v,
21065 "{NAME} frame {i} V vs ffmpeg (depth={depth}, {cfl_blocks} CFL blocks, \
21066 {angle_blocks} nonzero-angle_delta_uv blocks, {uv_overrides} mi-exact UV \
21067 neighbour overrides)"
21068 );
21069 }
21070 assert!(
21071 cfl_blocks > 0,
21072 "{NAME}: no UV_CFL_PRED block decoded (depth={depth}) -- the gate proves nothing"
21073 );
21074 assert!(
21075 angle_blocks > 0,
21076 "{NAME}: no nonzero angle_delta_uv chroma block decoded (depth={depth}) -- \
21077 the chroma intra-edge filter path never ran"
21078 );
21079 assert!(
21080 uv_overrides > 0,
21081 "{NAME}: no chroma edge-filter read ever took a mi-exact UV neighbour that \
21082 disagreed with its coarse 16x16 slot (depth={depth}) -- the r1 defect is \
21083 not exercised"
21084 );
21085 eprintln!(
21086 "{NAME}: pixel-exact at {depth}-bit, cfl_blocks={cfl_blocks} \
21087 angle_delta_uv_blocks={angle_blocks} uv_mi_overrides={uv_overrides}"
21088 );
21089 }
21090 assert!(
21091 compared > 0,
21092 "{NAME}: every arm refused -- the gate compared no pixels at all"
21093 );
21094 }
21095
21096 /// lane-reelckf r1: ReelC's key frames decoded with no refusal and WRONG
21097 /// CHROMA (luma bit-exact at every one of ten seek points), from two
21098 /// defects this gate pins:
21099 ///
21100 /// 1. a SKIPPED intra block whose `uv_mode` is `UV_CFL_PRED` still
21101 /// predicts with the CfL term -- libaom
21102 /// `predict_and_reconstruct_intra_block` (decodeframe.c) calls
21103 /// `av1_predict_intra_block_facade` unconditionally and only guards
21104 /// the residual on `mbmi->skip_txfm`. Three skip arms (the 16x16-level
21105 /// 1:4 chroma pair and the two sub-8x8 4x4 groups) dropped it.
21106 /// 2. the chroma intra-edge FILTER TYPE of a 1:4 pair comes from the
21107 /// CHROMA REFERENCE position (libaom `get_intra_edge_filter_type` ->
21108 /// `chroma_above_mbmi`/`chroma_left_mbmi`), not from the closing
21109 /// strip: at the closing strip the above cell is the pair's own first
21110 /// strip, the mi-exact UV map misses and the coarse fallback answers,
21111 /// which flipped `av1_use_intra_edge_upsample` (blk_wh 12 <= 16 for
21112 /// type 0, no upsample for type 1) and moved directional chroma by
21113 /// +-1..3.
21114 ///
21115 /// Recipe is a real `aomenc --sb-size=128 --cpu-used=0` (the shape ReelC
21116 /// uses) with 1:4 partitions and CfL on, both bit depths, and both
21117 /// counters hard-asserted per compared attempt.
21118 #[test]
21119 fn a_real_aomenc_sb128_stream_whose_skipped_cfl_and_1to4_chroma_pairs_decode_pixel_exact() {
21120 const NAME: &str =
21121 "a_real_aomenc_sb128_stream_whose_skipped_cfl_and_1to4_chroma_pairs_decode_pixel_exact";
21122 let _gate_lock = lock_gate_counters();
21123 if !have_ffmpeg() {
21124 eprintln!("SKIP {NAME}: no ffmpeg");
21125 return;
21126 }
21127 if !have_aomenc() {
21128 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
21129 return;
21130 }
21131 let mut compared = 0usize;
21132 let (width, height) = (256usize, 256usize);
21133 for depth in [8usize, 10] {
21134 let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" };
21135 let y4m = Command::new("ffmpeg")
21136 .args([
21137 "-v", "error", "-f", "lavfi", "-i",
21138 &format!(
21139 "mandelbrot=size={width}x{height},\
21140 noise=alls=20:allf=t+u:all_seed=7"
21141 ),
21142 "-pix_fmt", pix, "-strict", "-1", "-t", "1", "-vframes", "1",
21143 "-f", "yuv4mpegpipe", "-",
21144 ])
21145 .stdin(Stdio::null())
21146 .stdout(Stdio::piped())
21147 .stderr(Stdio::piped())
21148 .output()
21149 .expect("ffmpeg failed to run");
21150 assert!(
21151 y4m.status.success(),
21152 "{NAME}: ffmpeg fixture (depth={depth}): {}",
21153 String::from_utf8_lossy(&y4m.stderr)
21154 );
21155 let encode = || {
21156 let out = run_with_stdin(Command::new(aomenc_path())
21157 .args([
21158 "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=52",
21159 "--cpu-used=0", "--threads=1", "--row-mt=0", "--sb-size=128",
21160 "--kf-max-dist=0", "--enable-rect-partitions=1",
21161 "--enable-ab-partitions=0", "--enable-1to4-partitions=1",
21162 "--enable-cfl-intra=1", "--enable-tx-size-search=0",
21163 "--enable-filter-intra=0", "--enable-intra-edge-filter=1",
21164 "--reduced-tx-type-set=1", "--min-partition-size=4",
21165 "--max-partition-size=32",
21166 &format!("--input-bit-depth={depth}"),
21167 &format!("--bit-depth={depth}"),
21168 "--obu", "-o", "-", "-",
21169 ]), &y4m.stdout);
21170 assert!(
21171 out.status.success(),
21172 "aomenc refused the fixture (depth={depth}): {}",
21173 String::from_utf8_lossy(&out.stderr)
21174 );
21175 out.stdout
21176 };
21177 let stream = encode();
21178 assert_eq!(
21179 stream,
21180 encode(),
21181 "{NAME}: aomenc output is not reproducible (depth={depth})"
21182 );
21183 let before = crate::decode::reelc_chroma_counters();
21184 let frames = match decode_stream(&stream) {
21185 Ok(frames) => frames,
21186 Err(e) => {
21187 let msg = e.to_string();
21188 assert!(
21189 msg.contains("unsupported"),
21190 "{NAME}: decode failed (depth={depth}): {msg}"
21191 );
21192 eprintln!("{NAME}: depth={depth} arm refused (not compared): {msg}");
21193 continue;
21194 }
21195 };
21196 compared += 1;
21197 // Counters read only on an attempt that decoded AND is compared.
21198 let after = crate::decode::reelc_chroma_counters();
21199 let (skip_cfl, dir_pairs) = (after.0 - before.0, after.1 - before.1);
21200 let ffmpeg_frames = if depth == 10 {
21201 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
21202 } else {
21203 ffmpeg_decode_sequence(&stream, width, height, frames.len())
21204 };
21205 assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count");
21206 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21207 assert_eq!(got.y, want.y, "{NAME} frame {i} luma (depth={depth})");
21208 assert_eq!(
21209 got.u, want.u,
21210 "{NAME} frame {i} U (depth={depth}, {skip_cfl} skipped-CfL blocks, \
21211 {dir_pairs} directional 1:4 chroma pairs)"
21212 );
21213 assert_eq!(
21214 got.v, want.v,
21215 "{NAME} frame {i} V (depth={depth}, {skip_cfl} skipped-CfL blocks, \
21216 {dir_pairs} directional 1:4 chroma pairs)"
21217 );
21218 }
21219 // Defect 1 (skipped `UV_CFL_PRED`) is NOT asserted here: 20 aomenc
21220 // recipes (cq 40..63, 9 lavfi sources, min/max-partition 4..64,
21221 // both `--sb-size=128` and 64) never made the encoder pick a
21222 // skipped 1:4 / sub-8x8 CfL block, so an assert would only ever
21223 // fire on his real film. Its evidence is ReelC's own key frames
21224 // (lanes/reelckf-r1.report.md): ss=2700 went 499 wrong chroma
21225 // samples -> 0 on this fix alone. The count is printed so a future
21226 // recipe that does reach it is visible immediately. r2 pinned that
21227 // film frame as a fixture instead:
21228 // `a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact`
21229 // hard-asserts the counter.
21230 assert!(
21231 dir_pairs > 0,
21232 "{NAME}: no directional 1:4 chroma pair decoded (depth={depth}) -- defect 2 \
21233 is not exercised"
21234 );
21235 eprintln!(
21236 "{NAME}: pixel-exact at {depth}-bit over {} frames, skipped_cfl={skip_cfl} \
21237 directional_1to4_chroma_pairs={dir_pairs}",
21238 frames.len()
21239 );
21240 }
21241 assert!(
21242 compared > 0,
21243 "{NAME}: every arm refused -- the gate compared no pixels at all"
21244 );
21245 }
21246
21247 /// lane-ab16 r1: real `aomenc --enable-ab-partitions=1` streams whose
21248 /// 16x16 blocks are split T-shaped (`PARTITION_HORZ_A`/`_HORZ_B`/
21249 /// `_VERT_A`/`_VERT_B`: two 8x8 squares plus one 16x8/8x16 strip), the
21250 /// refusals "a HORZ_A/HORZ_B/VERT_A partition below 16x16" and "a coded
21251 /// (non-skip) HORZ_B/VERT_B rect strip below 16x16" this round lifts.
21252 /// `--min-partition-size=8 --max-partition-size=16` pins the level so
21253 /// every AB symbol in the stream is a 16x16 one; the squares go through
21254 /// `decode_leaf8`, the strips through `decode_leaf_rect`'s non-skip
21255 /// coefficient path (lane-rectx). The per-arm counter is sampled per
21256 /// attempt and summed only over attempts that actually decoded AND were
21257 /// compared, and EACH of the four arms must have fired -- a run where
21258 /// aomenc's RD only ever picked HORZ_A cannot pass as proof of four
21259 /// ([[gate-blind-to-feature]]). 8-bit and 10-bit; `--tile-columns=1` is
21260 /// NOT among the attempts (base tile defect, reproducer in the r1
21261 /// report), and `--enable-tx-size-search` is left at aomenc's default
21262 /// (ON) -- pinning it off hid a panic in the TX4 sub-grid of an 8x8
21263 /// square inside a `PARTITION_VERT_A`/`_B` (r2).
21264 #[test]
21265 fn a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact() {
21266 const NAME: &str =
21267 "a_real_aomenc_stream_with_ab_partitions_below_16x16_decodes_pixel_exact";
21268 let _gate_lock = lock_gate_counters();
21269 if !have_ffmpeg() {
21270 eprintln!("SKIP {NAME}: no ffmpeg");
21271 return;
21272 }
21273 if !have_aomenc() {
21274 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
21275 return;
21276 }
21277 struct Attempt {
21278 src: &'static str,
21279 w: usize,
21280 h: usize,
21281 cq: u32,
21282 ten_bit: bool,
21283 tile_cols: u32,
21284 /// Left at aomenc's default (ON) instead of pinned off: reaches
21285 /// the TX4 sub-grid of an 8x8 square inside a
21286 /// `PARTITION_VERT_A`/`_B` (r2's panic), at the cost of the
21287 /// strip-level split transform lane-rectx still refuses.
21288 tx_size_search: bool,
21289 }
21290 // Recipes chosen by a ~200-cell sweep of {source, size, cq} at this
21291 // level (r1 report): one cell per arm that is pixel-exact end to end,
21292 // plus two 10-bit cells. `--tile-columns=1` is deliberately absent --
21293 // it mismatches on blocks that are plain NONE/VERT with no AB symbol
21294 // in the failing superblock, i.e. a base tile defect this lane
21295 // neither introduced nor owns (reproducer pinned in the r1 report).
21296 let attempts = [
21297 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 22, ten_bit: false, tile_cols: 0, tx_size_search: false },
21298 Attempt { src: "rgbtestsrc=size=64x64", w: 64, h: 64, cq: 20, ten_bit: false, tile_cols: 0, tx_size_search: false },
21299 Attempt { src: "rgbtestsrc=size=64x64", w: 64, h: 64, cq: 50, ten_bit: false, tile_cols: 0, tx_size_search: false },
21300 Attempt { src: "mandelbrot=size=64x64:start_x=-1.0", w: 64, h: 64, cq: 14, ten_bit: false, tile_cols: 0, tx_size_search: false },
21301 // 10-bit: the only two cells of the sweep that are exact at this
21302 // depth (HORZ_A and VERT_A); the 10-bit HORZ_B/VERT_B cells all
21303 // trip the base chroma defect the r1 report pins, so those two
21304 // arms are proven 8-bit only.
21305 Attempt { src: "yuvtestsrc=size=64x64", w: 64, h: 64, cq: 30, ten_bit: true, tile_cols: 0, tx_size_search: false },
21306 Attempt { src: "mandelbrot=size=64x64:start_x=0.4", w: 64, h: 64, cq: 30, ten_bit: true, tile_cols: 0, tx_size_search: false },
21307 // `--enable-tx-size-search` at aomenc's default: an 8x8 square of
21308 // a VERT_A/VERT_B resolves to a 2x2 grid of TX4 units, which is
21309 // the reach lookup that had no table row and panicked (r2). These
21310 // attempts may legitimately stop at lane-rectx's still-standing
21311

Showing the first 1 MiB of this file. View raw.