forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

stream.rs22366 lines, 1.9 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;
31#[cfg(test)]
32use crate::decode::decode_key_frame_tile_lr;
33use crate::decode::{decode_inter_frame_tile_with_cdfs, decode_key_frame_tile_with_cdfs, q_ctx_of};
34use crate::encode::Picture;
35
36/// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a
37/// mid-film mismatch splits into "reconstruction" (compare against
38/// `ffmpeg -c:v libdav1d -filmgrain 0`) and "grain synthesis" in one run.
39fn no_grain() -> bool {
40 std::env::var_os("EC_AV1_NO_GRAIN").is_some()
41}
42
43// lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the
44// current thread, overriding the environment variable. Every ffmpeg/aomdec
45// pixel gate in this repo compares SHOWN frames only (class
46// gate-blind-to-hidden-frames), so the hidden alt-ref frames a real aomenc
47// stream carries were never compared at all; the gate that does compare
48// them needs a dump path that cannot race a sibling test's decode on
49// another thread, which a process-global env var cannot give.
50thread_local! {
51 static FINAL_DUMP_PREFIX: std::cell::RefCell<Option<String>> =
52 const { std::cell::RefCell::new(None) };
53}
54
55/// Sets (or with `None` clears) this thread's `EC_AV1_FINAL_DUMP` prefix.
56#[allow(dead_code)]
57pub(crate) fn set_final_dump_prefix(prefix: Option<String>) {
58 FINAL_DUMP_PREFIX.with(|c| *c.borrow_mut() = prefix);
59}
60
61fn final_dump_prefix() -> Option<String> {
62 FINAL_DUMP_PREFIX
63 .with(|c| c.borrow().clone())
64 .or_else(|| std::env::var("EC_AV1_FINAL_DUMP").ok())
65}
66
67/// 32x32-level 1:4 strip counters, for `decode_probe`'s fixture search:
68/// (HORZ_4 strips, VERT_4 strips, strips that read coefficients).
69/// lane-inter4 r1: the INTER-frame partition counters this lane's gates
70/// assert -- `(32x8, 8x32, 64x32, 32x64, 64x16, 16x64)` strips decoded.
71pub fn inter_rect_counters() -> (usize, usize, usize, usize, usize, usize) {
72 (
73 crate::decode::rect4_32_horz_inter_hits(),
74 crate::decode::rect4_32_vert_inter_hits(),
75 crate::decode::inter_sb_horz_hits(),
76 crate::decode::inter_sb_vert_hits(),
77 crate::decode::inter_sb_horz4_hits(),
78 crate::decode::inter_sb_vert4_hits(),
79 )
80}
81
82/// lane-r14 r2: luma transform units of an inter strip with a 64-px axis,
83/// coded as the truncated low-32 coefficient corner.
84pub fn rect64_inter_tu_hits() -> usize {
85 crate::decode::rect64_inter_tu_hits()
86}
87
88/// lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
89/// inter strip (`TX_32X8`/`TX_8X32`), `[32x8, 8x32]`.
90pub fn rect32x8_inter_tu_hits() -> [usize; 2] {
91 crate::decode::rect32x8_inter_tu_hits()
92}
93
94/// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherited a
95/// `tx_type` different from the group's FIRST sub-block, i.e. groups that can
96/// only decode right under `av1_get_tx_type`'s chroma-reference rule.
97pub fn sub8_chroma_tx_from_ref_hits() -> usize {
98 crate::decode::sub8_chroma_tx_from_ref_hits()
99}
100
101/// lane-intra16x4: `(16x4, 4x16, chroma-reference)` INTRA strips decoded inside
102/// an inter 16x16-level 1:4 partition.
103pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
104 crate::decode::intra16x4_in_inter_hits()
105}
106
107/// lane-sub8intra: INTRA 8x4/4x8 leaves inside an inter frame's sub-8x8
108/// HORZ/VERT partition, `(8x4, 4x8, chroma-reference, mixed groups, split
109/// 4x4 leaves)`.
110pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
111 crate::decode::sub8_intra_rect_hits()
112}
113
114/// lane-r14 r3: RECTANGULAR var-tx leaf transform units, `[32x16, 16x32]` --
115/// the leaves `sub_tx_size_map` produces when a 1:4 strip with a 64-px axis
116/// splits its transform (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`).
117pub fn vartx_rect_leaf_hits() -> [usize; 2] {
118 crate::decode::vartx_rect_leaf_hits()
119}
120
121/// How many rect intra strips read the `use_intrabc` symbol on the last decode.
122pub fn rect_intrabc_reads() -> usize {
123 crate::decode::rect_intrabc_reads()
124}
125
126/// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma a lossless
127/// frame walked as per-4x4 inter units.
128pub fn intrabc_rect8_lossless_luma_hits() -> usize {
129 crate::decode::intrabc_rect8_lossless_luma_hits()
130}
131
132/// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a
133/// lossless 4:4:4 frame walked as per-4x4 `Chroma4` units.
134pub fn intrabc_rect8_lossless_chroma_hits() -> usize {
135 crate::decode::intrabc_rect8_lossless_chroma_hits()
136}
137
138/// Gate-side reset for the lane-av1-ibc444rect counters above.
139pub fn reset_ibc444rect_hits() {
140 crate::decode::reset_ibc444rect_hits()
141}
142
143/// `(y, uv)` palette blocks RECONSTRUCTED inside an inter frame (lane-t900
144/// r22) -- the counter a screen-content witness gate reads to prove it
145/// exercises the inter-frame palette path, not the key frame's.
146pub fn intra_in_inter_palette_hits() -> (usize, usize) {
147 crate::decode::intra_in_inter_palette_hits()
148}
149
150/// `(y, uv)` palette blocks reconstructed on an 8x8 LEAF inside an inter
151/// frame (lane-t900 r23) -- the site-specific half of
152/// [`intra_in_inter_palette_hits`], which a >=16 block also moves.
153pub fn inter8_palette_hits() -> (usize, usize) {
154 crate::decode::inter8_palette_hits()
155}
156
157/// lane-rect64port r1: coded 64-level HORZ/VERT intra strips whose luma
158/// transform unit is the un-split TX_64X32 (orient 0) / TX_32X64 (orient 1).
159pub fn rect64_corner_tu_hits(orient: usize) -> usize {
160 crate::decode::rect64_corner_tu_hits(orient)
161}
162
163/// lane-inter16ab r4: RECTANGULAR var-tx leaves with a 4-px axis, `[8x4, 4x8]`
164/// -- what `sub_tx_size_map[TX_16X4] == TX_8X4` produces when a 16x16-level
165/// 1:4 inter strip splits its transform.
166pub fn vartx_rect_leaf4_hits() -> [usize; 2] {
167 crate::decode::vartx_rect_leaf4_hits()
168}
169
170/// lane-inter16ab r5: COMPOUND_WEDGE / wedge-INTERINTRA blocks that used a
171/// RECTANGULAR wedge codebook row, per shape (`RECT_WEDGE_SHAPES` order:
172/// 8x16, 16x8, 16x32, 32x16, 8x32, 32x8).
173pub fn rect_wedge_hits() -> [usize; 6] {
174 crate::decode::rect_wedge_hits()
175}
176
177/// lane-inter16ab r5: the wedge-interintra half of [`rect_wedge_hits`].
178pub fn rect_wii_hits() -> [usize; 6] {
179 crate::decode::rect_wii_hits()
180}
181
182/// lane-sb128c r7: the 128 root's rect arms -- (gathered edge HORZ, gathered
183/// edge VERT, inter 128x64 blocks, inter 64x128 blocks).
184pub fn sb128_rect_counters() -> (usize, usize, usize, usize) {
185 (
186 crate::decode::part128_edge_horz_hits(),
187 crate::decode::part128_edge_vert_hits(),
188 crate::decode::inter_sb128_horz_hits(),
189 crate::decode::inter_sb128_vert_hits(),
190 )
191}
192
193/// lane-av1-ibcrect: the 128 root's interior partition arms plus the key-frame
194/// intra 128-axis blocks -- (split, none, horz, vert, ab[4], intra_horz,
195/// intra_vert). Non-zero horz/vert mean a stream carried real PARTITION_HORZ/
196/// VERT at the 128 root, so an intrabc-rect hunt can tell "the partition was
197/// never chosen" from "chosen and decoded intra (or refused)".
198pub fn part128_census() -> (usize, usize, usize, usize, [usize; 4], usize, usize) {
199 (
200 crate::decode::part128_split_hits(),
201 crate::decode::part128_none_hits(),
202 crate::decode::part128_horz_hits(),
203 crate::decode::part128_vert_hits(),
204 crate::decode::part128_ab_hits(),
205 crate::decode::intra_sb128_hits().0,
206 crate::decode::intra_sb128_hits().1,
207 )
208}
209
210/// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip whose
211/// reconstruction ([`crate::decode::decode_intrabc_128rect`]) ran -- the
212/// engagement counter the sb128 intrabc-rect gate asserts on.
213pub fn intrabc_128rect_hits() -> usize {
214 crate::decode::intrabc_128rect_hits()
215}
216
217/// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc strip's
218/// mu-chunk walk read, one per `read_inter_plane` chroma call. At 4:2:2 a
219/// 64x64 mu chunk's chroma plane block is 32x64 and holds TWO STACKED
220/// TX_32X32 units per plane; the square-cut walk this gate witnesses read
221/// one. Measured on the pinned witness: 8 before, 48 after.
222pub fn intrabc_128rect_chroma_chunk_hits() -> usize {
223 crate::decode::intrabc_128rect_chroma_chunk_hits()
224}
225
226/// lane-av1-ibc128chunk: the 128-root intrabc strip's per-axis chroma chunk
227/// extents as `(64 >> ss_x) << 8 | (64 >> ss_y)` on the last chunk walked --
228/// 32|32 at 4:2:0, 32|64 at 4:2:2, 64|64 at 4:4:4.
229pub fn intrabc_128rect_chunk_shape() -> usize {
230 crate::decode::intrabc_128rect_chunk_shape()
231}
232
233/// Blocks reconstructed with intra block copy at an 8x8 LEAF specifically
234/// (lane-kf900 r7's shape); [`crate::decode::intrabc_hits`] counts every shape.
235pub fn leaf8_intrabc_hits() -> usize {
236 crate::decode::leaf8_intrabc_hits()
237}
238
239/// Blocks whose `use_intrabc` symbol came out 1 and took the DV path, at ANY
240/// shape -- the engagement counter the intrabc gates assert on. It counts
241/// "read a `use_intrabc` DV", not "reconstructed": a block the rect-strip
242/// reader REFUSES for an unported shape bumps it too (the symbol and the DV
243/// are parsed before the refusal). [`leaf8_intrabc_hits`] is its 8x8-leaf
244/// subset.
245pub fn intrabc_hits() -> usize {
246 crate::decode::intrabc_hits()
247}
248
249/// lane-av1txbands: sub-8x8 group chroma-reference leaves that USED intrabc and
250/// were SKIPPED -- the route that armed [`crate::decode::intrabc_hits`]'s chroma
251/// transform slot and then read no chroma coefficient. A non-zero value is what
252/// makes the disarm at that route load-bearing on a real stream.
253pub fn skipped_intrabc_chroma_arm_hits() -> usize {
254 crate::decode::skipped_intrabc_chroma_arm_hits()
255}
256
257/// lane-sb128c r8: the 128 root's INTRA (key-frame) rect arm -- (128x64
258/// blocks, 64x128 blocks, blocks per resolved intra `tx_depth` 0/1/2).
259pub fn intra_sb128_counters() -> (usize, usize, [usize; 3]) {
260 crate::decode::intra_sb128_hits()
261}
262
263/// lane-inter128intra r1: the 128 root's HORZ/VERT half coded INTRA inside an
264/// INTER frame -- (128x64 blocks, 64x128 blocks).
265pub fn intra128_in_inter_counters() -> [usize; 2] {
266 crate::decode::intra128_in_inter_hits()
267}
268
269/// lane-lossless128: intra 128-axis blocks decoded on a LOSSLESS frame, where
270/// every plane is a TX_4X4 unit. The engagement counter for
271/// `a_lossless_sb128_rect_intra_block_decodes_sample_exact`.
272pub fn intra128_lossless_counters() -> usize {
273 crate::decode::intra128_lossless_hits()
274}
275
276/// lane-av1-128rectspan: chroma transform units re-stamped by
277/// `decode_block_128rect`'s end-of-block replay, and how many of those
278/// replays stamped a height that was not the unit's own (the 4:2:2 signature
279/// -- zero on every stream this decoder admits, since 4:2:2 is refused by
280/// name at the sequence header).
281pub fn sb128rect_chroma_replay_counters() -> (usize, usize) {
282 crate::decode::sb128rect_chroma_replay_hits()
283}
284
285/// lane-sb128c r9: the four AB shapes at the 128 root, in `PARTITION_HORZ_A`,
286/// `_HORZ_B`, `_VERT_A`, `_VERT_B` order (key and inter tile paths share the
287/// counter -- it is bumped where the root symbol resolves).
288pub fn sb128_ab_counters() -> [usize; 4] {
289 crate::decode::part128_ab_hits()
290}
291
292/// lane-obmcrec r1: OBMC neighbours taken from the second half of a 1:4-strip
293/// chroma pair -- the shape whose filter record the r1 fix re-sourced.
294pub fn obmc_pair_filter_hits() -> usize {
295 crate::decode::obmc_pair_filter_hits()
296}
297
298/// Gate counters for the 4x32/32x4 rectangular strips: `(horz, vert, coeff)` hits.
299pub fn rect4_32_counters() -> (usize, usize, usize) {
300 (
301 crate::decode::rect4_32_horz_hits(),
302 crate::decode::rect4_32_vert_hits(),
303 crate::decode::rect4_coeff_hits(),
304 )
305}
306
307/// lane-inter4 r4: rectangular inter transform units coded whole, rect
308/// var-tx trees that split, and OBMC blends run on a 16x8/8x16 leaf -- the
309/// three counters a recipe sweep needs to see from outside the crate.
310pub fn rect_inter_tu_counters() -> (usize, usize, usize) {
311 (
312 crate::decode::rect_inter_tu_hits(),
313 crate::decode::rect_inter_txsplit_hits(),
314 crate::decode::obmc_rect_leaf_hits(),
315 )
316}
317
318/// Decode every frame in a raw AV1 OBU stream, in coding order.
319///
320/// A key frame becomes the reference for the inter frames that follow it,
321/// until the next key frame resets the DPB — the same single-slot chain
322/// [`crate::encode::encode_sequence`] threads on the write side. Only a
323/// `Frame` OBU (an uncompressed header and its tile group in one OBU, which
324/// is all this crate's encoder ever writes) carries a tile payload; sequence
325/// headers and temporal delimiters are consumed for the state they carry (or
326/// skipped) and produce no picture.
327///
328/// # Errors
329/// Returns an error when the stream is truncated or malformed (as
330/// [`Av1Parser`] reports it), when a frame header names anything this
331/// crate's tile decoders do not reconstruct (see their own docs), or when an
332/// inter frame appears before any key frame has supplied a reference.
333pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
334 let mut pictures = Vec::new();
335 decode_stream_with(data, |picture, _decode_idx, shown| {
336 if shown {
337 pictures.push(picture.clone());
338 }
339 Ok(())
340 })?;
341 Ok(pictures)
342}
343
344/// Streaming form of [`decode_stream`]: hand every completed picture to
345/// `sink` the moment it exists and drop it right after, so peak memory is one
346/// output picture plus the 8-slot DPB instead of the whole decoded stream --
347/// a 4K long-GOP segment costs the same as a short one. `decode_stream`
348/// itself is this function collecting into a `Vec`.
349///
350/// `sink` is called with the picture, the decode-order index of the coded
351/// frame it came from, and whether it is output: a hidden reference frame
352/// (`show_frame == 0`) is reported with `shown == false` and is NOT part of
353/// `decode_stream`'s output, a `show_existing_frame` output with `true`.
354/// The grain-synthesised picture is what a shown frame's sink sees; the
355/// reference bank keeps the clean one (spec 7.18.3.1). An `Err` the sink
356/// returns aborts the decode and is returned unchanged.
357///
358/// # Errors
359/// As [`decode_stream`], plus whatever `sink` returns.
360pub fn decode_stream_with(
361 data: &[u8],
362 sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
363) -> Result<()> {
364 decode_stream_with_threads(data, decode_threads(), sink)
365}
366
367/// lane-thread2: how many threads [`decode_stream_with`] decodes with --
368/// `EC_AV1_THREADS`, default 1. One is not "threading with a pool of one":
369/// it is the single-threaded decoder unchanged, which is what keeps every
370/// gate that reads this crate's per-thread counters meaningful.
371fn decode_threads() -> usize {
372 static N: std::sync::LazyLock<usize> = std::sync::LazyLock::new(|| {
373 crate::envflags::var("EC_AV1_THREADS")
374 .ok()
375 .and_then(|v| v.parse::<usize>().ok())
376 .filter(|&n| n > 0)
377 .unwrap_or(1)
378 });
379 *N
380}
381
382/// lane-thread2: output-order queue. A leaf frame decoded on a worker
383/// finishes whenever it finishes; `sink` must still see every picture in the
384/// order the stream codes them, so each sink call gets an `emit_seq` when the
385/// main thread reaches its frame header and is held here until every earlier
386/// one has been emitted. (The decode index the sink is TOLD is unchanged, and
387/// is deliberately not unique: a `show_existing_frame` re-output reports the
388/// count of frames decoded before it, per this function's contract.)
389#[derive(Default)]
390struct Reorder {
391 next: usize,
392 // lane-pool1: the picture is shared, not owned -- a decoded frame that
393 // refreshes a reference slot is already behind an `Arc` for the slot, and
394 // handing the output an owned `Picture` meant copying every plane of it
395 // (24 MB per 4K 10-bit frame) purely to put it in this queue.
396 pending: std::collections::BTreeMap<usize, (std::sync::Arc<Picture>, usize, bool)>,
397}
398
399impl Reorder {
400 fn push(
401 &mut self,
402 seq: usize,
403 picture: std::sync::Arc<Picture>,
404 decode_idx: usize,
405 shown: bool,
406 ) {
407 self.pending.insert(seq, (picture, decode_idx, shown));
408 }
409
410 /// Emits every queued picture whose turn has come. An `Err` from `sink`
411 /// aborts the decode, unchanged, exactly as the serial path did.
412 fn drain(&mut self, sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>) -> Result<()> {
413 while let Some((picture, decode_idx, shown)) = self.pending.remove(&self.next) {
414 self.next += 1;
415 sink(&picture, decode_idx, shown)?;
416 crate::timeline::output(decode_idx);
417 }
418 Ok(())
419 }
420}
421
422/// lane-thread2/3: how many coded frames this PROCESS has dispatched to a
423/// worker thread (see [`decode_stream_with_threads`]). Process-global and
424/// atomic on purpose: it is the only counter here a caller can read after a
425/// threaded decode, and it is what keeps a "decodes identically with 4
426/// threads" gate from silently proving nothing because every frame ran
427/// inline. (lane-thread2 counted only LEAF frames, the only ones it could
428/// dispatch; lane-thread3 dispatches every non-key, non-`show_existing_frame`
429/// frame, hence the rename.)
430static FRAMES_DISPATCHED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
431
432/// Reads [`FRAMES_DISPATCHED`].
433pub fn frames_dispatched() -> usize {
434 FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed)
435}
436
437/// lane-thread3: what one decoded frame stores into every reference slot its
438/// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated
439/// object -- so a slot costs an `Arc` clone instead of a picture copy.
440struct SlotValue {
441 /// lane-twostage: this frame's FILTERED pixels, still being produced
442 /// when the rest of this value is published.
443 pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>>,
444 /// The size those pixels will have, known from the tile decode.
445 width: usize,
446 height: usize,
447 cdfs: Cdfs,
448 motion_field: crate::motion_field::MotionField,
449 seg_map: Vec<u8>,
450 order_hint: u32,
451}
452
453/// lane-thread3: a reference slot's contents as a FUTURE. At `threads > 1`
454/// the 8-slot bank holds these instead of values: a slot refreshed by a frame
455/// that is still decoding on a worker holds the promise from the moment the
456/// parsing thread DISPATCHES that frame, so the next frame can be dispatched
457/// straight away and waits, on its own worker, for exactly the slots it
458/// reads. This is what makes a pyramid stream (aomenc's default, where nearly
459/// every coded frame refreshes a slot, so lane-thread2's leaf rule dispatched
460/// almost nothing) decode in parallel.
461///
462/// DEADLOCK ARGUMENT. A promise is installed into a slot on the parsing
463/// thread, in decode order, when its producer is dispatched; a consumer
464/// captures the promises of the slots it reads at ITS dispatch, which is
465/// strictly later in decode order. Every wait therefore points from a later
466/// coded frame to an earlier one -- the wait graph is the reference DAG, and
467/// is acyclic. The parsing thread waits only for a `show_existing_frame`
468/// output (again an earlier frame) and at the in-flight bound, where it waits
469/// for ANY worker to answer: the earliest in-flight frame has no earlier
470/// in-flight producer, so it is always runnable and the bound always clears.
471/// Each dispatched frame gets its own thread, so a blocked waiter never holds
472/// a resource its producer needs. A producer that errors or panics marks its
473/// promise `Failed`, so no consumer can wait for a value that never comes.
474struct SlotPromise<T = std::sync::Arc<SlotValue>> {
475 state: std::sync::Mutex<PromiseState<T>>,
476 ready: std::sync::Condvar,
477}
478
479enum PromiseState<T> {
480 Pending,
481 Ready(T),
482 Failed,
483}
484
485impl<T: Clone> SlotPromise<T> {
486 fn pending() -> std::sync::Arc<Self> {
487 std::sync::Arc::new(Self {
488 state: std::sync::Mutex::new(PromiseState::Pending),
489 ready: std::sync::Condvar::new(),
490 })
491 }
492
493 /// A slot filled by a frame the parsing thread decoded itself.
494 fn ready(value: T) -> std::sync::Arc<Self> {
495 std::sync::Arc::new(Self {
496 state: std::sync::Mutex::new(PromiseState::Ready(value)),
497 ready: std::sync::Condvar::new(),
498 })
499 }
500
501 fn fulfil(&self, value: T) {
502 *self.state.lock().expect("slot promise") = PromiseState::Ready(value);
503 self.ready.notify_all();
504 }
505
506 /// lane-twostage: fulfils only a promise the stage-1 sink did not
507 /// already fill (a superres frame, or a key frame, whose meta is
508 /// published here as it always was).
509 fn fulfil_if_pending(&self, value: impl FnOnce() -> T) {
510 let mut state = self.state.lock().expect("slot promise");
511 if matches!(*state, PromiseState::Pending) {
512 *state = PromiseState::Ready(value());
513 }
514 self.ready.notify_all();
515 }
516
517 fn fail(&self) {
518 let mut state = self.state.lock().expect("slot promise");
519 if matches!(*state, PromiseState::Pending) {
520 *state = PromiseState::Failed;
521 }
522 self.ready.notify_all();
523 }
524
525 /// Blocks until the producing frame has published this slot.
526 fn wait(&self) -> Result<T> {
527 let mut state = self.state.lock().expect("slot promise");
528 loop {
529 match &*state {
530 PromiseState::Ready(value) => return Ok(value.clone()),
531 PromiseState::Failed => {
532 return Err(Error::corrupt(
533 "AV1 decode_stream: a reference frame this frame depends on failed to decode",
534 ));
535 }
536 PromiseState::Pending => {
537 state = self.ready.wait(state).expect("slot promise");
538 }
539 }
540 }
541 }
542}
543
544/// One finished frame from a worker: its output position, whether the job was
545/// a frame DECODE (as opposed to a `show_existing_frame` output, which only
546/// waits for a slot and synthesises grain -- lane-thread3 counts the two
547/// against separate in-flight bounds, since a waiting output job costs no
548/// CPU), and either the (grain-synthesised) picture with the decode index to
549/// report or the error that aborts the stream.
550type LeafResult = (usize, bool, Result<(std::sync::Arc<Picture>, usize, bool)>);
551
552/// Waits for one in-flight job and emits whatever that unblocks.
553fn collect_one(
554 rx: &std::sync::mpsc::Receiver<LeafResult>,
555 decodes: &mut usize,
556 shows: &mut usize,
557 reorder: &mut Reorder,
558 sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>,
559) -> Result<()> {
560 // Every dispatched worker answers exactly once, panic included (it is
561 // caught and turned into an error below), so the sender count cannot
562 // reach zero while `in_flight > 0`.
563 let (seq, decode_job, result) = rx
564 .recv()
565 .map_err(|_| Error::corrupt("AV1 decode_stream: a worker thread vanished"))?;
566 if decode_job {
567 *decodes -= 1;
568 } else {
569 *shows -= 1;
570 }
571 let (picture, decode_idx, shown) = result?;
572 reorder.push(seq, picture, decode_idx, shown);
573 reorder.drain(sink)
574}
575
576/// [`decode_stream_with`] with an explicit worker count (lane-thread2).
577///
578/// `threads == 1` is the serial decoder. Above that, frames that no later
579/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags`
580/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads
581/// while the main thread keeps parsing headers and decoding the frames that
582/// DO feed the reference banks; `sink` still sees every picture in coded
583/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot
584/// of the banks taken before dispatch, so no decode state is shared.
585///
586/// The per-decode counters this crate's gates read are thread-local, so at
587/// `threads > 1` a leaf frame's counts land on the worker and are invisible
588/// to the caller; that is why the default is 1.
589///
590/// # Errors
591/// As [`decode_stream_with`]; a worker's error aborts the stream.
592pub fn decode_stream_with_threads(
593 data: &[u8],
594 threads: usize,
595 mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
596) -> Result<()> {
597 // lane-pool1: this replaced a `std::thread::scope` -- frame workers now
598 // come from a persistent pool (one per submitting thread, workers reused
599 // across frames, so their `thread_local!` decode scratch survives the
600 // frame). `jobs` is declared here and dropped at the end of the function,
601 // including on `?`, so no job outlives the data it borrows.
602 let jobs = crate::par::Batch::new("ec-av1-frame");
603 // lane-thread1: this stream's per-frame decode state (was 38 thread_local
604 // statics in decode.rs) -- one object, threaded down the decode call graph.
605 let fctx = &crate::decode::FrameCtx::new();
606 let final_dump = final_dump_prefix();
607 let mut parser = Av1Parser::new();
608 let mut pictures_shown: usize = 0;
609 let mut pictures_decoded: usize = 0;
610 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
611 // previous frame's `refresh_frame_flags` stored into it, exactly like the
612 // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,
613 // not simply "the previous frame decoded"; a frame whose own predecessor
614 // didn't refresh that slot (an altref/hidden frame, or any GOP with more
615 // than one live reference) must keep predicting from whatever picture is
616 // still sitting there. Round 7's cdffwd hunt: a global `reference`
617 // overwritten every frame silently always used "the most recent decode"
618 // instead, producing a bit-exact motion vector into the WRONG picture --
619 // luma-only (chroma coincidentally shares this fixture's flat regions)
620 // and small-magnitude (the two pictures mostly agree), which is exactly
621 // what made it look like a rounding bug rather than a wrong reference.
622 // lane-pool1: shared, not owned -- a frame refreshing k slots used to copy
623 // its whole picture k times, and its output a (k+1)-th time.
624 let mut ref_slots: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] =
625 std::array::from_fn(|_| None);
626 // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion
627 // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom
628 // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was
629 // decoded with -- `Picture` itself carries neither, so both ride
630 // alongside `ref_slots` on the exact same `refresh_frame_flags` update.
631 let mut motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES] =
632 std::array::from_fn(|_| None);
633 let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES];
634 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
635 // previous frame's `refresh_frame_flags` stored into it -- the frame's
636 // own end-of-tile adapted table, or (when the frame set
637 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
638 let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
639 // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also
640 // remembers the segment map the frame stored there decoded, which is what
641 // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds`
642 // (spec `load_previous_segment_ids`) for temporal segment-id prediction
643 // and for a `segmentation_update_map == 0` frame's inherited map.
644 let mut seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
645
646 // lane-thread2: output plumbing (inert at `threads == 1`, where nothing
647 // is ever dispatched and `reorder` emits each picture the moment it is
648 // pushed).
649 let mut emit_seq = 0usize;
650 let mut reorder = Reorder::default();
651 // lane-thread3: frame decodes and `show_existing_frame` outputs are
652 // bounded separately -- an output job is a promise wait plus a memcpy, so
653 // letting it eat a decode's budget just idles a core (measured: sharing
654 // one bound cost 4K 18.7 s at 244% CPU against 17.7 s at 287%).
655 let mut in_flight_decodes = 0usize;
656 let mut in_flight_shows = 0usize;
657 let in_flight_cap = threads + 2;
658 let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();
659 // lane-thread3: at `threads > 1` THIS is the reference bank -- one
660 // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled
661 // itself and pending for one an in-flight frame will fill. The owned
662 // arrays above are then untouched (and the single-threaded path never
663 // creates a promise: it stays exactly the decoder it was, which is what
664 // keeps every counter-reading gate meaningful).
665 let mut slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
666 std::array::from_fn(|_| None);
667 // lane-timeline: which decoded frame installed each slot's promise, so
668 // the timeline records a dependency EDGE (frame -> producing frame) and
669 // not just a slot number. `usize::MAX` = nobody yet.
670 let mut slot_owner = [usize::MAX; NUM_REF_FRAMES];
671
672 let mut pos = 0usize;
673 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec
674 // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone
675 // `OBU_FRAME_HEADER` first, with `show_existing_frame == false` and no
676 // tile payload of its own -- `OBU_FRAME` (the `ObuKind::Frame` arm below)
677 // only ever folds ONE tile group into the header's own OBU. Stash the
678 // header here and accumulate tiles from each `OBU_TILE_GROUP` that
679 // follows until every tile of the frame has arrived.
680 let mut pending_header: Option<Box<FrameHeader>> = None;
681 let mut pending_tiles: Vec<Tile> = Vec::new();
682 while pos < data.len() {
683 let obu = parser.parse_obu(&data[pos..])?;
684 let obu_offset = pos;
685 pos += obu.total_size;
686
687 if let ObuKind::FrameHeader(header) = &obu.kind {
688 if !header.show_existing_frame {
689 // Before this fix, this branch fired unconditionally for
690 // EVERY `FrameHeader` OBU (including this one), so a
691 // standalone header always fell into the `show_existing_frame`
692 // slot lookup below and misreported "a show_existing_frame
693 // header naming an empty reference slot" for a frame that was
694 // never a show_existing_frame header at all.
695 pending_header = Some(header.clone());
696 pending_tiles = Vec::new();
697 continue;
698 }
699 // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this
700 // OBU only names a DPB slot to output again -- the coded-frame
701 // count and the shown-picture count are different things (a
702 // hidden altref's own `Frame` OBU below is never pushed to
703 // `pictures` on its own; it is only pushed here, later, when a
704 // `show_existing_frame` header names its slot). Before r15 this
705 // arm didn't exist at all: every `ObuKind::Frame` was pushed
706 // unconditionally regardless of `show_frame`, so a hidden altref
707 // was emitted (wrongly, in decode order) and its real
708 // `show_existing_frame` output was silently dropped.
709 let slot = header.frame_to_show_map_idx as usize;
710 // lane-hdrlossless: libaom errors on the same stream
711 // (`decodeframe.c:4651`: `if (frame_to_show == NULL)
712 // aom_internal_error(... AOM_CODEC_UNSUP_BITSTREAM, "Buffer does
713 // not contain a decoded frame")`) -- a spec-conformant guard.
714 let empty_slot = || {
715 Error::unsupported(
716 "AV1 decode_stream",
717 "a show_existing_frame header naming an empty reference slot",
718 )
719 };
720 if threads > 1 {
721 // lane-thread3: the named slot may still be decoding on a
722 // worker, and the copy into the slots this header refreshes
723 // is then just the promise -- no value needed. The OUTPUT
724 // does need the picture, so it is produced on a worker too:
725 // waiting for it here would stall the parsing thread, and a
726 // stalled parser dispatches nothing (measured before this
727 // arm existed: 7.9 s of an 8.8 s 1080p decode, 18.9 s of
728 // 23.3 s at 4K, spent in this one wait). The wait still
729 // points at an earlier coded frame, so the argument in
730 // [`SlotPromise`] is unchanged.
731 let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?;
732 for i in 0..NUM_REF_FRAMES {
733 if header.refresh_frame_flags & (1 << i) != 0 {
734 slot_promises[i] = Some(promise.clone());
735 slot_owner[i] = slot_owner[slot];
736 }
737 }
738 let cap_t0 = crate::timeline::now();
739 let capped = in_flight_shows >= in_flight_cap;
740 while in_flight_shows >= in_flight_cap {
741 collect_one(
742 &rx,
743 &mut in_flight_decodes,
744 &mut in_flight_shows,
745 &mut reorder,
746 &mut sink,
747 )?;
748 }
749 if capped {
750 crate::timeline::cap_wait("show", cap_t0, crate::timeline::now());
751 }
752 let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
753 emit_seq += 1;
754 pictures_shown += 1;
755 let grain = header.film_grain;
756 let seq = SeqFlags::read(&parser);
757 let tx = tx.clone();
758 jobs.submit(move || {
759 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
760 let value = promise.wait()?;
761 let shown_picture = value.pixels.wait()?;
762 let output = if grain.apply_grain && !no_grain() {
763 std::sync::Arc::new(crate::film_grain::apply_grain(
764 &shown_picture,
765 &grain,
766 seq.mc_identity,
767 u32::from(seq.bit_depth),
768 &crate::decode::FrameCtx::new(),
769 ))
770 } else {
771 std::sync::Arc::clone(&shown_picture)
772 };
773 Ok((output, decode_idx, true))
774 }))
775 .unwrap_or_else(|_| {
776 Err(Error::corrupt(
777 "AV1 decode_stream: a worker thread panicked on a show_existing_frame output",
778 ))
779 });
780 let _ = tx.send((job_seq, false, reply));
781 });
782 in_flight_shows += 1;
783 while let Ok((seq, decode_job, result)) = rx.try_recv() {
784 if decode_job {
785 in_flight_decodes -= 1;
786 } else {
787 in_flight_shows -= 1;
788 }
789 let (picture, decode_idx, shown) = result?;
790 reorder.push(seq, picture, decode_idx, shown);
791 reorder.drain(&mut sink)?;
792 }
793 continue;
794 }
795 let picture = {
796 let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?;
797 for i in 0..NUM_REF_FRAMES {
798 if header.refresh_frame_flags & (1 << i) != 0 {
799 cdf_slots[i] = cdf_slots[slot].clone();
800 ref_slots[i] = Some(picture.clone());
801 motion_field_slots[i] = motion_field_slots[slot].clone();
802 seg_map_slots[i] = seg_map_slots[slot].clone();
803 order_hint_slots[i] = order_hint_slots[slot];
804 }
805 }
806 picture
807 };
808 let output = if header.film_grain.apply_grain && !no_grain() {
809 // lane-hbd10 r1: grain synthesis is bit-depth generic
810 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
811 let bit_depth = parser
812 .sequence_header()
813 .map_or(8, |seq| seq.color_config.bit_depth);
814 let mc_identity = parser
815 .sequence_header()
816 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
817 std::sync::Arc::new(crate::film_grain::apply_grain(
818 &picture,
819 &header.film_grain,
820 mc_identity,
821 bit_depth as u32,
822 fctx,
823 ))
824 } else {
825 picture
826 };
827 reorder.push(emit_seq, output, pictures_decoded, true);
828 emit_seq += 1;
829 reorder.drain(&mut sink)?;
830 pictures_shown += 1;
831 continue;
832 }
833 // `tiles_base_offset` is added to every `Tile::offset` below to reach
834 // an absolute position in `data`. `OBU_FRAME`'s tiles are relative to
835 // this OBU's own `obu_offset`; an accumulated run of `OBU_TILE_GROUP`s
836 // may span several different OBUs (each at a different offset in
837 // `data`), so those tiles are normalised to an absolute offset the
838 // moment they are appended to `pending_tiles`, and `tiles_base_offset`
839 // is 0 for that case.
840 let (header, tiles, tiles_base_offset): (Box<FrameHeader>, Vec<Tile>, usize) =
841 match obu.kind {
842 ObuKind::Frame(header, tiles) => (header, tiles, obu_offset),
843 ObuKind::TileGroup(new_tiles) => {
844 let header = pending_header.clone().ok_or_else(|| {
845 Error::corrupt(
846 "AV1 decode_stream: a tile group OBU with no preceding frame header",
847 )
848 })?;
849 let expected = header.tile_info.cols * header.tile_info.rows;
850 pending_tiles.extend(new_tiles.into_iter().map(|mut t| {
851 t.offset += obu_offset;
852 t
853 }));
854 if (pending_tiles.len() as u32) < expected {
855 continue;
856 }
857 pending_header = None;
858 (header, std::mem::take(&mut pending_tiles), 0)
859 }
860 _ => continue,
861 };
862 // Every tile is decoded below through `tile_bufs`; this only rejects a
863 // frame OBU that carries no tile group at all.
864 if tiles.is_empty() {
865 return Err(Error::unsupported(
866 "AV1 decode_stream",
867 "a frame OBU with no tile group",
868 ));
869 }
870 // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
871 // block of each 64x64) only reads a literal `cdef_idx` when
872 // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a
873 // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is
874 // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into
875 // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so
876 // a `cdef_bits > 0` stream no longer needs this refusal.
877 // Both frame types now read their transform size under
878 // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads
879 // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's
880 // `decode_inter_block`/`decode_inter_block8` read the recursive
881 // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the
882 // blanket inter-frame refusal that used to stand here is gone. What
883 // remains refused is named at its own site in `read_block_tx_size`.
884 // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`,
885 // libaom decodemv.c): three more per-block/per-SB symbols this crate
886 // never reads at all, each gated by a header field this decoder
887 // otherwise accepts uncomplaining -- the same silent-desync shape
888 // `use_filter_intra` was. `allow_screen_content_tools` gates both
889 // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/
890 // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel`
891 // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse
892 // before desyncing rather than silently miscode, the same pattern as
893 // the CDEF/TxMode::Select refusals above.
894 // lane-screen r2: key frames consume (not reconstruct) palette/
895 // intrabc syntax via read_intra_mode, and decode_inter_block/
896 // decode_inter_block8's own intra-sub-block branches now consume
897 // palette the same way (libaom's read_intra_block_mode_info has no
898 // intrabc call at all -- that symbol is intra-frame-only). A
899 // genuine palette/intrabc use still refuses by name deeper in the
900 // block readers, so no whole-frame refusal is needed here anymore.
901 // lane-realworld r5: both delta_q (maybe_read_delta_q, CURRENT_Q_IDX)
902 // and delta_lf (maybe_read_delta_lf, CURRENT_DELTA_LF ->
903 // Neighbours::delta_lf_grid -> lf_level) are now read and applied;
904 // no whole-frame refusal needed here anymore.
905 //
906 // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an
907 // earlier round), `BIT_DEPTH` is wired from this frame's own sequence
908 // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10`
909 // stream decodes pixel-exact against ffmpeg's own decode of the same
910 // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The
911 // blanket refusal that used to be here is gone; `film_grain.rs` and
912 // `superres.rs` still refuse narrowly by name (their own hardcoded
913 // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes
914 // will show up as a real pixel mismatch, not a silent truncation --
915 // the whole reason the widen (and this wiring) happened.
916 // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9,
917 // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the
918 // per-segment quantizer (spec 7.12.2) and loop-filter level
919 // (spec 7.14.4). The three features that instead REWRITE a block's
920 // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the
921 // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress
922 // symbols `decode_inter_block` unconditionally reads) -- have no
923 // reader on the inter path, so they still refuse by name rather than
924 // desyncing. aomenc's `--aq-mode` segmentation only ever sets
925 // `SEG_LVL_ALT_Q` (census gate
926 // `a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`:
927 // 1-pass, alt-ref-lag and two-pass arms, every frame header parsed).
928 let tile_bufs: Vec<&[u8]> = tiles
929 .iter()
930 .map(|t| {
931 data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size)
932 .ok_or(Error::NeedMore)
933 })
934 .collect::<Result<_>>()?;
935 let seq = SeqFlags::read(&parser);
936 // lane-thread3: at `threads > 1` every coded frame that is not a key
937 // frame is decoded on a worker -- frames that refresh reference slots
938 // included, which on a pyramid stream is nearly all of them. Its
939 // inputs are taken as promises and its output is published as one,
940 // installed into the slots it refreshes HERE, on the parsing thread,
941 // in decode order, so the next frame's dependencies are known without
942 // waiting for this one to finish (see [`SlotPromise`] for the
943 // deadlock argument). A key frame stays inline: it resets the whole
944 // bank and reads nothing, so there is nothing to gain.
945 if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame {
946 let cap_t0 = crate::timeline::now();
947 let capped = in_flight_decodes >= in_flight_cap;
948 while in_flight_decodes >= in_flight_cap {
949 collect_one(
950 &rx,
951 &mut in_flight_decodes,
952 &mut in_flight_shows,
953 &mut reorder,
954 &mut sink,
955 )?;
956 }
957 if capped {
958 crate::timeline::cap_wait("decode", cap_t0, crate::timeline::now());
959 }
960 // Exactly the slots this frame reads: `ref_frame_idx` names its
961 // references, and its `primary_ref_frame` CDFs/segment map, its
962 // reference order hints and every field `setup_motion_field`
963 // projects all come from those same slots. Nothing else is
964 // waited on.
965 let mut deps: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
966 std::array::from_fn(|_| None);
967 for i in 0..7 {
968 let slot = header.ref_frame_idx[i] as usize;
969 deps[slot] = slot_promises[slot].clone();
970 }
971 let dep_owner = slot_owner;
972 let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending);
973 if let Some(promise) = &produces {
974 for i in 0..NUM_REF_FRAMES {
975 if header.refresh_frame_flags & (1 << i) != 0 {
976 slot_promises[i] = Some(promise.clone());
977 slot_owner[i] = pictures_decoded;
978 }
979 }
980 }
981 let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);
982 emit_seq += 1;
983 pictures_decoded += 1;
984 let shown = header.show_frame;
985 if shown {
986 pictures_shown += 1;
987 }
988 let tx = tx.clone();
989 let dump = final_dump.clone();
990 crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown);
991 jobs.submit(move || {
992 let promise = produces;
993 // lane-twostage: stage 2 -- this frame's filtered pixels. Its
994 // consumers hold this promise from the moment stage 1 (CDFs,
995 // segment map, motion field, size) is published at the tile
996 // boundary, and wait on it at their first prediction.
997 let pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>> =
998 SlotPromise::pending();
999 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1000 crate::timeline::start(decode_idx);
1001 // The wait happens HERE, off the parsing thread, and only
1002 // for this frame's own references.
1003 let mut resolved: [Option<std::sync::Arc<SlotValue>>; NUM_REF_FRAMES] =
1004 std::array::from_fn(|_| None);
1005 for (slot, dep) in deps.iter().enumerate() {
1006 if let Some(dep) = dep {
1007 let t0 = crate::timeline::now();
1008 resolved[slot] = Some(dep.wait()?);
1009 crate::timeline::ref_wait(
1010 decode_idx,
1011 slot,
1012 dep_owner[slot],
1013 crate::timeline::now().saturating_sub(t0),
1014 );
1015 }
1016 }
1017 crate::timeline::refs_ready();
1018 // Fresh per-thread state: every field this path reads is
1019 // written from this frame's own header before it is read.
1020 let fctx = crate::decode::FrameCtx::new();
1021 // lane-twostage: the pictures behind this frame's own
1022 // references, waited for at the first `ref_planes` call
1023 // inside the tile decode rather than here.
1024 let ref_metas: [Option<std::sync::Arc<SlotValue>>; 8] =
1025 std::array::from_fn(|i| {
1026 if i == 0 {
1027 None
1028 } else {
1029 resolved
1030 .get(header.ref_frame_idx[i - 1] as usize)
1031 .cloned()
1032 .flatten()
1033 }
1034 });
1035 let pix_cell: std::sync::OnceLock<
1036 [Option<std::sync::Arc<Picture>>; 8],
1037 > = std::sync::OnceLock::new();
1038 let wait_pixels = || -> Result<[Option<&Picture>; 8]> {
1039 if pix_cell.get().is_none() {
1040 let mut pics: [Option<std::sync::Arc<Picture>>; 8] =
1041 Default::default();
1042 for (i, meta) in ref_metas.iter().enumerate() {
1043 if let Some(meta) = meta {
1044 let slot = header.ref_frame_idx[i - 1] as usize;
1045 let t0 = crate::timeline::now();
1046 pics[i] = Some(meta.pixels.wait()?);
1047 crate::timeline::ref_wait(
1048 decode_idx,
1049 slot,
1050 dep_owner[slot],
1051 crate::timeline::now().saturating_sub(t0),
1052 );
1053 }
1054 }
1055 let _ = pix_cell.set(pics);
1056 }
1057 let pics = pix_cell.get().expect("the pictures were just set");
1058 Ok(std::array::from_fn(|i| pics[i].as_deref()))
1059 };
1060 let refpix = decode::RefPix::lazy(
1061 std::array::from_fn(|i| {
1062 ref_metas[i].as_ref().map(|m| (m.width, m.height))
1063 }),
1064 &wait_pixels,
1065 );
1066 // Stage 1: published at this frame's tile boundary, before
1067 // its filters run (`take_segment_ids` copies the map, so
1068 // the filters that read it are unaffected).
1069 let stage1 = |cdfs: Cdfs,
1070 motion_field: crate::motion_field::MotionField,
1071 width: usize,
1072 height: usize| {
1073 if let Some(promise) = &promise {
1074 promise.fulfil(std::sync::Arc::new(SlotValue {
1075 pixels: pixels.clone(),
1076 width,
1077 height,
1078 cdfs,
1079 motion_field,
1080 seg_map: decode::take_segment_ids(&fctx),
1081 order_hint: header.order_hint,
1082 }));
1083 crate::timeline::slot_fulfil();
1084 }
1085 };
1086 // spec 7.9's `av1_setup_motion_field` runs inside
1087 // `RefSnapshot::take`, i.e. here, after those waits --
1088 // it reads the referenced slots' saved motion fields.
1089 let motion_fields =
1090 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.motion_field));
1091 let snap = RefSnapshot::take(
1092 &header,
1093 seq,
1094 &refpix,
1095 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)),
1096 std::array::from_fn(|i| {
1097 resolved[i].as_ref().map(|v| v.seg_map.as_slice())
1098 }),
1099 &motion_fields,
1100 std::array::from_fn(|i| resolved[i].as_ref().map_or(0, |v| v.order_hint)),
1101 );
1102 let out = decode_frame(
1103 &fctx,
1104 &header,
1105 &tile_bufs,
1106 seq,
1107 snap,
1108 decode_idx,
1109 shown_idx,
1110 dump.as_deref(),
1111 // lane-twostage publishes a frame's meta at its tile
1112 // boundary instead of after its filters, so a consumer
1113 // parses over its producer's filter tail. It is ON by
1114 // default since lane-sub8group: with every reference
1115 // pixel read deferred to the recon workers, the
1116 // consumer parses its WHOLE tile before it needs a
1117 // pixel, and the 4K critical chain shortens by 11-14%
1118 // in three interleaved pairs (14450/10594/14407 ms off
1119 // vs 12790/9207/12463 ms on) where it moved 3-7%
1120 // before. `EC_AV1_TWO_STAGE=0` turns it back off.
1121 (crate::envflags::var("EC_AV1_TWO_STAGE").as_deref() != Ok("0"))
1122 .then_some(&stage1 as &dyn Fn(_, _, _, _)),
1123 )?;
1124 // Publish before grain synthesis: every frame waiting on
1125 // this slot can start the moment the clean picture exists
1126 // (spec 7.18.3.1 -- the bank never stores grain).
1127 let picture = std::sync::Arc::new(out.picture);
1128 pixels.fulfil(picture.clone());
1129 if let Some(promise) = &promise {
1130 // Only a frame whose stage-1 sink never fired (a
1131 // superres frame) still has meta to publish here.
1132 promise.fulfil_if_pending(|| {
1133 std::sync::Arc::new(SlotValue {
1134 pixels: pixels.clone(),
1135 width: picture.width,
1136 height: picture.height,
1137 cdfs: out.stored_cdfs,
1138 motion_field: out.motion_field.expect(
1139 "a frame that published no stage 1 carries its motion field back",
1140 ),
1141 seg_map: out.seg_map,
1142 order_hint: header.order_hint,
1143 })
1144 });
1145 crate::timeline::slot_fulfil();
1146 }
1147 // Grain is synthesised for OUTPUT only: a hidden frame is
1148 // reported to the sink clean, exactly as the inline path
1149 // below reports it (spec 7.18.3.1).
1150 let output = if shown && header.film_grain.apply_grain && !no_grain() {
1151 std::sync::Arc::new(crate::film_grain::apply_grain(
1152 &picture,
1153 &header.film_grain,
1154 seq.mc_identity,
1155 u32::from(seq.bit_depth),
1156 &fctx,
1157 ))
1158 } else {
1159 picture
1160 };
1161 crate::timeline::grain_done();
1162 Ok((output, decode_idx, shown))
1163 }))
1164 .unwrap_or_else(|_| {
1165 Err(Error::corrupt(
1166 "AV1 decode_stream: a worker thread panicked decoding a frame",
1167 ))
1168 });
1169 // A frame nobody can decode must not leave its consumers
1170 // waiting for a slot that will never be filled.
1171 if reply.is_err() {
1172 // Neither stage may leave a consumer waiting for a value
1173 // that will never come.
1174 if let Some(promise) = &promise {
1175 promise.fail();
1176 }
1177 pixels.fail();
1178 }
1179 let _ = tx.send((job_seq, true, reply));
1180 });
1181 in_flight_decodes += 1;
1182 FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1183 // Anything that finished while this frame was being set up.
1184 while let Ok((seq, decode_job, result)) = rx.try_recv() {
1185 if decode_job {
1186 in_flight_decodes -= 1;
1187 } else {
1188 in_flight_shows -= 1;
1189 }
1190 let (picture, decode_idx, shown) = result?;
1191 reorder.push(seq, picture, decode_idx, shown);
1192 reorder.drain(&mut sink)?;
1193 }
1194 continue;
1195 }
1196 // lane-twostage: the inline path's references are decoded already,
1197 // so its handle never waits.
1198 let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| {
1199 if i == 0 {
1200 None
1201 } else {
1202 ref_slots
1203 .get(header.ref_frame_idx[i - 1] as usize)
1204 .and_then(|p| p.as_deref())
1205 }
1206 }));
1207 let snap = RefSnapshot::take(
1208 &header,
1209 seq,
1210 &inline_refpix,
1211 std::array::from_fn(|i| cdf_slots[i].as_ref()),
1212 std::array::from_fn(|i| seg_map_slots[i].as_deref()),
1213 &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
1214 order_hint_slots,
1215 );
1216 let bit_depth = seq.bit_depth;
1217 let FrameOutput {
1218 picture,
1219 stored_cdfs,
1220 motion_field,
1221 seg_map: decoded_seg_map,
1222 } = decode_frame(
1223 fctx,
1224 &header,
1225 &tile_bufs,
1226 seq,
1227 snap,
1228 pictures_decoded,
1229 pictures_shown,
1230 final_dump.as_deref(),
1231 None,
1232 )?;
1233 let motion_field = motion_field.expect("the inline path passes no stage-1 sink");
1234 pictures_decoded += 1;
1235 // lane-pool1: one allocation, then every slot store and the output
1236 // itself are refcount bumps instead of plane copies.
1237 let picture = std::sync::Arc::new(picture);
1238 if threads > 1 {
1239 // lane-thread3: only a key frame reaches this inline path at
1240 // `threads > 1`, and the bank it fills is the promise array --
1241 // already resolved, since the picture exists right here.
1242 if header.refresh_frame_flags != 0 {
1243 let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {
1244 pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)),
1245 width: picture.width,
1246 height: picture.height,
1247 cdfs: stored_cdfs,
1248 motion_field,
1249 seg_map: decoded_seg_map,
1250 order_hint: header.order_hint,
1251 }));
1252 for i in 0..NUM_REF_FRAMES {
1253 if header.refresh_frame_flags & (1 << i) != 0 {
1254 slot_promises[i] = Some(promise.clone());
1255 slot_owner[i] = pictures_decoded - 1;
1256 }
1257 }
1258 }
1259 } else {
1260 for i in 0..NUM_REF_FRAMES {
1261 if header.refresh_frame_flags & (1 << i) != 0 {
1262 cdf_slots[i] = Some(stored_cdfs.clone());
1263 // Spec 7.18.3.1: synthesized grain is never stored for
1264 // later prediction -- the reference bank always keeps the
1265 // clean, pre-grain decode, even though the frame pushed
1266 // onto the caller's output below carries the grained
1267 // picture.
1268 ref_slots[i] = Some(std::sync::Arc::clone(&picture));
1269 motion_field_slots[i] = Some(motion_field.clone());
1270 seg_map_slots[i] = Some(decoded_seg_map.clone());
1271 order_hint_slots[i] = header.order_hint;
1272 }
1273 }
1274 }
1275 // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a
1276 // KEY frame coded with `show_frame == 0`, output later by a
1277 // `show_existing_frame` header -- counted only once its tiles have
1278 // decoded, so the gate's assert covers decoded-and-compared frames.
1279 if header.frame_type == FrameType::Key && !header.show_frame {
1280 decode::note_fwd_kf();
1281 }
1282 if header.show_frame {
1283 let output = if header.film_grain.apply_grain && !no_grain() {
1284 let mc_identity = seq.mc_identity;
1285 std::sync::Arc::new(crate::film_grain::apply_grain(
1286 &picture,
1287 &header.film_grain,
1288 mc_identity,
1289 bit_depth as u32,
1290 fctx,
1291 ))
1292 } else {
1293 picture
1294 };
1295 reorder.push(emit_seq, output, pictures_decoded - 1, true);
1296 emit_seq += 1;
1297 reorder.drain(&mut sink)?;
1298 pictures_shown += 1;
1299 } else {
1300 // Hidden (alt-ref/forward-key) frames never reach
1301 // `decode_stream`'s output, but a decode-order consumer -- the
1302 // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs
1303 // them, so they are reported too, with `shown == false`.
1304 reorder.push(emit_seq, picture, pictures_decoded - 1, false);
1305 emit_seq += 1;
1306 reorder.drain(&mut sink)?;
1307 }
1308 }
1309 while in_flight_decodes + in_flight_shows > 0 {
1310 collect_one(
1311 &rx,
1312 &mut in_flight_decodes,
1313 &mut in_flight_shows,
1314 &mut reorder,
1315 &mut sink,
1316 )?;
1317 }
1318 debug_assert!(reorder.pending.is_empty(), "a frame was never emitted");
1319 crate::timeline::dump();
1320 Ok(())
1321}
1322
1323/// lane-thread2: the sequence-header bits a single frame's decode needs,
1324/// read once on the parsing thread so that [`decode_frame`] never touches the
1325/// [`Av1Parser`] (a worker thread has no access to it).
1326#[derive(Clone, Copy)]
1327pub(crate) struct SeqFlags {
1328 pub(crate) enable_filter_intra: bool,
1329 pub(crate) enable_dual_filter: bool,
1330 pub(crate) enable_edge_filter: bool,
1331 pub(crate) enable_masked_compound: bool,
1332 pub(crate) enable_jnt_comp: bool,
1333 pub(crate) enable_interintra_compound: bool,
1334 pub(crate) use_sb128: bool,
1335 pub(crate) bit_depth: u8,
1336 /// lane-av1mono: `color_config.mono_chrome` (spec 5.5.2):
1337 /// `NumPlanes == 1`, no chroma is coded or reconstructed.
1338 pub(crate) mono_chrome: bool,
1339 pub(crate) order_hint_bits: u32,
1340 pub(crate) mc_identity: bool,
1341 /// lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2). The decoder
1342 /// itself hardcodes 4:2:0 everywhere, so these exist only for the
1343 /// sequence-level refusal in [`decode_stream_with`] -- nothing downstream
1344 /// reads them. A monochrome header parses as 1,1, so `!(1,1)` singles out
1345 /// 4:4:4 (profile 1 / sRGB) and 4:2:2 (profile 2 below 12-bit).
1346 pub(crate) subsampling_x: u8,
1347 pub(crate) subsampling_y: u8,
1348}
1349
1350impl SeqFlags {
1351 fn read(parser: &Av1Parser) -> Self {
1352 let seq = parser.sequence_header();
1353 Self {
1354 enable_filter_intra: seq.is_some_and(|s| s.enable_filter_intra),
1355 enable_dual_filter: seq.is_some_and(|s| s.enable_dual_filter),
1356 enable_edge_filter: seq.is_some_and(|s| s.enable_intra_edge_filter),
1357 enable_masked_compound: seq.is_some_and(|s| s.enable_masked_compound),
1358 enable_jnt_comp: seq.is_some_and(|s| s.enable_jnt_comp),
1359 enable_interintra_compound: seq.is_some_and(|s| s.enable_interintra_compound),
1360 use_sb128: seq.is_some_and(|s| s.use_128x128_superblock),
1361 bit_depth: seq.map_or(8, |s| s.color_config.bit_depth),
1362 mono_chrome: seq.is_some_and(|s| s.color_config.mono_chrome),
1363 order_hint_bits: seq.map_or(0, |s| s.order_hint_bits),
1364 mc_identity: seq.is_some_and(|s| s.color_config.matrix_coefficients == 0),
1365 subsampling_x: seq.map_or(1, |s| s.color_config.subsampling_x),
1366 subsampling_y: seq.map_or(1, |s| s.color_config.subsampling_y),
1367 }
1368 }
1369}
1370
1371/// lane-thread2: everything one frame's decode reads out of the cross-frame
1372/// banks `decode_stream_with` owns -- taken on the parsing thread, before any
1373/// later frame can overwrite a slot, so a frame can be decoded anywhere.
1374pub(crate) struct RefSnapshot<'a> {
1375 /// lane-twostage: this frame's references, indexed by `ref_frame`
1376 /// (`LAST_FRAME` = 1) -- sizes now, pixels at the first prediction.
1377 pub(crate) refpix: &'a decode::RefPix<'a>,
1378 /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame
1379 /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the
1380 /// second case is the refusal [`decode_frame`] raises where it always
1381 /// did, so the error order over a malformed stream is unchanged).
1382 pub(crate) primary_cdfs: Option<Cdfs>,
1383 /// Spec `load_previous_segment_ids`, from the same slot.
1384 pub(crate) prev_seg_map: Option<Vec<u8>>,
1385 /// Spec 7.9's projection, already run against `motion_field_slots`.
1386 pub(crate) tpl_field: Option<crate::motion_field::TplField>,
1387 /// `order_hint_slots[ref_frame_idx[i]]` for `LAST_FRAME + i`.
1388 pub(crate) ref_order_hints: [u32; 7],
1389}
1390
1391impl<'a> RefSnapshot<'a> {
1392 /// Reads the banks for `header`. Every slot is passed in by reference so
1393 /// that the single-threaded path can borrow the DPB in place while a
1394 /// worker borrows the resolved [`SlotPromise`] values it waited on --
1395 /// spec 7.9's `setup_motion_field` therefore runs on the DECODING thread
1396 /// (lane-thread3), after those waits.
1397 fn take(
1398 header: &FrameHeader,
1399 seq: SeqFlags,
1400 refpix: &'a decode::RefPix<'a>,
1401 cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],
1402 seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],
1403 motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],
1404 order_hint_slots: [u32; NUM_REF_FRAMES],
1405 ) -> Self {
1406 let primary = (header.primary_ref_frame != PRIMARY_REF_NONE)
1407 .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize);
1408 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
1409 // this frame's header asks for it, and never for a key frame (which
1410 // codes no inter block at all).
1411 let tpl_field =
1412 (header.frame_type != FrameType::Key && header.use_ref_frame_mvs).then(|| {
1413 crate::motion_field::setup_motion_field(
1414 motion_field_slots,
1415 header.ref_frame_idx,
1416 header.order_hint,
1417 seq.order_hint_bits,
1418 header.mi_rows as usize,
1419 header.mi_cols as usize,
1420 )
1421 });
1422 if std::env::var_os("EC_TPL").is_some() {
1423 eprintln!(
1424 "EC_TPL order_hint={} use_ref_frame_mvs={} cells={}",
1425 header.order_hint,
1426 header.use_ref_frame_mvs,
1427 tpl_field
1428 .as_ref()
1429 .map_or(0, crate::motion_field::TplField::filled_cells)
1430 );
1431 }
1432 Self {
1433 refpix,
1434 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),
1435 prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)),
1436 tpl_field,
1437 ref_order_hints: std::array::from_fn(|i| {
1438 order_hint_slots[header.ref_frame_idx[i] as usize]
1439 }),
1440 }
1441 }
1442}
1443
1444/// lane-thread2: what one decoded frame contributes back to the stream --
1445/// its picture (clean, pre-grain: spec 7.18.3.1) plus the three pieces a
1446/// `refresh_frame_flags` bit stores into a reference slot.
1447pub(crate) struct FrameOutput {
1448 pub(crate) picture: Picture,
1449 pub(crate) stored_cdfs: Cdfs,
1450 /// lane-twostage: `None` when this frame handed its motion field to the
1451 /// stage-1 sink at its tile boundary instead of carrying it back here.
1452 pub(crate) motion_field: Option<crate::motion_field::MotionField>,
1453 pub(crate) seg_map: Vec<u8>,
1454}
1455
1456/// Spec 7.20's own `save_cdfs`: what a frame's `refresh_frame_flags` slots
1457/// keep -- the frame's INITIAL table when `disable_frame_end_update_cdf`,
1458/// otherwise the adapted end-of-tile table with every symbol counter zeroed
1459/// (libaom `av1_reset_cdf_symbol_counters`). lane-twostage: shared with the
1460/// stage-1 publish, which hands a consumer the same table it always got.
1461fn stored_cdfs_for(header: &FrameHeader, end_cdfs: Cdfs, started_from: Option<Cdfs>) -> Cdfs {
1462 if header.disable_frame_end_update_cdf {
1463 started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
1464 } else {
1465 let mut end_cdfs = end_cdfs;
1466 end_cdfs.reset_counts();
1467 end_cdfs
1468 }
1469}
1470
1471/// lane-thread2: one coded frame, decoded from its header, its tile payload
1472/// and a snapshot of the reference banks -- and from nothing else. Lifted
1473/// verbatim out of [`decode_stream_with`]'s loop so that the same code can
1474/// run on the parsing thread (a frame that refreshes a reference slot) or on
1475/// a worker (a leaf frame, see `decode_stream_with_threads`).
1476///
1477/// `fctx` is the DECODING thread's context: a worker uses a fresh one, which
1478/// is sound because every field this path reads is written by this function
1479/// (or by the tile decoders it calls) before it is read -- see the
1480/// `a_worker_context_starts_where_the_stream_context_would` gate.
1481///
1482/// # Errors
1483/// As [`decode_stream_with`], for this one frame.
1484#[allow(clippy::too_many_arguments)]
1485fn decode_frame(
1486 fctx: &crate::decode::FrameCtx,
1487 header: &FrameHeader,
1488 tile_bufs: &[&[u8]],
1489 seq: SeqFlags,
1490 snap: RefSnapshot<'_>,
1491 decode_idx: usize,
1492 shown_idx: usize,
1493 final_dump: Option<&str>,
1494 // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`.
1495 stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,
1496) -> Result<FrameOutput> {
1497 crate::census::frame_start(header, tile_bufs.iter().map(|t| t.len()).sum(), decode_idx);
1498 if header.segmentation.enabled {
1499 // lane-hdrlossless: libaom IMPLEMENTS these three -- they rewrite a
1500 // block's reference / skip / mode BEFORE the symbols are read
1501 // (`decodemv.c:431` SEG_LVL_SKIP, `:437` SEG_LVL_REF_FRAME /
1502 // SEG_LVL_GLOBALMV, `:1071` in `read_ref_frames`, `:1350` in
1503 // `read_is_inter_block`), so a conformant stream CAN carry them and
1504 // this is a capability gap, not a spec-conformant guard. Reachability
1505 // from `aomenc` is nil, for three independent reasons (lane-av1seglvl
1506 // census): the AQ modules clear the table then set `SEG_LVL_ALT_Q`
1507 // only (`aq_variance.c:61` clear + `:89` enable, `aq_complexity.c:74`
1508 // + `:118`, `aq_cyclicrefresh.c:616` + `:630`); the one other setter,
1509 // `configure_static_seg_features` (`encoder_utils.c:315`, which would
1510 // set ALT_LF/REF_FRAME/SKIP around alt-ref groups), is gated on
1511 // `hl_sf.static_segmentation` -- a speed feature libaom's own
1512 // `speed_features.h` documents as "Always set to 0" -- AND on the
1513 // second pass of a two-pass encode (`encoder_utils.c:738`); and
1514 // ROI/active-map maps are control-API only (`av1_apply_roi_map`,
1515 // `av1_apply_active_map`: the CLI exposes no flag for either). Kept as
1516 // a named gap: the lift is an INTER-block-path change (ref/skip/mode
1517 // selection) outside this lane's region. See `lanes/av1hdr.report.md`
1518 // §4.1 and `lanes/av1seglvl.report.md`.
1519 for segment in 0..MAX_SEGMENTS {
1520 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
1521 if header.segmentation.feature_enabled[segment][feature] {
1522 return Err(Error::unsupported(
1523 "AV1 decode_stream",
1524 "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)",
1525 ));
1526 }
1527 }
1528 }
1529 }
1530 // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the
1531 // primary reference frame's slot, and is all-zero without one.
1532 decode::set_segmentation(
1533 header.segmentation,
1534 header.mi_rows as usize,
1535 header.mi_cols as usize,
1536 snap.prev_seg_map.as_deref(),
1537 fctx,
1538 );
1539 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
1540 // symbol (spec 7.16's upscaling is a pixel-domain post-process
1541 // libaom's `decodeframe.c` runs between CDEF and loop restoration,
1542 // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile
1543 // reads stay bit-exact in sync and `crate::superres::upscale_picture`
1544 // (below, after decode) makes its `Picture` the spec-correct
1545 // `upscaled_width` instead of silently staying at `frame_width`.
1546 // lane-superres r10: an INTER frame under `use_superres` no longer
1547 // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3)
1548 // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/
1549 // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes
1550 // at the downscaled `frame_width` and upscales its own output the
1551 // same way the key-frame branch above does (see the inter branch
1552 // below). The combinations `predict_scaled` does not cover
1553 // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8
1554 // leaf) still refuse by name, deep in `decode.rs`, rather than
1555 // silently mispredicting -- see `refusal_inventory.rs`.
1556 // Loop restoration carries per-restoration-unit symbols in the tile
1557 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
1558 // superblock walk) -- lane-lr r2 ported the reader
1559 // (`crate::restoration`), r3 moved this refusal check to AFTER the
1560 // tile decode call below (was here, before it, in r2 -- meaning
1561 // `read_lr` was NEVER actually reached through `decode_stream`, the
1562 // gap the r3 gate caught live: 40/40 attempts hit this refusal with
1563 // zero `read_lr_unit` hits). Checking post-decode instead proves the
1564 // superblock walk actually survived `read_lr` (no desync) before
1565 // refusing on the true remaining gap: decoded Wiener/SGR filters are
1566 // stored per unit but never applied to pixels.
1567 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
1568 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
1569 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
1570 // zero vector only under `GmType == IDENTITY` -- any other warp
1571 // model needs the full affine/translation MV derivation this
1572 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
1573 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
1574 // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
1575 // to every one of the 7 single-reference slots `decode_inter_block`
1576 // can now select.
1577 //
1578 // lane-gm r2 STEP-8 ATTEMPT (reverted): removing this refusal
1579 // exposed a real pixel mismatch --
1580 // a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact
1581 // seed 43, frame 1 luma, with EC_WEDGE_GATE_ATTEMPTS=20
1582 // EC_AV1_REQUIRE_AOMENC=1 -- so the single-ref/compound MV wiring
1583 // is not yet provably correct end to end; keeping the refusal
1584 // until that seed is captured (EC_AV1_GATE_DUMP), self-pinned, and
1585 // root-caused rather than shipping a wrong decode.
1586 //
1587 // lane-gm r3 ROOT CAUSE (pinned, range-ladder-confirmed, still not
1588 // fixed): the mismatch is NOT an mv/mvstack/entropy bug -- msac
1589 // RANGE at the first divergent block (mi=(8,0), frame 1) matches
1590 // aomdec's own `EC_PART` trace bit-for-bit (rng=38664 both sides),
1591 // and this decoder's own `gm_get_motion_vector` for that block
1592 // (ROTZOOM, seed 43's own header) computes the spec-correct
1593 // mv=(-8,8) (hand-verified against mv.h's `block_center_x`/`_y`,
1594 // which found and fixed a real `- 1` omission in `warp.rs` --
1595 // harmless for THIS block's rounding but a genuine spec bug fixed
1596 // regardless). The actual gap: `reconinter.c`'s `allow_warp` has a
1597 // `global_warp_allowed` branch (`warp_types.global_warp_allowed =
1598 // is_global_mv_block(...)`, `reconinter_enc.c:281`) that predicts
1599 // an `is_global_mv_block` block (ROTZOOM/AFFINE GLOBALMV, >=8x8)
1600 // with the FULL per-pixel affine global-motion warp, independent
1601 // of `motion_mode` -- this decoder only ever builds a warp
1602 // prediction for local `WARPED_CAUSAL` motion mode and falls back
1603 // to plain translational MC with the block-centre mv for every
1604 // other GLOBALMV block, which is only a centre-point approximation
1605 // of the true per-pixel warp. That is the entire remaining gap.
1606 // lane-gm r4: `decode.rs` now feeds `global_motion[ref]` into
1607 // `crate::warp::global_warp_params` for every single-ref
1608 // `is_global_mv_block` (ROTZOOM/AFFINE), matching `allow_warp`'s
1609 // `global_warp_allowed` branch -- ROTZOOM is pin-verified
1610 // (`gm-seed43.obu`, frame 1 luma MATCH) and TRANSLATION already
1611 // worked (`gm_get_motion_vector`'s translation-only mv, no warp
1612 // needed). AFFINE is untested this round (no aomenc fixture in the
1613 // wedge gate reached a 6-parameter model) -- keep refusing it by
1614 // name rather than shipping an unverified decode.
1615 // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom
1616 // can never write a 6-parameter model -- its encoder-side search is
1617 // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`,
1618 // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) --
1619 // which is why four rounds of `--enable-global-motion=1` recipes
1620 // never reached the case. `scripts/build-aom-affine-oracle.sh` widens
1621 // exactly that search range in a side build, and
1622 // `a_real_affine_global_motion_stream_decodes_pixel_exact` below
1623 // decodes its output pixel-exact against ffmpeg with
1624 // `affine_gm_hits() > 0`, i.e. real blocks predicted through the
1625 // 6-parameter warp. Nothing in the decoder needed changing: the
1626 // header reader already reads params 4/5 with their own subexp refs
1627 // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s
1628 // shear-validity check + `warp_affine` are model-agnostic.
1629 // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two
1630 // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and
1631 // refused the shape by name rather than guess-fix it. r5 localized
1632 // the mismatch to an ordinary NEWMV/GOLDEN block, not the new
1633 // global-warp branch at all -- proving "two active slots" was a
1634 // correlated symptom, not the cause. r6 range-laddered that block
1635 // against aomdec's `EC_TRACE_MODE` (identical `rng` before/after
1636 // mode info -- symbol consumption bit-exact) and found the real
1637 // defect in `mvstack.rs`'s single-reference predictor fallback:
1638 // libaom's `setup_ref_mv_list` fills any `mv_ref_list` slot the real
1639 // neighbour scan left short with this block's OWN global motion
1640 // vector for its ref (`gm_get_motion_vector`), not zero -- invisible
1641 // whenever the live ref's global motion is itself
1642 // identity/translation, wrong the moment it's a real ROTZOOM/AFFINE
1643 // and the querying block's own stack comes up short (frame 14's
1644 // mi=(0,0), the very first block decoded, has no neighbours at
1645 // all). Fixed at the predictor fallback; the refusal above (single
1646 // untested shape: AFFINE on a single-ref frame) stays, but the
1647 // *multi-slot* refusal this comment used to guard is lifted -- the
1648 // r5/r6 pin (seed-43 wedge-gate mismatch) now decodes all 24 frames
1649 // byte-exact with it gone.
1650 // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
1651 // `comp_mode` per block whenever this frame's own `reference_select`
1652 // header bit is set (spec 5.11.25), and refuse by name the blocks
1653 // that pick `COMPOUND_REFERENCE` -- two-reference motion
1654 // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
1655 // is wired at the block level too (forced NEAREST_NEARESTMV compound
1656 // of `skip_mode_frame`, plain average blend), so the old blanket
1657 // `skip_mode_present` refusal is gone.
1658 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
1659 // which tile's end-of-tile adapted CDFs become the frame's own.
1660 // lane-tiles r8: this comment used to claim a `!= 0` refusal existed
1661 // "further down" -- it did not (`decode.rs` reads
1662 // `tile_info.context_update_tile_id` generically at both the
1663 // key-frame and inter-frame tile loops' `result_cdfs = cdfs` sites,
1664 // never hardcoded to tile 0); stale documentation, not a real gap.
1665 // `a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact`
1666 // hard-asserts a live aomenc stream naming tile 1/2/3 decodes
1667 // pixel-exact, so the capability is now proven as well as described
1668 // correctly.
1669 //
1670 // lane-tiles r4/r6/r7/r8: the multi-tile refusal itself is scoped,
1671 // not blanket. `decode_key_frame_tile_with_cdfs` and (r6)
1672 // `decode_inter_frame_tile_with_cdfs` both genuinely loop every
1673 // tile, `mvstack.rs`'s `MiGrid` is bounded per tile
1674 // (`MiGrid::set_tile_bounds`), and `PlaneBuf`'s `tile_x0/y0/x1/y1`
1675 // origin receives real values at every call site (r6's
1676 // `set_tile_origin` sweep). r7 proved the two remaining
1677 // tile-*column* gaps closed (inter frames, >2 columns with loop
1678 // filtering on). r8 proved tile *rows* the same way: the per-tile
1679 // loop's row math (`tile_num / tile_info.cols`,
1680 // `mi_row_starts`/`set_tile_origin`'s `y0`/`y1`) is exactly
1681 // symmetric with the column path already proven, and
1682 // `a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact`
1683 // (bypass gate, loop filter ON) confirmed it: 20/20 pixel-exact.
1684 // `a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_
1685 // stream` below re-proves it through this entry point. Tile columns
1686 // and tile rows (any count, loop filter on) are no longer capped.
1687 // `Tile::offset` is relative to the buffer `parse_obu` was handed
1688 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
1689 // to `obu_offset`, not to `data` as a whole.
1690 let enable_filter_intra = seq.enable_filter_intra;
1691 let enable_dual_filter = seq.enable_dual_filter;
1692 let enable_edge_filter = seq.enable_edge_filter;
1693 // Inter frames' intra blocks read this through a thread-local that only
1694 // the key-frame tile path used to set; without this call a stream whose
1695 // inter frames are decoded on a thread that previously decoded a
1696 // different sequence would inherit that sequence's bit.
1697 crate::decode::set_enable_edge_filter(enable_edge_filter, fctx);
1698 // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the
1699 // key-frame and the inter tile path read the 128 partition root and
1700 // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and
1701 // libaom's quadrant visit order into the inter loop too). A frame at
1702 // most 64x64 decodes identically either way (its 128 root reads no
1703 // symbol -- neither half is in frame, so SPLIT is inferred), so the
1704 // flag is only armed for frames bigger than one 64x64 superblock.
1705 let use_sb128 = seq.use_sb128;
1706 let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);
1707 crate::decode::set_sb128(sb128_active, fctx);
1708 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
1709 // which every dequant/inverse-transform clamp reads -- set per frame,
1710 // not once per process, for the same cross-sequence-on-one-thread
1711 // reason as `set_enable_edge_filter` above. Defaults to 8 when no
1712 // sequence header has been seen yet, matching every existing fixture.
1713 let bit_depth = seq.bit_depth;
1714 // lane-av112bit: the blanket 12-bit refusal is LIFTED for the paths the
1715 // lane's witnesses prove byte-exact against ffmpeg on real `aomenc
1716 // --bit-depth=12` streams (key frame and inter sequence, CDEF and loop
1717 // restoration ON, grain off -- gates
1718 // `a_real_aomenc_12bit_stream_decodes_pixel_exact` and
1719 // `a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact`). The
1720 // rounding sites that move at 12 bits are parameterised from libaom's
1721 // own rule (`mc.rs`'s `round_pair` -- convolve.h:81..86's `intbufrange`
1722 // delta: round_0 += bd-10, non-compound round_1 -= bd-10; the Wiener
1723 // pair via `get_conv_params_wiener`; the compound post-rounds absorb
1724 // the CONV_BUF gain), and CDEF/deblock/quant tables/SGR/palette reads/
1725 // superres upscale were already bit-depth generic (10-bit-proven).
1726 // Everything no 12-bit witness reached stays refused BY NAME at its own
1727 // site: warp (decode.rs, warp's reduce bits inherit the 12-bit round_0)
1728 // and any per-feature gap the witnesses' counters prove unreached -- see
1729 // the 12-bit refusals in decode.rs and `refusal_inventory.rs`.
1730 // lane-av112bitg: film grain joined the witnessed set (`grain_refusal`
1731 // deleted; the two-arm witness is
1732 // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
1733 // lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2) are parsed by
1734 // `ec-av1-syntax` -- profile 1 forces 4:4:4, profile 2 below 12-bit forces
1735 // 4:2:2, and the sRGB identity description forces full-range 4:4:4 -- but
1736 // the decoder reads them NOWHERE: every chroma extent is hardcoded 4:2:0
1737 // (`let (chroma_w, chroma_h) = (bw / 2, bh / 2)` at every rect site,
1738 // `chroma_side = side / 2` in `decode_block`) and the probe emits 4:2:0
1739 // planes only. Measured consequence: EVERY 4:4:4 stream desyncs at the
1740 // first chroma transform (a444-cu6 block (0,0): aomdec reads
1741 // `EC_COEFF plane=1 tx=TX_8X16` at rng 39857 where ours reads a 4-wide,
1742 // 8-high 4:2:0 chroma block at the same rng) and then decodes pixels that
1743 // are silently wrong. Refuse by name rather than return garbage. A
1744 // `num_planes == 1` (monochrome) header keeps its parsed 1,1 and is
1745 // unaffected. Gates: `a_non_420_subsampled_sequence_header_is_refused_by_
1746 // name` below (hand-built profile 1/2 headers plus a real aomenc 4:4:4
1747 // stream).
1748 // lane-av1-444: 4:4:4 (ss 0,0) is decoded. 4:2:2 (ss_x != ss_y) is not.
1749 if seq.subsampling_x != seq.subsampling_y {
1750 return Err(Error::unsupported(
1751 "AV1 decode_stream",
1752 "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",
1753 ));
1754 }
1755 // lane-av1-qmatrix: `quantization_params.using_qmatrix` + `qm_y`/`qm_u`/
1756 // `qm_v` (spec 5.9.12) select per-plane INVERSE QUANTISATION MATRICES --
1757 // spec 7.12.3's per-position `dqv` scale, libaom `get_dqv` over
1758 // `iwt_matrix_ref`. The parsed 4-bit values ARE the table levels
1759 // (libaom `quant_params->qmatrix_level_y/u/v`); 15 is libaom's flat
1760 // NULL-table sentinel, and a `using_qmatrix == 0` frame keeps all three
1761 // parked there, selecting no matrix. Frame-constant: recorded here (the
1762 // spot where this decoder refused such frames until this lane), read by
1763 // every dequantisation call site through [`crate::decode::block_iqmatrix`].
1764 // A real `aomenc --enable-qm=1` stream (`using_qmatrix = 1`, levels 5)
1765 // decodes byte-exact vs ffmpeg; the witness is
1766 // `a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact` below.
1767 let q = &header.quantization;
1768 // When the bit is UNSET the parsed 4-bit fields read 0 but mean nothing
1769 // (spec: they are not even coded): libaom parks the level at
1770 // `NUM_QM_LEVELS - 1`, its flat NULL-table sentinel
1771 // (`setup_segmentation_dequant`: `use_qmatrix ? qmatrix_level_y : 15`),
1772 // so a matrix-free frame selects no matrix.
1773 let flat = crate::qm::NUM_QM_LEVELS as u8 - 1;
1774 let levels = if q.using_qmatrix {
1775 [q.qm_y, q.qm_u, q.qm_v]
1776 } else {
1777 [flat; 3]
1778 };
1779 crate::decode::set_qm_levels(levels, fctx);
1780 // lane-av112bit: the frame-level half of the 12-bit gate -- screen
1781 // content tools. Neither palette nor intrabc has a 12-bit witness (the
1782 // 12-bit gates are natural content), and both hang off this header bit:
1783 // `allow_screen_content_tools` is what lets a block code a palette or
1784 // read a `use_intrabc` symbol. Refusing the FRAME by name keeps every
1785 // palette/intrabc code path 12-bit-unreachable rather than unwitnessed
1786 // and trusted. Gate:
1787 // `a_12bit_screen_content_stream_is_refused_by_name`.
1788 if bit_depth == 12 && header.allow_screen_content_tools {
1789 return Err(Error::unsupported(
1790 "AV1 decode_stream",
1791 "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)",
1792 ));
1793 }
1794 // lane-dpm1: a LOSSLESS frame (`qindex == 0` with zero deltas, spec 5.9.12)
1795 // is a different tile syntax, and this decoder has none of it: libaom
1796 // forces TX_4X4 with the WALSH-HADAMARD transform over every block (so no
1797 // `tx_depth` symbol is coded at all), and `is_cfl_allowed` narrows to
1798 // `plane_bsize == BLOCK_4X4` instead of the 32x32 rule, which changes the
1799 // `uv_mode` ALPHABET. Measured on his own screen-capture row at libaom
1800 // `-crf 5` (base_q_idx 0): the very first block, mi(0,0) BLOCK_32X32,
1801 // reads `uv_mode` off the CfL alphabet where libaom reads the plain one
1802 // (ours 12 = UV_CFL_PRED, aomdec 1 = V_PRED) and the tile desyncs at
1803 // symbol four of the frame. Refuse by name rather than return a picture
1804 // that is silently wrong from luma sample 0 (class `refusal-hides-a-defect`
1805 // read the other way: a silent wrong decode is worse than a named gap).
1806 // lane-lossless: `CodedLossless` (spec 5.9.12) -- every segment at
1807 // `qindex == 0` with zero plane deltas. The tile reader then forces TX_4X4
1808 // with the Walsh-Hadamard transform on every plane, codes no `tx_type`
1809 // symbol and narrows `is_cfl_allowed` to `plane_bsize == BLOCK_4X4`
1810 // (libaom `read_tx_size`/`read_tx_type`/`is_cfl_allowed`).
1811 //
1812 // lane-av1mixloss: PER-SEGMENT lossless (libaom `decodeframe.c:5205`) --
1813 // the header parser computes `lossless[segment_id]` for all 8 segments
1814 // (`qindex == 0` with zero plane deltas, `segment_qindex` applying that
1815 // segment's own `SEG_LVL_ALT_Q`) and `coded_lossless` = every segment
1816 // lossless. Everything FRAME-level already keys on the header's fields,
1817 // exactly as libaom gates them on `features->coded_lossless`/
1818 // `all_lossless`: `tx_mode` is `Only4x4` only when EVERY segment is
1819 // lossless, CDEF and the loop-filter levels are forced to 0 only then,
1820 // and loop restoration only on `all_lossless`. What this decoder lacked
1821 // was the BLOCK level: every block-decoder rule -- `read_tx_size`'s TX_4X4
1822 // early return, the suppressed `tx_type`, the Walsh-Hadamard,
1823 // `is_cfl_allowed`'s narrowing, the 4x4 chroma rasters -- indexes
1824 // `xd->lossless[segment_id]`, so a frame whose segments DISAGREE codes
1825 // lossless blocks inside a lossy frame. aomenc WRITES one:
1826 // `--end-usage=q --cq-level=0 --aq-mode=1` (variance AQ over a lossless
1827 // base) gives a high-variance segment a positive `SEG_LVL_ALT_Q` while a
1828 // flat one stays at `qindex == 0`. The table goes in whole and
1829 // [`decode::lossless`] resolves it per block through the block's own
1830 // `segment_id` (set by the spec-order `segment_id` read that precedes
1831 // every mode/transform symbol). Witness:
1832 // `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact`.
1833 crate::decode::set_lossless_per_seg(header.lossless, fctx);
1834 crate::decode::set_bit_depth(bit_depth, fctx);
1835 // lane-av1mono: the sequence header's `mono_chrome`, set per frame like
1836 // the bit depth so a mono frame decoded on a thread that last saw a
1837 // 4:2:0 one never inherits the wrong plane count.
1838 crate::decode::set_mono(seq.mono_chrome, fctx);
1839 crate::decode::set_subsampling(seq.subsampling_x, seq.subsampling_y, fctx);
1840 // lane-av1txr: spec 5.9.2 `disable_cdf_update` -- a frame that sets it
1841 // codes every tile symbol against the CDFs it started with, so the tile
1842 // readers must not adapt (libaom `decodeframe.c:2909`:
1843 // `allow_update_cdf = allow_update_cdf && !cm->features.disable_cdf_update`).
1844 crate::decode::set_disable_cdf_update(header.disable_cdf_update, fctx);
1845 // spec 7.16: this frame's superres state, for the filter chain --
1846 // `decode.rs` upscales between CDEF and loop restoration and sizes
1847 // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an
1848 // unscaled frame so a later frame never inherits it.
1849 crate::decode::set_superres(
1850 if header.use_superres {
1851 header.upscaled_width
1852 } else {
1853 0
1854 },
1855 u32::from(header.superres_denom),
1856 fctx,
1857 );
1858 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
1859 let enable_masked_compound = seq.enable_masked_compound;
1860 let enable_jnt_comp = seq.enable_jnt_comp;
1861 // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's
1862 // read site doc.
1863 let enable_interintra_compound = seq.enable_interintra_compound;
1864 let interp_fixed = match header.interpolation_filter {
1865 ec_av1_syntax::InterpolationFilter::Switchable => None,
1866 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
1867 };
1868 // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
1869 // from that reference slot's saved CDF state instead of the spec 8.4
1870 // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
1871 // builds.
1872 // lane-hdrlossless: libaom errors on the same stream (`decodeframe.c:5075`:
1873 // `if (features->primary_ref_frame != PRIMARY_REF_NONE &&
1874 // get_primary_ref_frame_buf(cm) == NULL) aom_internal_error(...,
1875 // AOM_CODEC_CORRUPT_FRAME, "Reference frame containing this frame's
1876 // initial frame context is unavailable.")`) -- a spec-conformant guard.
1877 let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
1878 None
1879 } else {
1880 Some(snap.primary_cdfs.clone().ok_or_else(|| {
1881 Error::unsupported(
1882 "AV1 decode_stream",
1883 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
1884 )
1885 })?)
1886 };
1887 let started_from = initial_cdfs.clone();
1888 // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame.
1889 decode::set_coeff_trace_frame(decode_idx);
1890 // lane-t900 r9: one line per DECODE-order frame naming the header
1891 // fields a desync cliff is usually keyed on (frame type, base q,
1892 // primary_ref, the 7 ref slots, refresh mask, order hints).
1893 if std::env::var_os("EC_PROBE_HDR").is_some() {
1894 eprintln!(
1895 "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={:?}",
1896 header.frame_type,
1897 header.show_frame,
1898 header.show_existing_frame,
1899 header.quantization.base_q_idx,
1900 header.primary_ref_frame,
1901 header.ref_frame_idx,
1902 header.refresh_frame_flags,
1903 header.order_hint,
1904 header.tile_info.cols,
1905 header.tile_info.rows,
1906 header.tx_mode,
1907 header.interpolation_filter,
1908 header.reduced_tx_set,
1909 header.allow_warped_motion,
1910 header.is_motion_mode_switchable,
1911 header.use_ref_frame_mvs,
1912 header.skip_mode_present,
1913 header.cdef.bits,
1914 header.loop_restoration.frame_restoration_type,
1915 );
1916 }
1917
1918 let order_hint_bits = seq.order_hint_bits;
1919 // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
1920 // of the picture sitting in each of its 7 single references' DPB
1921 // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
1922 // (a later frame projects from it) whether or not this frame itself
1923 // reads temporal candidates.
1924 let ref_order_hints = snap.ref_order_hints;
1925
1926 crate::timeline::bind(
1927 decode_idx,
1928 if header.frame_type == FrameType::Key {
1929 'K'
1930 } else if header.show_frame {
1931 'P'
1932 } else {
1933 'A'
1934 },
1935 header.show_frame,
1936 );
1937 crate::timeline::hdr_done();
1938 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
1939 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
1940 &tile_bufs,
1941 &header.tile_info,
1942 header.mi_cols,
1943 header.mi_rows,
1944 header.quantization.base_q_idx,
1945 crate::quant::QuantDeltas {
1946 y_dc: i32::from(header.quantization.delta_q_y_dc),
1947 u_dc: i32::from(header.quantization.delta_q_u_dc),
1948 u_ac: i32::from(header.quantization.delta_q_u_ac),
1949 v_dc: i32::from(header.quantization.delta_q_v_dc),
1950 v_ac: i32::from(header.quantization.delta_q_v_ac),
1951 },
1952 header.frame_width,
1953 header.frame_height,
1954 enable_filter_intra,
1955 enable_edge_filter,
1956 &header.cdef,
1957 &header.loop_filter,
1958 &header.loop_restoration,
1959 initial_cdfs,
1960 header.tx_mode == TxMode::Select,
1961 header.reduced_tx_set,
1962 header.allow_screen_content_tools,
1963 header.allow_intrabc,
1964 header.delta,
1965 fctx,
1966 )?;
1967 // A key frame codes no inter blocks -- its own saved motion
1968 // field has no cells set, matching libaom's own "intra frame
1969 // contributes nothing to a later projection" behaviour, but
1970 // still carries `order_hint`/`ref_order_hints` for the distance
1971 // arithmetic a later frame's projection needs.
1972 let motion_field = crate::motion_field::MotionField::new(
1973 header.mi_cols as usize,
1974 header.mi_rows as usize,
1975 header.order_hint,
1976 ref_order_hints,
1977 // `frame_type` for the DPB slot: a key (or intra-only) frame is
1978 // never a projection source, and never spends a `ref_stamp`.
1979 true,
1980 );
1981 (picture, end_cdfs, Some(motion_field))
1982 } else {
1983 let last_slot = header.ref_frame_idx[0] as usize;
1984 let _ = last_slot;
1985 // lane-hdrlossless: libaom errors on the same stream -- a stream may
1986 // OPEN on an intra-only frame, but a reference resolving to a slot
1987 // that is still NULL is `AOM_CODEC_CORRUPT_FRAME "Inter frame
1988 // requests nonexistent reference"` (`decodeframe.c:5008-5031`) -- a
1989 // spec-conformant guard.
1990 if snap.refpix.dims(1).is_none() {
1991 return Err(Error::unsupported(
1992 "AV1 decode_stream",
1993 "an inter frame with no key frame before it",
1994 ));
1995 }
1996 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
1997 // (spec 7.8/7.20). Any of them having no picture yet is not a
1998 // stream error on its own: `decode_inter_block` only needs a
1999 // given slot when a block actually selects that reference, and
2000 // refuses by name there if the slot is still empty -- widened
2001 // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
2002 // one of the 7 single-reference slots.
2003 // lane-fimv r1: record the header state the fimv gate asserts on
2004 // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause).
2005 if header.force_integer_mv {
2006 decode::note_force_integer_mv_frame();
2007 }
2008 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
2009 // this frame's header actually asks for temporal candidates --
2010 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
2011 // behaviour bit for bit when this is `None` (see its own doc).
2012 // lane-twostage: the stage-1 sink is handed the table a consumer
2013 // would have read out of the slot, not the raw end-of-tile one.
2014 let started_from_stage1 = started_from.clone();
2015 let stage1_adapter = stage1.map(|sink| {
2016 move |end_cdfs: Cdfs,
2017 motion_field: crate::motion_field::MotionField,
2018 width: usize,
2019 height: usize| {
2020 sink(
2021 stored_cdfs_for(header, end_cdfs, started_from_stage1.clone()),
2022 motion_field,
2023 width,
2024 height,
2025 )
2026 }
2027 });
2028 let tpl_field = &snap.tpl_field;
2029 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
2030 &tile_bufs,
2031 &header.tile_info,
2032 header.mi_cols,
2033 header.mi_rows,
2034 header.quantization.base_q_idx,
2035 crate::quant::QuantDeltas {
2036 y_dc: i32::from(header.quantization.delta_q_y_dc),
2037 u_dc: i32::from(header.quantization.delta_q_u_dc),
2038 u_ac: i32::from(header.quantization.delta_q_u_ac),
2039 v_dc: i32::from(header.quantization.delta_q_v_dc),
2040 v_ac: i32::from(header.quantization.delta_q_v_ac),
2041 },
2042 header.frame_width,
2043 header.frame_height,
2044 snap.refpix,
2045 &header.cdef,
2046 &header.loop_filter,
2047 &header.loop_restoration,
2048 initial_cdfs,
2049 header.allow_high_precision_mv,
2050 header.force_integer_mv,
2051 header.ref_frame_sign_bias,
2052 header.global_motion,
2053 interp_fixed,
2054 enable_dual_filter,
2055 order_hint_bits,
2056 header.order_hint,
2057 ref_order_hints,
2058 tpl_field.as_ref(),
2059 header.reference_select,
2060 enable_masked_compound,
2061 enable_jnt_comp,
2062 enable_interintra_compound,
2063 header.skip_mode_present,
2064 header.skip_mode_frame,
2065 header.reduced_tx_set,
2066 header.tx_mode == TxMode::Select,
2067 header.is_motion_mode_switchable,
2068 header.allow_warped_motion,
2069 header.allow_screen_content_tools,
2070 header.delta,
2071 enable_filter_intra,
2072 stage1_adapter
2073 .as_ref()
2074 .map(|f| f as &dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)),
2075 fctx,
2076 )?;
2077 (picture, end_cdfs, motion_field)
2078 };
2079 // lane-lr r4: the Wiener/self-guided pixel filters are wired
2080 // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
2081 // `uses_lr` frames now decode all the way to pixels.
2082 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
2083 // *initial* table into the slots it refreshes, not the adapted
2084 // end-of-tile one.
2085 let stored_cdfs = stored_cdfs_for(header, end_cdfs, started_from);
2086 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
2087 use std::io::Write;
2088 if let Ok(mut f) = std::fs::OpenOptions::new()
2089 .create(true)
2090 .append(true)
2091 .open(&path)
2092 {
2093 let _ = writeln!(f, "=== frame idx={} ===", shown_idx);
2094 let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
2095 let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
2096 let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
2097 let _ = writeln!(f, "skip {:?}", stored_cdfs.skip);
2098 let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv);
2099 let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv);
2100 let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv);
2101 let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint);
2102 }
2103 }
2104 // lane-comppin r3: decode-order (not display-order) dump of every
2105 // frame's own post-deblock buffer -- the pre-existing pixel diff
2106 // (`scratch_isolate_pinned_mismatch`) only ever compares *shown*
2107 // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a
2108 // later shown frame is otherwise invisible; diff this byte-for-byte
2109 // against `EC_AV1_POSTFILT_DUMP.fN` from the instrumented aomdec
2110 // build to isolate whether the defect is in a hidden frame's own
2111 // reconstruction or downstream of it.
2112 if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") {
2113 use std::io::Write;
2114 let idx = decode_idx;
2115 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
2116 // lane-hbd r4: debug dump narrows to u8 -- this diagnostic
2117 // predates 10-bit support and is an 8-bit-oracle comparison
2118 // only (aomdec's own dump is 8-bit here too).
2119 let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
2120 let _ = f.write_all(&narrow(&picture.y));
2121 let _ = f.write_all(&narrow(&picture.u));
2122 let _ = f.write_all(&narrow(&picture.v));
2123 }
2124 }
2125 // lane-hidden r1: the frame exactly as it is about to be stored into
2126 // the reference slots -- after deblock/CDEF/LR/superres, in DECODE
2127 // order, hidden (`show_frame == 0`) alt-ref frames included, and
2128 // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the
2129 // u8-narrowing diagnostic dumps above. Matches the instrumented
2130 // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte
2131 // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a
2132 // hidden frame's pixels comparable at all.
2133 if let Some(prefix) = final_dump {
2134 use std::io::Write;
2135 if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{decode_idx}")) {
2136 let mut buf = Vec::new();
2137 for plane in [&picture.y, &picture.u, &picture.v] {
2138 if bit_depth == 8 {
2139 buf.extend(plane.iter().map(|&s| s as u8));
2140 } else {
2141 for &s in plane {
2142 buf.extend_from_slice(&s.to_le_bytes());
2143 }
2144 }
2145 }
2146 let _ = f.write_all(&buf);
2147 }
2148 }
2149 Ok(FrameOutput {
2150 picture,
2151 stored_cdfs,
2152 motion_field,
2153 seg_map: decode::take_segment_ids(fctx),
2154 })
2155}
2156
2157/// lane-intra14 r1: INTRA-coded 1:4 strips decoded on the INTER block path
2158/// (64x16, 16x64, 32x8, 8x32) -- the counters a recipe sweep needs from
2159/// outside the crate.
2160pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) {
2161 (
2162 crate::decode::intra_rect4_strip_in_inter_hits(0),
2163 crate::decode::intra_rect4_strip_in_inter_hits(1),
2164 crate::decode::intra_rect4_strip_in_inter_hits(2),
2165 crate::decode::intra_rect4_strip_in_inter_hits(3),
2166 )
2167}
2168
2169#[cfg(test)]
2170pub(crate) mod tests {
2171 use super::*;
2172 use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
2173
2174 fn test_card(width: usize, height: usize) -> Pic {
2175 let mut picture = Pic::grey(width, height);
2176 for row in 0..height {
2177 for col in 0..width {
2178 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
2179 }
2180 }
2181 for row in 0..height / 2 {
2182 for col in 0..width / 2 {
2183 let i = row * width / 2 + col;
2184 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
2185 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
2186 }
2187 }
2188 picture
2189 }
2190
2191 fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic {
2192 let mut picture = Pic::grey(width, height);
2193 for y in 0..height {
2194 for x in 0..width {
2195 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
2196 let gradient = sx * 200.0 / width as f64;
2197 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
2198 }
2199 }
2200 for y in 0..height / 2 {
2201 for x in 0..width / 2 {
2202 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
2203 let i = y * width / 2 + x;
2204 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
2205 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
2206 }
2207 }
2208 picture
2209 }
2210
2211 /// lane-av1txr: a sequence header describing any chroma shape but 4:2:0 is
2212 /// refused by name, because the decoder reconstructs every chroma extent
2213 /// at hardcoded 4:2:0 (`bw / 2, bh / 2` at every rect site) and the probe
2214 /// emits 4:2:0 planes only -- a 4:4:4 stream "decodes" into silently wrong
2215 /// pixels (measured: a444-cu6's first chroma transform reads a 4x2-wide/
2216 /// 8-high 4:2:0 chroma at aomdec's `TX_8X16` entry rng 39857, then
2217 /// desyncs; every 4:4:4 fixture measured byte-differs from ffmpeg).
2218 ///
2219 /// Reachability, not a pixel claim: the header is written at the two
2220 /// profiles that force a non-4:2:0 shape (spec 5.5.2 -- profile 1 forces
2221 /// 4:4:4 with no coded bit; profile 2 below 12-bit forces 4:2:2) and the
2222 /// tile is never reached. The 4:2:0 CONTROL below proves the refusal is
2223 /// about the shape, not about this construction.
2224 #[test]
2225 fn a_non_420_subsampled_sequence_header_is_refused_by_name() {
2226 const NAME: &str = "a_non_420_subsampled_sequence_header_is_refused_by_name";
2227 const REFUSAL: &str = "a chroma format of 4:2:2";
2228 let fctx = &crate::decode::FrameCtx::new();
2229 let picture = test_card(64, 64);
2230 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2231 for (profile, label, sx, sy) in [(2u8, "4:2:2", 1u8, 0u8)] {
2232 let color = ec_av1_syntax::ColorConfig {
2233 num_planes: 3,
2234 subsampling_x: sx,
2235 subsampling_y: sy,
2236 ..Default::default()
2237 };
2238 let (mut seq, header) =
2239 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
2240 seq.seq_profile = profile;
2241 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2242 stream
2243 .extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap());
2244 let err = decode_stream(&stream).unwrap_err().to_string();
2245 assert!(
2246 err.contains(REFUSAL),
2247 "{NAME}: expected the non-4:2:0 refusal for the {label} header, got: {err}"
2248 );
2249 }
2250 // CONTROL: the same construction at profile 0 (4:2:0) still decodes.
2251 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2252 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2253 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap());
2254 let frames = decode_stream(&stream).expect("the 4:2:0 control must decode");
2255 assert_eq!(
2256 frames.len(),
2257 1,
2258 "{NAME}: the 4:2:0 control decoded no frame"
2259 );
2260 }
2261 /// lane-av1-422bigblock: the two witnessed 4:2:2 big-block defects, pinned
2262 /// as fixtures (`git add -f`; `fixtures/` is gitignored).
2263 ///
2264 /// `422_allskip_2f.obu` (62 bytes) is a 128x128 profile-2 key frame plus
2265 /// its all-skip first inter frame: the pre-port decoder read phantom
2266 /// coefficient units in the inter frame and then panicked in
2267 /// `reconstruct_mc_rect` on a full-height 4:2:2 chroma rect. At this
2268 /// lane's HEAD the block-half port's per-axis plane-block model already
2269 /// has it entropy-locked (all 20 key-frame coefficient units pair
2270 /// rng-for-rng with the instrumented oracle, the inter frame reads
2271 /// zero, matching the oracle) and pixel-exact vs aomdec.
2272 ///
2273 /// `422_sb128_3f.obu` (12543 bytes) carries the f2 128x128
2274 /// `PARTITION_NONE` non-skip inter block: the mu-chunk chroma walk cut
2275 /// each chunk's 32x64 chroma into a `chroma_side`-square 64x64 (twice
2276 /// the units the oracle codes), indexed the prediction buffer at the
2277 /// square `chroma_side` instead of `chroma_stride` (the empty-slice
2278 /// panic at `push_mc_rect_tx`'s densify), and the reference plane
2279 /// resolution guessed every non-4:4:4 picture quarter-height, so the
2280 /// bottom mu-chunk row predicted from a clamped row-63 edge. All fixed;
2281 /// both witnesses decode pixel-exact vs aomdec on the lane's local
2282 /// `EC_AV1_ALLOW_422_PROBE` patch-run-restore build (recipe and measured
2283 /// numbers in `lanes/av1422bigblock.report.md`).
2284 ///
2285 /// `decode_stream` itself still refuses 4:2:2 at the sequence header --
2286 /// unconditionally, per the standing family rule -- so the committed
2287 /// assertion is the byte pin (fnv1a64, the same load-bearing-identity
2288 /// fingerprint as the cdf-forwarding gate) plus the refusal-by-name
2289 /// contract over the pinned bytes.
2290 #[test]
2291 fn the_pinned_422_bigblock_witnesses_are_present_and_refuse_by_name() {
2292 const NAME: &str = "the_pinned_422_bigblock_witnesses_are_present_and_refuse_by_name";
2293 const REFUSAL: &str = "a chroma format of 4:2:2";
2294 for (file, bytes, fp) in [
2295 ("422_allskip_2f.obu", 62usize, 0x7e4d69d3c728c55f_u64),
2296 ("422_sb128_3f.obu", 12543, 0x5171e0aab8000da7),
2297 ] {
2298 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2299 .join("fixtures")
2300 .join(file);
2301 let data = std::fs::read(&path).unwrap_or_else(|e| {
2302 panic!(
2303 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
2304 path.display()
2305 )
2306 });
2307 assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
2308 assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
2309 let err = decode_stream(&data).unwrap_err().to_string();
2310 assert!(
2311 err.contains(REFUSAL),
2312 "{NAME}: {file} must refuse by name, got: {err}"
2313 );
2314 }
2315 }
2316
2317 /// lane-av1-ibc128chunk: the WITNESS for the 128-root intrabc strip's
2318 /// de-square-cut mu-chunk chroma walk, and the byte pin for it.
2319 ///
2320 /// `decode_intrabc_128rect` cut each mu chunk's chroma plane block with
2321 /// `chunk_chroma = cside * 64 / side` -- a `chroma_side`-SQUARE chunk,
2322 /// i.e. the 4:2:0 count on BOTH axes (the same defect lane-av1-422bigblock
2323 /// fixed, and witnessed, in `decode_inter_block` and
2324 /// `decode_block_128rect`; this copy was deferred there as unwitnessed).
2325 /// At 4:2:2 a 64x64 mu chunk's chroma plane block is 32x64, so it holds
2326 /// TWO STACKED TX_32X32 units per plane: the square-cut walk read one per
2327 /// plane per chunk, left the chunk's lower 32 chroma rows with no
2328 /// residual at all, and stamped each unit's entropy context over a
2329 /// 16x16-mi luma span instead of 16x8.
2330 ///
2331 /// Measured red-before on the pinned witness (parent `a7d22aec`, via the
2332 /// local `EC_AV1_ALLOW_422_PROBE` patch-run-restore build): 8 chroma
2333 /// units stamped over the stream's two reached blocks and frames 0 and 3
2334 /// diverge from `aomdec` (45135 / 44540 of 245760 samples each), the
2335 /// first difference at Y sample 98368 -- frame 0, row 256, col 64, the
2336 /// top-left corner of the first 128x64 intrabc block at mi(64,0). The
2337 /// red build then lost 4 of the stream's 6 intrabc blocks to the desync.
2338 /// Green-after, same fixture: 48 chroma units stamped, all 6 blocks
2339 /// decoded, and ALL FIVE frames byte-identical to `aomdec --rawvideo`.
2340 ///
2341 /// Committed code refuses 4:2:2 at the sequence header, so the decode
2342 /// assertions above are probe-measured and reproducible from the lane
2343 /// report's recipe; what this gate can assert in committed code is the
2344 /// byte pin, the refusal-by-name contract, and -- in the arm below --
2345 /// that the per-axis walk is still spelled per-axis in the source.
2346 #[test]
2347 fn the_pinned_422_intrabc_sb128_strip_witnesses_refuse_by_name() {
2348 const NAME: &str = "the_pinned_422_intrabc_sb128_strip_witnesses_refuse_by_name";
2349 const REFUSAL: &str = "a chroma format of 4:2:2";
2350 for (file, bytes, fp) in [
2351 (
2352 "422_intrabc_sb128_strip.obu",
2353 1672usize,
2354 0x50f5cfc576e4cd00_u64,
2355 ),
2356 (
2357 "422_intrabc_sb128_strip_notxsearch.obu",
2358 1675,
2359 0xd4936f252ff8cff0,
2360 ),
2361 ] {
2362 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2363 .join("fixtures")
2364 .join(file);
2365 let data = std::fs::read(&path).unwrap_or_else(|e| {
2366 panic!(
2367 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
2368 path.display()
2369 )
2370 });
2371 assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
2372 assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
2373 let err = decode_stream(&data).unwrap_err().to_string();
2374 assert!(
2375 err.contains(REFUSAL),
2376 "{NAME}: {file} must refuse by name, got: {err}"
2377 );
2378 }
2379 }
2380
2381 /// lane-av1-ibc128chunk: the SOURCE-SCAN arm of the witness gate above.
2382 ///
2383 /// The decode-level half of the red/green evidence cannot run in
2384 /// committed code (the 4:2:2 refusal stands), so this arm pins the thing
2385 /// that would silently bring the defect back: the square-cut
2386 /// `chunk_chroma = cside * 64 / side` expression, and the per-axis
2387 /// replacements that replaced it at BOTH sites in
2388 /// [`decode_intrabc_128rect`] -- the mu-chunk read walk and the
2389 /// `mu_chroma` per-unit context replay. It also pins the per-axis
2390 /// counters' accessors so the arms stay reachable, and the walk's own
2391 /// per-axis extent, derived here from the same `64 >> ss` form the
2392 /// witnesses measured (4:2:0 = one TX_32X32 per plane per chunk,
2393 /// 4:2:2 = two stacked, 4:4:4 = four).
2394 #[test]
2395 fn the_intrabc_128rect_chroma_chunk_walk_stays_per_axis() {
2396 const NAME: &str = "the_intrabc_128rect_chroma_chunk_walk_stays_per_axis";
2397 let src = include_str!("decode.rs");
2398 let body = src
2399 .split_once("fn decode_intrabc_128rect(")
2400 .expect("decode_intrabc_128rect must exist")
2401 .1
2402 .split_once("\nfn ")
2403 .expect("decode_intrabc_128rect must be a top-level fn")
2404 .0;
2405 // Scan CODE only: the fix's own comments quote the old expression to
2406 // say what it was, and a prose mention must not read as a
2407 // reintroduction (nor mask one).
2408 let stripped: Vec<&str> = body
2409 .lines()
2410 .map(|l| l.split_once("//").map_or(l, |(c, _)| c))
2411 .collect();
2412 let code = stripped.join("\n");
2413 let body = code.as_str();
2414 assert_eq!(
2415 body.matches("cside * 64 / side").count(),
2416 0,
2417 "{NAME}: the square-cut `cside * 64 / side` chunk extent is BACK in \
2418 decode_intrabc_128rect -- that expression is the 4:2:2 defect this \
2419 gate exists for (a 64x64 mu chunk's chroma plane block is \
2420 (64 >> ss_x) x (64 >> ss_y), not `chroma_side` square)"
2421 );
2422 // The per-axis chunk extent, declared once at the mu-chunk read walk
2423 // and once at the `mu_chroma` replay -- the two de-square-cut sites.
2424 //
2425 // The replay must ALSO enumerate every unit inside a chunk, not just
2426 // its first: counting mu CHUNKS in `rows`/`cols` and then stepping the
2427 // mi origin and reading the grid per UNIT only agrees when a chunk
2428 // holds exactly one unit (4:2:0). At 4:2:2 and 4:4:4 a chunk holds two
2429 // or four, so the per-unit body alone left the rest of the chunk with
2430 // the composed-grid smearing the replay exists to undo.
2431 for name in [
2432 "let chunk_chroma_w = (64usize) >> ss_x(fctx);",
2433 "let chunk_chroma_h = (64usize) >> ss_y(fctx);",
2434 ] {
2435 assert_eq!(
2436 body.matches(name).count(),
2437 2,
2438 "{NAME}: `{name}` must appear at BOTH de-square-cut sites in \
2439 decode_intrabc_128rect (the mu-chunk read walk and the mu_chroma \
2440 context replay), found {}",
2441 body.matches(name).count()
2442 );
2443 }
2444 for name in [
2445 "let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);",
2446 "for kr in 0..ur {",
2447 "for kc in 0..uc {",
2448 ] {
2449 assert_eq!(
2450 body.matches(name).count(),
2451 1,
2452 "{NAME}: `{name}` must appear exactly once in \
2453 decode_intrabc_128rect -- the mu_chroma replay must walk chunk \
2454 THEN unit (decode_inter_block's `mu_chroma_units` shape), found {}",
2455 body.matches(name).count()
2456 );
2457 }
2458 for name in [
2459 "let unit_luma_w = cu_tx << ss_x(fctx);",
2460 "let unit_luma_h = cu_tx << ss_y(fctx);",
2461 "let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));",
2462 "let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));",
2463 "neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h)",
2464 ] {
2465 assert_eq!(
2466 body.matches(name).count(),
2467 1,
2468 "{NAME}: `{name}` must appear exactly once in \
2469 decode_intrabc_128rect, found {}",
2470 body.matches(name).count()
2471 );
2472 }
2473 // The replay's own unit luma span is the lossless/lossy `cu << ss` form
2474 // (site 2 spells it separately from the read walk's `cu_tx << ss`).
2475 for name in [
2476 "let unit_luma_w = cu << ss_x(fctx);",
2477 "let unit_luma_h = cu << ss_y(fctx);",
2478 ] {
2479 assert_eq!(
2480 body.matches(name).count(),
2481 1,
2482 "{NAME}: `{name}` must appear exactly once in \
2483 decode_intrabc_128rect, found {}",
2484 body.matches(name).count()
2485 );
2486 }
2487 // The per-axis chunk extent the geometry demands, spelled out here so
2488 // the scan and the witnesses cannot disagree about it.
2489 let per_axis_units = |ss_x: u32, ss_y: u32| (64 >> ss_x) / 32 * (64 >> ss_y) / 32;
2490 assert_eq!(per_axis_units(1, 1), 1, "{NAME}: 4:2:0 must stay one unit");
2491 assert_eq!(per_axis_units(1, 0), 2, "{NAME}: 4:2:2 must be two units");
2492 assert_eq!(per_axis_units(0, 0), 4, "{NAME}: 4:4:4 must be four units");
2493 // The counters the probe arms read must stay exported.
2494 for name in [
2495 "pub fn intrabc_128rect_chroma_chunk_hits()",
2496 "pub fn intrabc_128rect_chunk_shape()",
2497 ] {
2498 assert!(
2499 src.contains(name),
2500 "{NAME}: the accessor `{name}` must stay in decode.rs"
2501 );
2502 }
2503 }
2504 /// lane-av1422warp: the SECOND 4:2:2 coverage witness -- the one
2505 /// `422_sb128_3f.obu` could not be, because that stream's inter content
2506 /// is skip-heavy (see `lanes/av1422stripwrite.report.md`, which named a
2507 /// second fixture with real residuals, compound and warped motion above
2508 /// the vertical midpoint as the thing that would justify lifting the
2509 /// refusal). This is that fixture.
2510 ///
2511 /// `422_residual_compound_warp_16f.obu` (38845 bytes), sha256
2512 /// `d78e2afb43ce311d3d82335a945c6f80f62db4537966d881c1349a68b3aecb95`:
2513 ///
2514 /// ```text
2515 /// ffmpeg -f lavfi -i "mandelbrot=size=256x288:rate=24:maxiter=220:start_scale=3:end_scale=0.35:end_pts=300,rotate=a=0.10*t:c=none:ow=256:oh=288" \
2516 /// -frames:v 24 -pix_fmt yuv422p -f yuv4mpegpipe src422.y4m
2517 /// aomenc --codec=av1 --profile=2 --input-bit-depth=8 --limit=16
2518 /// --width=256 --height=288 --lag-in-frames=25 --auto-alt-ref=1
2519 /// --enable-global-motion=1 --pass=1
2520 /// --cq-level=24 --cpu-used=0
2521 /// --threads=4 --kf-min-dist=0 --kf-max-dist=999999 \
2522 /// src422.y4m -o a1.webm
2523 /// ffmpeg -i a1.webm -c copy -f obu -y a1.obu
2524 /// ```
2525 ///
2526 /// CORRECTED by lane-av1422lrless (reviewer P2). This doc previously
2527 /// carried a different ffmpeg filter (`rotate=a=0.10`, no `*t`, no
2528 /// `:c=none:ow/oh`) and a `-n ffp --pass=2 --fpf=...` two-pass line.
2529 /// **Neither produced these bytes.** Re-encoding from the recorded
2530 /// source `src422.y4m` (sha256
2531 /// `4d35eaf65d1a5541b3177e1183644c163b3868d8f141bed0ce9fdf833280ba9f`)
2532 /// was measured three ways: the two-pass form gives 38774 bytes
2533 /// (`e93c4ed7...`), and only adding `--pass=1` reproduces these 38845
2534 /// bytes byte for byte (`d78e2afb...`). `aomenc` DEFAULTS to two-pass,
2535 /// so the flag has to be stated to get back the pinned stream. The
2536 /// recipe above is the one that was actually run.
2537 ///
2538 /// Measured on a patch-run-restore build (the `EC_AV1_ALLOW_422_PROBE`
2539 /// bypass applied for the run, reverted after -- it is deliberately NOT
2540 /// committed, and the refusal below is what the committed tree asserts):
2541 ///
2542 /// - all 16 frames pixel-exact against `aomdec --rawvideo`, 2359296
2543 /// bytes each, sha256 `4bfc2395e5ca6ea178f606e6b1ced773e26fc2d85b
2544 /// c3a6cdb63a402939aeb203` on both sides;
2545 /// - the entropy stream pairs bit-for-bit against the instrumented
2546 /// oracle -- 246735 symbol reads each, no divergence anywhere in the
2547 /// stream, not merely at the window this lane spent nine rounds
2548 /// narrowing;
2549 /// - the arms this fixture exists to cover really fire ABOVE the
2550 /// vertical midpoint: 3 upper-half blocks on a non-`TRANSLATION`
2551 /// global-motion model (`top_half_warp_hits`, gated on libaom's
2552 /// `is_global_mv_block` per slot) and 3 upper-half
2553 /// `GLOBAL_GLOBALMV` compound blocks (`top_half_compound_hits`),
2554 /// alongside 25 compound-warp, 18 compound-warp-8x8-leaf, 84
2555 /// rotzoom global-warp, 22 Wiener and 10 SGRPROJ loop-restoration
2556 /// units frame-globally.
2557 ///
2558 /// The loop-restoration numbers are load-bearing twice over: decoding
2559 /// this stream is what exposed the per-axis `read_lr` corner bug
2560 /// (`restoration.rs`, `av1_loop_restoration_corners_in_sb`), whose fix
2561 /// is what made the whole sequence pair. 4:2:0 and 4:4:4 are unchanged
2562 /// by it -- byte-identical to their pre-lane decodes, with the LR gate
2563 /// family green.
2564 ///
2565 /// Like its two siblings, the committed assertion is the byte pin plus
2566 /// the refusal-by-name contract: with the header refusal standing,
2567 /// NO committed test can decode a 4:2:2 stream, because the bypass that
2568 /// would allow it must never be committed.
2569 #[test]
2570 fn the_pinned_422_residual_compound_warp_witness_is_present_and_refuses_by_name() {
2571 const NAME: &str =
2572 "the_pinned_422_residual_compound_warp_witness_is_present_and_refuses_by_name";
2573 const REFUSAL: &str = "a chroma format of 4:2:2";
2574 const FILE: &str = "422_residual_compound_warp_16f.obu";
2575 const BYTES: usize = 38845;
2576 const FP: u64 = 0x0e73a51e2cc0c424;
2577 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2578 .join("fixtures")
2579 .join(FILE);
2580 let data = std::fs::read(&path).unwrap_or_else(|e| {
2581 panic!(
2582 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
2583 path.display()
2584 )
2585 });
2586 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
2587 assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted");
2588 let err = decode_stream(&data).unwrap_err().to_string();
2589 assert!(
2590 err.contains(REFUSAL),
2591 "{NAME}: {FILE} must refuse by name, got: {err}"
2592 );
2593 }
2594 /// lane-av1422lrless: the LR-OFF half of the 4:2:2 coverage pair.
2595 ///
2596 /// This is `422_residual_compound_warp_16f.obu`'s recipe with EXACTLY
2597 /// ONE flag changed, `--enable-restoration=0`, and that is a measured
2598 /// claim rather than an assertion: both arms were re-encoded from the
2599 /// same source `src422.y4m` (sha256
2600 /// `4d35eaf65d1a5541b3177e1183644c163b3868d8f141bed0ce9fdf833280ba9f`)
2601 /// with the same aomenc invocation, and the LR-on arm reproduces the
2602 /// committed 38845 bytes byte for byte. So the pair is controlled, and
2603 /// the corners code is the only thing that can differ between their
2604 /// decodes: with restoration off, every plane's `frame_restoration_type`
2605 /// is `RESTORE_NONE`, so `read_lr` skips each plane and never computes a
2606 /// range. The LR-on stream exercises the range; this one proves the skip
2607 /// is the skip.
2608 ///
2609 /// ```text
2610 /// aomenc --codec=av1 --profile=2 --input-bit-depth=8 --limit=16
2611 /// --width=256 --height=288 --lag-in-frames=25 --auto-alt-ref=1
2612 /// --enable-global-motion=1 --pass=1 --enable-restoration=0
2613 /// --cq-level=24 --cpu-used=0
2614 /// --threads=4 --kf-min-dist=0 --kf-max-dist=999999 \
2615 /// src422.y4m -o a3.webm
2616 /// ffmpeg -i a3.webm -c copy -f obu -y a3.obu
2617 /// ```
2618 ///
2619 /// 38538 bytes, sha256
2620 /// `8bed368f7ec4bca772137c6a9c2af89e1b2767ed5f937b91bd9e72ec60aeb42f`.
2621 ///
2622 /// Measured on a patch-run-restore build (the `EC_AV1_ALLOW_422_PROBE`
2623 /// bypass applied for the run, reverted after -- deliberately not
2624 /// committed, and the refusal asserted below is what this tree ships):
2625 ///
2626 /// - all 16 frames pixel-exact against `aomdec --rawvideo`, 2359296
2627 /// bytes each, sha256 `1cf47bc9e06a6e286452dfe4ffe457a85b6badd25
2628 /// 657dfd36af48262e8eb2464` on both sides;
2629 /// - the entropy stream pairs **244756-for-244756** against the
2630 /// instrumented oracle with no divergence anywhere -- a different
2631 /// read count from the LR-on sibling's 246735, which is the corners
2632 /// skip showing up in the symbol stream, so the two arms really are
2633 /// on different paths;
2634 /// - **loop restoration is proved off, not inferred from the flag**:
2635 /// all five LR counters read zero where the LR-on sibling reads
2636 /// `lr_wiener` 22, `lr_sgrproj` 10, `lr_stripe0` 26, `lr_last_stripe`
2637 /// 28;
2638 /// - and it carries MORE of the coverage than its sibling, which is
2639 /// what rescues the thin leg of the lift argument: **top-half
2640 /// compound 11** against the sibling's 3, and top-half warp 5 against
2641 /// 3. Frame-globally compound_warp 25, compound_warp_8 15, rotzoom
2642 /// global-warp 77, cdef_idx 39, part128_split 95. The stronger arm is
2643 /// the one where `read_lr` does nothing at all, so the engagement is
2644 /// not an artefact of the code under test.
2645 ///
2646 /// Same scope as its siblings, for the same reason: with the header
2647 /// refusal standing no committed test can decode a 4:2:2 stream,
2648 /// because the bypass that would allow it must never be committed.
2649 #[test]
2650 fn the_pinned_422_lr_off_witness_is_present_and_refuses_by_name() {
2651 const NAME: &str = "the_pinned_422_lr_off_witness_is_present_and_refuses_by_name";
2652 const REFUSAL: &str = "a chroma format of 4:2:2";
2653 const FILE: &str = "422_residual_compound_warp_nolr_16f.obu";
2654 const BYTES: usize = 38538;
2655 const FP: u64 = 0x4b8ff761701e2bef;
2656 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2657 .join("fixtures")
2658 .join(FILE);
2659 let data = std::fs::read(&path).unwrap_or_else(|e| {
2660 panic!(
2661 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
2662 path.display()
2663 )
2664 });
2665 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
2666 assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted");
2667 let err = decode_stream(&data).unwrap_err().to_string();
2668 assert!(
2669 err.contains(REFUSAL),
2670 "{NAME}: {FILE} must refuse by name, got: {err}"
2671 );
2672 }
2673
2674 /// lane-av1-qmatrix: WITNESS for the lifted `using_qmatrix` refusal (the
2675 /// old gate `a_frame_using_quantisation_matrices_is_refused_by_name` is
2676 /// its mirror image -- its own panic said "flip this gate to a witness"
2677 /// the moment the dequant landed).
2678 ///
2679 /// A REAL `aomenc --enable-qm=1` stream (same source and recipe as the
2680 /// refusal's gate, plus its `--enable-qm=0` control) now DECODES, and
2681 /// every frame of both arms is pixel-exact against ffmpeg's own decode
2682 /// of the same OBU. The census proves the feature non-vacuously both
2683 /// ways (class `gate-blind-to-feature`): the parsed frame headers really
2684 /// carry `using_qmatrix = 1`, the dequantiser really SCALED transform
2685 /// units through a matrix on the qm-on arm (`qm_scaled_units() > 0`),
2686 /// and the qm-off control really scaled none (`== 0`).
2687 #[test]
2688 fn a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact() {
2689 const NAME: &str = "a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact";
2690 if !have_ffmpeg() || !have_aomenc() {
2691 eprintln!(
2692 "SKIP {NAME}: needs ffmpeg + an aomenc oracle at {}",
2693 aomenc_path().display()
2694 );
2695 return;
2696 }
2697 const W: usize = 128;
2698 const H: usize = 96;
2699 const FRAMES: usize = 3;
2700 // Every frame header's (using_qmatrix, qm_y, qm_u, qm_v), parsed
2701 // straight off the encoded bytes.
2702 let qm_headers = |stream: &[u8]| -> Vec<(bool, u8, u8, u8)> {
2703 let mut parser = Av1Parser::new();
2704 let mut pos = 0usize;
2705 let mut out = Vec::new();
2706 while pos < stream.len() {
2707 let obu = parser.parse_obu(&stream[pos..]).unwrap();
2708 pos += obu.total_size;
2709 if let ObuKind::Frame(header, _) = obu.kind {
2710 let q = &header.quantization;
2711 out.push((q.using_qmatrix, q.qm_y, q.qm_u, q.qm_v));
2712 }
2713 }
2714 out
2715 };
2716 // `census_attempt` hands back only the stream LENGTH; this witness
2717 // needs the BYTES to hand ffmpeg, so the same recipe (its base args
2718 // verbatim, `testsrc2` 128x96 @ 25fps, 3 frames) runs inline.
2719 let encode = |extra: &[&str]| -> Vec<u8> {
2720 let y4m = Command::new("ffmpeg")
2721 .args([
2722 "-v",
2723 "error",
2724 "-f",
2725 "lavfi",
2726 "-i",
2727 &format!("testsrc2=size={W}x{H}:rate=25"),
2728 "-t",
2729 "0.12",
2730 "-pix_fmt",
2731 "yuv420p",
2732 "-strict",
2733 "-1",
2734 "-f",
2735 "yuv4mpegpipe",
2736 "-",
2737 ])
2738 .stdin(Stdio::null())
2739 .stdout(Stdio::piped())
2740 .stderr(Stdio::piped())
2741 .output()
2742 .expect("ffmpeg failed to run");
2743 assert!(y4m.status.success(), "ffmpeg refused the {W}x{H} fixture");
2744 let mut args: Vec<String> = [
2745 "--codec=av1",
2746 "--passes=1",
2747 "--end-usage=q",
2748 "--threads=1",
2749 "--row-mt=0",
2750 "--kf-max-dist=9999",
2751 "--lag-in-frames=0",
2752 ]
2753 .iter()
2754 .map(|s| (*s).to_owned())
2755 .collect();
2756 args.push(format!("--limit={FRAMES}"));
2757 args.extend(extra.iter().map(|s| (*s).to_owned()));
2758 args.extend([
2759 "--obu".to_owned(),
2760 "-o".to_owned(),
2761 "-".to_owned(),
2762 "-".to_owned(),
2763 ]);
2764 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
2765 assert!(
2766 out.status.success(),
2767 "aomenc refused {args:?}: {}",
2768 String::from_utf8_lossy(&out.stderr)
2769 );
2770 out.stdout
2771 };
2772 // Pixel-exact every decoded frame of `stream` against ffmpeg, plane
2773 // by plane, first differing sample named.
2774 let compare = |stream: &[u8], frames: usize, label: &str| {
2775 let want = ffmpeg_decode_sequence(stream, W, H, frames);
2776 let got =
2777 decode_stream(stream).unwrap_or_else(|e| panic!("{NAME}: {label} decode: {e}"));
2778 assert_eq!(got.len(), want.len(), "{NAME}: {label} frame count");
2779 for (i, (g, w)) in got.iter().zip(want.iter()).enumerate() {
2780 for (plane, (gp, wp)) in [(&g.y, &w.y), (&g.u, &w.u), (&g.v, &w.v)]
2781 .into_iter()
2782 .enumerate()
2783 {
2784 assert_eq!(
2785 gp,
2786 wp,
2787 "{NAME}: {label} frame {i} plane {plane} differs from ffmpeg (first mismatching sample: got {}, want {})",
2788 gp.iter()
2789 .zip(wp.iter())
2790 .find(|(a, b)| a != b)
2791 .map_or(0, |(a, _)| *a),
2792 gp.iter()
2793 .zip(wp.iter())
2794 .find(|(a, b)| a != b)
2795 .map_or(0, |(_, b)| *b)
2796 );
2797 }
2798 }
2799 };
2800
2801 // CONTROL: the same source and recipe with quantisation matrices OFF
2802 // -- unchanged by this lane, and it must not scale a single unit
2803 // through a matrix.
2804 crate::quant::reset_qm_scaled_units();
2805 let control_stream = encode(&["--enable-qm=0"]);
2806 let control_frames = decode_stream(&control_stream)
2807 .unwrap_or_else(|e| panic!("{NAME}: the --enable-qm=0 control must decode, got: {e}"))
2808 .len();
2809 assert!(
2810 control_frames >= 1,
2811 "{NAME}: the qm-off control decoded no frame"
2812 );
2813 for (using, y, u, v) in qm_headers(&control_stream) {
2814 assert!(
2815 !using,
2816 "{NAME}: the control's frame header set using_qmatrix"
2817 );
2818 assert_eq!(
2819 (y, u, v),
2820 (0, 0, 0),
2821 "{NAME}: the control's frame header carried qm levels {y}/{u}/{v}"
2822 );
2823 }
2824 compare(&control_stream, control_frames, "qm-off control");
2825 assert_eq!(
2826 crate::quant::qm_scaled_units(),
2827 0,
2828 "{NAME}: the qm-off control scaled units through a matrix"
2829 );
2830
2831 // The qm-on stream: decodes now, pixel-exact, levels 5 per plane as
2832 // aomenc writes them.
2833 crate::quant::reset_qm_scaled_units();
2834 let qm_stream = encode(&["--enable-qm=1"]);
2835 let qm_frames = decode_stream(&qm_stream)
2836 .unwrap_or_else(|e| panic!("{NAME}: the --enable-qm=1 stream must decode, got: {e}"))
2837 .len();
2838 assert!(qm_frames >= 1, "{NAME}: the qm-on stream decoded no frame");
2839 let headers = qm_headers(&qm_stream);
2840 assert!(
2841 !headers.is_empty() && headers.iter().all(|h| h.0),
2842 "{NAME}: not every qm-on frame header set using_qmatrix: {headers:?}"
2843 );
2844 assert!(
2845 headers.iter().all(|h| (h.1, h.2, h.3) == (5, 5, 5)),
2846 "{NAME}: expected aomenc's qm levels 5/5/5, got {headers:?}"
2847 );
2848 compare(&qm_stream, qm_frames, "qm-on");
2849 let scaled = crate::quant::qm_scaled_units();
2850 assert!(
2851 scaled > 0,
2852 "{NAME}: the --enable-qm=1 stream dequantized every unit flat -- \
2853 the matrices were never applied (class gate-blind-to-feature)"
2854 );
2855 eprintln!(
2856 "{NAME}: qm-off control {control_frames} frames exact (0 matrix-scaled units), \
2857 qm-on {qm_frames} frames exact ({scaled} matrix-scaled units, levels 5/5/5)"
2858 );
2859 }
2860
2861 /// lane-av1mono: the INVERSE of the pilot's
2862 /// `a_real_libaom_monochrome_key_frame_is_refused_by_name`, which the
2863 /// pilot's merge `d71084ae` landed on `main` (after this lane's base
2864 /// `7f4e8301`): the very same recipe now decodes, and its luma is
2865 /// byte-exact against ffmpeg's own decode of the same OBU. A merge of this
2866 /// lane into `main` must therefore resolve that pinning gate by adopting
2867 /// this witness in its place.
2868 ///
2869 /// `ffmpeg -pix_fmt gray -c:v libaom-av1` sets `color_config.mono_chrome`,
2870 /// so libaom codes NO chroma symbol anywhere in the sequence -- not the
2871 /// mode syntax, not a coefficient. That reaches all three classes this lane
2872 /// had to close: chroma SYMBOL reads (`uv_mode`/cfl/angle/palette), chroma
2873 /// COEFFICIENT reads on the rect-strip paths that call `read_coeffs_rect`
2874 /// DIRECTLY instead of through `read_plane`'s own plane gate, and the
2875 /// palette-mode neighbour band a mono sub-8x8 leaf must still clear before
2876 /// it returns (an uncleared band made the next block read `palette_y_mode`
2877 /// off the wrong CDF row and silently desynced the rest of the tile --
2878 /// measured at decode-order frame 33 of this very recipe).
2879 ///
2880 /// The 4:2:0 twin of the same source and settings is the control: it proves
2881 /// the recipe is decodable, so a failure here is about the plane count and
2882 /// not about the source or the encoder settings.
2883 #[test]
2884 fn a_real_libaom_monochrome_key_frame_decodes_pixel_exact() {
2885 const NAME: &str = "a_real_libaom_monochrome_key_frame_decodes_pixel_exact";
2886 if !have_ffmpeg() {
2887 eprintln!("SKIP {NAME}: no ffmpeg");
2888 return;
2889 }
2890 let emit = |pix: &str| -> Vec<u8> {
2891 let out = Command::new("ffmpeg")
2892 .args([
2893 "-v",
2894 "error",
2895 "-f",
2896 "lavfi",
2897 "-i",
2898 "testsrc2=size=320x240:rate=30:duration=2",
2899 "-pix_fmt",
2900 pix,
2901 "-c:v",
2902 "libaom-av1",
2903 "-cpu-used",
2904 "8",
2905 "-b:v",
2906 "300k",
2907 "-f",
2908 "obu",
2909 "-",
2910 ])
2911 .stdin(Stdio::null())
2912 .stdout(Stdio::piped())
2913 .stderr(Stdio::piped())
2914 .output()
2915 .expect("ffmpeg failed to run");
2916 assert!(
2917 out.status.success(),
2918 "{NAME}: ffmpeg ({pix}) failed: {}",
2919 String::from_utf8_lossy(&out.stderr)
2920 );
2921 out.stdout
2922 };
2923 // CONTROL: the identical recipe at 4:2:0 still decodes.
2924 let twin = decode_stream(&emit("yuv420p")).expect("the 4:2:0 twin must decode");
2925 assert!(!twin.is_empty(), "{NAME}: the 4:2:0 twin decoded no frames");
2926 // THE WITNESS: the monochrome stream decodes and every luma sample
2927 // equals ffmpeg's own decode of the same OBU.
2928 let gray = emit("gray");
2929 let ours = decode_stream(&gray)
2930 .unwrap_or_else(|e| panic!("{NAME}: the monochrome stream is REFUSED again: {e}"));
2931 let (width, height) = (320usize, 240usize);
2932 const FRAMES: usize = 60;
2933 assert_eq!(ours.len(), FRAMES, "{NAME}: expected {FRAMES} mono frames");
2934 let reference = ffmpeg_decode_gray_sequence(&gray, width, height, FRAMES);
2935 for (i, plane) in reference.chunks_exact(width * height).enumerate() {
2936 assert_eq!(ours[i].width, width, "{NAME}: frame {i} width");
2937 assert_eq!(ours[i].height, height, "{NAME}: frame {i} height");
2938 assert_eq!(
2939 ours[i].y.len(),
2940 width * height,
2941 "{NAME}: frame {i} luma length"
2942 );
2943 for (j, (got, want)) in plane.iter().zip(ours[i].y.iter()).enumerate() {
2944 assert_eq!(
2945 *want,
2946 u16::from(*got),
2947 "{NAME}: frame {i} luma sample {j} (row {}, col {}) is {want}, ffmpeg says {got}",
2948 j / width,
2949 j % width
2950 );
2951 }
2952 }
2953 eprintln!(
2954 "{NAME}: 4:2:0 twin {} frames, monochrome {} frames byte-exact vs ffmpeg",
2955 twin.len(),
2956 ours.len()
2957 );
2958 }
2959
2960 /// lane-t900 r25: the refusal "a frame OBU with no tile group" names a
2961 /// shape the parser cannot hand [`decode_stream`].
2962 ///
2963 /// `tiles` reaches that check from exactly two places -- `ObuKind::Frame`'s
2964 /// own vector and the `ObuKind::TileGroup` accumulation -- and both are
2965 /// filled by `ec_av1_syntax`'s `parse_tile_group`, whose only success path
2966 /// pushes one `Tile` per `tile_num` of the INCLUSIVE range
2967 /// `tg_start..=tg_end`. That range is never empty: the single-tile-group
2968 /// case takes `(0, num_tiles - 1)` saturating at 0, and the multi-group
2969 /// case rejects `end < start` as corrupt. So an `OBU_FRAME` either fails to
2970 /// parse or carries at least one tile, however short its payload is --
2971 /// including the empty payload the charter for this round asked to build,
2972 /// which parses into ONE zero-byte tile rather than none.
2973 ///
2974 /// Sweeping a real frame OBU's tile payload from empty upwards asserts both
2975 /// halves: every `Frame` OBU that parses has a tile, and `decode_stream`
2976 /// never reports this refusal for any of them.
2977 #[test]
2978 fn a_frame_obu_that_parses_always_carries_at_least_one_tile() {
2979 let fctx = &crate::decode::FrameCtx::new();
2980 const REFUSAL: &str = "a frame OBU with no tile group";
2981 let picture = test_card(64, 64);
2982 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2983 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2984 let mut frame_obus_parsed = 0;
2985 for len in 0..=encoded.tile.len().min(24) {
2986 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2987 stream.extend_from_slice(
2988 &crate::frame::frame_obu(&seq, &header, &encoded.tile[..len]).unwrap(),
2989 );
2990 let mut parser = Av1Parser::new();
2991 let mut pos = 0usize;
2992 while pos < stream.len() {
2993 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
2994 break;
2995 };
2996 pos += obu.total_size;
2997 if let ObuKind::Frame(_, tiles) = &obu.kind {
2998 frame_obus_parsed += 1;
2999 assert!(
3000 !tiles.is_empty(),
3001 "a {len}-byte tile payload parsed into a frame OBU with no tile group -- \
3002 the refusal {REFUSAL:?} is reachable after all"
3003 );
3004 }
3005 }
3006 if let Err(e) = decode_stream(&stream) {
3007 let e = e.to_string();
3008 assert!(
3009 !e.contains(REFUSAL),
3010 "a {len}-byte tile payload reached {REFUSAL:?}: {e}"
3011 );
3012 }
3013 }
3014 assert!(
3015 frame_obus_parsed >= 2,
3016 "the sweep parsed {frame_obus_parsed} frame OBUs -- it proves nothing about the \
3017 refusal's reachability"
3018 );
3019 }
3020
3021 /// lane-t900 r27, negative gate: a frame whose segmentation enables one of
3022 /// the three MODE-OVERRIDING features -- `SEG_LVL_REF_FRAME` (forces a
3023 /// block's reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both
3024 /// suppress symbols `decode_inter_block` reads unconditionally) -- is
3025 /// refused BY NAME and outputs no picture, rather than desyncing on the
3026 /// first block that would have obeyed the override.
3027 ///
3028 /// Written, not hand-built: `write_segmentation_params` (spec 5.9.14)
3029 /// codes `feature_enabled`/`feature_data` for every segment, so a real
3030 /// key frame carrying the flag is a two-line change to the header the
3031 /// encoder already produced. Swept over all three features and over the
3032 /// first, a middle and the last segment id.
3033 #[test]
3034 fn a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name() {
3035 let fctx = &crate::decode::FrameCtx::new();
3036 const REFUSAL: &str = "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
3037 let picture = test_card(64, 64);
3038 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3039 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
3040 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
3041 for segment in [0usize, 3, 7] {
3042 let mut header = key.clone();
3043 header.segmentation.enabled = true;
3044 header.segmentation.update_map = true;
3045 header.segmentation.update_data = true;
3046 header.segmentation.feature_enabled[segment][feature] = true;
3047 header.segmentation.feature_data[segment][feature] = 1;
3048 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
3049 stream.extend_from_slice(
3050 &crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap(),
3051 );
3052 let mut shown = 0;
3053 let err = decode_stream_with(&stream, |_, _, _| {
3054 shown += 1;
3055 Ok(())
3056 })
3057 .unwrap_err()
3058 .to_string();
3059 assert!(
3060 err.contains(REFUSAL),
3061 "feature {feature} segment {segment}: expected {REFUSAL:?}, got: {err}"
3062 );
3063 assert_eq!(
3064 shown, 0,
3065 "feature {feature} segment {segment}: a refused frame produced a picture"
3066 );
3067 }
3068 }
3069 }
3070
3071 /// One census attempt: encode `frames` frames of `source` with real
3072 /// aomenc plus `extra` args, decode with THIS decoder, and return the
3073 /// stream's byte length with either the picture count or the refusal (any
3074 /// decode error) it produced. A census is about what the encoder emits,
3075 /// so a refusal is data here, not a failure.
3076 fn census_attempt(
3077 source: &str,
3078 width: usize,
3079 height: usize,
3080 frames: usize,
3081 extra: &[&str],
3082 ) -> (usize, std::result::Result<usize, String>) {
3083 let duration = format!("{}", frames as f64 / 25.0);
3084 let src = format!("{source}=size={width}x{height}:rate=25");
3085 let y4m = Command::new("ffmpeg")
3086 .args([
3087 "-v",
3088 "error",
3089 "-f",
3090 "lavfi",
3091 "-i",
3092 &src,
3093 "-t",
3094 &duration,
3095 "-pix_fmt",
3096 "yuv420p",
3097 "-strict",
3098 "-1",
3099 "-f",
3100 "yuv4mpegpipe",
3101 "-",
3102 ])
3103 .stdin(Stdio::null())
3104 .stdout(Stdio::piped())
3105 .stderr(Stdio::piped())
3106 .output()
3107 .expect("ffmpeg failed to run");
3108 assert!(
3109 y4m.status.success(),
3110 "ffmpeg refused the {width}x{height} fixture"
3111 );
3112 let limit = format!("--limit={frames}");
3113 let mut args: Vec<String> = [
3114 "--codec=av1",
3115 "--passes=1",
3116 "--end-usage=q",
3117 "--threads=1",
3118 "--row-mt=0",
3119 "--kf-max-dist=9999",
3120 "--lag-in-frames=0",
3121 ]
3122 .iter()
3123 .map(|s| (*s).to_owned())
3124 .collect();
3125 args.push(limit);
3126 args.extend(extra.iter().map(|s| (*s).to_owned()));
3127 args.extend([
3128 "--obu".to_owned(),
3129 "-o".to_owned(),
3130 "-".to_owned(),
3131 "-".to_owned(),
3132 ]);
3133 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3134 assert!(
3135 out.status.success(),
3136 "aomenc refused {args:?}: {}",
3137 String::from_utf8_lossy(&out.stderr)
3138 );
3139 let stream = out.stdout;
3140 let result = match decode_stream(&stream) {
3141 Ok(pictures) => Ok(pictures.len()),
3142 Err(e) => Err(e.to_string()),
3143 };
3144 (stream.len(), result)
3145 }
3146
3147 /// lane-av1seglvl: encode `frames` frames of `source` with real aomenc
3148 /// plus `extra` args and return the raw `.obu` bytes -- the census's
3149 /// half-sibling of [`census_attempt`] that keeps the STREAM instead of
3150 /// only its decode verdict, so the caller can parse the frame headers'
3151 /// segmentation tables themselves.
3152 fn encode_aomenc_stream(
3153 source: &str,
3154 width: usize,
3155 height: usize,
3156 frames: usize,
3157 extra: &[&str],
3158 ) -> Vec<u8> {
3159 let duration = format!("{}", frames as f64 / 25.0);
3160 let src = format!("{source}=size={width}x{height}:rate=25");
3161 let y4m = Command::new("ffmpeg")
3162 .args([
3163 "-v",
3164 "error",
3165 "-f",
3166 "lavfi",
3167 "-i",
3168 &src,
3169 "-t",
3170 &duration,
3171 "-pix_fmt",
3172 "yuv420p",
3173 "-strict",
3174 "-1",
3175 "-f",
3176 "yuv4mpegpipe",
3177 "-",
3178 ])
3179 .stdin(Stdio::null())
3180 .stdout(Stdio::piped())
3181 .stderr(Stdio::piped())
3182 .output()
3183 .expect("ffmpeg failed to run");
3184 assert!(
3185 y4m.status.success(),
3186 "ffmpeg refused the {width}x{height} fixture"
3187 );
3188 let limit = format!("--limit={frames}");
3189 let mut args: Vec<String> = [
3190 "--codec=av1",
3191 "--passes=1",
3192 "--end-usage=q",
3193 "--threads=1",
3194 "--row-mt=0",
3195 "--kf-max-dist=9999",
3196 "--lag-in-frames=0",
3197 ]
3198 .iter()
3199 .map(|s| (*s).to_owned())
3200 .collect();
3201 args.push(limit);
3202 args.extend(extra.iter().map(|s| (*s).to_owned()));
3203 args.extend([
3204 "--obu".to_owned(),
3205 "-o".to_owned(),
3206 "-".to_owned(),
3207 "-".to_owned(),
3208 ]);
3209 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3210 assert!(
3211 out.status.success(),
3212 "aomenc refused {args:?}: {}",
3213 String::from_utf8_lossy(&out.stderr)
3214 );
3215 out.stdout
3216 }
3217
3218 /// lane-av1seglvl: encode `frames` frames with a real TWO-PASS aomenc
3219 /// (pass 1 writes the stats file into the session temp dir, pass 2
3220 /// consumes it) and return the `.obu` bytes. This is the only shape that
3221 /// reaches libaom's `is_stat_consumption_stage_twopass` segmentation
3222 /// setup (`configure_static_seg_features`), so the census is not proven
3223 /// over the encoder's whole reachable surface without it.
3224 fn encode_aomenc_stream_twopass(
3225 source: &str,
3226 width: usize,
3227 height: usize,
3228 frames: usize,
3229 extra: &[&str],
3230 ) -> Vec<u8> {
3231 let duration = format!("{}", frames as f64 / 25.0);
3232 let src = format!("{source}=size={width}x{height}:rate=25");
3233 let y4m = Command::new("ffmpeg")
3234 .args([
3235 "-v",
3236 "error",
3237 "-f",
3238 "lavfi",
3239 "-i",
3240 &src,
3241 "-t",
3242 &duration,
3243 "-pix_fmt",
3244 "yuv420p",
3245 "-strict",
3246 "-1",
3247 "-f",
3248 "yuv4mpegpipe",
3249 "-",
3250 ])
3251 .stdin(Stdio::null())
3252 .stdout(Stdio::piped())
3253 .stderr(Stdio::piped())
3254 .output()
3255 .expect("ffmpeg failed to run");
3256 assert!(
3257 y4m.status.success(),
3258 "ffmpeg refused the {width}x{height} fixture"
3259 );
3260 let limit = format!("--limit={frames}");
3261 let fpf =
3262 std::env::temp_dir().join(format!("ec-av1-segldapass-{}.fpf", std::process::id()));
3263 let mut base: Vec<String> = [
3264 "--codec=av1",
3265 "--passes=2",
3266 "--end-usage=q",
3267 "--threads=1",
3268 "--row-mt=0",
3269 "--kf-max-dist=9999",
3270 "--lag-in-frames=0",
3271 ]
3272 .iter()
3273 .map(|s| (*s).to_owned())
3274 .collect();
3275 base.push(limit);
3276 base.extend(extra.iter().map(|s| (*s).to_owned()));
3277 let mut pass1 = base.clone();
3278 pass1.extend(["--pass=1".to_owned(), format!("--fpf={}", fpf.display())]);
3279 pass1.extend([
3280 "--obu".to_owned(),
3281 "-o".to_owned(),
3282 "/dev/null".to_owned(),
3283 "-".to_owned(),
3284 ]);
3285 let out1 = run_with_stdin(Command::new(aomenc_path()).args(&pass1), &y4m.stdout);
3286 assert!(
3287 out1.status.success(),
3288 "aomenc pass 1 refused {pass1:?}: {}",
3289 String::from_utf8_lossy(&out1.stderr)
3290 );
3291 let mut pass2 = base;
3292 pass2.extend(["--pass=2".to_owned(), format!("--fpf={}", fpf.display())]);
3293 pass2.extend([
3294 "--obu".to_owned(),
3295 "-o".to_owned(),
3296 "-".to_owned(),
3297 "-".to_owned(),
3298 ]);
3299 let out2 = run_with_stdin(Command::new(aomenc_path()).args(&pass2), &y4m.stdout);
3300 let _ = std::fs::remove_file(&fpf);
3301 assert!(
3302 out2.status.success(),
3303 "aomenc pass 2 refused {pass2:?}: {}",
3304 String::from_utf8_lossy(&out2.stderr)
3305 );
3306 out2.stdout
3307 }
3308
3309 /// lane-av1seglvl: walk every frame OBU of `stream` and tally which
3310 /// `SEG_LVL` features the frame headers actually ENABLE, plus the shape
3311 /// counters a census premise is asserted against: frames with
3312 /// segmentation on, of which `update_map == 1` (the map is coded) and
3313 /// `update_map == 0` (every block's id is INHERITED), and frames whose
3314 /// table carries a real `SEG_LVL_ALT_Q` delta.
3315 /// The last vector counts per SEGMENT-FEATURE INSTANCE (a frame with
3316 /// ALT_Q on all 8 segments contributes 8), which is all the verdict
3317 /// needs: only index `SEG_LVL_ALT_Q` may be non-zero.
3318 /// Returns `(enabled_frames, update_map_frames, inherited_frames,
3319 /// alt_q_frames, feature_instances: [usize; SEG_LVL_MAX])`.
3320 #[allow(clippy::type_complexity)]
3321 fn segmentation_feature_census(
3322 stream: &[u8],
3323 ) -> (usize, usize, usize, usize, [usize; SEG_LVL_MAX]) {
3324 let mut parser = Av1Parser::new();
3325 let obus = parser
3326 .parse_temporal_unit(stream)
3327 .unwrap_or_else(|e| panic!("the census stream does not even parse: {e}"));
3328 let mut enabled = 0usize;
3329 let mut update_map = 0usize;
3330 let mut inherited = 0usize;
3331 let mut alt_q = 0usize;
3332 let mut feature_frames = [0usize; SEG_LVL_MAX];
3333 for obu in &obus {
3334 if let ObuKind::Frame(header, _) = &obu.kind {
3335 let seg = &header.segmentation;
3336 if !seg.enabled {
3337 continue;
3338 }
3339 enabled += 1;
3340 if seg.update_map {
3341 update_map += 1;
3342 } else {
3343 inherited += 1;
3344 }
3345 let mut any_q = false;
3346 for segment in 0..MAX_SEGMENTS {
3347 for feature in 0..SEG_LVL_MAX {
3348 if seg.feature_enabled[segment][feature] {
3349 feature_frames[feature] += 1;
3350 if feature == SEG_LVL_ALT_Q {
3351 any_q = true;
3352 }
3353 }
3354 }
3355 }
3356 if any_q {
3357 alt_q += 1;
3358 }
3359 }
3360 }
3361 (enabled, update_map, inherited, alt_q, feature_frames)
3362 }
3363
3364 /// lane-hdrlossless WITNESS → lane-av1mixloss LIFT. `--end-usage=q
3365 /// --cq-level=0 --aq-mode=1` (variance AQ over a lossless base) gives a
3366 /// high-variance segment a positive `SEG_LVL_ALT_Q` while a flat segment
3367 /// stays at `qindex == 0` (`aq_variance.c` sets `SEG_LVL_ALT_Q` per
3368 /// segment and only clamps when `base_qindex != 0`, so a lossless base is
3369 /// exactly where the mixed case comes from): a frame MIXING lossless and
3370 /// lossy segments, which this decoder refused by name until the
3371 /// per-segment lossless table (libaom `decodeframe.c:5205`,
3372 /// `xd->lossless[segment_id]`; `read_tx_size` returns TX_4X4 before it
3373 /// reads a symbol, `decodeframe.c:1170`) landed. Non-vacuity, three ways:
3374 /// (1) the header census proves the arms REALLY carry a mixed frame
3375 /// (class `gate-blind-to-feature` -- variance AQ over a lossless base is
3376 /// the whole point, not the flag spelling), (2) the WHT-unit counter
3377 /// proves the per-segment lossless reconstruction really ran, and (3)
3378 /// every decoded plane is compared SAMPLE-EXACT against ffmpeg's libaom,
3379 /// which accepts the same stream -- so the old refusal named a capability
3380 /// gap, and this gate now proves the gap closed on a real encoder output.
3381 #[test]
3382 fn a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact() {
3383 const NAME: &str = "a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact";
3384 if !have_ffmpeg() {
3385 eprintln!("SKIP {NAME}: no ffmpeg");
3386 return;
3387 }
3388 if !have_aomenc() {
3389 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3390 return;
3391 }
3392 const FRAMES: usize = 4;
3393 const WIDTH: usize = 256;
3394 const HEIGHT: usize = 192;
3395 // (source, per-arm overrides). `--end-usage=q --cq-level=0` is the
3396 // lossless base; `--aq-mode=1` is variance AQ, the only aomenc path
3397 // that sets `SEG_LVL_ALT_Q` with no clamp at base 0 (`aq_variance.c`).
3398 // Several arms because the segment split depends on the encoder's own
3399 // variance decisions (class knob-never-reached-the-tool: require at
3400 // least one arm to actually mix, and fail if none does).
3401 let arms: [(&str, &[&str]); 3] = [
3402 (
3403 "testsrc2=size=256x192:rate=25",
3404 &[
3405 "--end-usage=q",
3406 "--cq-level=0",
3407 "--aq-mode=1",
3408 "--good",
3409 "--cpu-used=3",
3410 "--sb-size=64",
3411 ],
3412 ),
3413 (
3414 "testsrc2=size=256x192:rate=25",
3415 &[
3416 "--end-usage=q",
3417 "--cq-level=0",
3418 "--aq-mode=1",
3419 "--good",
3420 "--cpu-used=5",
3421 "--sb-size=64",
3422 ],
3423 ),
3424 (
3425 "gradients=size=256x192:rate=25",
3426 &[
3427 "--end-usage=q",
3428 "--cq-level=0",
3429 "--aq-mode=1",
3430 "--good",
3431 "--cpu-used=6",
3432 "--sb-size=64",
3433 ],
3434 ),
3435 ];
3436 let mut mixed_arms = 0usize;
3437 // The WHT-unit delta below is a process-wide counter: serialize the
3438 // arms against the other counter-reading gates.
3439 let _gate_lock = lock_gate_counters();
3440 for (src, extra) in &arms {
3441 let y4m = Command::new("ffmpeg")
3442 .args([
3443 "-v",
3444 "error",
3445 "-f",
3446 "lavfi",
3447 "-i",
3448 *src,
3449 "-t",
3450 "0.16",
3451 "-pix_fmt",
3452 "yuv420p",
3453 "-strict",
3454 "-1",
3455 "-f",
3456 "yuv4mpegpipe",
3457 "-",
3458 ])
3459 .stdin(Stdio::null())
3460 .stdout(Stdio::piped())
3461 .stderr(Stdio::piped())
3462 .output()
3463 .expect("ffmpeg failed to run");
3464 assert!(y4m.status.success(), "{NAME}: ffmpeg failed for {src}");
3465 let limit = format!("--limit={FRAMES}");
3466 let mut args: Vec<String> = [
3467 "--codec=av1",
3468 "--passes=1",
3469 "--threads=1",
3470 "--obu",
3471 "-o",
3472 "-",
3473 "-",
3474 ]
3475 .iter()
3476 .map(|s| (*s).to_owned())
3477 .collect();
3478 args.insert(1, limit);
3479 args.extend(extra.iter().map(|s| (*s).to_owned()));
3480 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3481 assert!(
3482 out.status.success(),
3483 "{NAME}: aomenc refused {args:?}: {}",
3484 String::from_utf8_lossy(&out.stderr)
3485 );
3486 let stream = out.stdout;
3487 // (2) the stream really carries a frame the old refusal named.
3488 let mut parser = Av1Parser::new();
3489 let (mut pos, mut mixed) = (0usize, 0usize);
3490 while pos < stream.len() {
3491 let obu = parser.parse_obu(&stream[pos..]).expect("aomenc OBU parses");
3492 pos += obu.total_size.max(1);
3493 let header = match &obu.kind {
3494 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
3495 _ => continue,
3496 };
3497 if header.lossless.iter().any(|&l| l) && !header.lossless.iter().all(|&l| l) {
3498 mixed += 1;
3499 }
3500 }
3501 if mixed == 0 {
3502 eprintln!("{NAME}: arm {extra:?} coded no mixed frame -- trying the next");
3503 continue;
3504 }
3505 // (3) ours DECODES it, sample-exact against ffmpeg's libaom (the
3506 // reference decode doubles as the libaom-accepts proof). The
3507 // WHT-unit delta proves the per-segment lossless reconstruction
3508 // really ran inside a frame that is NOT `CodedLossless`.
3509 let before = crate::decode::lossless_wht_units();
3510 let ours = decode_stream(&stream).unwrap_or_else(|e| {
3511 panic!("{NAME}: a mixed-lossless frame decodes after the per-segment lift: {e}")
3512 });
3513 let wht_units = crate::decode::lossless_wht_units() - before;
3514 let refs = ffmpeg_decode_sequence(&stream, WIDTH, HEIGHT, FRAMES);
3515 assert_eq!(ours.len(), FRAMES, "{NAME}: frame count");
3516 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
3517 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
3518 .iter()
3519 .enumerate()
3520 {
3521 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
3522 assert_eq!(
3523 bad, 0,
3524 "{NAME}: arm {extra:?} frame {i} plane {plane}: {bad} samples differ"
3525 );
3526 }
3527 }
3528 assert!(
3529 wht_units > 0,
3530 "{NAME}: arm {extra:?} reconstructed no Walsh-Hadamard unit -- the mixed census is lying or the lossless path never ran"
3531 );
3532 mixed_arms += 1;
3533 eprintln!(
3534 "{NAME}: arm {extra:?}: {mixed} mixed frame(s), {FRAMES} frames sample-exact vs ffmpeg, {wht_units} WHT units"
3535 );
3536 }
3537 assert!(
3538 mixed_arms > 0,
3539 "{NAME}: no arm produced a mixed lossless/lossy frame -- the witness is vacuous \
3540 (re-measure the aomenc recipe)"
3541 );
3542 }
3543
3544 /// lane-t900 r27 CENSUS behind the negative gate above: does a real
3545 /// aomenc ever ENABLE one of the three mode-overriding segmentation
3546 /// features? Measured over the recipes that turn segmentation on --
3547 /// `--aq-mode=1/2/3` (variance, complexity and cyclic-refresh AQ) and
3548 /// `--deltaq-mode=1` -- with the refusal as the instrument: if one of
3549 /// those features appeared, the decode would stop by name.
3550 ///
3551 /// lane-av1seglvl re-scope: r27's arms were all `--passes=1
3552 /// --lag-in-frames=0`, so they never coded an alt-ref frame or ran an
3553 /// encoder second pass -- the only shapes where libaom's OTHER seg
3554 /// feature setup (`configure_static_seg_features`) could ever run. The
3555 /// re-scoped half below adds alt-ref-group arms and a real two-pass arm,
3556 /// and upgrades the instrument from the refusal (blind to a pure-ALT_LF
3557 /// stream) to a direct parse of every frame header's `feature_enabled`
3558 /// table: over all of it, aomenc enables `SEG_LVL_ALT_Q` and nothing
3559 /// else.
3560 #[test]
3561 fn a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature() {
3562 if !have_aomenc() {
3563 eprintln!("SKIP a_segmentation_census_over_real_aq_streams: no aomenc");
3564 return;
3565 }
3566 const REFUSAL: &str = "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
3567 let recipes: [(&str, Vec<&str>); 6] = [
3568 ("baseline", vec!["--cpu-used=4", "--cq-level=40"]),
3569 (
3570 "aq-mode=1",
3571 vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=40"],
3572 ),
3573 (
3574 "aq-mode=2",
3575 vec!["--cpu-used=4", "--aq-mode=2", "--cq-level=40"],
3576 ),
3577 (
3578 "aq-mode=3",
3579 vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=40"],
3580 ),
3581 (
3582 "aq-mode=3 cq10",
3583 vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=10"],
3584 ),
3585 (
3586 "deltaq-mode=1",
3587 vec!["--cpu-used=4", "--deltaq-mode=1", "--cq-level=40"],
3588 ),
3589 ];
3590 // Arrival, not intent (class knob-never-reached-the-tool): a recipe
3591 // whose stream is byte-for-byte the baseline's changed nothing, and a
3592 // census over such arms would be vacuous. Measured r27: only
3593 // `--aq-mode=3` (cyclic refresh) does -- aq-mode 1/2 and deltaq-mode=1
3594 // all reproduce the baseline's 7147 B at this recipe.
3595 let mut baseline_bytes = 0usize;
3596 let mut segment_symbols = 0usize;
3597 let mut refused = 0usize;
3598 let mut decoded = 0usize;
3599 for (name, extra) in &recipes {
3600 let before = crate::decode::segment_id_hits();
3601 let (bytes, result) = census_attempt("mandelbrot", 192, 128, 8, extra);
3602 match result {
3603 Ok(pictures) => {
3604 decoded += 1;
3605 let symbols = crate::decode::segment_id_hits() - before;
3606 segment_symbols += symbols;
3607 if *name == "baseline" {
3608 baseline_bytes = bytes;
3609 }
3610 eprintln!(
3611 "SEGCENSUS {name}: {bytes} B{}, {pictures} pictures, segment_id symbols {symbols}",
3612 if bytes == baseline_bytes && *name != "baseline" {
3613 " (== baseline: the flag changed nothing)"
3614 } else {
3615 ""
3616 }
3617 );
3618 }
3619 Err(e) => {
3620 eprintln!("SEGCENSUS {name}: {bytes} B, refused: {e}");
3621 assert!(
3622 !e.contains(REFUSAL),
3623 "{name}: a real aomenc stream DOES enable a mode-overriding \
3624 segmentation feature -- the refusal is a capability gap, not a \
3625 claim about the encoder: {e}"
3626 );
3627 refused += 1;
3628 }
3629 }
3630 }
3631 eprintln!(
3632 "SEGCENSUS: {} recipes, {decoded} decoded, {refused} refused for other reasons",
3633 recipes.len()
3634 );
3635 assert_eq!(
3636 decoded,
3637 recipes.len(),
3638 "every recipe must decode; {refused} refused"
3639 );
3640 assert!(
3641 segment_symbols > 0,
3642 "no recipe coded a single segment_id symbol -- segmentation never arrived, so \
3643 this census measures nothing about the three mode-overriding features"
3644 );
3645
3646 // lane-av1seglvl re-scope: the r27 arms above are all `--passes=1
3647 // --lag-in-frames=0`, which never codes an alt-ref frame -- the one
3648 // frame type whose segmentation libaom sets up differently
3649 // (`configure_static_seg_features`, encoder_utils.c:738, is further
3650 // gated on the second pass AND on `hl_sf.static_segmentation`, which
3651 // speed_features.h itself documents as "Always set to 0"). The arms
3652 // below cover that whole remaining surface: alt-ref groups under
3653 // `--aq-mode`, a high-cq arm (the branch's own `high_q` gate is
3654 // `avg_q > 48`), and a genuine two-pass encode. The instrument is no
3655 // longer the refusal -- the refusal only fires on
3656 // REF_FRAME/SKIP/GLOBALMV, so an ALT_LF-only stream would decode
3657 // silently past it -- but a direct parse of every frame header's
3658 // `feature_enabled` table.
3659 let lag_recipes: [(&str, &str, usize, usize, Vec<&str>); 3] = [
3660 (
3661 "aq-mode=1 lag16 mandelbrot",
3662 "mandelbrot",
3663 192,
3664 128,
3665 vec![
3666 "--cpu-used=4",
3667 "--aq-mode=1",
3668 "--cq-level=45",
3669 "--lag-in-frames=16",
3670 "--auto-alt-ref=1",
3671 ],
3672 ),
3673 (
3674 "aq-mode=1 lag16 screen",
3675 "testsrc2",
3676 256,
3677 192,
3678 vec![
3679 "--cpu-used=4",
3680 "--aq-mode=1",
3681 "--cq-level=45",
3682 "--lag-in-frames=16",
3683 "--auto-alt-ref=1",
3684 ],
3685 ),
3686 (
3687 "aq-mode=1 lag16 cq63 high_q",
3688 "mandelbrot",
3689 192,
3690 128,
3691 vec![
3692 "--cpu-used=4",
3693 "--aq-mode=1",
3694 "--cq-level=63",
3695 "--lag-in-frames=16",
3696 "--auto-alt-ref=1",
3697 ],
3698 ),
3699 // `--aq-mode=2 lag16` (complexity AQ over an alt-ref group) was
3700 // measured 2026-09-24: it encodes and decodes cleanly but codes
3701 // ZERO segmentation-enabled frames -- complexity AQ never reaches
3702 // the seg table at this recipe -- so as a census arm it measures
3703 // nothing (class gate-blind-to-feature) and was dropped; the
3704 // 1-pass `aq-mode=2` r27 arm above stays.
3705 ];
3706 let mut total_enabled = 0usize;
3707 let mut total_inherited = 0usize;
3708 let mut total_alt_q = 0usize;
3709 let mut feature_frames = [0usize; SEG_LVL_MAX];
3710 for (name, source, w, h, extra) in &lag_recipes {
3711 let stream = encode_aomenc_stream(source, *w, *h, 40, extra);
3712 let (enabled, umap, inherited, alt_q, frames_per_feature) =
3713 segmentation_feature_census(&stream);
3714 eprintln!(
3715 "SEGCENSUS {name}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}"
3716 );
3717 total_enabled += enabled;
3718 total_inherited += inherited;
3719 total_alt_q += alt_q;
3720 for (f, n) in frames_per_feature.iter().enumerate() {
3721 feature_frames[f] += n;
3722 }
3723 }
3724 // The two-pass arm: `configure_static_seg_features` runs ONLY at
3725 // `is_stat_consumption_stage_twopass`, so this is the arm that would
3726 // catch its ALT_LF/REF_FRAME/SKIP tables if the dead speed feature
3727 // were ever revived.
3728 {
3729 let stream = encode_aomenc_stream_twopass(
3730 "mandelbrot",
3731 192,
3732 128,
3733 40,
3734 &[
3735 "--cpu-used=4",
3736 "--aq-mode=1",
3737 "--cq-level=45",
3738 "--lag-in-frames=16",
3739 "--auto-alt-ref=1",
3740 ],
3741 );
3742 let (enabled, umap, inherited, alt_q, frames_per_feature) =
3743 segmentation_feature_census(&stream);
3744 eprintln!(
3745 "SEGCENSUS twopass aq-mode=1 lag16: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}"
3746 );
3747 total_enabled += enabled;
3748 total_inherited += inherited;
3749 total_alt_q += alt_q;
3750 for (f, n) in frames_per_feature.iter().enumerate() {
3751 feature_frames[f] += n;
3752 }
3753 }
3754 // Premise (class gate-blind-to-feature): the arms must actually reach
3755 // the shapes the census speaks about -- segmentation-carrying frames,
3756 // frames whose map is INHERITED (update_map == 0), and frames with a
3757 // real ALT_Q table -- or the "only ALT_Q" verdict below measures
3758 // nothing.
3759 assert!(
3760 total_enabled > 0 && total_alt_q > 0,
3761 "no lag/two-pass arm carried a segmentation-enabled frame -- the census premise \
3762 never arrived"
3763 );
3764 assert!(
3765 total_inherited > 0,
3766 "no arm carried an update_map == 0 frame -- the map-inheritance path the decoder \
3767 reads segment ids through is unmeasured"
3768 );
3769 // The census verdict, over every frame of every arm: segmentation on
3770 // aomenc's CLI carries SEG_LVL_ALT_Q and NOTHING else. The three
3771 // mode-overriding features and the four ALT_LF deltas have no encoder
3772 // path: `configure_static_seg_features` (the only setter of ALT_LF/
3773 // REF_FRAME/SKIP in the tree) is gated on `hl_sf.static_segmentation`,
3774 // documented "Always set to 0" (speed_features.h), and ROI/active-map
3775 // are control-API only (aomenc.c has no flag for either).
3776 for (feature, frames) in feature_frames.iter().enumerate() {
3777 if feature == SEG_LVL_ALT_Q {
3778 continue;
3779 }
3780 assert_eq!(
3781 *frames, 0,
3782 "feature index {feature} appeared on {frames} frames of real aomenc output -- \
3783 the refusal's encoder-never-writes claim is FALSE and the mode path needs \
3784 porting before this census can stay green"
3785 );
3786 }
3787 eprintln!(
3788 "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"
3789 );
3790 }
3791
3792 /// lane-av1seglvl WITNESS: the reaching stream. `--aq-mode=1` turns
3793 /// segmentation on for every frame; `--lag-in-frames=16 --auto-alt-ref=1`
3794 /// adds real alt-ref groups, so the stream mixes map-CODING frames
3795 /// (`update_map == 1`: the key frame and each group's arf) with dozens of
3796 /// map-INHERITING frames (`update_map == 0`), and an inheriting block's
3797 /// id is the MIN of the previous map over its own footprint while the
3798 /// saved map itself inherits that footprint VERBATIM
3799 /// (`copy_segment_id`, decodemv.c:342) -- heterogeneous footprints are
3800 /// exactly what a 1:4-split arf leaves behind. Stamping the minified id
3801 /// (the pre-lane defect) flattened those footprints and mis-dequantized
3802 /// scattered blocks frames later: 2 luma bytes of mandelbrot frame 35
3803 /// differed from the oracle, everything else exact.
3804 ///
3805 /// Both arms decode EVERY frame in decode order -- hidden arfs included
3806 /// -- byte-exact against the instrumented oracle, and every SHOWN frame
3807 /// pixel-exact against ffmpeg; the census counters prove the premise
3808 /// (segmentation symbols read, a wider-than-zero quantizer span from
3809 /// `SEG_LVL_ALT_Q`, and an inheritance-heavy shape).
3810 #[test]
3811 fn a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact() {
3812 const NAME: &str =
3813 "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact";
3814 if !have_aomenc() {
3815 eprintln!("SKIP {NAME}: no aomenc");
3816 return;
3817 }
3818 if !have_ffmpeg() {
3819 eprintln!("SKIP {NAME}: no ffmpeg");
3820 return;
3821 }
3822 let extra = [
3823 "--cpu-used=4",
3824 "--aq-mode=1",
3825 "--cq-level=45",
3826 "--lag-in-frames=16",
3827 "--auto-alt-ref=1",
3828 ];
3829 let arms: [(&str, &str, usize, usize); 2] = [
3830 ("screen testsrc2", "testsrc2", 256, 192),
3831 ("film mandelbrot", "mandelbrot", 192, 128),
3832 ];
3833 for (arm, source, width, height) in &arms {
3834 let stream = encode_aomenc_stream(source, *width, *height, 40, &extra);
3835 // Premise: the shape under test really arrived -- segmentation on
3836 // every frame, the map both coded and inherited, and real ALT_Q
3837 // tables. An aomenc drift that dropped any of these would make
3838 // the decode below prove nothing (class gate-blind-to-feature).
3839 let (enabled, umap, inherited, alt_q, _) = segmentation_feature_census(&stream);
3840 eprintln!(
3841 "{NAME} {arm}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q-carrying {alt_q}"
3842 );
3843 assert!(
3844 enabled > 0 && umap > 0,
3845 "{arm}: no segmentation-carrying/map-coding frame -- the premise is gone"
3846 );
3847 assert!(
3848 inherited > 0,
3849 "{arm}: no update_map == 0 frame -- the map-inheritance path under test never runs"
3850 );
3851 assert!(
3852 alt_q > 0,
3853 "{arm}: no frame carries a SEG_LVL_ALT_Q table -- the feature under test never fires"
3854 );
3855 // Every frame in decode order -- hidden arfs included (each one
3856 // re-surfaces via show-existing in this recipe, so `hidden == 0`
3857 // is possible while `frames` still covers the whole coded set) --
3858 // byte-exact against the oracle.
3859 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, arm);
3860 assert!(frames > 0, "{arm}: decoded nothing");
3861 assert_eq!(
3862 frames, enabled,
3863 "{arm}: decode-order frame count != segmentation-enabled frame count -- the \
3864 parse and the decode disagree about the stream"
3865 );
3866 let _ = hidden;
3867 // And every shown frame pixel-exact against ffmpeg.
3868 crate::decode::reset_segment_hits();
3869 let pictures = decode_stream(&stream)
3870 .unwrap_or_else(|e| panic!("{NAME} {arm}: decode refused: {e}"));
3871 assert!(
3872 crate::decode::segment_id_hits() > 0,
3873 "{arm}: zero segment_id symbols read -- the decode proved nothing about \
3874 segmentation"
3875 );
3876 let (lo, hi) = crate::decode::block_q_span();
3877 assert!(
3878 hi > lo,
3879 "{arm}: every block dequantized at the same qindex ({lo}) -- SEG_LVL_ALT_Q \
3880 never changed any block's quantizer"
3881 );
3882 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, *width, *height, pictures.len());
3883 for (i, (ours, theirs)) in pictures.iter().zip(&ffmpeg_frames).enumerate() {
3884 assert_eq!(ours.y, theirs.y, "{NAME} {arm}: frame {i} luma vs ffmpeg");
3885 assert_eq!(ours.u, theirs.u, "{NAME} {arm}: frame {i} U vs ffmpeg");
3886 assert_eq!(ours.v, theirs.v, "{NAME} {arm}: frame {i} V vs ffmpeg");
3887 }
3888 eprintln!(
3889 "{NAME} {arm}: {frames} frames decode-order exact vs oracle ({hidden} hidden), {} shown frames exact vs ffmpeg, q span {lo}..{hi}, segment_id symbols {}",
3890 pictures.len(),
3891 crate::decode::segment_id_hits()
3892 );
3893 }
3894 }
3895
3896 /// lane-t900 r27, WITNESS half of the proof for "an OBMC neighbour whose
3897 /// switchable interp filter was never recorded" (the structural half is
3898 /// `decode::tests::every_inter_record_publishes_an_obmc_readable_filter`,
3899 /// which shows no INTER cell is ever stamped with the `[3, 3]`
3900 /// sentinel): real OBMC streams whose frames use a SWITCHABLE (and dual)
3901 /// interp filter decode with the refusal firing 0 times while OBMC blends
3902 /// really read the neighbour band -- a decode that never read one would
3903 /// pass just as well and prove nothing (class gate-blind-to-feature).
3904 #[test]
3905 fn a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour() {
3906 if !have_aomenc() {
3907 eprintln!("SKIP a_real_obmc_stream_reads_a_recorded_switchable_filter: no aomenc");
3908 return;
3909 }
3910 // `--cpu-used=0` is load-bearing: at speed 4 aomenc settles on a
3911 // FRAME-level fixed interp filter, every neighbour then legitimately
3912 // carries the sentinel, and the band is never read at all (measured
3913 // r27: 0 reads over two speed-4 streams).
3914 let base = vec![
3915 "--cpu-used=0",
3916 "--enable-obmc=1",
3917 "--enable-dual-filter=1",
3918 "--min-partition-size=8",
3919 "--max-partition-size=16",
3920 "--enable-palette=0",
3921 "--enable-intrabc=0",
3922 ];
3923 let recipes: [(&str, usize, usize, Vec<&str>); 2] = [
3924 (
3925 "obmc dual cq40",
3926 192,
3927 128,
3928 [vec!["--cq-level=40"], base.clone()].concat(),
3929 ),
3930 (
3931 "obmc dual cq20",
3932 192,
3933 128,
3934 [vec!["--cq-level=20"], base.clone()].concat(),
3935 ),
3936 ];
3937 let mut reads = 0usize;
3938 let mut decoded = 0usize;
3939 for (name, w, h, extra) in &recipes {
3940 let before = crate::decode::obmc_filter_band_reads();
3941 let obmc_before = crate::decode::obmc_hits();
3942 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 8, extra);
3943 match result {
3944 Ok(pictures) => {
3945 decoded += 1;
3946 let got = crate::decode::obmc_filter_band_reads() - before;
3947 reads += got;
3948 eprintln!(
3949 "OBMCFILT {name}: {bytes} B, {pictures} pictures, {got} band reads, \
3950 {} OBMC blocks",
3951 crate::decode::obmc_hits() - obmc_before
3952 );
3953 }
3954 Err(e) => {
3955 assert!(
3956 !e.contains(
3957 "an OBMC neighbour whose switchable interp filter was never recorded"
3958 ),
3959 "{name}: a real OBMC stream reached the unrecorded-filter refusal -- \
3960 a publication site is missing: {e}"
3961 );
3962 eprintln!("OBMCFILT {name}: {bytes} B, refused for another reason: {e}");
3963 }
3964 }
3965 }
3966 assert!(
3967 decoded > 0,
3968 "no OBMC recipe decoded -- the witness is vacuous"
3969 );
3970 assert!(
3971 reads > 0,
3972 "every OBMC blend took the fixed-filter path: the band was never read, so this \
3973 proves nothing about the refusal"
3974 );
3975 }
3976
3977 /// lane-t900 r27 CENSUS for the three SUPERRES refusals -- "warp
3978 /// prediction with a scaled reference", "a sub-8x8 inter block under a
3979 /// scaled reference" and "an 8x8 partition leaf under a scaled reference".
3980 /// Six real `--superres-mode` encodes (fixed denominators and the auto
3981 /// mode, warped motion and OBMC on), decoded by this decoder: the table it
3982 /// prints is which of the three a real encoder actually reaches.
3983 ///
3984 /// Every one of them is a REAL capability gap (unlike the enumerated
3985 /// refusals elsewhere in the inventory), so this gate asserts the measured
3986 /// shape rather than "no refusal": at least one recipe must decode (else
3987 /// the census says nothing), and any refusal must be one of the three
3988 /// named superres ones -- a fourth string would be a new gap this round
3989 /// did not measure.
3990 #[test]
3991 fn a_superres_census_over_six_real_streams_records_which_scaled_refusals_fire() {
3992 if !have_aomenc() {
3993 eprintln!("SKIP a_superres_census_over_six_real_streams: no aomenc");
3994 return;
3995 }
3996 const WARP: &str = "warp prediction with a scaled reference";
3997 const SUB8: &str = "a sub-8x8 inter block under a scaled reference";
3998 const LEAF8: &str = "an 8x8 partition leaf under a scaled reference";
3999 let common = [
4000 "--enable-warped-motion=1",
4001 "--enable-obmc=1",
4002 "--enable-palette=0",
4003 "--enable-intrabc=0",
4004 ];
4005 let recipes: [(&str, usize, usize, Vec<&str>); 6] = [
4006 (
4007 "denom12 320x180 cq32",
4008 320,
4009 180,
4010 vec![
4011 "--cpu-used=4",
4012 "--superres-mode=1",
4013 "--superres-denominator=12",
4014 "--cq-level=32",
4015 ],
4016 ),
4017 (
4018 "denom12 320x180 cq50",
4019 320,
4020 180,
4021 vec![
4022 "--cpu-used=4",
4023 "--superres-mode=1",
4024 "--superres-denominator=12",
4025 "--cq-level=50",
4026 ],
4027 ),
4028 (
4029 "denom16 320x180 cq32",
4030 320,
4031 180,
4032 vec![
4033 "--cpu-used=4",
4034 "--superres-mode=1",
4035 "--superres-denominator=16",
4036 "--cq-level=32",
4037 ],
4038 ),
4039 (
4040 "denom10 192x128 cq32",
4041 192,
4042 128,
4043 vec![
4044 "--cpu-used=4",
4045 "--superres-mode=1",
4046 "--superres-denominator=10",
4047 "--cq-level=32",
4048 ],
4049 ),
4050 (
4051 "auto 320x180 cq50",
4052 320,
4053 180,
4054 vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"],
4055 ),
4056 (
4057 "auto 192x128 cq50",
4058 192,
4059 128,
4060 vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"],
4061 ),
4062 ];
4063 let (mut decoded, mut warp, mut sub8, mut leaf8) = (0, 0, 0, 0);
4064 // lane-t900 r36 (class [[gate-blind-to-feature]]): unknown refusal
4065 // strings used to `other += 1` and panic on the spot, so the census
4066 // summary below -- the whole point of the gate -- never printed when
4067 // one fired. They are collected instead, reported in the summary, and
4068 // asserted after it.
4069 let mut other: Vec<String> = Vec::new();
4070 for (name, w, h, extra) in &recipes {
4071 let mut args = extra.clone();
4072 args.extend_from_slice(&common);
4073 let before = crate::mc::predict_scaled_hits();
4074 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 10, &args);
4075 match result {
4076 Ok(pictures) => {
4077 decoded += 1;
4078 eprintln!(
4079 "SUPERRES {name}: {bytes} B, {pictures} pictures, scaled MC blocks {}",
4080 crate::mc::predict_scaled_hits() - before
4081 );
4082 }
4083 Err(e) => {
4084 eprintln!("SUPERRES {name}: {bytes} B, refused: {e}");
4085 if e.contains(WARP) {
4086 warp += 1;
4087 } else if e.contains(SUB8) {
4088 sub8 += 1;
4089 } else if e.contains(LEAF8) {
4090 leaf8 += 1;
4091 } else {
4092 other.push(format!("{name}: {e}"));
4093 }
4094 }
4095 }
4096 }
4097 eprintln!(
4098 "SUPERRES CENSUS: 6 streams, {decoded} decoded, warp {warp}x, sub8 {sub8}x, leaf8 {leaf8}x, other {}x",
4099 other.len()
4100 );
4101 assert!(
4102 other.is_empty(),
4103 "{} superres stream(s) stopped on a string this census does not know: {other:?}",
4104 other.len()
4105 );
4106 // Measured r27: the four FIXED-denominator recipes all stop at the
4107 // 8x8-leaf refusal, and the two `--superres-mode=3` (auto) streams
4108 // decode with ZERO scaled MC blocks -- auto picked denominator 8, so
4109 // those two arms carry no scaling at all and prove nothing. The warp
4110 // and sub-8x8 refusals never fire because the 8x8-leaf one sits in
4111 // front of them: whichever partition path a scaled frame takes, the
4112 // leaf guard is reached first. Lifting the leaf gap is what makes the
4113 // other two measurable, so this gate pins the ORDER, not just a count.
4114 assert!(
4115 decoded > 0,
4116 "no superres recipe decoded -- the census is vacuous"
4117 );
4118 // lane-t900 r28: all three scaled refusals are LIFTED, so the census
4119 // now pins the opposite shape -- every fixed-denominator recipe must
4120 // DECODE, and none of the three strings may come back.
4121 assert_eq!(
4122 (warp, sub8, leaf8),
4123 (0, 0, 0),
4124 "a scaled-reference refusal came back (warp {warp}, sub8 {sub8}, leaf8 {leaf8})"
4125 );
4126 assert!(
4127 decoded > 0,
4128 "no superres recipe decoded -- the census is vacuous"
4129 );
4130 }
4131
4132 /// lane-t900 r25, negative gate: a `show_existing_frame` header naming a
4133 /// slot no frame has refreshed is refused BY NAME, and outputs no picture.
4134 ///
4135 /// The OBU is hand-built because [`crate::frame::write_frame_header`]
4136 /// refuses to write one (it writes shown key and inter frames only): spec
4137 /// 5.9.2's whole header for this case is `show_existing_frame` (1) plus
4138 /// `frame_to_show_map_idx` (3), the sequence carrying neither a decoder
4139 /// model nor frame ids.
4140 ///
4141 /// Deviation from the round's charter, which asked for a key frame first
4142 /// with the named slot's `refresh_frame_flags` bit clear: a SHOWN key frame
4143 /// refreshes every slot (spec 5.9.2 forces `refresh_frame_flags` to
4144 /// `all_frames` and does not code it, which is also what
4145 /// `write_frame_header` does), so the only reachable empty-slot stream is
4146 /// one where no frame has refreshed that slot yet. The stream below is a
4147 /// valid sequence header followed by the header OBU, and every one of the
4148 /// eight slots is tried.
4149 #[test]
4150 fn a_show_existing_frame_header_naming_an_empty_slot_is_refused_by_name() {
4151 const REFUSAL: &str = "a show_existing_frame header naming an empty reference slot";
4152 let (seq, _) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
4153 for slot in 0..NUM_REF_FRAMES as u32 {
4154 let mut w = ec_core::BitWriter::new();
4155 w.write_bit(true); // show_existing_frame
4156 w.write_bits(slot, 3); // frame_to_show_map_idx
4157 crate::bits::write_byte_alignment(&mut w);
4158 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
4159 stream.extend_from_slice(&crate::obu::wrap_obu(
4160 &ec_av1_syntax::obu::ObuHeader {
4161 obu_type: ec_av1_syntax::obu::ObuType::FrameHeader,
4162 extension_flag: false,
4163 has_size_field: true,
4164 temporal_id: 0,
4165 spatial_id: 0,
4166 },
4167 &w.into_bytes(),
4168 ));
4169
4170 let mut shown = 0;
4171 let err = decode_stream_with(&stream, |_, _, _| {
4172 shown += 1;
4173 Ok(())
4174 })
4175 .unwrap_err()
4176 .to_string();
4177 assert!(
4178 err.contains(REFUSAL),
4179 "slot {slot}: expected {REFUSAL:?}, got: {err}"
4180 );
4181 assert_eq!(
4182 shown, 0,
4183 "slot {slot}: an empty slot was output as a picture"
4184 );
4185 }
4186 }
4187
4188 /// lane-t900 r25, negative gate: an inter frame whose `ref_frame_idx[0]`
4189 /// slot holds no picture -- a stream that opens on an inter frame -- is
4190 /// refused BY NAME rather than predicting from nothing.
4191 ///
4192 /// Deviation from the round's charter, which asked for a real aomenc
4193 /// two-frame stream with the key frame's OBUs stripped: this crate's own
4194 /// `write_frame_header` writes a shown INTER frame (short reference
4195 /// signalling and non-identity global motion are the parts it refuses), so
4196 /// the fixture is built from the writers, needs neither ffmpeg nor aomenc,
4197 /// and is byte-identical on every run. The tile payload is a real key
4198 /// frame's; the refusal fires on the header's reference lookup, before any
4199 /// tile is decoded.
4200 #[test]
4201 fn an_inter_frame_opening_a_stream_is_refused_by_name() {
4202 let fctx = &crate::decode::FrameCtx::new();
4203 const REFUSAL: &str = "an inter frame with no key frame before it";
4204 let picture = test_card(64, 64);
4205 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4206 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
4207 let inter = FrameHeader {
4208 frame_type: FrameType::Inter,
4209 frame_is_intra: false,
4210 // Keeps `primary_ref_frame`, `frame_size_with_refs` and
4211 // `use_ref_frame_mvs` out of the written header (spec 5.9.2).
4212 error_resilient_mode: true,
4213 primary_ref_frame: PRIMARY_REF_NONE,
4214 refresh_frame_flags: 0x02,
4215 order_hint: 1,
4216 ..key
4217 };
4218 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
4219 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
4220
4221 let mut shown = 0;
4222 let err = decode_stream_with(&stream, |_, _, _| {
4223 shown += 1;
4224 Ok(())
4225 })
4226 .unwrap_err()
4227 .to_string();
4228 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
4229 assert_eq!(
4230 shown, 0,
4231 "an inter frame with no reference produced a picture"
4232 );
4233 }
4234
4235 /// lane-t900 r26, negative gate: an inter frame whose own coded size is
4236 /// SHORTER than the reference it predicts from is refused BY NAME, and
4237 /// outputs no picture beyond the key frame that preceded it.
4238 ///
4239 /// The height mismatch is the one size difference this decoder cannot
4240 /// absorb: `mc::predict_scaled` scales horizontally (a `use_superres`
4241 /// reference), and nothing on this path scales vertically. The fixture is
4242 /// written, not hand-built: a shown key frame at 64x64 (which refreshes
4243 /// every slot), then a shown inter frame carrying
4244 /// `frame_size_override_flag` with `error_resilient_mode` set -- the one
4245 /// combination [`crate::frame::write_frame_header`] writes, since
4246 /// `frame_size_with_refs` (spec 5.9.7) is only read when error resilience
4247 /// is OFF. The inter frame's tile payload is the key frame's; the refusal
4248 /// fires on the reference's dimensions before a tile symbol is read.
4249 #[test]
4250 fn an_inter_frame_shorter_than_its_reference_is_refused_by_name() {
4251 let fctx = &crate::decode::FrameCtx::new();
4252 const REFUSAL: &str =
4253 "a reference picture whose height does not match this frame's own true size";
4254 let picture = test_card(64, 64);
4255 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4256 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
4257 let inter = FrameHeader {
4258 frame_type: FrameType::Inter,
4259 frame_is_intra: false,
4260 error_resilient_mode: true,
4261 primary_ref_frame: PRIMARY_REF_NONE,
4262 refresh_frame_flags: 0x02,
4263 order_hint: 1,
4264 frame_size_override_flag: true,
4265 frame_height: 32,
4266 render_height: 32,
4267 ..key.clone()
4268 };
4269 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
4270 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &key, &encoded.tile).unwrap());
4271 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
4272
4273 let mut shown = 0;
4274 let err = decode_stream_with(&stream, |_, _, _| {
4275 shown += 1;
4276 Ok(())
4277 })
4278 .unwrap_err()
4279 .to_string();
4280 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
4281 assert_eq!(
4282 shown, 1,
4283 "expected the key frame alone, got {shown} pictures"
4284 );
4285 }
4286
4287 /// lane-t900 r26, negative gate: an inter frame naming a
4288 /// `primary_ref_frame` whose reference slot has never been refreshed is
4289 /// refused BY NAME rather than decoded from the spec 8.4 default tables.
4290 ///
4291 /// Enumeration first, because the refusal's premise is an invariant: the
4292 /// picture slots and the CDF slots are written by exactly two loops in
4293 /// [`decode_stream`] (the `show_existing_frame` arm's copy and the
4294 /// end-of-frame store), and both walk the SAME `refresh_frame_flags` mask
4295 /// writing `ref_slots[i]` and `cdf_slots[i]` together -- so no slot can
4296 /// hold a picture without CDFs, and the reachable case is a slot nothing
4297 /// has refreshed at all. That is what this builds: a stream that OPENS on
4298 /// a non-error-resilient inter frame (the only header shape that codes
4299 /// `primary_ref_frame` at all, spec 5.9.2), tried at all eight slots.
4300 ///
4301 /// This refusal, not "an inter frame with no key frame before it", is the
4302 /// one such a stream reaches: the CDF load happens in the header path,
4303 /// before the reference pictures are looked up.
4304 #[test]
4305 fn an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name() {
4306 let fctx = &crate::decode::FrameCtx::new();
4307 const REFUSAL: &str =
4308 "a frame naming primary_ref_frame at a reference slot with no saved CDF state";
4309 // The invariant above, read off the source: every line that stores a
4310 // picture into a slot sits in a block that stores that slot's CDFs too.
4311 let src = include_str!("stream.rs");
4312 let stores: Vec<usize> = src
4313 .lines()
4314 .enumerate()
4315 .filter(|(_, l)| l.trim().starts_with("ref_slots[i] = "))
4316 .map(|(i, _)| i)
4317 .collect();
4318 assert_eq!(
4319 stores.len(),
4320 2,
4321 "the picture slots gained a writer -- check it stores cdf_slots too"
4322 );
4323 let lines: Vec<&str> = src.lines().collect();
4324 for &i in &stores {
4325 let window = lines[i.saturating_sub(6)..(i + 6).min(lines.len())].join("\n");
4326 assert!(
4327 window.contains("cdf_slots[i] = "),
4328 "line {} stores a reference picture with no cdf_slots store beside it: a slot \
4329 can then hold a picture with no saved CDF state",
4330 i + 1
4331 );
4332 }
4333
4334 let picture = test_card(64, 64);
4335 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4336 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
4337 for slot in 0..NUM_REF_FRAMES as u8 {
4338 let inter = FrameHeader {
4339 frame_type: FrameType::Inter,
4340 frame_is_intra: false,
4341 // `primary_ref_frame` is coded only when error resilience is
4342 // off (spec 5.9.2); `frame_size_override_flag` stays clear so
4343 // the header writes a plain `frame_size()`.
4344 error_resilient_mode: false,
4345 primary_ref_frame: 0,
4346 ref_frame_idx: [slot; ec_av1_syntax::REFS_PER_FRAME],
4347 refresh_frame_flags: 0x02,
4348 order_hint: 1,
4349 ..key.clone()
4350 };
4351 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
4352 stream
4353 .extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
4354
4355 let mut shown = 0;
4356 let err = decode_stream_with(&stream, |_, _, _| {
4357 shown += 1;
4358 Ok(())
4359 })
4360 .unwrap_err()
4361 .to_string();
4362 assert!(
4363 err.contains(REFUSAL),
4364 "slot {slot}: expected {REFUSAL:?}, got: {err}"
4365 );
4366 assert_eq!(
4367 shown, 0,
4368 "slot {slot}: a frame with no CDF state produced a picture"
4369 );
4370 }
4371 }
4372
4373 /// lane-t900 r26, enumeration: no frame header a stream can carry derives
4374 /// an empty mode-info grid, so "a frame with no mode-info grid" names a
4375 /// case outside the coded domain.
4376 ///
4377 /// `compute_image_size` (spec 5.9.9) is `mi_cols = 2 * ((frame_width + 7)
4378 /// >> 3)`, which is 0 only for `frame_width == 0`, and a frame width is
4379 /// never 0 on any of the three paths that set one:
4380 ///
4381 /// * `frame_size()` (5.9.5) reads `frame_width_minus_1` and adds one, or
4382 /// takes the sequence's `max_frame_width` (itself `+ 1`-coded);
4383 /// * `superres_params()` (5.9.8) divides by a denominator of 9..=16 with
4384 /// rounding, whose minimum over the whole 16-bit upscaled-width domain
4385 /// is enumerated below and is 1, not 0;
4386 /// * `show_existing_frame` and `frame_size_with_refs()` copy a slot's own
4387 /// dimensions, which came from one of the above.
4388 ///
4389 /// The sweep drives the REAL header reader (write a header, parse it back)
4390 /// over every width and every height a 16-bit `frame_size()` can code,
4391 /// per axis -- the derivation is independent per axis -- rather than
4392 /// re-deriving the formula here.
4393 #[test]
4394 fn every_frame_size_a_header_can_code_has_a_mode_info_grid() {
4395 let mut sizes: Vec<u32> = (1..=1024).collect();
4396 sizes.extend([2048, 4095, 4096, 8192, 16384, 32768, 65535, 65536]);
4397 // `mi_cols` is nondecreasing in `frame_width`, so an empty grid can
4398 // only appear at the SMALL end -- which is why a size this crate's
4399 // tile-info writer cannot express (its tile log2 range runs out well
4400 // before 65536) is skipped rather than worked around, while every
4401 // size up to 1024 must be covered.
4402 let mut skipped: Vec<u32> = Vec::new();
4403 for n in sizes {
4404 for (w, h) in [(n, 16), (16, n)] {
4405 let Ok((seq, header)) =
4406 crate::encode::key_frame_headers(w as usize, h as usize, 100)
4407 else {
4408 skipped.push(n);
4409 continue;
4410 };
4411 let Ok(stream) = crate::frame::frame_obu(&seq, &header, &[]) else {
4412 skipped.push(n);
4413 continue;
4414 };
4415 let mut parser = Av1Parser::new();
4416 parser
4417 .parse_obu(&crate::sequence::sequence_header_obu(&seq).unwrap())
4418 .unwrap();
4419 let obu = parser.parse_obu(&stream).unwrap();
4420 let ObuKind::Frame(parsed, _) = &obu.kind else {
4421 panic!("{w}x{h}: the written frame OBU did not parse as one");
4422 };
4423 assert!(
4424 parsed.mi_cols >= 2 && parsed.mi_rows >= 2,
4425 "{w}x{h} parsed to a {}x{} mode-info grid",
4426 parsed.mi_cols,
4427 parsed.mi_rows
4428 );
4429 }
4430 }
4431 assert!(
4432 skipped.iter().all(|&n| n > 1024),
4433 "the writer could not express these small frame sizes, so the small end of the \
4434 sweep is incomplete: {skipped:?}"
4435 );
4436 // The superres arm, which no writer here can express: spec 5.9.8's
4437 // `(upscaled_width * 8 + denom / 2) / denom` over its whole domain.
4438 for denom in 9u32..=16 {
4439 for upscaled in [1u32, 2, 3, 7, 8, 9, 255, 4096, 65535, 65536] {
4440 let width = (upscaled * 8 + denom / 2) / denom;
4441 assert!(
4442 width >= 1,
4443 "superres denom {denom} maps an upscaled width of {upscaled} to {width}, \
4444 which would derive an empty mode-info grid"
4445 );
4446 }
4447 }
4448 }
4449
4450 /// lane-interedge r1: one attempt of the inter frame-edge half-strip gate --
4451 /// encode `width x height` with real aomenc (rect partitions ON, every other
4452 /// lane's open tool pinned off), decode it, and return
4453 /// `(inter_edge_strip hits, frames whose LUMA differs, frames whose CHROMA
4454 /// differs)` against ffmpeg. A refusal or a decode error is a hard failure:
4455 /// this recipe reached every size without one (measured r1).
4456 fn inter_edge_strip_attempt(
4457 name: &str,
4458 width: usize,
4459 height: usize,
4460 bit_depth: u32,
4461 cq: u32,
4462 frames: usize,
4463 ) -> ([usize; 6], usize, usize) {
4464 let duration = format!("{}", frames as f64 / 25.0);
4465 let source = format!("mandelbrot=size={width}x{height}:rate=25");
4466 let pix_fmt = if bit_depth == 10 {
4467 "yuv420p10le"
4468 } else {
4469 "yuv420p"
4470 };
4471 let y4m = Command::new("ffmpeg")
4472 .args([
4473 "-v",
4474 "error",
4475 "-f",
4476 "lavfi",
4477 "-i",
4478 &source,
4479 "-t",
4480 &duration,
4481 "-pix_fmt",
4482 pix_fmt,
4483 "-strict",
4484 "-1",
4485 "-f",
4486 "yuv4mpegpipe",
4487 "-",
4488 ])
4489 .stdin(Stdio::null())
4490 .stdout(Stdio::piped())
4491 .stderr(Stdio::piped())
4492 .output()
4493 .expect("ffmpeg failed to run");
4494 assert!(
4495 y4m.status.success(),
4496 "{name}: ffmpeg refused the {width}x{height} {bit_depth}-bit fixture: {}",
4497 String::from_utf8_lossy(&y4m.stderr)
4498 );
4499 let depth_arg = format!("--bit-depth={bit_depth}");
4500 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
4501 let cq_arg = format!("--cq-level={cq}");
4502 let limit_arg = format!("--limit={frames}");
4503 let out = run_with_stdin(
4504 Command::new(aomenc_path()).args([
4505 "--codec=av1",
4506 "--passes=1",
4507 "--end-usage=q",
4508 &cq_arg,
4509 // cpu-used >= 1 keeps libaom on 64x64 superblocks at these
4510 // sizes (`av1_select_sb_size`).
4511 "--cpu-used=4",
4512 "--threads=1",
4513 "--row-mt=0",
4514 "--kf-max-dist=9999",
4515 &limit_arg,
4516 // decode order == display order, so the compare below covers
4517 // every frame the stream carries (class gate-blind-to-hidden-frames).
4518 "--lag-in-frames=0",
4519 &depth_arg,
4520 &input_depth_arg,
4521 // Rect partitions stay ON: the frame-edge strip is a FORCED
4522 // (gathered) HORZ/VERT, but with rect coding off the encoder
4523 // answers that gathered symbol SPLIT every time and no edge
4524 // strip ever fires (lane-oddh r2's finding, re-measured r1).
4525 "--enable-rect-partitions=1",
4526 "--enable-ab-partitions=0",
4527 "--enable-1to4-partitions=0",
4528 "--min-partition-size=8",
4529 "--max-partition-size=64",
4530 // Other lanes' open gaps this recipe must not trip.
4531 "--enable-palette=0",
4532 "--enable-intrabc=0",
4533 "--enable-warped-motion=0",
4534 "--enable-obmc=0",
4535 "--enable-masked-comp=0",
4536 "--enable-interintra-comp=0",
4537 "--enable-onesided-comp=0",
4538 "--enable-interintra-wedge=0",
4539 "--enable-smooth-interintra=0",
4540 "--enable-ref-frame-mvs=0",
4541 "--enable-angle-delta=0",
4542 "--enable-cfl-intra=0",
4543 "--enable-directional-intra=0",
4544 "--enable-smooth-intra=0",
4545 "--enable-paeth-intra=0",
4546 "--enable-filter-intra=0",
4547 "--enable-tx-size-search=0",
4548 "--obu",
4549 "-o",
4550 "-",
4551 "-",
4552 ]),
4553 &y4m.stdout,
4554 );
4555 assert!(
4556 out.status.success(),
4557 "aomenc refused: {}",
4558 String::from_utf8_lossy(&out.stderr)
4559 );
4560 let stream = out.stdout;
4561
4562 // Reset, never a delta: a refused attempt's hits must not leak into the
4563 // next one (class counter-from-refused-stream).
4564 crate::decode::reset_inter_edge_strip_hits();
4565 let decoded = decode_stream(&stream).unwrap_or_else(|e| {
4566 panic!("{name}: {width}x{height} {bit_depth}-bit cq {cq} did not decode: {e}")
4567 });
4568 let hits = crate::decode::inter_edge_strip_hits();
4569 let reference = if bit_depth == 10 {
4570 ffmpeg_decode_sequence_10bit(&stream, width, height, frames)
4571 } else {
4572 ffmpeg_decode_sequence(&stream, width, height, frames)
4573 };
4574 assert_eq!(
4575 decoded.len(),
4576 reference.len(),
4577 "{name}: {width}x{height} {bit_depth}-bit cq {cq} frame count"
4578 );
4579 assert!(
4580 decoded.len() >= frames,
4581 "{name}: {width}x{height} {bit_depth}-bit cq {cq} decoded only {} frames",
4582 decoded.len()
4583 );
4584 let (mut luma_bad, mut chroma_bad) = (0usize, 0usize);
4585 for (ours, theirs) in decoded.iter().zip(&reference) {
4586 if ours.y != theirs.y {
4587 luma_bad += 1;
4588 }
4589 if ours.u != theirs.u || ours.v != theirs.v {
4590 chroma_bad += 1;
4591 }
4592 }
4593 (hits, luma_bad, chroma_bad)
4594 }
4595
4596 /// lane-interedge r1 GATE (was lane-oddh r2's `#[ignore]`d twin): the INTER
4597 /// frame-edge half strips -- a `PARTITION_HORZ`/`PARTITION_VERT` forced by
4598 /// the gathered edge symbol at the 64, 32 or 16 level whose second half lies
4599 /// outside the true frame. Both of the user's films are height mod 16 == 8
4600 /// (1920x792, 3840x1608), so every inter frame crosses these nodes.
4601 ///
4602 /// r1 root cause: the inter tile's 32-level `PARTITION_HORZ`/`PARTITION_VERT`
4603 /// decoded the SECOND strip unconditionally, while libaom `decode_partition`
4604 /// (decodeframe.c, PARTITION_HORZ) guards it with `has_rows`/`has_cols` --
4605 /// so at the edge we read symbols the encoder never wrote. With that guard
4606 /// removed this gate's 72x192 cq 32 arm refuses outright and its 104x192 arm
4607 /// decodes luma rows 127..191 of frame 5 wrong (measured r1).
4608 ///
4609 /// The compare is LUMA-exact per frame plus a CONTROL size with no edge node
4610 /// at all: chroma is excluded because a chroma-only inter residue that has
4611 /// nothing to do with the frame edge is open on main (lanes/tiny-r3,
4612 /// lanes/gmaffine-r4, lanes/palette2-r8) and the control below reproduces it
4613 /// with `inter_edge_strip_hits` all zero.
4614 #[test]
4615 fn a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact() {
4616 const NAME: &str = "a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact";
4617 let _gate_lock = lock_gate_counters();
4618 if !have_ffmpeg() || !have_aomenc() {
4619 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
4620 return;
4621 }
4622 let frames = 6usize;
4623 // h mod 16 == 8 (bottom edge) and w mod 16 == 8 (right edge).
4624 let sizes: &[(usize, usize)] = &[(192, 72), (192, 88), (72, 192), (88, 192), (104, 192)];
4625 let mut totals = [0usize; 6];
4626 let mut compared = 0u32;
4627 let mut chroma_frames = 0usize;
4628 for &(width, height) in sizes {
4629 for bit_depth in [8u32, 10] {
4630 for cq in [20u32, 32, 45] {
4631 let (hits, luma_bad, chroma_bad) =
4632 inter_edge_strip_attempt(NAME, width, height, bit_depth, cq, frames);
4633 assert_eq!(
4634 luma_bad, 0,
4635 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {luma_bad} of {frames} \
4636 frames differ from ffmpeg in LUMA (edge hits {hits:?})"
4637 );
4638 // merge J, after lane-rectchroma2: the chroma residue this
4639 // gate used to tolerate WAS this decoder's -- the per-axis
4640 // narrow-block MC kernel decision read side x side instead
4641 // of the block's true dims. Full-plane now.
4642 assert_eq!(
4643 chroma_bad, 0,
4644 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {chroma_bad} of \
4645 {frames} frames differ from ffmpeg in CHROMA (edge hits {hits:?})"
4646 );
4647 for (t, h) in totals.iter_mut().zip(hits) {
4648 *t += h;
4649 }
4650 chroma_frames += chroma_bad;
4651 compared += 1;
4652 }
4653 }
4654 }
4655 // Every level x axis this recipe reaches must have fired on a COMPARED
4656 // attempt. h32 (a bottom-edge HORZ at the 32 level) is not asserted: no
4657 // recipe found in r1 makes libaom answer that gathered symbol HORZ
4658 // (sweep ~/.cache/interedge-tmp/h32.sh, 3 sizes x 6 cq, all SPLIT); it
4659 // is the transposed twin of v32, which this gate does fire.
4660 assert!(
4661 totals[0] > 0 && totals[1] > 0 && totals[3] > 0 && totals[4] > 0 && totals[5] > 0,
4662 "{NAME}: {compared} attempts luma-exact but the edge strips did not all fire \
4663 (h64,v64,h32,v32,h16,v16 = {totals:?}) -- the recipe no longer reaches the arms \
4664 this gate exists for"
4665 );
4666 // CONTROL: a size with no frame-edge node anywhere (192x128, both axes
4667 // 0 mod 64). It must be luma-exact with ZERO edge hits -- that is what
4668 // makes the chroma exclusion above a statement about a foreign defect
4669 // rather than about this lane's code.
4670 let (chits, cluma, cchroma) = inter_edge_strip_attempt(NAME, 192, 128, 8, 32, frames);
4671 assert_eq!(
4672 (chits, cluma, cchroma),
4673 ([0usize; 6], 0usize, 0usize),
4674 "{NAME}: control 192x128 (no frame-edge node) must be pixel-exact with no edge hits"
4675 );
4676 eprintln!(
4677 "{NAME}: {compared} attempts luma-exact over {} sizes, edge hits \
4678 (h64,v64,h32,v32,h16,v16)={totals:?}, 0 refusals; chroma-only frames {chroma_frames} \
4679 (control 192x128: hits {chits:?}, chroma-only frames {cchroma} -- foreign defect)",
4680 sizes.len()
4681 );
4682 }
4683
4684 /// lane-sb128 r4 GATE (was lane-oddh r2's refusal gate): the SAME real
4685 /// aomenc 64x72 `--cpu-used=0 --sb-size=128` stream that once desynced at
4686 /// the very first symbol now decodes PIXEL-EXACT against aomdec. mi_rows
4687 /// = 18 > 16, so the BLOCK_128X128 root reads a real gathered partition
4688 /// symbol (2 symbols: has_cols false, has_rows true) -- exactly the case
4689 /// r1 mis-read as a 10-symbol BLOCK_64X64 partition.
4690 ///
4691 /// The `use_128x128_superblock` assert is the "knob reached the tool"
4692 /// half: without it an aomenc that ignored `--sb-size=128` would leave
4693 /// the gate proving nothing about 128 superblocks.
4694 #[test]
4695 fn a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact() {
4696 if !have_ffmpeg() || !have_aomenc() {
4697 eprintln!("SKIP: no ffmpeg/aomenc");
4698 return;
4699 }
4700 let (width, height) = (64usize, 72usize);
4701 let y4m = Command::new("ffmpeg")
4702 .args([
4703 "-v",
4704 "error",
4705 "-f",
4706 "lavfi",
4707 "-i",
4708 "mandelbrot=size=64x72:rate=25:start_x=-0.6:start_y=-0.4",
4709 "-t",
4710 "0.04",
4711 "-pix_fmt",
4712 "yuv420p",
4713 "-f",
4714 "yuv4mpegpipe",
4715 "-",
4716 ])
4717 .stdin(Stdio::null())
4718 .stdout(Stdio::piped())
4719 .stderr(Stdio::piped())
4720 .output()
4721 .expect("ffmpeg failed to run");
4722 assert!(
4723 y4m.status.success(),
4724 "ffmpeg fixture: {}",
4725 String::from_utf8_lossy(&y4m.stderr)
4726 );
4727 let out = run_with_stdin(
4728 Command::new(aomenc_path()).args([
4729 "--codec=av1",
4730 "--passes=1",
4731 "--end-usage=q",
4732 "--cq-level=32",
4733 "--cpu-used=0",
4734 "--sb-size=128",
4735 "--min-partition-size=16",
4736 "--kf-max-dist=0",
4737 "--limit=1",
4738 "--threads=1",
4739 "--row-mt=0",
4740 "--obu",
4741 "-o",
4742 "-",
4743 "-",
4744 ]),
4745 &y4m.stdout,
4746 );
4747 assert!(
4748 out.status.success(),
4749 "aomenc refused: {}",
4750 String::from_utf8_lossy(&out.stderr)
4751 );
4752 let stream = out.stdout;
4753
4754 // The knob actually arrived: this stream's sequence header codes
4755 // `use_128x128_superblock = 1`.
4756 let mut parser = Av1Parser::new();
4757 let mut pos = 0usize;
4758 let mut sb128 = false;
4759 while pos < stream.len() {
4760 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
4761 break;
4762 };
4763 pos += obu.total_size.max(1);
4764 if let Some(seq) = parser.sequence_header() {
4765 sb128 = seq.use_128x128_superblock;
4766 break;
4767 }
4768 }
4769 assert!(
4770 sb128,
4771 "aomenc ignored --sb-size=128: this stream is 64x64-superblock"
4772 );
4773
4774 let _guard = lock_gate_counters();
4775 let before = crate::decode::part128_symbols() + crate::decode::part128_gathered_symbols();
4776 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, "sb128-oddh-64x72");
4777 assert!(frames > 0, "no frames decoded for {width}x{height}");
4778 // The 128 root actually READ a partition symbol here: at mi_rows=18
4779 // `has_rows` is true, so BLOCK_128X128 is not a forced split.
4780 let part128 =
4781 crate::decode::part128_symbols() + crate::decode::part128_gathered_symbols() - before;
4782 assert!(
4783 part128 > 0,
4784 "{width}x{height} decoded without reading a single BLOCK_128X128 \
4785 partition symbol -- the gate proves nothing about the 128 root"
4786 );
4787 eprintln!(
4788 "a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact: \
4789 {frames} frames pixel-exact ({hidden} hidden) at {width}x{height}, \
4790 part128_symbols={part128}"
4791 );
4792 }
4793
4794 /// `decode_stream` on a lone key frame's stream matches both the tile
4795 /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and
4796 /// the encoder's own reconstruction, at an even and an odd size.
4797 #[test]
4798 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
4799 // lane-b128m: the ENCODER writes at this process's superblock size, so
4800 // its own trial decode -- and the raw tile decode below -- must be given
4801 // that size too (class: stale header in the test harness).
4802 let fctx = &crate::decode::FrameCtx::for_encoder();
4803 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
4804 let picture = test_card(width, height);
4805 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4806 let via_tile = decode_key_frame_tile_lr(
4807 &encoded.tile,
4808 encoded.mi_cols,
4809 encoded.mi_rows,
4810 encoded.base_q_idx,
4811 width as u32,
4812 height as u32,
4813 // lane-fintra: the sequence bit the encoder wrote this tile under
4814 // (stale-header class -- a hard-coded `false` here reads one symbol
4815 // short at the first DC_PRED block once the search offers filter intra).
4816 crate::encode::filter_intra_on(),
4817 &encoded.cdef,
4818 &encoded.loop_filter,
4819 encoded.tx_select,
4820 // lane-intertx: the frame's own `reduced_tx_set` -- a screen
4821 // key frame at preset 0 codes the wider intra alphabets, so
4822 // the old hardcoded `true` (ours "always" wrote true) is a
4823 // stale-header bug waiting for the first screen fixture.
4824 encoded.reduced_tx_set,
4825 // `allow_screen_content_tools` off the frame the encoder
4826 // actually wrote: a screen-content picture codes two palette
4827 // symbols per intra block, and a raw tile decode that guessed
4828 // `false` desyncs at the first one (class: test asserts
4829 // against a stale header).
4830 encoded.screen,
4831 // ... and its own `allow_intrabc` (stale-header class).
4832 encoded.allow_intrabc,
4833 &encoded.loop_restoration,
4834 fctx,
4835 )
4836 .unwrap();
4837 let via_stream = decode_stream(&encoded.stream).unwrap();
4838 assert_eq!(via_stream.len(), 1, "{width}x{height}: one picture");
4839 assert_eq!(via_stream[0].y, via_tile.y, "{width}x{height}: luma");
4840 assert_eq!(via_stream[0].u, via_tile.u, "{width}x{height}: U");
4841 assert_eq!(via_stream[0].v, via_tile.v, "{width}x{height}: V");
4842 assert_eq!(
4843 via_stream[0].y, encoded.reconstruction.y,
4844 "{width}x{height}: luma vs encoder reconstruction"
4845 );
4846 }
4847 }
4848
4849 /// A GOP (key frame plus panned inter frames, so blocks actually take
4850 /// motion) decodes bit-exact through `decode_stream` alone, threading its
4851 /// own DPB rather than a test-supplied reference.
4852 fn gop_round_trips(width: usize, height: usize, fctx: &crate::decode::FrameCtx) {
4853 let pictures: Vec<_> = (0..4)
4854 .map(|i| panned_test_card(width, height, i * 3))
4855 .collect();
4856 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
4857 let decoded = decode_stream(&encoded.stream).unwrap();
4858 assert_eq!(decoded.len(), encoded.frames.len());
4859 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
4860 assert_eq!(
4861 got.y, frame.reconstruction.y,
4862 "{width}x{height} frame {i} luma"
4863 );
4864 assert_eq!(
4865 got.u, frame.reconstruction.u,
4866 "{width}x{height} frame {i} U"
4867 );
4868 assert_eq!(
4869 got.v, frame.reconstruction.v,
4870 "{width}x{height} frame {i} V"
4871 );
4872 }
4873 }
4874
4875 #[test]
4876 fn decode_stream_round_trips_a_gop() {
4877 let fctx = &crate::decode::FrameCtx::for_encoder();
4878 gop_round_trips(128, 64, fctx);
4879 }
4880
4881 /// Same claim at a size that is not a whole number of 32x32 blocks, so
4882 /// the inter frame's 16x16-leaf split path is exercised too.
4883 #[test]
4884 fn decode_stream_round_trips_an_odd_size_gop() {
4885 let fctx = &crate::decode::FrameCtx::for_encoder();
4886 gop_round_trips(216, 96, fctx);
4887 }
4888
4889 /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures
4890 /// `decode_stream` collects, in the same order -- the streaming path is
4891 /// the decoder now (`decode_stream` is a collecting wrapper), so an
4892 /// equivalence check here is what keeps every gate's Vec-shaped assert
4893 /// meaningful. Also pins the sink contract: one call per shown picture,
4894 /// decode indices non-decreasing, and an `Err` from the sink aborting.
4895 #[test]
4896 fn streaming_decode_matches_the_collecting_one() {
4897 let fctx = &crate::decode::FrameCtx::for_encoder();
4898 let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect();
4899 let stream = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
4900 .unwrap()
4901 .stream;
4902 let collected = decode_stream(&stream).unwrap();
4903
4904 let mut shown = Vec::new();
4905 let mut idxs = Vec::new();
4906 let mut live = 0usize;
4907 decode_stream_with(&stream, |p, idx, is_shown| {
4908 live += 1;
4909 if is_shown {
4910 idxs.push(idx);
4911 shown.push(p.clone());
4912 }
4913 Ok(())
4914 })
4915 .unwrap();
4916 assert_eq!(
4917 shown.len(),
4918 collected.len(),
4919 "callback count vs shown frames"
4920 );
4921 assert!(
4922 live >= shown.len(),
4923 "every shown picture is also a callback"
4924 );
4925 assert!(
4926 idxs.windows(2).all(|w| w[0] <= w[1]),
4927 "decode indices out of order: {idxs:?}"
4928 );
4929 for (i, (got, want)) in shown.iter().zip(&collected).enumerate() {
4930 assert_eq!(got.y, want.y, "frame {i} luma");
4931 assert_eq!(got.u, want.u, "frame {i} U");
4932 assert_eq!(got.v, want.v, "frame {i} V");
4933 }
4934
4935 // A sink error stops the decode and comes back unchanged.
4936 let mut seen = 0usize;
4937 let err = decode_stream_with(&stream, |_, _, _| {
4938 seen += 1;
4939 Err(Error::corrupt("sink says stop"))
4940 })
4941 .unwrap_err();
4942 assert_eq!(seen, 1, "decode continued past a failing sink");
4943 assert!(format!("{err}").contains("sink says stop"), "{err}");
4944 }
4945
4946 use crate::probe::run_with_stdin;
4947 use std::process::{Command, Stdio};
4948
4949 /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`,
4950 /// `skip_mode`/compound) all read a process-global atomic counter delta
4951 /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to
4952 /// prove a real block picked the feature under test, not just that a
4953 /// header bit was set. Under `cargo test`'s default parallel run, a
4954 /// SIBLING test's own decode bumps the same global counter mid-gate --
4955 /// a false "fired" reading pixel-compares an attempt the gate would
4956 /// otherwise `continue` past, on top of genuine defects that path may
4957 /// still have. Serialising every counter-delta gate behind this one
4958 /// mutex makes firing detection honest again (matches the existing
4959 /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`).
4960 static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
4961 /// Three-bucket gate summary (class [[gate-skips-on-its-own-failure]]):
4962 /// every attempt lands in exactly one bucket -- decoded pixel-exact WITH
4963 /// the feature counter moving, decoded pixel-exact WITHOUT it, or a named
4964 /// refusal -- and the three sum to the attempts made.
4965 fn gate_buckets(name: &str, counted_exact: u32, uncounted_exact: u32, named_refusals: usize) {
4966 eprintln!(
4967 "{name}: buckets counted-exact={counted_exact} uncounted-exact={uncounted_exact} \
4968 named-refusals={named_refusals} (attempts {})",
4969 counted_exact as usize + uncounted_exact as usize + named_refusals
4970 );
4971 }
4972
4973 pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
4974 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
4975 }
4976
4977 /// lane-cdfflake: a cheap, dependency-free (FNV-1a, not cryptographic --
4978 /// this is a load-bearing-identity fingerprint for flake triage, not a
4979 /// security digest, so no `sha2` dep is pulled in) fixture fingerprint
4980 /// for the cdf-forwarding gate's instrumentation below.
4981 fn fnv1a64(bytes: &[u8]) -> u64 {
4982 let mut hash = 0xcbf29ce484222325u64;
4983 for &b in bytes {
4984 hash ^= b as u64;
4985 hash = hash.wrapping_mul(0x100000001b3);
4986 }
4987 hash
4988 }
4989
4990 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
4991 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
4992 /// aomenc gate decodes its stream through ffmpeg and is meaningless
4993 /// without it -- turns it into a hard failure. Without this the require
4994 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
4995 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
4996 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
4997 fn have_ffmpeg() -> bool {
4998 let present = Command::new("ffmpeg")
4999 .arg("-version")
5000 .stdout(Stdio::null())
5001 .stderr(Stdio::null())
5002 .status()
5003 .is_ok_and(|s| s.success());
5004 assert!(
5005 present
5006 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
5007 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
5008 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
5009 );
5010 present
5011 }
5012
5013 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
5014 fn ffmpeg_decode_sequence(
5015 stream: &[u8],
5016 width: usize,
5017 height: usize,
5018 frames: usize,
5019 ) -> Vec<Pic> {
5020 let out = run_with_stdin(
5021 Command::new("ffmpeg").args([
5022 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
5023 ]),
5024 stream,
5025 );
5026 assert!(
5027 out.status.success(),
5028 "ffmpeg refused the stream: {}",
5029 String::from_utf8_lossy(&out.stderr)
5030 );
5031 let (luma, chroma) = (width * height, width * height / 4);
5032 let frame_bytes = luma + 2 * chroma;
5033 assert_eq!(
5034 out.stdout.len(),
5035 frame_bytes * frames,
5036 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
5037 String::from_utf8_lossy(&out.stderr)
5038 );
5039 (0..frames)
5040 .map(|i| {
5041 let base = i * frame_bytes;
5042 Pic {
5043 width,
5044 height,
5045 y: out.stdout[base..base + luma]
5046 .iter()
5047 .map(|&v| u16::from(v))
5048 .collect(),
5049 u: out.stdout[base + luma..base + luma + chroma]
5050 .iter()
5051 .map(|&v| u16::from(v))
5052 .collect(),
5053 v: out.stdout[base + luma + chroma..base + frame_bytes]
5054 .iter()
5055 .map(|&v| u16::from(v))
5056 .collect(),
5057 }
5058 })
5059 .collect()
5060 }
5061
5062 /// As [`ffmpeg_decode_sequence`], for a MONOCHROME stream: one 8-bit luma
5063 /// plane per frame, exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes
5064 /// (lane-av1mono). Fed through [`run_with_stdin`] for the reason its doc
5065 /// records.
5066 fn ffmpeg_decode_gray_sequence(
5067 stream: &[u8],
5068 width: usize,
5069 height: usize,
5070 frames: usize,
5071 ) -> Vec<u8> {
5072 let out = run_with_stdin(
5073 Command::new("ffmpeg").args([
5074 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "gray", "-",
5075 ]),
5076 stream,
5077 );
5078 assert!(
5079 out.status.success(),
5080 "ffmpeg refused the monochrome stream: {}",
5081 String::from_utf8_lossy(&out.stderr)
5082 );
5083 assert_eq!(
5084 out.stdout.len(),
5085 width * height * frames,
5086 "expected {frames} monochrome frames, ffmpeg said: {}",
5087 String::from_utf8_lossy(&out.stderr)
5088 );
5089 out.stdout
5090 }
5091
5092 /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples
5093 /// are 2-byte little-endian, one full 16-bit range regardless of the
5094 /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the
5095 /// bit depth). The 8-bit helper above stays untouched -- every existing
5096 /// gate depends on it.
5097 fn ffmpeg_decode_sequence_10bit(
5098 stream: &[u8],
5099 width: usize,
5100 height: usize,
5101 frames: usize,
5102 ) -> Vec<Pic> {
5103 let out = run_with_stdin(
5104 Command::new("ffmpeg").args([
5105 "-v",
5106 "error",
5107 "-f",
5108 "obu",
5109 "-i",
5110 "-",
5111 "-f",
5112 "rawvideo",
5113 "-pix_fmt",
5114 "yuv420p10le",
5115 "-",
5116 ]),
5117 stream,
5118 );
5119 assert!(
5120 out.status.success(),
5121 "ffmpeg refused the stream: {}",
5122 String::from_utf8_lossy(&out.stderr)
5123 );
5124 let (luma, chroma) = (width * height, width * height / 4);
5125 let frame_samples = luma + 2 * chroma;
5126 let frame_bytes = frame_samples * 2;
5127 assert_eq!(
5128 out.stdout.len(),
5129 frame_bytes * frames,
5130 "expected {frames} 4:2:0 10-bit frames, ffmpeg said: {}",
5131 String::from_utf8_lossy(&out.stderr)
5132 );
5133 fn le16(bytes: &[u8]) -> Vec<u16> {
5134 bytes
5135 .chunks_exact(2)
5136 .map(|c| u16::from_le_bytes([c[0], c[1]]))
5137 .collect()
5138 }
5139 (0..frames)
5140 .map(|i| {
5141 let base = i * frame_bytes;
5142 Pic {
5143 width,
5144 height,
5145 y: le16(&out.stdout[base..base + luma * 2]),
5146 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
5147 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
5148 }
5149 })
5150 .collect()
5151 }
5152
5153 /// lane-svtinter: an SVT-AV1 screen stream whose frame height is not a
5154 /// multiple of the superblock size codes PALETTE blocks in the bottom
5155 /// (and right) superblock row that hang off the mi grid. Spec 5.11.50
5156 /// `palette_tokens` reads the colour-index map only over the block's
5157 /// `onscreenWidth x onscreenHeight` corner and replicates it outward;
5158 /// this decoder read the full block grid, so it consumed colour-index
5159 /// symbols libaom never wrote and desynced the rest of the tile -- either
5160 /// a wrong bottom superblock row (1599 luma samples in this stream's
5161 /// frame 0, ~80k per inter frame after) or, further along the same tile,
5162 /// a bogus "a Golomb tail longer than this decoder reads" refusal.
5163 ///
5164 /// Unlike its lane-svt1 sibling above this one BUILDS its stream: the
5165 /// recipe is synthetic (`smptebars,drawgrid` through `libsvtav1 -preset 8
5166 /// -svtav1-params screen-content-mode=1`), and 384x152 puts a 32x32
5167 /// palette block at mi row 32 of a 38-mi-tall frame, 24 of its 32 rows
5168 /// on screen. `palette_onscreen_cut_hits` is asserted non-zero so the row
5169 /// cannot pass on a stream that never cuts a palette map (class
5170 /// gate-blind-to-feature).
5171 #[test]
5172 fn an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly() {
5173 const NAME: &str = "an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly";
5174 if !have_ffmpeg() {
5175 eprintln!("SKIP {NAME}: no ffmpeg");
5176 return;
5177 }
5178 let (width, height) = (384usize, 152usize);
5179 let out = Command::new("ffmpeg")
5180 .args([
5181 "-v",
5182 "error",
5183 "-f",
5184 "lavfi",
5185 "-i",
5186 "smptebars=s=384x152:r=12,drawgrid=w=8:h=8:t=1:c=black",
5187 "-frames:v",
5188 "4",
5189 "-c:v",
5190 "libsvtav1",
5191 "-preset",
5192 "8",
5193 "-crf",
5194 "30",
5195 "-svtav1-params",
5196 "lp=1:screen-content-mode=1",
5197 "-g",
5198 "12",
5199 "-f",
5200 "obu",
5201 "-",
5202 ])
5203 .stdin(Stdio::null())
5204 .stdout(Stdio::piped())
5205 .stderr(Stdio::piped())
5206 .output()
5207 .expect("ffmpeg failed to run");
5208 if !out.status.success() || out.stdout.is_empty() {
5209 eprintln!(
5210 "SKIP {NAME}: no libsvtav1 in this ffmpeg: {}",
5211 String::from_utf8_lossy(&out.stderr)
5212 );
5213 return;
5214 }
5215 let stream = out.stdout;
5216 crate::decode::reset_palette_onscreen_cut_hits();
5217 let decoded = decode_stream(&stream).expect("the SVT-AV1 screen stream decodes");
5218 assert_eq!(decoded.len(), 4, "{NAME}: frame count");
5219 assert!(
5220 crate::decode::palette_onscreen_cut_hits() > 0,
5221 "{NAME}: no palette map is cut by the frame edge here -- the gate would pass blind"
5222 );
5223 let want = ffmpeg_decode_sequence(&stream, width, height, decoded.len());
5224 assert_eq!(want.len(), decoded.len(), "{NAME}: ffmpeg frame count");
5225 for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
5226 assert_eq!(got.y, want.y, "{NAME}: frame {i} luma vs ffmpeg");
5227 assert_eq!(got.u, want.u, "{NAME}: frame {i} U vs ffmpeg");
5228 assert_eq!(got.v, want.v, "{NAME}: frame {i} V vs ffmpeg");
5229 }
5230 }
5231
5232 /// lane-svt1: an SVT-AV1 (v3.1.2, `-preset 8 -crf 35`) screen key frame
5233 /// codes 16x16 PALETTE blocks with `skip == 1` whose `tx_depth` split the
5234 /// luma transform. [`crate::decode::decode_block`] armed the palette
5235 /// prediction only when the transform covered the whole block, so that one
5236 /// block predicted DC off its own edges instead: the right symbols (the
5237 /// whole mode ladder diffs clean against an instrumented aomdec) and the
5238 /// wrong pixels -- 812 luma samples in frame 0, carried by the V_PRED
5239 /// blocks under it to 10122 samples over the 12-frame stream.
5240 ///
5241 /// No lavfi recipe witnesses it in a stream this decoder otherwise decodes:
5242 /// 6 sources x 5 sizes x 6 crf values through `libsvtav1 -preset 8
5243 /// -svtav1-params screen-content-mode=1` produced 8 streams that reach the
5244 /// path, and every one of them either refuses on an unrelated Golomb tail
5245 /// or misses by ~200k samples on unrelated inter-frame defects (both
5246 /// recorded in `lanes/svt1.report.md`). So the gate rides the kept stream
5247 /// named by `EC_AV1_SVT1_STREAM` and SKIPs when it is unset -- the screen
5248 /// crop itself is never committed to `fixtures/`.
5249 ///
5250 /// `skip_split_tx_override_hits` is asserted non-zero so the row cannot
5251 /// pass on a stream that never reaches the fixed arm (class
5252 /// gate-blind-to-feature).
5253 #[test]
5254 fn an_svt_screen_palette_block_with_a_split_transform_decodes_exactly() {
5255 const NAME: &str = "an_svt_screen_palette_block_with_a_split_transform_decodes_exactly";
5256 let Ok(path) = std::env::var("EC_AV1_SVT1_STREAM") else {
5257 eprintln!("SKIP {NAME}: EC_AV1_SVT1_STREAM names no stream");
5258 return;
5259 };
5260 if !have_ffmpeg() {
5261 eprintln!("SKIP {NAME}: no ffmpeg");
5262 return;
5263 }
5264 let data = match std::fs::read(&path) {
5265 Ok(data) => data,
5266 Err(e) => {
5267 eprintln!("SKIP {NAME}: {path}: {e}");
5268 return;
5269 }
5270 };
5271 crate::decode::reset_skip_split_tx_override_hits();
5272 let decoded = decode_stream(&data).expect("the kept SVT-AV1 screen stream decodes");
5273 assert!(
5274 crate::decode::skip_split_tx_override_hits() > 0,
5275 "{NAME}: no skipped split-transform palette block in {path} -- the gate would pass blind"
5276 );
5277 let (width, height) = (decoded[0].width, decoded[0].height);
5278 let want = ffmpeg_decode_sequence(&data, width, height, decoded.len());
5279 for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
5280 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");
5281 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");
5282 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");
5283 }
5284 }
5285
5286 /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an
5287 /// independent decoder, not just this crate checking its own tile path.
5288 #[test]
5289 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
5290 let fctx = &crate::decode::FrameCtx::for_encoder();
5291 if !have_ffmpeg() {
5292 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
5293 return;
5294 }
5295 // lane-av1straddle: 216x96 joins 128x64 because only a size whose
5296 // 32x32 blocks straddle the right-hand frame edge can see the writer
5297 // coding a transform unit that starts outside the frame -- libdav1d
5298 // AND libaom both refused the whole key frame while it did, and this
5299 // crate's own (lenient) decoder only differed in the last block's V.
5300 for &(width, height) in &[(128usize, 64usize), (216usize, 96usize)] {
5301 let pictures: Vec<_> = (0..3)
5302 .map(|i| panned_test_card(width, height, i * 3))
5303 .collect();
5304 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
5305 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
5306 let decoded = decode_stream(&encoded.stream).unwrap();
5307 assert_eq!(decoded.len(), 3);
5308 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
5309 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
5310 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
5311 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
5312 }
5313 // ... and the encoder's own reconstruction is what ffmpeg sees,
5314 // so the check fails on a writer-side desync too, not only on a
5315 // decoder-side one.
5316 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
5317 let rec = &frame.reconstruction;
5318 assert_eq!(
5319 rec.y, want.y,
5320 "{width}x{height} frame {i} luma: reconstruction vs ffmpeg"
5321 );
5322 assert_eq!(
5323 rec.u, want.u,
5324 "{width}x{height} frame {i} U: reconstruction vs ffmpeg"
5325 );
5326 assert_eq!(
5327 rec.v, want.v,
5328 "{width}x{height} frame {i} V: reconstruction vs ffmpeg"
5329 );
5330 }
5331 }
5332 }
5333
5334 /// lane-av1rect: the encoder used to REFUSE every size where a 32x32
5335 /// block straddles BOTH true frame edges at once ("straddles the true
5336 /// frame edge in a way that needs a rectangular (HORZ/VERT) transform
5337 /// this encoder does not code yet"). That refusal was a misreading of
5338 /// spec 5.11.4: a block whose `hasRows` and `hasCols` are BOTH false
5339 /// reads no partition symbol at all and is `PARTITION_SPLIT` by
5340 /// inference, down to the 8x8 leaves whose own mi origin is inside the
5341 /// frame -- exactly the leaves this writer already codes for the
5342 /// one-axis case, and no rectangular transform anywhere. The sweep walks
5343 /// the corners around the 32-multiples (each width has a 16x16 column
5344 /// whose right half is outside, each height a row whose bottom half is,
5345 /// so the bottom-right 16x16 of every size here is cut on both axes) and
5346 /// three-way compares: our decoder, the encoder's own reconstruction and
5347 /// ffmpeg, over a 4-frame GOP so the inter writer's copy of the same
5348 /// signaling is covered too. `edge_both_cut_hits` proves the decoder
5349 /// really took the inferred-split path rather than the gate passing on
5350 /// geometry that never fires it.
5351 #[test]
5352 fn a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg() {
5353 let fctx = &crate::decode::FrameCtx::for_encoder();
5354 if !have_ffmpeg() {
5355 eprintln!(
5356 "SKIP a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg: no ffmpeg"
5357 );
5358 return;
5359 }
5360 const FRAMES: usize = 4;
5361 let mut both_cut = 0usize;
5362 for &width in &[200usize, 216, 232, 248] {
5363 for &height in &[104usize, 120, 136, 152] {
5364 let pictures: Vec<_> = (0..FRAMES as i64)
5365 .map(|i| panned_test_card(width, height, i * 3))
5366 .collect();
5367 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
5368 .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
5369 // Reset per attempt, never a delta across sizes (class
5370 // counter-from-refused-stream).
5371 crate::decode::reset_edge_both_cut_hits();
5372 let decoded = decode_stream(&encoded.stream)
5373 .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
5374 both_cut += crate::decode::edge_both_cut_hits().iter().sum::<usize>();
5375 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
5376 assert_eq!(
5377 ffmpeg_frames.len(),
5378 FRAMES,
5379 "{width}x{height}: ffmpeg decoded {} of {FRAMES} frames",
5380 ffmpeg_frames.len()
5381 );
5382 assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
5383 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
5384 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
5385 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
5386 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
5387 }
5388 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
5389 let rec = &frame.reconstruction;
5390 assert_eq!(
5391 rec.y, want.y,
5392 "{width}x{height} frame {i} luma: recon vs ffmpeg"
5393 );
5394 assert_eq!(
5395 rec.u, want.u,
5396 "{width}x{height} frame {i} U: recon vs ffmpeg"
5397 );
5398 assert_eq!(
5399 rec.v, want.v,
5400 "{width}x{height} frame {i} V: recon vs ffmpeg"
5401 );
5402 }
5403 }
5404 }
5405 assert!(
5406 both_cut > 0,
5407 "no partition node in the whole sweep was coded as the both-axes-cut \
5408 inferred split -- the gate is blind to the feature it pins"
5409 );
5410 }
5411
5412 /// lane-corner: sizes whose LAST superblock is cut by the true frame
5413 /// edge on BOTH axes with more than half of each still inside -- so
5414 /// `has_cols` and `has_rows` are both true and the spec lets that
5415 /// superblock stay a whole 64x64 `PARTITION_NONE` block, which this
5416 /// encoder's roots take (`EC_AV1_B64EDGE` on the inter side, the key
5417 /// frame's own `Superblock::Whole`). The sibling luma-only test
5418 /// (`encoder.rs`'s `a_non_superblock_aligned_clip_...`) is blind to
5419 /// chroma (class `metric-blind-to-a-plane`), so this one compares all
5420 /// three planes three ways: our decoder, the encoder's own
5421 /// reconstruction, and ffmpeg.
5422 #[test]
5423 fn a_doubly_cut_superblock_root_round_trips_in_every_plane() {
5424 let fctx = &crate::decode::FrameCtx::for_encoder();
5425 if !have_ffmpeg() {
5426 eprintln!("SKIP a_doubly_cut_superblock_root_round_trips_in_every_plane: no ffmpeg");
5427 return;
5428 }
5429 const FRAMES: usize = 4;
5430 // Each size leaves MORE than half of its last superblock row (and,
5431 // but for 200x120's 8-px column, of its last column) inside, which is
5432 // what makes the root legal there at all; 248x168/232x168/248x184 are
5433 // cut on BOTH axes at once. 1920x1080 -- the user's own export shape
5434 // -- is the same case: 1080 = 16*64 + 56, a 56-px bottom straddle.
5435 for &(width, height) in &[(248usize, 168usize), (232, 168), (200, 120), (248, 184)] {
5436 let pictures: Vec<_> = (0..FRAMES as i64)
5437 .map(|i| panned_test_card(width, height, i * 3))
5438 .collect();
5439 let _ = crate::encode::take_b64_edge_hits();
5440 let _ = crate::encode::take_i64_root_hits();
5441 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
5442 .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
5443 let edges = crate::encode::take_b64_edge_hits();
5444 let [i64_whole, i64_offered, i64_edge] = crate::encode::take_i64_root_hits();
5445 eprintln!(
5446 "{width}x{height}: edge inter 64 roots {edges}, key 64 roots {i64_whole} of \
5447 {i64_offered} offered, {i64_edge} of them cut by the frame edge"
5448 );
5449 // gate-blind-to-feature: without this the three-way compare below
5450 // passes on a stream that never coded a whole root at the cut
5451 // superblock at all.
5452 assert!(
5453 i64_edge > 0,
5454 "{width}x{height}: no 64x64 root sat on a superblock the frame edge cuts"
5455 );
5456 let decoded = decode_stream(&encoded.stream)
5457 .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
5458 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
5459 assert_eq!(
5460 ffmpeg_frames.len(),
5461 FRAMES,
5462 "{width}x{height}: ffmpeg frame count"
5463 );
5464 assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
5465 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
5466 assert_eq!(
5467 got.y, want.y,
5468 "{width}x{height} frame {i} luma: ours vs ffmpeg"
5469 );
5470 assert_eq!(
5471 got.u, want.u,
5472 "{width}x{height} frame {i} U: ours vs ffmpeg"
5473 );
5474 assert_eq!(
5475 got.v, want.v,
5476 "{width}x{height} frame {i} V: ours vs ffmpeg"
5477 );
5478 }
5479 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
5480 let rec = &frame.reconstruction;
5481 assert_eq!(
5482 rec.y, want.y,
5483 "{width}x{height} frame {i} luma: recon vs ffmpeg"
5484 );
5485 assert_eq!(
5486 rec.u, want.u,
5487 "{width}x{height} frame {i} U: recon vs ffmpeg"
5488 );
5489 assert_eq!(
5490 rec.v, want.v,
5491 "{width}x{height} frame {i} V: recon vs ffmpeg"
5492 );
5493 }
5494 }
5495 }
5496
5497 /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME`
5498 /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s
5499 /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc
5500 /// attempts never could: frame 0 is a real key frame (this crate's own
5501 /// encoder, real texture), refreshing all 8 DPB slots as spec requires --
5502 /// slot 3 keeps that exact picture from here on. Frame 1 is a hand-coded
5503 /// inter frame whose lone 32x32 block is *intra* (`DC_PRED`, `skip`),
5504 /// refreshing only slot 0 with a flat 128 block -- distinguishable from
5505 /// frame 0's real texture, so slot 0 (`LAST_FRAME`) and slot 3
5506 /// (`GOLDEN_FRAME`) hold visibly different pictures once frame 2 runs.
5507 /// Frame 2 is a hand-coded inter frame naming `ref_frame_idx[3] = 3`
5508 /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose
5509 /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME`
5510 /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy
5511 /// of GOLDEN's picture, so its output must equal frame 0's own
5512 /// reconstruction exactly, and must differ from frame 1's -- proof the
5513 /// decoder actually read the golden plane, not silently substituted
5514 /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a
5515 /// deblock/MC residue that turned out to be film-grain synthesis
5516 /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN);
5517 /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing
5518 /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so
5519 /// this fixture flips back to its round-4 pixel-exact form. ffmpeg
5520 /// decodes the identical wire bytes as the foreign oracle
5521 /// (shared-oracle-blindness class): this crate's own decoder agreeing
5522 /// with itself would prove nothing.
5523 #[test]
5524 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
5525 let fctx = &crate::decode::FrameCtx::new();
5526 if !have_ffmpeg() {
5527 eprintln!(
5528 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
5529 );
5530 return;
5531 }
5532 use crate::cdf_state::Cdfs;
5533 use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of};
5534 use crate::encode::{inter_frame_headers, key_frame_headers};
5535 use crate::frame::frame_obu;
5536 use crate::msac::SymbolEncoder;
5537 use crate::mvstack::{
5538 GOLDEN_FRAME, MiGrid, find_mv_stack, single_ref_p1_ctx, single_ref_p3_ctx,
5539 single_ref_p5_ctx,
5540 };
5541 use crate::obu::temporal_delimiter;
5542
5543 let (width, height) = (32usize, 32usize);
5544 let base_q_idx = 100u8;
5545 // The whole picture is one 32x32 block: `partition_ctx`/`skip_ctx`/
5546 // `intra_inter_ctx`'s neighbour inputs are all "no neighbour yet" --
5547 // a fresh `Neighbours`' `above_side_mi`/`left_side_mi` start at `SB`
5548 // (64), so `partition_ctx_mi`'s `side_mi * 2 <= side` (32) is false
5549 // on both axes (ctx 0), and `above_skip`/`left_skip`/`above_inter`/
5550 // `left_inter`/`above_ref`/`left_ref` all start `false`/`-1`
5551 // (decode.rs `Neighbours::new`) -- computed here without
5552 // constructing the (module-private) `Neighbours` itself.
5553 const PARTITION_NONE: usize = 0;
5554 let ii_ctx = intra_inter_ctx(false, false, false, false);
5555 let sr_p1_ctx = single_ref_p1_ctx(None, None, None, None);
5556 let sr_p3_ctx = single_ref_p3_ctx(None, None, None, None);
5557 let sr_p5_ctx = single_ref_p5_ctx(None, None, None, None);
5558
5559 for run in 0..4 {
5560 let picture = test_card(width, height);
5561 let key = encode_key_frame_with_ctx(&picture, base_q_idx, 0.5, fctx).unwrap();
5562 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
5563
5564 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
5565 // 128 block (no neighbours to predict `DC_PRED` from).
5566 let (_, mut header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
5567 // These two tiles are hand-coded from a FRESH `Cdfs`, so the
5568 // frames must not carry CDF state the way the encoder's own inter
5569 // frames now do (spec 7.20): with the bit set, what each frame
5570 // stores is what it started from -- the defaults -- which is
5571 // exactly what the next hand-coded tile assumes.
5572 header1.disable_frame_end_update_cdf = true;
5573 let tile1 = {
5574 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
5575 let mut enc = SymbolEncoder::new();
5576 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
5577 enc.symbol(1, &mut cdfs.skip[0]); // skip
5578 enc.symbol(0, &mut cdfs.intra_inter[ii_ctx]); // is_inter = false
5579 enc.symbol(0, &mut cdfs.y_mode[3]); // DC_PRED, size group 3 (32x32)
5580 enc.symbol(0, &mut cdfs.uv_mode_cfl[0]); // DC_PRED
5581 enc.finish()
5582 };
5583 let mut stream = key.stream.clone();
5584 stream.extend(temporal_delimiter());
5585 stream.extend(frame_obu(&seq, &header1, &tile1).unwrap());
5586
5587 // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME,
5588 // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0).
5589 let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap();
5590 header2.disable_frame_end_update_cdf = true;
5591 header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1
5592 let tile2 = {
5593 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
5594 let mut enc = SymbolEncoder::new();
5595 let grid = MiGrid::new(8, 8);
5596 let stack = find_mv_stack(&grid, 0, 0, 8, 8, GOLDEN_FRAME, 8, 8);
5597 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
5598 enc.symbol(1, &mut cdfs.skip[0]); // skip
5599 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter = true
5600 enc.symbol(0, &mut cdfs.single_ref[sr_p1_ctx][0]); // p1: LAST/LAST2/LAST3/GOLDEN group
5601 enc.symbol(1, &mut cdfs.single_ref[sr_p3_ctx][2]); // p3: GOLDEN/LAST3 sub-group
5602 enc.symbol(1, &mut cdfs.single_ref[sr_p5_ctx][4]); // p5: GOLDEN_FRAME
5603 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new -> not NEWMV
5604 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero -> not GLOBALMV
5605 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // nearest -> NEARESTMV, (0, 0)
5606 enc.finish()
5607 };
5608 stream.extend(temporal_delimiter());
5609 stream.extend(frame_obu(&seq, &header2, &tile2).unwrap());
5610
5611 let before = non_last_ref_hits();
5612 let decoded = decode_stream(&stream).unwrap();
5613 assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures");
5614 assert!(
5615 non_last_ref_hits() > before,
5616 "run {run}: GOLDEN_FRAME never fired"
5617 );
5618
5619 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3);
5620 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
5621 assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg");
5622 assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg");
5623 assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg");
5624 }
5625 assert_eq!(
5626 decoded[0].y, key.reconstruction.y,
5627 "run {run}: frame 0 vs the encoder's own reconstruction"
5628 );
5629 assert_eq!(
5630 decoded[2].y, key.reconstruction.y,
5631 "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names"
5632 );
5633 assert_ne!(
5634 decoded[2].y, decoded[1].y,
5635 "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \
5636 distinguishable -- the gate proves nothing"
5637 );
5638 }
5639 }
5640
5641 /// Builds a `gradients` lavfi source string with colours derived from
5642 /// `seed`, not left to the filter's own default.
5643 ///
5644 /// Measured (lane-fixdet r1): ffmpeg's `gradients` source IGNORES its
5645 /// `seed=` parameter for colour selection -- five encodes of an
5646 /// identical command line (same `seed=`, same everything) produced five
5647 /// different fixtures, because the unset `c0..c9` stops are randomized
5648 /// from something other than that seed. Every one of this file's ~20
5649 /// gate fixtures built a `gradients` source this way, so none of them
5650 /// had a reproducible input: a pin captured from one run could not be
5651 /// regenerated, and "attempt N failed" was as likely to be a different
5652 /// fixture as a different decode outcome.
5653 ///
5654 /// Freezing the colours outright (as the earliest four gates below do,
5655 /// hand-picking `c0=red:c1=blue:c2=green`) fixes reproducibility but
5656 /// throws away the per-attempt content variety the sweep gates need to
5657 /// make features (OBMC, warp, wedge, ...) fire at all -- this repo's own
5658 /// `sampler-decorrelated-gate` class. So: derive `c0..c3` deterministically
5659 /// FROM the seed with a plain integer hash, and keep passing `seed=`
5660 /// itself too, so a future ffmpeg that actually honours it only adds
5661 /// more variety, never removes the determinism this buys.
5662 fn gradients_source(seed: u32, width: usize, height: usize, tail: &str) -> String {
5663 fn hash_color(seed: u32, salt: u32) -> String {
5664 let h = seed
5665 .wrapping_mul(2_654_435_761)
5666 .wrapping_add(salt.wrapping_mul(0x9E37_79B9))
5667 ^ (seed.rotate_left(13));
5668 format!("0x{:06x}", h & 0x00ff_ffff)
5669 }
5670 let (c0, c1, c2, c3) = (
5671 hash_color(seed, 0),
5672 hash_color(seed, 1),
5673 hash_color(seed, 2),
5674 hash_color(seed, 3),
5675 );
5676 format!(
5677 "gradients=size={width}x{height}:c0={c0}:c1={c1}:c2={c2}:c3={c3}:seed={seed}:{tail}"
5678 )
5679 }
5680
5681 /// The determinism guard: same seed twice must byte-match ffmpeg's own
5682 /// output; different seeds must not. Regresses this fix if it ever
5683 /// breaks.
5684 #[test]
5685 fn gradients_source_is_reproducible_per_seed() {
5686 if !have_ffmpeg() {
5687 eprintln!("SKIP gradients_source_is_reproducible_per_seed: no ffmpeg");
5688 return;
5689 }
5690 fn render_hash(lavfi: &str) -> Vec<u8> {
5691 let out = Command::new("ffmpeg")
5692 .args([
5693 "-v",
5694 "error",
5695 "-f",
5696 "lavfi",
5697 "-i",
5698 lavfi,
5699 "-frames:v",
5700 "1",
5701 "-f",
5702 "rawvideo",
5703 "-",
5704 ])
5705 .stdin(Stdio::null())
5706 .stdout(Stdio::piped())
5707 .stderr(Stdio::piped())
5708 .output()
5709 .expect("ffmpeg failed to run");
5710 assert!(out.status.success(), "ffmpeg refused {lavfi}");
5711 out.stdout
5712 }
5713 let a1 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
5714 let a2 = render_hash(&gradients_source(43, 64, 64, "duration=0.04:rate=25"));
5715 let a3 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
5716 assert_eq!(a1, a3, "same seed must reproduce byte-identical output");
5717 assert_ne!(a1, a2, "different seeds must not collide");
5718 }
5719
5720 /// Encodes a real libaom-av1 stream (via ffmpeg's own encoder, not this
5721 /// crate's) with the same reduced-partition flags lane-av1adst's r6
5722 /// probe found still select `ADST_ADST`/`ADST_DCT`/`DCT_ADST` on
5723 /// gradient content (TX_SET_INTRA_2), and decodes it with
5724 /// [`decode_stream`] -- lifting the round-2 refusal is only real if it
5725 /// gets past an encoder this crate never wrote a byte of.
5726 fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {
5727 libaom_encode_with(lavfi, width, height, crf, &[])
5728 }
5729
5730 /// As [`libaom_encode`], with extra encoder args appended -- used to pin
5731 /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8`
5732 /// RD search is not otherwise stable run-to-run on this box, and lavfi
5733 /// `gradients` needs its own `seed=` for the same reason) and to gate
5734 /// individual feature flags (`-enable-cdef 0`) a given fixture needs off.
5735 fn libaom_encode_with(
5736 lavfi: &str,
5737 width: usize,
5738 height: usize,
5739 crf: u32,
5740 extra: &[&str],
5741 ) -> Option<Vec<u8>> {
5742 let mut args = vec![
5743 "-v",
5744 "error",
5745 "-f",
5746 "lavfi",
5747 "-i",
5748 lavfi,
5749 "-frames:v",
5750 "1",
5751 "-pix_fmt",
5752 "yuv420p",
5753 "-c:v",
5754 "libaom-av1",
5755 ];
5756 let crf_str = crf.to_string();
5757 args.extend(["-crf", &crf_str]);
5758 args.extend([
5759 "-cpu-used",
5760 "8",
5761 "-enable-rect-partitions",
5762 "0",
5763 "-enable-ab-partitions",
5764 "0",
5765 "-enable-1to4-partitions",
5766 "0",
5767 "-enable-angle-delta",
5768 "0",
5769 "-enable-cfl-intra",
5770 "0",
5771 ]);
5772 args.extend(extra.iter().copied());
5773 args.extend(["-f", "obu", "-"]);
5774 let out = Command::new("ffmpeg")
5775 .args(&args)
5776 .stdin(Stdio::null())
5777 .stdout(Stdio::piped())
5778 .stderr(Stdio::piped())
5779 .output()
5780 .expect("ffmpeg failed to run");
5781 if !out.status.success() {
5782 eprintln!(
5783 "ffmpeg refused to encode {lavfi} at {width}x{height}: {}",
5784 String::from_utf8_lossy(&out.stderr)
5785 );
5786 return None;
5787 }
5788 Some(out.stdout)
5789 }
5790
5791 /// The end-to-end gate: two real libaom-av1 configs, decoded with
5792 /// [`decode_stream`] and checked against ffmpeg's own decode of the same
5793 /// bytes. Not every config this encoder writes decodes yet (partitions
5794 /// below 16x16, AB partitions, CfL and others remain round-2 gaps per the
5795 /// r6 catalogue) -- both configs here pick `cpu-used 8` plus the
5796 /// partition/angle-delta/CfL flags r6 found narrow the encoder onto this
5797 /// decoder's supported syntax, while still landing on non-`DCT_DCT` tx
5798 /// types on gradient content.
5799 #[test]
5800 fn a_real_libaom_stream_with_adst_decodes_end_to_end() {
5801 if !have_ffmpeg() {
5802 eprintln!("SKIP a_real_libaom_stream_with_adst_decodes_end_to_end: no ffmpeg");
5803 return;
5804 }
5805 let configs: [(String, usize, usize, u32); 2] = [
5806 ("testsrc2=size=64x64:rate=1".to_string(), 64, 64, 15),
5807 (gradients_source(42, 64, 64, "rate=1"), 64, 64, 15),
5808 ];
5809 let mut verdicts = Vec::new();
5810 for (lavfi, width, height, crf) in configs {
5811 let lavfi = lavfi.as_str();
5812 let Some(stream) = libaom_encode(lavfi, width, height, crf) else {
5813 verdicts.push(format!("{lavfi}: ffmpeg itself refused to encode"));
5814 continue;
5815 };
5816 match decode_stream(&stream) {
5817 Ok(frames) => {
5818 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
5819 let matches = frames[0].y == ffmpeg_frames[0].y
5820 && frames[0].u == ffmpeg_frames[0].u
5821 && frames[0].v == ffmpeg_frames[0].v;
5822 verdicts.push(format!(
5823 "{lavfi}: decoded, {} ffmpeg's own decode",
5824 if matches { "MATCHES" } else { "MISMATCHES" }
5825 ));
5826 // Not a hard `assert!`: libaom's own mode decisions at
5827 // `cpu-used 8` are not observed stable run-to-run on this
5828 // box (multi-threaded RD search), so a run that happens
5829 // to land on a still-unsupported syntax element (e.g. a
5830 // partition below 16x16, a separate round-2 gap) can
5831 // decode without erroring yet disagree -- that failure
5832 // mode belongs to those other gaps, not to this round's
5833 // ADST wiring, and the eprintln below reports it either
5834 // way rather than hiding it.
5835 }
5836 Err(e) => {
5837 verdicts.push(format!("{lavfi}: still refuses ({e})"));
5838 }
5839 }
5840 }
5841 eprintln!("libaom ADST end-to-end verdicts:");
5842 for v in &verdicts {
5843 eprintln!(" {v}");
5844 }
5845 }
5846
5847 /// lane-dgolomb: the `force_integer_mv` gate. libaom turns screen-content
5848 /// tools on for DARK, SMOOTH content -- its `av1_set_screen_content_options`
5849 /// counts 16x16 blocks with 2..=4 distinct luma values -- and then sets
5850 /// `force_integer_mv` on any inter frame whose source is pixel-identical to
5851 /// the previously coded source (`av1_is_integer_mv`: `cs_rate >= 0.8` and
5852 /// `C == T`, every collocated 8x8 block matching, is the only path that
5853 /// returns 1). Both hold on his real AV1 films, and this decoder used to
5854 /// drop `lower_mv_precision`'s `is_integer` half as unreachable, so every
5855 /// temporal MV candidate on such a frame came out at eighth-pel: the frame
5856 /// decoded without any error into a whole-frame prediction mismatch, and
5857 /// the desync surfaced blocks later as "a Golomb tail longer than this
5858 /// decoder reads".
5859 ///
5860 /// The source is SYNTHETIC (no film sample lives in `fixtures`): the
5861 /// near-flat dark pattern libaom's own screen-content detector counts as
5862 /// screen content, at the film-B crop size 1920x1024, SCROLLING globally
5863 /// 5 px per frame and frozen on frame 8 -- an exact duplicate of frame 7
5864 /// (the `C == T` trigger) whose twin is not among its own references, so
5865 /// its blocks still code real motion under `force_integer_mv`.
5866 ///
5867 /// lane-dpm1 made this gate SENSITIVE: with the `force_integer_mv` branch
5868 /// of [`crate::motion_field::lower_mv_precision`] stubbed out (`if false
5869 /// &&`) the stream decodes WRONG -- frame 8, luma sample 25695, 20 against
5870 /// ffmpeg's 19 -- where the previous patch-in-a-static-background recipe
5871 /// (and two others tried) still decoded byte-exact: there the used mv-stack
5872 /// slots came from agreeing spatial neighbours and the rounded temporal
5873 /// entries never won one. The gate asserts both halves: at least one INTER
5874 /// frame really carries `force_integer_mv` (class `gate-blind-to-feature`),
5875 /// and every shown frame decodes sample-exact against ffmpeg's own decode.
5876 #[test]
5877 fn a_libaom_force_integer_mv_stream_decodes_exact() {
5878 const NAME: &str = "a_libaom_force_integer_mv_stream_decodes_exact";
5879 if !have_ffmpeg() {
5880 eprintln!("SKIP {NAME}: no ffmpeg");
5881 return;
5882 }
5883 let (w, h, frames) = (1920usize, 1024usize, 16usize);
5884 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
5885 let mut off = 0usize;
5886 for f in 0..frames {
5887 // lane-dpm1: the WHOLE picture scrolls 5 px per frame and freezes
5888 // on frame 8, so (a) every block of the frozen frame -- including
5889 // mi(0,0), which has no spatial neighbour at all -- still codes
5890 // real motion against the references that are not its twin, and
5891 // (b) 40 eighth-pels projected over the pyramid's distances lands
5892 // on non-multiples of 8 (40/2 = 20 -> 16). A patch moving inside a
5893 // static background was NOT sensitive: there the used stack slots
5894 // came from spatial neighbours that agreed, and the rounded
5895 // temporal entries never won one.
5896 if f > 0 && f != 8 {
5897 off = (off + 5) % h;
5898 }
5899 let mut y = vec![0u8; w * h];
5900 for row in 0..h {
5901 let src = (row + off) % h;
5902 for col in 0..w {
5903 // 2..=4 distinct values per 16x16 block, all dark: the
5904 // screen-content detector's own counting rule.
5905 y[row * w + col] =
5906 16 + ((col / 32 + src / 32) % 5) as u8 + ((col / 4 + src / 4) % 3) as u8;
5907 }
5908 }
5909 raw.extend_from_slice(&y);
5910 raw.extend(std::iter::repeat_n(128u8, w * h / 2));
5911 }
5912 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
5913 let src = std::env::temp_dir().join(format!("ec-av1-intmv-{}.yuv", std::process::id()));
5914 std::fs::write(&src, &raw).expect("raw source");
5915 let out = Command::new("ffmpeg")
5916 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
5917 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
5918 .arg(&src)
5919 .args(["-an", "-threads", "1", "-g", "16", "-c:v", "libaom-av1"])
5920 .args([
5921 "-cpu-used",
5922 "6",
5923 "-b:v",
5924 "0",
5925 "-crf",
5926 "35",
5927 "-f",
5928 "obu",
5929 "-",
5930 ])
5931 .stdin(Stdio::null())
5932 .stdout(Stdio::piped())
5933 .stderr(Stdio::piped())
5934 .output()
5935 .expect("ffmpeg failed to run");
5936 let _ = std::fs::remove_file(&src);
5937 if !out.status.success() {
5938 eprintln!(
5939 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
5940 String::from_utf8_lossy(&out.stderr)
5941 );
5942 return;
5943 }
5944 let stream = out.stdout;
5945
5946 // Half of the gate: the stream must actually carry the feature.
5947 let mut parser = Av1Parser::new();
5948 let (mut pos, mut int_mv_inter) = (0usize, 0usize);
5949 while pos < stream.len() {
5950 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
5951 pos += obu.total_size.max(1);
5952 let header = match &obu.kind {
5953 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
5954 _ => continue,
5955 };
5956 if header.force_integer_mv && !header.frame_is_intra && header.use_ref_frame_mvs {
5957 int_mv_inter += 1;
5958 }
5959 }
5960 assert!(
5961 int_mv_inter > 0,
5962 "{NAME} went blind: libaom coded no inter frame with force_integer_mv"
5963 );
5964
5965 let ours = decode_stream(&stream).expect("libaom screen-content stream decodes");
5966 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
5967 assert_eq!(ours.len(), frames, "shown frame count");
5968 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
5969 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
5970 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
5971 assert!(
5972 first.is_none(),
5973 "frame {i} plane {plane} differs from ffmpeg at sample {} \
5974 ({int_mv_inter} force_integer_mv inter frames in this stream)",
5975 first.unwrap()
5976 );
5977 }
5978 }
5979 }
5980
5981 /// lane-dpm1: the 128x128-INTRA-inside-an-INTER-frame chroma context gate.
5982 /// A 128x128 block codes its chroma as four TX_32X32 units, one per 64x64
5983 /// mu chunk, and libaom stamps the coefficient context PER UNIT. The two
5984 /// INTER mu-chunk sites set `mu_chroma` so the block tail re-stamps the
5985 /// four units in mu order; the INTRA-in-inter site did not, so the
5986 /// whole-block record left every unit carrying the TOP-LEFT unit's level.
5987 /// The next block then read its `txb_skip` off ctx 11 where libaom reads
5988 /// ctx 10 (class `override-slot-on-one-arm`) -- one symbol on the wrong
5989 /// CDF row, tile desynced, and because the loop-restoration coefficients
5990 /// live in the same tile data the damage showed up as a +-1 luma sample at
5991 /// the TOP of the frame (measured: frame 1, luma sample 66, ours 146 /
5992 /// ffmpeg 145, with 1.7M samples wrong behind it).
5993 ///
5994 /// Source: the repository's own 2160p colour-bar fixture at the native
5995 /// gate's crop (1920x1024 out of the middle), 12 frames, libaom
5996 /// `-cpu-used 6 -crf 45 -g 12` -- the first reference point of
5997 /// `bd_rate_screen_native`'s "bars 2160p" row, which is where the assertion
5998 /// caught it. The gate asserts the tool fired (class
5999 /// `gate-blind-to-feature`) and that every shown frame decodes sample-exact
6000 /// against ffmpeg's own decode.
6001 #[test]
6002 fn a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact() {
6003 const NAME: &str = "a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact";
6004 if !have_ffmpeg() {
6005 eprintln!("SKIP {NAME}: no ffmpeg");
6006 return;
6007 }
6008 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6009 .join("../../fixtures/video/h264-2160p-23.976-8bit.mp4");
6010 if !clip.exists() {
6011 eprintln!("SKIP {NAME}: the 2160p bars fixture is missing");
6012 return;
6013 }
6014 let (w, h, frames) = (1920usize, 1024usize, 12usize);
6015 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
6016 let src = std::env::temp_dir().join(format!("ec-av1-i128-{}.yuv", std::process::id()));
6017 let load = Command::new("ffmpeg")
6018 .args(["-v", "error", "-y", "-i"])
6019 .arg(&clip)
6020 .args([
6021 "-frames:v",
6022 &frames.to_string(),
6023 "-vf",
6024 "crop=1920:1024:960:568",
6025 ])
6026 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
6027 .arg(&src)
6028 .output()
6029 .expect("ffmpeg failed to run");
6030 assert!(
6031 load.status.success(),
6032 "{NAME}: {}",
6033 String::from_utf8_lossy(&load.stderr)
6034 );
6035 let out = Command::new("ffmpeg")
6036 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
6037 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
6038 .arg(&src)
6039 .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"])
6040 .args([
6041 "-cpu-used",
6042 "6",
6043 "-b:v",
6044 "0",
6045 "-crf",
6046 "45",
6047 "-f",
6048 "obu",
6049 "-",
6050 ])
6051 .stdin(Stdio::null())
6052 .stdout(Stdio::piped())
6053 .stderr(Stdio::piped())
6054 .output()
6055 .expect("ffmpeg failed to run");
6056 let _ = std::fs::remove_file(&src);
6057 if !out.status.success() {
6058 eprintln!(
6059 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
6060 String::from_utf8_lossy(&out.stderr)
6061 );
6062 return;
6063 }
6064 let stream = out.stdout;
6065 let before = crate::decode::intra_128_in_inter_hits();
6066 let ours = decode_stream(&stream).expect("libaom bars stream decodes");
6067 assert!(
6068 crate::decode::intra_128_in_inter_hits() > before,
6069 "{NAME} went blind: no 128-rooted intra block inside an inter frame"
6070 );
6071 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
6072 assert_eq!(ours.len(), frames, "shown frame count");
6073 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
6074 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
6075 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
6076 assert!(
6077 first.is_none(),
6078 "frame {i} plane {plane} differs from ffmpeg at sample {}",
6079 first.unwrap()
6080 );
6081 }
6082 }
6083 }
6084
6085 /// lane-lossless: the refusal became an implementation, so its gate became
6086 /// a DECODE-EXACT one (class `refusal-lifted-without-a-gate`). libaom at
6087 /// `-crf 0` codes `base_q_idx == 0` -- the same lossless frame his
6088 /// screen-capture row gets at `-crf 5` -- where every plane is TX_4X4 with
6089 /// the Walsh-Hadamard transform, no `tx_type` symbol is coded
6090 /// (`read_tx_type`, `decodetxb.c`: "No need to read transform type for
6091 /// lossless mode(qindex==0)") and `is_cfl_allowed` (`blockd.h`) narrows to
6092 /// a BLOCK_4X4 chroma plane block. The gate asserts the stream really is
6093 /// lossless (class `gate-blind-to-feature`), that every KEY frame decodes
6094 /// sample-exact against ffmpeg, and that the still-unimplemented lossless
6095 /// INTER frame is refused BY NAME rather than decoded wrong.
6096 #[test]
6097 fn a_lossless_libaom_key_frame_decodes_sample_exact() {
6098 const NAME: &str = "a_lossless_libaom_key_frame_decodes_sample_exact";
6099 if !have_ffmpeg() {
6100 eprintln!("SKIP {NAME}: no ffmpeg");
6101 return;
6102 }
6103 let (w, h, frames) = (256usize, 128usize, 2usize);
6104 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
6105 for f in 0..frames {
6106 for row in 0..h {
6107 for col in 0..w {
6108 raw.push(((col * 7 + row * 13 + f * 31) % 251) as u8);
6109 }
6110 }
6111 // lane-lossless2: TEXTURED chroma. A flat chroma plane codes one
6112 // `txb_skip` symbol per 4x4 unit with every context at 0, which
6113 // is blind to both the unit ORDER and the per-unit contexts
6114 // (class `gate-blind-to-feature`).
6115 for row in 0..h / 2 {
6116 for col in 0..w / 2 {
6117 raw.push((((col + f) * 11 + row * 5) % 251) as u8);
6118 }
6119 }
6120 for row in 0..h / 2 {
6121 for col in 0..w / 2 {
6122 raw.push(((col * 3 + (row + f) * 17) % 251) as u8);
6123 }
6124 }
6125 }
6126 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
6127 let src = std::env::temp_dir().join(format!("ec-av1-lossless-{}.yuv", std::process::id()));
6128 std::fs::write(&src, &raw).expect("raw source");
6129 let encode = |gop: &str| {
6130 let out = Command::new("ffmpeg")
6131 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
6132 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
6133 .arg(&src)
6134 .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
6135 .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"])
6136 .stdin(Stdio::null())
6137 .stdout(Stdio::piped())
6138 .stderr(Stdio::piped())
6139 .output()
6140 .expect("ffmpeg failed to run");
6141 out
6142 };
6143 let out = encode("1");
6144 let _ = std::fs::remove_file(&src);
6145 if !out.status.success() {
6146 eprintln!(
6147 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
6148 String::from_utf8_lossy(&out.stderr)
6149 );
6150 return;
6151 }
6152 let stream = out.stdout;
6153 // Half of the gate: the stream must really carry a lossless frame
6154 // (class `gate-blind-to-feature`).
6155 let mut parser = Av1Parser::new();
6156 let (mut pos, mut lossless) = (0usize, 0usize);
6157 while pos < stream.len() {
6158 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
6159 pos += obu.total_size.max(1);
6160 let header = match &obu.kind {
6161 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
6162 _ => continue,
6163 };
6164 if header.lossless.iter().all(|&l| l) {
6165 lossless += 1;
6166 }
6167 }
6168 assert_eq!(
6169 lossless, frames,
6170 "{NAME} went blind: libaom coded no lossless key frame at -crf 0"
6171 );
6172 let ours = decode_stream(&stream).expect("a lossless key-frame stream decodes");
6173 let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
6174 assert_eq!(ours.len(), frames, "{NAME}: frame count");
6175 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
6176 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
6177 .iter()
6178 .enumerate()
6179 {
6180 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
6181 assert_eq!(
6182 bad, 0,
6183 "{NAME}: frame {i} plane {plane}: {bad} samples differ"
6184 );
6185 }
6186 }
6187 }
6188
6189 /// lane-lossless2: the refusal `a_lossless_inter_frame_is_refused_by_name`
6190 /// pinned became an implementation, so its gate became a DECODE-EXACT one
6191 /// (class `refusal-lifted-without-a-gate`). A lossless INTER frame codes
6192 /// its chroma plane as 4x4 transform units, plane-major inside each 64x64
6193 /// mu chunk (libaom `read_tx_size` returns TX_4X4 for every plane under
6194 /// `xd->lossless[..]`, and `decode_token_recon_block` walks
6195 /// `for (plane..) for (blk_row..) for (blk_col..)`), which is what
6196 /// `decode::read_inter_chroma_lossless` reads. The source carries TEXTURED
6197 /// CHROMA and real motion on purpose: a flat-chroma source codes one
6198 /// `txb_skip` symbol per unit and is blind to both the unit order and the
6199 /// per-unit contexts (class `gate-blind-to-feature`).
6200 #[test]
6201 fn a_lossless_libaom_inter_frame_decodes_sample_exact() {
6202 const NAME: &str = "a_lossless_libaom_inter_frame_decodes_sample_exact";
6203 if !have_ffmpeg() {
6204 eprintln!("SKIP {NAME}: no ffmpeg");
6205 return;
6206 }
6207 // (w, h, frames, gop, bit depth, 128-superblock, screen content)
6208 // lane-lossless2: the SCREEN rows carry palette blocks, which is what
6209 // caught the whole-block palette prediction being handed to a 4x4
6210 // chroma unit.
6211 // lane-lossless3: the last row is a screen source with INTER frames --
6212 // the row that caught both of this lane's defects (a skip 8x8 leaf
6213 // restoring the previous block's luma level band over the zeros
6214 // `av1_reset_entropy_context` writes, and a rect sub-8x8 INTRA leaf
6215 // reading one TX_4X8 unit where a lossless frame codes two TX_4X4).
6216 let cases: [(usize, usize, usize, &str, u32, bool, bool); 7] = [
6217 (256, 128, 8, "4", 8, false, false),
6218 (192, 96, 6, "3", 10, false, false),
6219 (320, 192, 6, "3", 8, false, false),
6220 (256, 256, 4, "2", 8, true, false),
6221 (320, 192, 2, "1", 8, false, true),
6222 (640, 384, 2, "1", 8, false, true),
6223 (640, 384, 6, "3", 8, false, true),
6224 ];
6225 for &(w, h, frames, gop, depth, sb128, screen) in &cases {
6226 let tag = format!(
6227 "{w}x{h} {depth}-bit gop {gop}{}{}",
6228 if sb128 { " sb128" } else { "" },
6229 if screen { " screen" } else { "" }
6230 );
6231 let mut raw: Vec<u8> = Vec::new();
6232 let put = |v: u32, raw: &mut Vec<u8>| {
6233 if depth == 10 {
6234 raw.extend_from_slice(&((v * 4) as u16).to_le_bytes());
6235 } else {
6236 raw.push(v as u8);
6237 }
6238 };
6239 // A screen source is a few flat colours in 16x16 tiles plus
6240 // 1-px text-like rows -- what makes libaom code palette blocks.
6241 const PAL: [u32; 8] = [16, 60, 110, 145, 180, 210, 235, 128];
6242 for f in 0..frames {
6243 for row in 0..h {
6244 for col in 0..w {
6245 let v = if screen {
6246 if row % 7 == 0 && col % 3 == 0 {
6247 if (col / 3 + row + f) % 2 == 1 {
6248 16
6249 } else {
6250 235
6251 }
6252 } else {
6253 PAL[((col + 4 * f) / 16 + row / 16) % PAL.len()]
6254 }
6255 } else {
6256 (((col + 2 * f) * 7 + row * 13) % 251) as u32
6257 };
6258 put(v, &mut raw);
6259 }
6260 }
6261 for plane in 0..2usize {
6262 for row in 0..h / 2 {
6263 for col in 0..w / 2 {
6264 let v = if screen {
6265 PAL[((col + 2 * f) / 8 + row / 8 + plane) % PAL.len()]
6266 } else if plane == 0 {
6267 (((col + f) * 11 + row * 5) % 251) as u32
6268 } else {
6269 ((col * 3 + (row + f) * 17) % 251) as u32
6270 };
6271 put(v, &mut raw);
6272 }
6273 }
6274 }
6275 }
6276 let pix = if depth == 10 {
6277 "yuv420p10le"
6278 } else {
6279 "yuv420p"
6280 };
6281 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
6282 let src = std::env::temp_dir().join(format!(
6283 "ec-av1-lossless2-{}-{w}x{h}-{depth}.yuv",
6284 std::process::id()
6285 ));
6286 std::fs::write(&src, &raw).expect("raw source");
6287 let mut cmd = Command::new("ffmpeg");
6288 cmd.args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", pix])
6289 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
6290 .arg(&src)
6291 .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
6292 .args(["-pix_fmt", pix, "-cpu-used", "6", "-b:v", "0", "-crf", "0"]);
6293 if sb128 {
6294 cmd.args(["-aom-params", "sb-size=128"]);
6295 }
6296 if screen {
6297 cmd.args(["-aom-params", "tune-content=screen"]);
6298 }
6299 let out = cmd
6300 .args(["-f", "obu", "-"])
6301 .stdin(Stdio::null())
6302 .stdout(Stdio::piped())
6303 .stderr(Stdio::piped())
6304 .output()
6305 .expect("ffmpeg failed to run");
6306 let _ = std::fs::remove_file(&src);
6307 if !out.status.success() {
6308 eprintln!(
6309 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
6310 String::from_utf8_lossy(&out.stderr)
6311 );
6312 return;
6313 }
6314 let stream = out.stdout;
6315 // The stream must really be lossless AND really carry inter frames
6316 // (class `gate-blind-to-feature`).
6317 let mut parser = Av1Parser::new();
6318 let (mut pos, mut lossless, mut inters) = (0usize, 0usize, 0usize);
6319 while pos < stream.len() {
6320 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
6321 pos += obu.total_size.max(1);
6322 let header = match &obu.kind {
6323 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
6324 _ => continue,
6325 };
6326 if header.lossless.iter().all(|&l| l) {
6327 lossless += 1;
6328 }
6329 if header.frame_type == FrameType::Inter {
6330 inters += 1;
6331 }
6332 }
6333 assert!(
6334 lossless >= frames,
6335 "{NAME} [{tag}] went blind: {lossless} lossless frames"
6336 );
6337 assert!(
6338 screen || inters > 0,
6339 "{NAME} [{tag}] went blind: no inter frame at gop {gop}"
6340 );
6341 let ours = decode_stream(&stream)
6342 .unwrap_or_else(|e| panic!("{NAME} [{tag}]: a lossless inter stream decodes: {e}"));
6343 let refs = if depth == 10 {
6344 ffmpeg_decode_sequence_10bit(&stream, w, h, frames)
6345 } else {
6346 ffmpeg_decode_sequence(&stream, w, h, frames)
6347 };
6348 assert_eq!(ours.len(), frames, "{NAME} [{tag}]: frame count");
6349 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
6350 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
6351 .iter()
6352 .enumerate()
6353 {
6354 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
6355 assert_eq!(
6356 bad, 0,
6357 "{NAME} [{tag}]: frame {i} plane {plane}: {bad} samples differ"
6358 );
6359 }
6360 }
6361 }
6362 }
6363
6364 /// lane-av1-llband: the pinned 4:4:4 LOSSLESS key frame
6365 /// (`fixtures/ll444-lossless-key.obu`, the `ll444` recipe's frame 0 --
6366 /// `testsrc2 128x96` yuv444p cut to its key frame) decodes sample-exact,
6367 /// and its HORZ/VERT strips really walked their chroma as 4x4 units at
6368 /// subsampling 0/0 (one unit per mi cell). That unit walk used the 4:2:0
6369 /// span (8 luma px per 4x4 chroma unit) unconditionally, so every unit
6370 /// past the first column/row read its `txb_skip` context two mi cells
6371 /// over and stamped a 2-cell smear -- the 178-byte key-frame miss, first
6372 /// divergence at the 16x8 leaf mi (16,24)'s U bc=2 unit (oracle
6373 /// `txb_skip` base 0 off `above[26]`, ours base 1 off the polluted
6374 /// `above[29]`). The counter assertion is the non-vacuity half (class
6375 /// `gate-blind-to-feature`): a stream that never reaches the 4:4:4 unit
6376 /// walk must not pass.
6377 #[test]
6378 fn a_real_aomenc_lossless_444_key_frame_decodes_sample_exact() {
6379 const NAME: &str = "a_real_aomenc_lossless_444_key_frame_decodes_sample_exact";
6380 if !have_ffmpeg() {
6381 eprintln!("SKIP {NAME}: no ffmpeg");
6382 return;
6383 }
6384 let Ok(stream) = std::fs::read(pin_dir().join("ll444-lossless-key.obu")) else {
6385 eprintln!(
6386 "SKIP {NAME}: no pinned bytes at {} -- regenerate with \
6387 `testsrc2 128x96` yuv444p 6 frames, aomenc --profile=1 --lossless=1 \
6388 --enable-palette=0 --enable-intrabc=0, cut to the key frame's OBUs",
6389 pin_dir().join("ll444-lossless-key.obu").display()
6390 );
6391 return;
6392 };
6393 // Blindness guard: the pinned fixture must really be a lossless frame.
6394 let mut parser = Av1Parser::new();
6395 let mut pos = 0usize;
6396 let mut lossless = false;
6397 while pos < stream.len() {
6398 let obu = parser.parse_obu(&stream[pos..]).expect("aomenc OBU parses");
6399 pos += obu.total_size.max(1);
6400 if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = obu.kind {
6401 lossless = h.lossless.iter().all(|&l| l);
6402 }
6403 }
6404 assert!(
6405 lossless,
6406 "{NAME} went blind: the pinned frame is not lossless"
6407 );
6408 let before = crate::decode::rect_split_lossless_chroma444_hits();
6409 let ours = decode_stream(&stream).expect("a 444 lossless key-frame stream decodes");
6410 assert_eq!(ours.len(), 1, "{NAME}: frame count");
6411 assert!(
6412 crate::decode::rect_split_lossless_chroma444_hits() > before,
6413 "{NAME} went blind: no lossless HORZ/VERT strip walked its chroma \
6414 as 4x4 units at subsampling 0/0"
6415 );
6416 let refs = Command::new("ffmpeg")
6417 .args([
6418 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv444p", "-",
6419 ])
6420 .stdin(Stdio::piped())
6421 .stdout(Stdio::piped())
6422 .stderr(Stdio::piped())
6423 .spawn()
6424 .and_then(|mut child| {
6425 use std::io::Write as _;
6426 child.stdin.as_mut().expect("stdin").write_all(&stream)?;
6427 child.wait_with_output()
6428 })
6429 .expect("ffmpeg 444 decode failed");
6430 assert!(
6431 refs.status.success(),
6432 "{}",
6433 String::from_utf8_lossy(&refs.stderr)
6434 );
6435 let frame = &ours[0];
6436 let planes = [
6437 (&frame.y, frame.width * frame.height),
6438 (&frame.u, frame.width * frame.height),
6439 (&frame.v, frame.width * frame.height),
6440 ];
6441 let mut off = 0usize;
6442 for (plane, (g, len)) in planes.iter().enumerate() {
6443 let raw = &refs.stdout[off..off + len];
6444 let bad = g
6445 .iter()
6446 .zip(raw.iter())
6447 .filter(|&(&a, &b)| a != u16::from(b))
6448 .count();
6449 assert_eq!(bad, 0, "{NAME}: plane {plane}: {bad} samples differ");
6450 off += len;
6451 }
6452 }
6453
6454 /// As [`ffmpeg_decode_sequence`], for a 4:4:4 stream: chroma planes are
6455 /// FULL resolution (`yuv444p` rawvideo), the shape lane-av1-llinter's
6456 /// lossless profile-1 fixture codes.
6457 fn ffmpeg_decode_sequence_444(
6458 stream: &[u8],
6459 width: usize,
6460 height: usize,
6461 frames: usize,
6462 ) -> Vec<Pic> {
6463 let out = run_with_stdin(
6464 Command::new("ffmpeg").args([
6465 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv444p", "-",
6466 ]),
6467 stream,
6468 );
6469 assert!(
6470 out.status.success(),
6471 "ffmpeg refused the 4:4:4 stream: {}",
6472 String::from_utf8_lossy(&out.stderr)
6473 );
6474 let plane = width * height;
6475 let frame_bytes = 3 * plane;
6476 assert_eq!(
6477 out.stdout.len(),
6478 frame_bytes * frames,
6479 "expected {frames} 4:4:4 frames, ffmpeg said: {}",
6480 String::from_utf8_lossy(&out.stderr)
6481 );
6482 (0..frames)
6483 .map(|i| {
6484 let base = i * frame_bytes;
6485 Pic {
6486 width,
6487 height,
6488 y: out.stdout[base..base + plane]
6489 .iter()
6490 .map(|&v| u16::from(v))
6491 .collect(),
6492 u: out.stdout[base + plane..base + 2 * plane]
6493 .iter()
6494 .map(|&v| u16::from(v))
6495 .collect(),
6496 v: out.stdout[base + 2 * plane..base + 3 * plane]
6497 .iter()
6498 .map(|&v| u16::from(v))
6499 .collect(),
6500 }
6501 })
6502 .collect()
6503 }
6504
6505 /// lane-av1-llinter: the firing gate for the lossless 4:4:4 INTER chroma
6506 /// fix. The fixture is the report's dodge2 stream pinned into `fixtures/`:
6507 /// aomenc profile 1 over testsrc2 128x96 yuv444p, `--lossless=1`,
6508 /// `--sb-size=64 --min-partition-size=64 --max-partition-size=64`, 6
6509 /// frames; 37658 bytes, sha256
6510 /// `5a070fa351a3f2109de855234f2b3d0a872970f3e7f658db21f65c12eeb135b4`.
6511 /// The firing counter is the EXISTING `decode::chroma_split_tx_hits` (one
6512 /// bump per lossless chroma TX unit read): with min=max partition 64 the
6513 /// roots stay whole 64x64 inter blocks -- no 8x8 leaf exists in this
6514 /// stream -- so every chroma unit goes through the big-block ss-aware
6515 /// lossless route this lane fixed (fixes 2-5). A 4:2:0 lossless stream
6516 /// fires the same counter, but the fixture bytes are pinned, so the gate
6517 /// cannot run on anything else; the pre-fix 4:2:0-hardcoded math corrupts
6518 /// at 4:4:4, so the pixel-exact compares are what prove the ss-aware path
6519 /// (class `gate-blind-to-feature`). Every frame must come out pixel-exact
6520 /// through BOTH the oracle `aomdec --rawvideo` and ffmpeg. The
6521 /// default-partition ll444 stream is deliberately NOT claimed here: its
6522 /// key frame is still the intra lane's named sub8-chroma stop
6523 /// (lanes/av1llintra.report.md).
6524 #[test]
6525 fn a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact() {
6526 const NAME: &str = "a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact";
6527 const FIXTURE_LEN: usize = 37658;
6528 const FIXTURE_FNV: u64 = 0xf68d_c26f_a14d_283c;
6529 const W: usize = 128;
6530 const H: usize = 96;
6531 const FRAMES: usize = 6;
6532 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
6533 .join("fixtures/ll444_minp64_inter.obu");
6534 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
6535 panic!(
6536 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
6537 which is a failure, not a skip",
6538 obu.display()
6539 )
6540 });
6541 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
6542 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
6543
6544 let _guard = lock_gate_counters();
6545 let before = crate::decode::chroma_split_tx_hits();
6546 let frames = decode_stream(&stream)
6547 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
6548 let hits = crate::decode::chroma_split_tx_hits();
6549 assert!(
6550 hits > before,
6551 "{NAME}: gate is vacuous -- no lossless chroma TX unit was read \
6552 (delta {before} -> {hits})"
6553 );
6554 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
6555 for f in &frames {
6556 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
6557 }
6558
6559 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
6560 if aomdec_path().is_file() {
6561 let dir = std::env::temp_dir().join(format!("ec-av1-ll444-{}", std::process::id()));
6562 let _ = std::fs::remove_dir_all(&dir);
6563 std::fs::create_dir_all(&dir).expect("scratch dir");
6564 let raw = dir.join("aomdec.raw");
6565 let out = Command::new(aomdec_path())
6566 .args(["--codec=av1", "--rawvideo", "-o"])
6567 .arg(&raw)
6568 .arg(&obu)
6569 .stdin(Stdio::null())
6570 .stdout(Stdio::piped())
6571 .stderr(Stdio::piped())
6572 .output()
6573 .expect("aomdec failed to run");
6574 assert!(
6575 out.status.success(),
6576 "{NAME}: the oracle aomdec refused the stream: {}",
6577 String::from_utf8_lossy(&out.stderr)
6578 );
6579 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
6580 let _ = std::fs::remove_dir_all(&dir);
6581 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
6582 for (i, f) in frames.iter().enumerate() {
6583 let base = i * W * H * 3;
6584 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
6585 .into_iter()
6586 .zip(["y", "u", "v"])
6587 {
6588 let want = &ref_raw[base + off..base + off + W * H];
6589 let bad = plane
6590 .iter()
6591 .zip(want)
6592 .filter(|&(&a, &b)| a as u8 != b)
6593 .count();
6594 assert_eq!(
6595 bad, 0,
6596 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ"
6597 );
6598 }
6599 }
6600 } else {
6601 eprintln!(
6602 "SKIP {NAME} aomdec arm: no oracle aomdec at {}",
6603 aomdec_path().display()
6604 );
6605 }
6606
6607 // ffmpeg's decoder: same frames, full-resolution chroma.
6608 if have_ffmpeg() {
6609 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
6610 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() {
6611 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
6612 .iter()
6613 .enumerate()
6614 {
6615 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
6616 assert_eq!(
6617 bad, 0,
6618 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
6619 );
6620 }
6621 }
6622 } else {
6623 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
6624 }
6625 }
6626
6627 /// lane-av1llpredgate2: the debug-exact pin for the ss-aware
6628 /// `obmc_skip_chroma_above` decision (lane-av1-llpred2). Fixture is the
6629 /// llpred/llpred2 reports' stream pinned into `fixtures/`: testsrc2
6630 /// 128x96 yuv444p, aomenc `--profile=1 --lossless=1 --enable-palette=0
6631 /// --enable-intrabc=0 --min-partition-size=8 --max-partition-size=64`,
6632 /// 6 frames; 34037 bytes, sha256
6633 /// `04fb6d38de5382e647bfb70b6a17802f1fccc5502e6698c0394167891f2b27dc`.
6634 ///
6635 /// This is a DEBUG-build path by construction: the old ratio-based ss
6636 /// derivation read `write_h >> trailing_zeros(0)` = `>> 64` on this
6637 /// stream's 4:4:4 OBMC rect strips, a panic ONLY under
6638 /// debug_assertions (release wraps and was already byte-exact), so
6639 /// `cargo test`'s default dev profile is the profile where the defect
6640 /// class reproduces and where the parent's byte-exact proof was
6641 /// measured.
6642 ///
6643 /// No skip-arm counter gate is possible on this stream, measured:
6644 /// OBMC runs 77 times with 20 rect leaves, but
6645 /// `obmc_skip_chroma_above` returns true 0 times -- at 4:4:4 the skip
6646 /// needs a 4x4/8x4/4x8 PLANE block and min-partition-8 never codes one.
6647 /// So per the lane ticket the proof splits in two: the decision TABLE
6648 /// (4:2:0 rect strips still skip, 4:4:4 shifts never leave `usize`)
6649 /// stays pinned by `decode::obmc_skip_chroma_tests::
6650 /// rect_strips_skip_above_chroma_at_420_and_shift_never_overflows`,
6651 /// and THIS stream gate pins the end-to-end behaviour -- every sample
6652 /// of every frame must match the oracle aomdec exactly, so a returning
6653 /// chroma diff (the lane-av1-llpred ss-blind re-blend class
6654 /// `obmc-ss-blind-chroma-above`) or the debug shift panic goes red
6655 /// here by name.
6656 #[test]
6657 fn a_lossless_444_min_partition8_inter_stream_decodes_sample_exact() {
6658 const NAME: &str = "a_lossless_444_min_partition8_inter_stream_decodes_sample_exact";
6659 const FIXTURE_LEN: usize = 34037;
6660 const FIXTURE_FNV: u64 = 0x2c8f_4a2c_c025_52da;
6661 const W: usize = 128;
6662 const H: usize = 96;
6663 const FRAMES: usize = 6;
6664 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
6665 .join("fixtures/ll444_minp8_inter.obu");
6666 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
6667 panic!(
6668 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
6669 which is a failure, not a skip",
6670 obu.display()
6671 )
6672 });
6673 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
6674 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
6675
6676 let _guard = lock_gate_counters();
6677 let frames = decode_stream(&stream)
6678 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
6679 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
6680 for f in &frames {
6681 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
6682 }
6683
6684 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
6685 if aomdec_path().is_file() {
6686 let dir = std::env::temp_dir().join(format!("ec-av1-llminp8-{}", std::process::id()));
6687 let _ = std::fs::remove_dir_all(&dir);
6688 std::fs::create_dir_all(&dir).expect("scratch dir");
6689 let raw = dir.join("aomdec.raw");
6690 let out = Command::new(aomdec_path())
6691 .args(["--codec=av1", "--rawvideo", "-o"])
6692 .arg(&raw)
6693 .arg(&obu)
6694 .stdin(Stdio::null())
6695 .stdout(Stdio::piped())
6696 .stderr(Stdio::piped())
6697 .output()
6698 .expect("aomdec failed to run");
6699 assert!(
6700 out.status.success(),
6701 "{NAME}: the oracle aomdec refused the stream: {}",
6702 String::from_utf8_lossy(&out.stderr)
6703 );
6704 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
6705 let _ = std::fs::remove_dir_all(&dir);
6706 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
6707 for (i, f) in frames.iter().enumerate() {
6708 let base = i * W * H * 3;
6709 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
6710 .into_iter()
6711 .zip(["y", "u", "v"])
6712 {
6713 let want = &ref_raw[base + off..base + off + W * H];
6714 let bad = plane
6715 .iter()
6716 .zip(want)
6717 .filter(|&(&a, &b)| a as u8 != b)
6718 .count();
6719 assert_eq!(
6720 bad, 0,
6721 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \
6722 (class obmc-ss-blind-chroma-above)"
6723 );
6724 }
6725 }
6726 } else {
6727 eprintln!(
6728 "SKIP {NAME} aomdec arm: no oracle aomdec at {}",
6729 aomdec_path().display()
6730 );
6731 }
6732
6733 // ffmpeg's decoder: same frames, full-resolution chroma.
6734 if have_ffmpeg() {
6735 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
6736 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() {
6737 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
6738 .iter()
6739 .enumerate()
6740 {
6741 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
6742 assert_eq!(
6743 bad, 0,
6744 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
6745 );
6746 }
6747 }
6748 } else {
6749 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
6750 }
6751 }
6752
6753 /// lane-av1-444sb: the byte-exact pin for the ss-aware 128-rect chroma
6754 /// unit walk (`decode_block_128rect`). The parent walk hardcoded the
6755 /// 4:2:0 mu-chunk span -- one 32x32 chroma unit per 64x64 chunk, chunk
6756 /// offsets `*32`, clip step `*8` -- so at 4:4:4 a 128-root HORZ/VERT
6757 /// intra block coded HALF its chroma units, left the remaining units'
6758 /// coefficients unread and desynced the tile from the first such block
6759 /// on; every superblock after SB(0,0) carried damage and the chroma
6760 /// first-diffs sat on the 64/128 grid.
6761 ///
6762 /// `crates/ec-av1/fixtures/444_sb128rect_lr_witness.obu`, 794 bytes,
6763 /// sha256
6764 /// `27825e14633a4b23e37d48a2acdc7f5d814ca4fadd0b8797d72a1ffb34061e80`:
6765 /// `ffmpeg -i bands444.y4m -frames:v 3 -vf scale=192:160 -pix_fmt
6766 /// yuv444p -f yuv4mpegpipe` piped to `aomenc --codec=av1 --profile=1
6767 /// --passes=1 --end-usage=q --cq-level=32 --cpu-used=0 --threads=1
6768 /// --row-mt=0 --sb-size=128 --lag-in-frames=0 --auto-alt-ref=0
6769 /// --kf-max-dist=1000 --i444 --enable-restoration=1 --obu --limit=3`.
6770 /// Real content is required: the synthetic lavfi sources this lane swept
6771 /// (testsrc2/testsrc/smptebars/mandelbrot/gradients) all decode frame 0
6772 /// exact because they never force a 128-root rect; bands does (kf
6773 /// PARTITION_VERT 64x128 at mi(0,32) plus an intra-in-inter 64x128).
6774 ///
6775 /// Non-vacuity via the `decode::intra_sb128_hits` delta: a stream that
6776 /// stopped coding 128-axis intra blocks reads 0 and the gate fails
6777 /// instead of passing over a decode that never reached the fixed body
6778 /// (class `gate-blind-to-feature`). The oracle arms pin every sample of
6779 /// every frame against both aomdec and ffmpeg, so a returning chroma
6780 /// span regression goes red here by name.
6781 #[test]
6782 fn a_444_sb128_root_rect_stream_with_restoration_decodes_pixel_exact() {
6783 const NAME: &str = "a_444_sb128_root_rect_stream_with_restoration_decodes_pixel_exact";
6784 const FIXTURE_LEN: usize = 794;
6785 const FIXTURE_FNV: u64 = 0xf5a7_27f4_3fa7_abc3;
6786 const W: usize = 192;
6787 const H: usize = 160;
6788 const FRAMES: usize = 3;
6789 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
6790 .join("fixtures/444_sb128rect_lr_witness.obu");
6791 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
6792 panic!(
6793 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
6794 which is a failure, not a skip",
6795 obu.display()
6796 )
6797 });
6798 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
6799 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
6800
6801 let _guard = lock_gate_counters();
6802 let before = crate::decode::intra_sb128_hits();
6803 let before_replay = crate::decode::sb128rect_chroma_replay_hits();
6804 let frames = decode_stream(&stream)
6805 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
6806 let (horz, vert, _) = crate::decode::intra_sb128_hits();
6807 assert!(
6808 horz - before.0 + (vert - before.1) > 0,
6809 "{NAME}: this stream coded NO 128-axis intra block -- the fixed body \
6810 never ran (class gate-blind-to-feature)"
6811 );
6812 // lane-av1-128rectspan: the block-level `record_split_luma_rect`
6813 // above clobbers the per-unit chroma contexts, so every coded unit
6814 // replays its own state after it -- the arm the span fix sits on.
6815 // The delta keeps THAT arm non-vacuous (a 128-root rect stream that
6816 // stopped replaying reads 0), and the mismatch half is the 4:2:2
6817 // signature: this stream is 4:4:4 (ss 0,0), where the unit's luma
6818 // width and height are equal, so a replay that stamped one axis with
6819 // the other's span would still read 0 here -- the counter is what
6820 // names the day 4:2:2 (ss 1,0, refused by name at the sequence
6821 // header) is admitted, rather than letting the 8-row spill below the
6822 // block corrupt the next block's `txb_skip` silently.
6823 let after_replay = crate::decode::sb128rect_chroma_replay_hits();
6824 assert!(
6825 after_replay.0 > before_replay.0,
6826 "{NAME}: no 128-root rect block replayed a chroma unit's own mi state -- the \
6827 replay arm never ran (class gate-blind-to-feature)"
6828 );
6829 assert_eq!(
6830 after_replay.1,
6831 before_replay.1,
6832 "{NAME}: the tail replay stamped {} unit(s) over a height that was not the \
6833 unit's own luma height (4:2:2 spans leaked into an admitted stream)",
6834 after_replay.1 - before_replay.1
6835 );
6836 eprintln!(
6837 "{NAME}: replayed {} chroma unit(s), {} span mismatch(es)",
6838 after_replay.0 - before_replay.0,
6839 after_replay.1 - before_replay.1
6840 );
6841 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
6842 for f in &frames {
6843 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
6844 }
6845 // All three frames are pinned byte-exact against both oracles (the
6846 // aomdec/ffmpeg arms below run over `.take(3)`): frame 0's keyframe
6847 // PARTITION_VERT 64x128, frame 1's inter pieces, and frame 2 -- whose
6848 // right superblock column (the 128-root VERT piece at the frame edge)
6849 // is three intra blocks (64x64, 64x32, 64x32) whose chroma units ride
6850 // the inter-frame intra tail. That tail read ONE whole-plane chroma
6851 // unit with the block-level context where 4:4:4 codes four
6852 // plane-major TX_32X32 units with per-unit contexts and the
6853 // offset-10 `get_txb_ctx` rows, which left three quarters of the
6854 // planes' residual unread and misaligned the symbol stream from the
6855 // first chroma unit on (f2 PREFILT Y 6952 / U 9568 / V 13496, first
6856 // diffs entering at column 128). Fixed on lane-av1-rect128recon;
6857 // the earlier "LR never restores RU row 0" attribution on this frame
6858 // was a stage-ladder mixup, refuted in lane-av1lrflush r3.
6859
6860 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
6861 if aomdec_path().is_file() {
6862 let dir = std::env::temp_dir().join(format!("ec-av1-444sb-{}", std::process::id()));
6863 let _ = std::fs::remove_dir_all(&dir);
6864 std::fs::create_dir_all(&dir).expect("scratch dir");
6865 let raw = dir.join("aomdec.raw");
6866 let out = Command::new(aomdec_path())
6867 .args(["--codec=av1", "--rawvideo", "-o"])
6868 .arg(&raw)
6869 .arg(&obu)
6870 .stdin(Stdio::null())
6871 .stdout(Stdio::piped())
6872 .stderr(Stdio::piped())
6873 .output()
6874 .expect("aomdec failed to run");
6875 assert!(
6876 out.status.success(),
6877 "{NAME}: the oracle aomdec refused the stream: {}",
6878 String::from_utf8_lossy(&out.stderr)
6879 );
6880 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
6881 let _ = std::fs::remove_dir_all(&dir);
6882 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
6883 for (i, f) in frames.iter().enumerate().take(3) {
6884 let base = i * W * H * 3;
6885 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
6886 .into_iter()
6887 .zip(["y", "u", "v"])
6888 {
6889 let want = &ref_raw[base + off..base + off + W * H];
6890 let bad = plane
6891 .iter()
6892 .zip(want)
6893 .filter(|&(&a, &b)| a as u8 != b)
6894 .count();
6895 assert_eq!(
6896 bad, 0,
6897 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \
6898 (class 444-128rect-chroma-span)"
6899 );
6900 }
6901 }
6902 } else {
6903 eprintln!(
6904 "SKIP {NAME} aomdec arm: no oracle aomdec at {}",
6905 aomdec_path().display()
6906 );
6907 }
6908
6909 // ffmpeg's decoder: same frames, full-resolution chroma. Same
6910 // three-frame scope as the aomdec arm above.
6911 if have_ffmpeg() {
6912 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
6913 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate().take(3) {
6914 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
6915 .iter()
6916 .enumerate()
6917 {
6918 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
6919 assert_eq!(
6920 bad, 0,
6921 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
6922 );
6923 }
6924 }
6925 } else {
6926 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
6927 }
6928 }
6929
6930 /// lane-av1444rect (H1): the 4:4:4 LOSSY cell with a 1:4 (HORZ_4 /
6931 /// VERT_4) partition -- the largest correctness gap the chroma-format
6932 /// sweep left, and the first 4:4:4 lossy exactness gate in the crate.
6933 ///
6934 /// **The defect.** `decode_inter_block`'s `around_c` gathered a 1:4
6935 /// strip's chroma coefficient context at the 4:2:0 PAIR extent
6936 /// (`(16, 8)` HORZ / `(8, 16)` VERT) with no `ss` gate, so at ss (0,0)
6937 /// it read one extra luma mi row of LEFT chroma context. At 4:4:4
6938 /// `is_chroma_reference` (av1_common_int.h:1454) reduces both parity
6939 /// clauses to `!subsampling_y` / `!subsampling_x`, so every block is its
6940 /// own chroma reference and no pair exists: the strip codes its own
6941 /// 16x4 chroma over its own context. Our U unit's `get_txb_ctx` then saw
6942 /// a neighbour libaom does not have, and the arithmetic coder forked.
6943 ///
6944 /// **The recipe** (sha256
6945 /// `77f727e76d81fe48cd03709f799131677c04869b163e18d78e96bc742ec69153`,
6946 /// 6441 bytes, 2 frames, `testsrc2 128x96 rate=25` yuv444p):
6947 /// ```text
6948 /// ffmpeg -f lavfi -i "testsrc2=size=128x96:rate=25" -frames:v 2 \
6949 /// -pix_fmt yuv444p -f yuv4mpegpipe - | \
6950 /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=20 \
6951 /// --cpu-used=2 --threads=1 --row-mt=0 --lag-in-frames=0 \
6952 /// --kf-max-dist=100 --limit=2 - out.obu
6953 /// ```
6954 /// (`rate=25` is load-bearing: `testsrc2`'s pattern is time-parameterised,
6955 /// so `rate=1` produces a different, already-exact stream.)
6956 ///
6957 /// Red before the fix: frame 1, 8884 of 36864 samples wrong, first at
6958 /// Y(91,32); the first wrong symbol was read 26263 of the frame, both
6959 /// sides at mi (8,16) -- ours a luma-shaped `txb_skip` row (our
6960 /// re-indexed chroma ctx 1), the oracle `decodetxb.c:158` on the U plane
6961 /// with `txb_skip_ctx = 7`.
6962 ///
6963 /// Non-vacuity, three ways: the pinned stream must really be ss (0,0)
6964 /// (asserted through the oracle aomdec's own sequence header, below);
6965 /// `decode::rect4_inter_own_chroma444_hits()` must be non-zero, so the
6966 /// 1:4-strip route the fix sits on really ran; and the SAME source and
6967 /// flags at 4:2:0 must leave that counter at zero, which is what makes
6968 /// it the 4:4:4-only route rather than a tally every strip bumps.
6969 #[test]
6970 fn a_444_lossy_rect4_inter_stream_decodes_pixel_exact() {
6971 const NAME: &str = "a_444_lossy_rect4_inter_stream_decodes_pixel_exact";
6972 const FIXTURE_LEN: usize = 6441;
6973 const FIXTURE_FNV: u64 = 0x0436_8b2d_2e91_72b0;
6974 const W: usize = 128;
6975 const H: usize = 96;
6976 const FRAMES: usize = 2;
6977 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
6978 .join("fixtures/444_lossy_rect4_inter_witness.obu");
6979 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
6980 panic!(
6981 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
6982 which is a failure, not a skip",
6983 obu.display()
6984 )
6985 });
6986 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
6987 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
6988
6989 let _guard = lock_gate_counters();
6990 crate::decode::reset_rect4_inter_own_chroma444_hits();
6991 let frames = decode_stream(&stream).unwrap_or_else(|e| {
6992 panic!("{NAME}: the pinned 4:4:4 lossy stream no longer decodes cleanly: {e}")
6993 });
6994 let own_chroma = crate::decode::rect4_inter_own_chroma444_hits();
6995 assert!(
6996 own_chroma > 0,
6997 "{NAME}: no 1:4 inter strip read its chroma context over its own \
6998 extent -- the corrected route never ran (class gate-blind-to-feature)"
6999 );
7000 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
7001 for (i, f) in frames.iter().enumerate() {
7002 assert_eq!((f.width, f.height), (W, H), "{NAME}: frame {i} dimensions");
7003 // At 4:4:4 the chroma planes are full resolution. A decoder that
7004 // kept the 4:2:0 extent would hand quarter-size chroma planes to
7005 // the byte compare below, which cannot pass -- but say so here
7006 // rather than let the compare stand in for the shape claim.
7007 assert_eq!(
7008 f.u.len(),
7009 W * H,
7010 "{NAME}: frame {i} chroma plane is {} samples; at 4:4:4 it must be \
7011 full resolution ({W}x{H})",
7012 f.u.len()
7013 );
7014 }
7015 if aomdec_path().is_file() {
7016 let (decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME);
7017 eprintln!(
7018 "{NAME}: {decoded} frame(s) byte-exact vs aomdec, {own_chroma} \
7019 own-extent 1:4 chroma gather(s)"
7020 );
7021 } else {
7022 eprintln!("{NAME}: no oracle aomdec, pixel arm skipped");
7023 }
7024
7025 // The specificity arm: the SAME source, flags and 1:4 partitions at
7026 // 4:2:0 must not touch the 4:4:4-only route. If a later change made
7027 // the counter fire everywhere, this arm is what catches it.
7028 if !have_aomenc() {
7029 eprintln!("{NAME}: no aomenc, 4:2:0 specificity arm skipped");
7030 return;
7031 }
7032 let source = format!("testsrc2=size={W}x{H}:rate=25");
7033 let y4m = Command::new("ffmpeg")
7034 .args([
7035 "-v",
7036 "error",
7037 "-f",
7038 "lavfi",
7039 "-i",
7040 &source,
7041 "-frames:v",
7042 "2",
7043 "-pix_fmt",
7044 "yuv420p",
7045 "-strict",
7046 "-1",
7047 "-f",
7048 "yuv4mpegpipe",
7049 "-",
7050 ])
7051 .stdin(Stdio::null())
7052 .stdout(Stdio::piped())
7053 .stderr(Stdio::piped())
7054 .output()
7055 .expect("ffmpeg failed to run");
7056 assert!(
7057 y4m.status.success(),
7058 "{NAME}: ffmpeg refused the 4:2:0 control source: {}",
7059 String::from_utf8_lossy(&y4m.stderr)
7060 );
7061 let out = run_with_stdin(
7062 Command::new(aomenc_path()).args([
7063 "--codec=av1",
7064 "--passes=1",
7065 "--end-usage=q",
7066 "--cq-level=20",
7067 "--cpu-used=2",
7068 "--threads=1",
7069 "--row-mt=0",
7070 "--lag-in-frames=0",
7071 "--kf-max-dist=100",
7072 "--limit=2",
7073 "--obu",
7074 "-o",
7075 "-",
7076 "-",
7077 ]),
7078 &y4m.stdout,
7079 );
7080 assert!(
7081 out.status.success(),
7082 "{NAME}: aomenc refused the 4:2:0 control recipe: {}",
7083 String::from_utf8_lossy(&out.stderr)
7084 );
7085 crate::decode::reset_rect4_inter_own_chroma444_hits();
7086 decode_stream(&out.stdout)
7087 .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control stream was refused: {e}"));
7088 let (h4, v4, _, _) = crate::decode::inter16_rect4_counters();
7089 // The control must actually code 1:4 inter strips, or it says nothing
7090 // about the arm the fix touches. Measured: 16 HORZ_4, 28 VERT_4.
7091 assert!(
7092 h4 + v4 > 0,
7093 "{NAME}: the 4:2:0 control coded NO 1:4 inter strip ({h4} HORZ_4, {v4} \
7094 VERT_4) -- the identity arm below would say nothing about 1:4 strips"
7095 );
7096 assert_eq!(
7097 crate::decode::rect4_inter_own_chroma444_hits(),
7098 0,
7099 "{NAME}: the 4:2:0 control fired the ss_x-0 own-extent route -- the route \
7100 is not specific to the 4:4:4 cell it was fixed for"
7101 );
7102 // The identity half: the fix adds an arm gated on `ss_x == 0`, so a
7103 // 4:2:0 stream must stay byte-exact through it. This is the arm that
7104 // would go red if the new arm were ever widened past ss_x 0.
7105 if aomdec_path().is_file() {
7106 decode_all_frames_vs_oracle(&out.stdout, &format!("{NAME}-420"));
7107 }
7108 eprintln!("{NAME}: 4:2:0 control {h4} HORZ_4 / {v4} VERT_4 strips, 0 own-extent gathers");
7109 }
7110
7111 /// lane-av1lrflush: the pipelined loop-restoration band release flushes
7112 /// RU row 0 on the inter frame whose top superblock row carries a
7113 /// 128-root rect -- the exact shape lanes/av1444sb.report.md r2 named as
7114 /// its stop-with-site DEFECT 3 ("`pipe_run_lr`'s `rrows` branch plus the
7115 /// `ls.note`/`ls.close` band release never flushes RU row 0 on frame 2").
7116 /// r3 REFUTED that defect by measurement: on this fixture the filter
7117 /// pipeline (deblock/CDEF/LR band workers over `ls.note` releases)
7118 /// produces output byte-identical to the whole-frame path on every frame
7119 /// -- this gate pins that refutation so a future band-accounting
7120 /// regression on a 128-root-rect inter frame cannot land silently.
7121 ///
7122 /// Non-vacuity, twice over: the `PIPELINE_TAKEN` delta proves the second
7123 /// decode really constructed the pipeline on both inter frames (frame 0
7124 /// is a key frame and the key-frame path runs whole-frame filters by
7125 /// construction), and the `LR_PIPELINE_ROW0` delta proves the pipeline's
7126 /// band release itself flushed RU row 0 -- a process-global counter
7127 /// bumped by `pipe_run_lr`'s worker, so frame 0's whole-frame LR (which
7128 /// runs on the gate's own thread and satisfies the thread-local
7129 /// `LR_STRIPE0_HITS`) cannot fake it. Frames 0/1 are additionally asserted
7130 /// byte-exact against BOTH the oracle aomdec and ffmpeg THROUGH the
7131 /// pipeline. (Frame 2's own residual is the entropy lane's inter
7132 /// rect-strip recon defect -- see lanes/av1lrflush.report.md r3 -- and
7133 /// is identical on the serial and pipelined runs, so the pipeline
7134 /// equality covers it without pinning its wrong samples.)
7135 #[test]
7136 fn a_444_sb128_witness_lr_pipeline_flushes_ru_row_0_pixel_exact() {
7137 const NAME: &str = "a_444_sb128_witness_lr_pipeline_flushes_ru_row_0_pixel_exact";
7138 const FIXTURE_LEN: usize = 794;
7139 const FIXTURE_FNV: u64 = 0xf5a7_27f4_3fa7_abc3;
7140 const W: usize = 192;
7141 const H: usize = 160;
7142 const FRAMES: usize = 3;
7143 /// The inter (pipelinable) frames of the witness; frame 0 is the key
7144 /// frame and never constructs the pipeline.
7145 const INTER_FRAMES: u64 = 2;
7146 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7147 .join("fixtures/444_sb128rect_lr_witness.obu");
7148 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
7149 panic!(
7150 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot \
7151 run, which is a failure, not a skip",
7152 obu.display()
7153 )
7154 });
7155 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
7156 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
7157
7158 let _guard = lock_gate_counters();
7159 let serial =
7160 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: serial decode failed: {e}"));
7161 assert_eq!(serial.len(), FRAMES, "{NAME}: frame count");
7162
7163 let pipe_before = crate::decode::pipeline_taken_frames();
7164 let row0_before = crate::decode::lr_pipeline_row0_flushes();
7165 let piped = {
7166 let _bands = crate::par::override_filter_threads(4);
7167 decode_stream(&stream)
7168 .unwrap_or_else(|e| panic!("{NAME}: pipelined decode failed: {e}"))
7169 };
7170 assert_eq!(piped.len(), FRAMES, "{NAME}: frame count");
7171 assert_eq!(
7172 crate::decode::pipeline_taken_frames() - pipe_before,
7173 INTER_FRAMES,
7174 "{NAME}: the filter pipeline did not take both inter frames -- the \
7175 arm decoded serial and proves nothing (class \
7176 gate-blind-to-feature)"
7177 );
7178 // f1 restores all three planes, f2 all but U -> 3 + 2 row-0 flushes.
7179 // `LR_PIPELINE_ROW0` is process-global and bumped by the pipeline's
7180 // own worker, so this delta cannot be satisfied by frame 0's
7181 // whole-frame LR (which runs on this test's thread and never touches
7182 // the counter).
7183 assert_eq!(
7184 crate::decode::lr_pipeline_row0_flushes() - row0_before,
7185 5,
7186 "{NAME}: the pipeline never flushed RU row 0 ({} planes' worth \
7187 expected) -- the named defect class is present (class \
7188 lr-band-release)",
7189 5
7190 );
7191
7192 // The refutation itself: pipeline == serial, byte for byte, on every
7193 // frame -- including frame 2, the 128-root-rect inter frame the
7194 // r2 defect named.
7195 for (i, (s, p)) in serial.iter().zip(piped.iter()).enumerate() {
7196 for (pl, (a, b)) in [(&s.y, &p.y), (&s.u, &p.u), (&s.v, &p.v)]
7197 .into_iter()
7198 .enumerate()
7199 {
7200 assert_eq!(
7201 a, b,
7202 "{NAME}: pipelined frame {i} plane {pl} differs from the \
7203 whole-frame path (class lr-band-release)"
7204 );
7205 }
7206 }
7207
7208 // Frames 0/1 through the PIPELINE, byte-exact vs both oracles.
7209 if aomdec_path().is_file() {
7210 let dir = std::env::temp_dir().join(format!("ec-av1-lrflush-{}", std::process::id()));
7211 let _ = std::fs::remove_dir_all(&dir);
7212 std::fs::create_dir_all(&dir).expect("scratch dir");
7213 let raw = dir.join("aomdec.raw");
7214 let out = Command::new(aomdec_path())
7215 .args(["--codec=av1", "--rawvideo", "-o"])
7216 .arg(&raw)
7217 .arg(&obu)
7218 .stdin(Stdio::null())
7219 .stdout(Stdio::piped())
7220 .stderr(Stdio::piped())
7221 .output()
7222 .expect("aomdec failed to run");
7223 assert!(
7224 out.status.success(),
7225 "{NAME}: the oracle aomdec refused the stream: {}",
7226 String::from_utf8_lossy(&out.stderr)
7227 );
7228 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
7229 let _ = std::fs::remove_dir_all(&dir);
7230 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
7231 for (i, f) in piped.iter().enumerate().take(2) {
7232 let base = i * W * H * 3;
7233 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
7234 .into_iter()
7235 .zip(["y", "u", "v"])
7236 {
7237 let want = &ref_raw[base + off..base + off + W * H];
7238 let bad = plane
7239 .iter()
7240 .zip(want)
7241 .filter(|&(&a, &b)| a as u8 != b)
7242 .count();
7243 assert_eq!(
7244 bad, 0,
7245 "{NAME}: aomdec frame {i} plane {p} THROUGH THE PIPELINE: \
7246 {bad} samples differ (class lr-band-release)"
7247 );
7248 }
7249 }
7250 } else {
7251 eprintln!(
7252 "SKIP {NAME} aomdec arm: no oracle aomdec at {}",
7253 aomdec_path().display()
7254 );
7255 }
7256 if have_ffmpeg() {
7257 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
7258 for (i, (got, want)) in piped.iter().zip(refs.iter()).enumerate().take(2) {
7259 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
7260 .iter()
7261 .enumerate()
7262 {
7263 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
7264 assert_eq!(
7265 bad, 0,
7266 "{NAME}: ffmpeg frame {i} plane {p} THROUGH THE PIPELINE: \
7267 {bad} samples differ"
7268 );
7269 }
7270 }
7271 } else {
7272 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
7273 }
7274 }
7275
7276 /// lane-av1-444interband: the DEFAULT-partition lossless 4:4:4 pin for
7277 /// the inter 16x4/4x16 strip's chroma band stamping (the pair_chroma
7278 /// 4:2:0-only gate, commit d5325172). Fixture pinned into `fixtures/`:
7279 /// testsrc2 128x96 yuv444p, aomenc `--profile=1 --lossless=1
7280 /// --enable-palette=0 --enable-intrabc=0 --passes=1 --cpu-used=4
7281 /// --limit=6 --obu` (the av1llkf.report.md recipe), 6 frames; 32487
7282 /// bytes, sha256
7283 /// `1e6dd4e05038c8d51e2c8d29f8c337130c4fea0aed629415535e6e53af9a2c72`.
7284 ///
7285 /// This is the stream whose frame 1 desynced at the 16x4 inter strip
7286 /// mi(2,8) -- its U bc=0 `txb_skip` read base 0 where aom reads base 1,
7287 /// because the skipped strip (1,8)'s pair-form context stamp smeared
7288 /// zero over `left[2][1]`. Two pins, both measured at d5325172:
7289 /// end-to-end, every sample of every frame must match the oracle
7290 /// aomdec exactly (the pre-fix tree refuses mid-frame-1, so the gate
7291 /// is red by refusal, not by silent pass), and the 1:4 counter delta
7292 /// must show the strips decoded WITHOUT the pair rewrite firing
7293 /// (`horz4=20 vert4=28 chroma_pairs=0` -- chroma_pairs > 0 on this
7294 /// pairless 4:4:4 stream is the defect reappearing, the
7295 /// class `pair-rewrite-at-ss0`).
7296 #[test]
7297 fn a_lossless_444_defaultp_inter_strip_stream_decodes_byte_exact() {
7298 const NAME: &str = "a_lossless_444_defaultp_inter_strip_stream_decodes_byte_exact";
7299 const FIXTURE_LEN: usize = 32487;
7300 const FIXTURE_FNV: u64 = 0x5278_9f0f_ce2d_1e52;
7301 const W: usize = 128;
7302 const H: usize = 96;
7303 const FRAMES: usize = 6;
7304 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7305 .join("fixtures/ll444_defaultp_inter_strip.obu");
7306 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
7307 panic!(
7308 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
7309 which is a failure, not a skip",
7310 obu.display()
7311 )
7312 });
7313 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
7314 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
7315
7316 let _guard = lock_gate_counters();
7317 let strips_before = decode::inter16_rect4_counters();
7318 let frames = decode_stream(&stream)
7319 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
7320 let strips_after = decode::inter16_rect4_counters();
7321 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
7322 for f in &frames {
7323 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
7324 }
7325 // The 1:4 strips must have fired, and the 4:2:0 pair rewrite must
7326 // NOT have (there are no chroma pairs at ss 0/0).
7327 let (horz4, vert4, chroma_pairs) = (
7328 strips_after.0 - strips_before.0,
7329 strips_after.1 - strips_before.1,
7330 strips_after.2 - strips_before.2,
7331 );
7332 assert_eq!(horz4, 20, "{NAME}: HORZ_4 strip count moved");
7333 assert_eq!(vert4, 28, "{NAME}: VERT_4 strip count moved");
7334 assert_eq!(
7335 chroma_pairs, 0,
7336 "{NAME}: chroma pairs closed on a 4:4:4 stream \
7337 (class pair-rewrite-at-ss0)"
7338 );
7339
7340 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
7341 if aomdec_path().is_file() {
7342 let dir = std::env::temp_dir().join(format!("ec-av1-ll444dp-{}", std::process::id()));
7343 let _ = std::fs::remove_dir_all(&dir);
7344 std::fs::create_dir_all(&dir).expect("scratch dir");
7345 let raw = dir.join("aomdec.raw");
7346 let out = Command::new(aomdec_path())
7347 .args(["--codec=av1", "--rawvideo", "-o"])
7348 .arg(&raw)
7349 .arg(&obu)
7350 .stdin(Stdio::null())
7351 .stdout(Stdio::piped())
7352 .stderr(Stdio::piped())
7353 .output()
7354 .expect("aomdec failed to run");
7355 assert!(
7356 out.status.success(),
7357 "{NAME}: the oracle aomdec refused the stream: {}",
7358 String::from_utf8_lossy(&out.stderr)
7359 );
7360 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
7361 let _ = std::fs::remove_dir_all(&dir);
7362 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
7363 for (i, f) in frames.iter().enumerate() {
7364 let base = i * W * H * 3;
7365 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
7366 .into_iter()
7367 .zip(["y", "u", "v"])
7368 {
7369 let want = &ref_raw[base + off..base + off + W * H];
7370 let bad = plane
7371 .iter()
7372 .zip(want)
7373 .filter(|&(&a, &b)| a as u8 != b)
7374 .count();
7375 assert_eq!(
7376 bad, 0,
7377 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \
7378 (class pair-rewrite-at-ss0)"
7379 );
7380 }
7381 }
7382 } else {
7383 eprintln!(
7384 "SKIP {NAME} aomdec arm: no oracle aomdec at {}",
7385 aomdec_path().display()
7386 );
7387 }
7388 }
7389
7390 /// lane-av1-leaf8oob: the OOB pin for [`decode_leaf8`]'s intrabc chroma
7391 /// frame-copy buffers. The closure hardcoding the leaf's chroma
7392 /// prediction at `4x4` (`vec![0u16; 4 * 4]`, `predict_with_filter` at
7393 /// `4, 4`) carried the 4:2:0 halving of an 8x8 luma leaf into every
7394 /// subsampling: at 4:4:4 the leaf's own chroma plane block is 8x8
7395 /// (`csz == 8`), so the 16-sample override reached
7396 /// [`PlaneBuf::reconstruct`] as an 8x8 prediction and indexed
7397 /// `prediction[16]` of a 16-sample buffer --
7398 /// `index out of bounds: the len is 16 but the index is 16` at the
7399 /// reconstruct call, on every conformant stream of this shape (a panic,
7400 /// never a refusal). Same signature class as lane-lossless128's
7401 /// 128-axis lossless extent (`len 16, index 16` there too).
7402 ///
7403 /// `crates/ec-av1/fixtures/444_leaf8_oob.obu`, 3577 bytes, sha256
7404 /// `72bed2791d1ceba8be7926a052c7838c5d96d4f9d56d28fb69789a753d3593af`
7405 /// (force-added past the `fixtures` gitignore like every sibling
7406 /// fixture): the lane ticket's witness-hunt reproducer (s1a/s2e) -- a
7407 /// 320x256, 3-frame, 8-bit 4:4:4 screen-content keyframe run whose
7408 /// census pins 4 intrabc 8x8 leaves (the oracle's own MB dump opens on
7409 /// unbroken inter-classified intra = intrabc blocks). The encoding
7410 /// recipe is not independently recoverable in this lane; the bytes are
7411 /// pinned by length + FNV-1a64 here and by the oracle raw fingerprint
7412 /// below.
7413 ///
7414 /// WHAT THIS GATE DOES NOT CLAIM: sample-exactness -- and it pins no
7415 /// pixel baseline. Measured against the oracle aomdec (`--rawvideo`;
7416 /// comparison method ground-truthed by the green
7417 /// `a_lossless_sb128_rect_intra_block_decodes_sample_exact` and
7418 /// `a_lossless_444_min_partition8_inter_stream_decodes_sample_exact`
7419 /// witnesses on this same tree), this stream DIVERGES and its output is
7420 /// not even self-deterministic: frame 0's first differing LUMA sample
7421 /// is at (275,128), the (y, u, v) differing counts per frame are
7422 /// (20811, 35467, 32320)/(20308, 39177, 35994)/(20131, 39588, 36601) of
7423 /// 81920 samples per plane, and under `EC_AV1_PLANE_SENTINEL=1` the
7424 /// chroma counts move (u f0 35467 -> 35630) while luma stays put.
7425 /// Sentinel-vs-uninit output diffing localises that dependence to 458
7426 /// WHOLE 8x8 chroma blocks (frame 0: chroma x >= 96, y >= 64) reading
7427 /// samples this decode never wrote -- ambient memory in those slots,
7428 /// hence any pixel-exact assert here drifts run to run with the batch.
7429 /// Both facts belong to ONE pre-existing defect this lane must not
7430 /// chase (the ticket's fix touches only leaf8's chroma prediction
7431 /// buffers, which cannot feed a luma sample, and the pre-fix run never
7432 /// got past the panicked leaf): a decode desync on this stream around
7433 /// frame-0 SB (3..4, 2), after which samples diverge from the oracle
7434 /// and the misread layout leaves chroma blocks unreconstructed.
7435 /// Disposition: `deferred(unblock: divergence lane -- EC trace pairing
7436 /// against the oracle on this fixture)`. So this gate pins exactly what
7437 /// its ticket owns: fixture identity, a decode that RUNS TO COMPLETION
7438 /// where the old code died with `len 16, index 16`, and the arm counter.
7439 ///
7440 /// Assertions (all before/without any skip path):
7441 /// 1. fixture bytes: exact length + FNV-1a64;
7442 /// 2. `decode_stream` succeeds -- 3 frames, 320x256 (the pre-fix run
7443 /// died here with the len-16/index-16 panic);
7444 /// 3. non-vacuity: `leaf8_intrabc_hits` moves (measured 0 -> 4), so the
7445 /// arm owning the fixed buffers really fired;
7446 /// 4. the oracle aomdec still decodes the pinned bytes (raw size +
7447 /// fingerprint), anchoring the deferred divergence comparison.
7448 #[test]
7449 fn an_intrabc_8x8_leaf_chroma_frame_copy_at_444_decodes_without_the_oob() {
7450 const NAME: &str = "an_intrabc_8x8_leaf_chroma_frame_copy_at_444_decodes_without_the_oob";
7451 const FIXTURE_LEN: usize = 3577;
7452 const FIXTURE_FNV: u64 = 0x86b9_3a51_fe16_353c;
7453 const W: usize = 320;
7454 const H: usize = 256;
7455 const FRAMES: usize = 3;
7456 let obu =
7457 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures/444_leaf8_oob.obu");
7458 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
7459 panic!(
7460 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
7461 which is a failure, not a skip",
7462 obu.display()
7463 )
7464 });
7465 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
7466 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
7467
7468 let _guard = lock_gate_counters();
7469 crate::decode::reset_leaf8_intrabc_hits();
7470 let frames = decode_stream(&stream)
7471 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
7472 assert!(
7473 crate::decode::leaf8_intrabc_hits() > 0,
7474 "{NAME}: gate is vacuous -- no intrabc 8x8 leaf was decoded, so the arm \
7475 owning the fixed chroma buffers never fired"
7476 );
7477 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
7478 for f in &frames {
7479 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
7480 }
7481
7482 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
7483 if aomdec_path().is_file() {
7484 let dir = std::env::temp_dir().join(format!("ec-av1-leaf8oob-{}", std::process::id()));
7485 let _ = std::fs::remove_dir_all(&dir);
7486 std::fs::create_dir_all(&dir).expect("scratch dir");
7487 let raw = dir.join("aomdec.raw");
7488 let out = Command::new(aomdec_path())
7489 .args(["--codec=av1", "--rawvideo", "-o"])
7490 .arg(&raw)
7491 .arg(&obu)
7492 .stdin(Stdio::null())
7493 .stdout(Stdio::piped())
7494 .stderr(Stdio::piped())
7495 .output()
7496 .expect("aomdec failed to run");
7497 assert!(
7498 out.status.success(),
7499 "{NAME}: the oracle aomdec refused the stream: {}",
7500 String::from_utf8_lossy(&out.stderr)
7501 );
7502 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
7503 let _ = std::fs::remove_dir_all(&dir);
7504 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
7505 assert_eq!(
7506 fnv1a64(&ref_raw),
7507 0x3821_0bcb_f572_973c,
7508 "{NAME}: aomdec raw fingerprint moved"
7509 );
7510 } else {
7511 eprintln!(
7512 "SKIP {NAME} aomdec arm: no oracle aomdec at {}",
7513 aomdec_path().display()
7514 );
7515 }
7516 }
7517 /// lane-lossless128: a LOSSLESS key frame that codes a 128-axis
7518 /// (`BLOCK_64X128`) intra block -- the shape libaom's `read_tx_size` forces
7519 /// to `TX_4X4` on its very first line (`decodeframe.c:1183`), so every plane
7520 /// of the block is a 4x4 transform unit and NO `tx_size_cat3` symbol is
7521 /// coded.
7522 ///
7523 /// On the merged base `decode_block_128rect` had no lossless carve-out: it
7524 /// read `logical_tx = 64` off `depth == 0`, handed `PlaneBuf::reconstruct`
7525 /// a 64x64 geometry with the 16-sample 4x4 residual
7526 /// [`TxParams::run`](crate::decode::TxParams) produced -- `index out of
7527 /// bounds: the len is 16 but the index is 16` at the reconstruction call,
7528 /// on EVERY conformant stream of this shape (a panic, never a refusal).
7529 ///
7530 /// `crates/ec-av1/fixtures/lossless_sb128_rect_kf.obu`, 3471 bytes, sha256
7531 /// `013b07979c8be999c70d47f32768c2bf959be086a893f60dde1b0f5e35d4f475`:
7532 /// `aomenc --codec=av1 --passes=1 --threads=1 --obu --lossless=1
7533 /// --cpu-used=0` over a 320x256, 4-frame source that is flat grey except a
7534 /// textured 64x128 patch in the top-right corner -- which is what makes the
7535 /// 128 root take `PARTITION_VERT` and code the `BLOCK_64X128` at mi(0,64).
7536 ///
7537 /// The counter delta keeps the gate non-vacuous: a stream that stopped
7538 /// coding the shape reads 0 and the gate fails instead of passing on a
7539 /// decode that never reached the fixed body (class
7540 /// `gate-blind-to-feature`).
7541 #[test]
7542 fn a_lossless_sb128_rect_intra_block_decodes_sample_exact() {
7543 const NAME: &str = "a_lossless_sb128_rect_intra_block_decodes_sample_exact";
7544 // The pixel arm needs ffmpeg; the decode and its counter deltas do
7545 // not, so a box without ffmpeg still proves the shape was reached
7546 // (class `gate-skips-on-its-own-failure`) -- the skip is still named.
7547 let ffmpeg = have_ffmpeg();
7548 if !ffmpeg {
7549 eprintln!("SKIP {NAME}: no ffmpeg -- the ffmpeg pixel arm only");
7550 }
7551 let (w, h, frames) = (320usize, 256usize, 4usize);
7552 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7553 .join("fixtures/lossless_sb128_rect_kf.obu");
7554 let stream = std::fs::read(&path)
7555 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
7556 let before = crate::decode::intra128_lossless_hits();
7557 let before_replay = crate::decode::sb128rect_chroma_replay_hits();
7558 let ours = decode_stream(&stream)
7559 .unwrap_or_else(|e| panic!("{NAME}: a lossless 128-axis key frame decodes: {e}"));
7560 let hits = crate::decode::intra128_lossless_hits() - before;
7561 assert!(
7562 hits > 0,
7563 "{NAME}: this stream coded NO lossless 128-axis intra block -- the fixed body \
7564 was never reached (class gate-blind-to-feature)"
7565 );
7566 // lane-av1-128rectspan: the 4:2:0 twin of the 4:4:4 gate's replay
7567 // assertion. This stream codes the 64x128 block at mi(0,64) with
7568 // TX_4X4 chroma units, so the end-of-block replay re-stamps each of
7569 // them over its own luma-mi rows -- the arm the span fix sits on, on
7570 // the OTHER admitted ss (1,1). The mismatch half is the 4:2:2
7571 // signature and reads 0 here because 4:2:2 is refused by name at the
7572 // sequence header; it is the tripwire for the day it is not.
7573 let after_replay = crate::decode::sb128rect_chroma_replay_hits();
7574 assert!(
7575 after_replay.0 > before_replay.0,
7576 "{NAME}: no 128-axis block replayed a chroma unit's own mi state -- the replay \
7577 arm never ran (class gate-blind-to-feature)"
7578 );
7579 assert_eq!(
7580 after_replay.1,
7581 before_replay.1,
7582 "{NAME}: the tail replay stamped {} unit(s) over a height that was not the \
7583 unit's own luma height (4:2:2 spans leaked into an admitted stream)",
7584 after_replay.1 - before_replay.1
7585 );
7586 eprintln!(
7587 "{NAME}: replayed {} chroma unit(s), {} span mismatch(es)",
7588 after_replay.0 - before_replay.0,
7589 after_replay.1 - before_replay.1
7590 );
7591 if !ffmpeg {
7592 return;
7593 }
7594 let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
7595 assert_eq!(ours.len(), frames, "{NAME}: decode-order frame count");
7596 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
7597 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
7598 .iter()
7599 .enumerate()
7600 {
7601 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
7602 assert_eq!(
7603 bad, 0,
7604 "{NAME}: frame {i} plane {plane}: {bad} samples differ from ffmpeg"
7605 );
7606 }
7607 }
7608 eprintln!("{NAME}: {frames} frames sample-exact, intra128_lossless hits {hits}");
7609 }
7610
7611 /// lane-av1-loss64: the generator for the two gates below -- a deterministic
7612 /// 1-frame lossless superblock-128 aomenc stream of `testsrc2`. `extra`
7613 /// flags land last (aomenc keeps the LAST occurrence of a repeated flag).
7614 /// The recipe is the one lanes/av1rect14.report.md section 2 measured
7615 /// (`--lossless=1 --sb-size=128 --enable-1to4-partitions=1`); the
7616 /// `--min-partition-size` override is what steers the bottom superblock
7617 /// row's RD into overhanging 64x64 `NONE` blocks (the shape the first fix
7618 /// clips) or, at 8, keeps sub-8x8 partitions out of the second gate's
7619 /// stream so the whole frame is decodable.
7620 fn lossless_sb128_testsrc2(width: usize, height: usize, extra: &[&str]) -> Vec<u8> {
7621 let mut ff = Command::new("ffmpeg");
7622 let out = ff
7623 .args(["-v", "error", "-f", "lavfi", "-i"])
7624 .arg(format!("testsrc2=s={width}x{height}:r=25"))
7625 .args([
7626 "-frames:v",
7627 "1",
7628 "-pix_fmt",
7629 "yuv420p",
7630 "-strict",
7631 "-1",
7632 "-f",
7633 "yuv4mpegpipe",
7634 "-",
7635 ])
7636 .stdin(Stdio::null())
7637 .stdout(Stdio::piped())
7638 .stderr(Stdio::piped())
7639 .output()
7640 .expect("ffmpeg failed to run");
7641 assert!(
7642 out.status.success(),
7643 "ffmpeg failed for testsrc2 {width}x{height}"
7644 );
7645 let y4m = out.stdout;
7646 let out = run_with_stdin(
7647 Command::new(aomenc_path())
7648 .args(["--codec=av1", "--bit-depth=8", "--input-bit-depth=8"])
7649 .args([
7650 "--passes=1",
7651 "--cpu-used=0",
7652 "--lag-in-frames=0",
7653 "--kf-max-dist=1",
7654 "--limit=1",
7655 "--threads=1",
7656 "--tile-columns=0",
7657 "--lossless=1",
7658 "--sb-size=128",
7659 "--enable-1to4-partitions=1",
7660 ])
7661 .args(extra)
7662 .args(["--obu", "-o", "-", "-"]),
7663 &y4m,
7664 );
7665 assert!(
7666 out.status.success(),
7667 "aomenc failed: {}",
7668 String::from_utf8_lossy(&out.stderr)
7669 );
7670 out.stdout
7671 }
7672
7673 /// lane-av1-loss64: a lossless superblock-128 frame whose intra blocks
7674 /// overhang the bottom frame edge codes NO coefficient symbols for the
7675 /// chroma transform units whose 4x4 origin sits outside the frame's mi
7676 /// grid -- libaom `decode_reconstruct_tx` returns before any read
7677 /// (`decodeframe.c:299`, `blk_row >= max_blocks_high || blk_col >=
7678 /// max_blocks_wide`, the limits from `max_block_wide/high`,
7679 /// av1_common_int.h:1565). The square multi-transform-unit chroma loop in
7680 /// [`crate::decode`] carried no such clip (the luma loop had one) and read
7681 /// `txb_skip`+coefficients for the phantom units: on the measured stream
7682 /// the first lossless 64x64 `NONE` block, at mi(48,0), overhangs the
7683 /// 240-px frame by 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units,
7684 /// not eight -- 32 phantom unit reads per plane desynced the tile and
7685 /// every later symbol (including partition reads, which is what made
7686 /// aomdec's zero-`value=8/9` census look like a partition-reader defect
7687 /// in the rect14 review) decoded as garbage.
7688 ///
7689 /// Fail-pre-fix, measured on the ed12fe52 probe: both arms differ from
7690 /// ffmpeg at byte 41120 (luma row 128 col 160, the first block decoded
7691 /// after the phantom reads). The counter delta pins non-vacuity (class
7692 /// `gate-blind-to-feature`): 96 clipped units on each arm.
7693 #[test]
7694 fn a_lossless_sb128_square_frame_clips_overhanging_chroma_tus() {
7695 const NAME: &str = "a_lossless_sb128_square_frame_clips_overhanging_chroma_tus";
7696 if !have_ffmpeg() {
7697 eprintln!("SKIP {NAME}: no ffmpeg");
7698 return;
7699 }
7700 // Arm 0 is the rect14 report's `loss320` recipe verbatim; arm 1 is its
7701 // `lnone` companion (1:4 and rect partitions off) -- both coded the
7702 // overhanging 64x64 blocks and both desynced at byte 41120 pre-fix.
7703 let arms: [&[&str]; 2] = [
7704 &["--min-partition-size=4"],
7705 &[
7706 "--min-partition-size=4",
7707 "--enable-1to4-partitions=0",
7708 "--enable-rect-partitions=0",
7709 ],
7710 ];
7711 let mut clips_total = 0usize;
7712 for (arm, extra) in arms.iter().enumerate() {
7713 let stream = lossless_sb128_testsrc2(320, 240, extra);
7714 crate::decode::reset_loss64_hits();
7715 let ours =
7716 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: arm {arm} decodes: {e}"));
7717 let clips = crate::decode::chroma_edge_tu_clip_hits();
7718 assert!(
7719 clips > 0,
7720 "{NAME}: arm {arm} clipped NO overhanging chroma transform unit -- \
7721 the fixed body was never reached (class gate-blind-to-feature)"
7722 );
7723 clips_total += clips;
7724 let refs = ffmpeg_decode_sequence(&stream, 320, 240, 1);
7725 assert_eq!(ours.len(), 1, "{NAME}: arm {arm} frame count");
7726 for (plane, (g, r)) in [
7727 (&ours[0].y, &refs[0].y),
7728 (&ours[0].u, &refs[0].u),
7729 (&ours[0].v, &refs[0].v),
7730 ]
7731 .iter()
7732 .enumerate()
7733 {
7734 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
7735 assert_eq!(
7736 bad, 0,
7737 "{NAME}: arm {arm} plane {plane}: {bad} samples differ from ffmpeg"
7738 );
7739 }
7740 }
7741 eprintln!("{NAME}: 2 arms full-frame exact, {clips_total} chroma units clipped");
7742 }
7743
7744 /// lane-av1-loss64: a SKIPPED intrabc rect strip on a lossless frame
7745 /// zeroes its whole entropy-band footprint (libaom
7746 /// `av1_reset_entropy_context`, `if (mbmi->skip_txfm)` decodeframe.c:1262 ->
7747 /// blockd.c:58) instead of leaving the previous occupant's luma bands
7748 /// standing. The skip arm of `decode_intrabc_owned_rect` never wrote the
7749 /// luma bands: the lossless `read_block_tx_size_rect` resolves the 4x4
7750 /// leaf list before it looks at `skip`, so the tail took the
7751 /// per-transform-unit record path (chroma only) with no per-unit luma
7752 /// writes ever run. The next block then read a STALE band: on the 320x242
7753 /// `--min-partition-size=4` sibling of this stream the skipped 8x16
7754 /// intrabc strip at mi(48,66) left a 7 in left[48] and mi(48,68)'s first
7755 /// transform unit read `txb_skip_ctx` 3 where aomdec reads 1 (measured
7756 /// `EC_ECDUMP` against the instrumented aomdec) -- a coefficient-walk
7757 /// desync at byte 61712 with every mode symbol still matching.
7758 ///
7759 /// This gate uses the same `--min-partition-size=4` arm that reaches the
7760 /// sub-8x8 VERT -> 4x8 skipped-intrabc leaf. Post-fix it is full-frame
7761 /// exact: the skip path uses libaom's clamped 4x4 chroma intrabc
7762 /// prediction (`decodeframe.c:1011-1065`, `reconinter_template.inc:186-207`)
7763 /// instead of the ordinary skipped-intra DC predictor. The old route first
7764 /// differed at U(104,92) with the entropy ladder fully synced.
7765 ///
7766 /// Fail-pre-fix, measured on the ed12fe52 probe: differs at byte 41120
7767 /// (the chroma-clip class, fixed in the same lane). Single-mutation on
7768 /// the lane tree with ONLY this gate's walk reverted: differs at byte
7769 /// 61712, the band-leak site.
7770 #[test]
7771 fn a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands() {
7772 const NAME: &str = "a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands";
7773 if !have_ffmpeg() {
7774 eprintln!("SKIP {NAME}: no ffmpeg");
7775 return;
7776 }
7777 let stream = lossless_sb128_testsrc2(320, 242, &["--min-partition-size=4"]);
7778 crate::decode::reset_loss64_hits();
7779 crate::decode::reset_skipped_intrabc_chroma_arm_hits();
7780 let ours = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: decodes: {e}"));
7781 let resets = crate::decode::skip_lossless_band_reset_hits();
7782 let intrabc_skips = crate::decode::skipped_intrabc_chroma_arm_hits();
7783 assert!(
7784 resets > 0,
7785 "{NAME}: this stream coded NO skipped lossless intrabc rect strip -- \
7786 the fixed body was never reached (class gate-blind-to-feature)"
7787 );
7788 assert!(
7789 intrabc_skips > 0,
7790 "{NAME}: this stream coded NO skipped sub-8x8 intrabc chroma leaf -- \
7791 the clamped chroma prediction fix was never reached (class gate-blind-to-feature)"
7792 );
7793 let refs = ffmpeg_decode_sequence(&stream, 320, 242, 1);
7794 assert_eq!(ours.len(), 1, "{NAME}: frame count");
7795 for (plane, (g, r)) in [
7796 (&ours[0].y, &refs[0].y),
7797 (&ours[0].u, &refs[0].u),
7798 (&ours[0].v, &refs[0].v),
7799 ]
7800 .iter()
7801 .enumerate()
7802 {
7803 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
7804 assert_eq!(
7805 bad, 0,
7806 "{NAME}: plane {plane}: {bad} samples differ from ffmpeg"
7807 );
7808 }
7809 eprintln!(
7810 "{NAME}: full-frame exact, {resets} band resets, \
7811 {intrabc_skips} skipped intrabc chroma predictions"
7812 );
7813 }
7814
7815 /// lane-av1-ibc444rect: an unskipped intrabc `BLOCK_8X4`/`BLOCK_4X8` leaf
7816 /// on a lossless 4:4:4 frame walks its coefficients as per-4x4 inter
7817 /// `TX_4X4` units on every plane -- `read_tx_size`'s lossless first line
7818 /// (`decodeframe.c:1203`) forces TX_4X4 before any tree, the frame's
7819 /// `TxMode` is `ONLY_4X4` so no var-tx tree is read either, and
7820 /// `av1_read_tx_type`'s qindex==0 early return (`decodemv.c:681`) drops
7821 /// the tx_type symbol the lossy 4x4 inter sets carry -- NOT the single
7822 /// `LumaRect8x4Inter`/`ChromaRect8x4` rect unit the non-lossless arm
7823 /// reads, and not the lossy per-unit arm's tx_type read.
7824 ///
7825 /// The pinned fixture `ll444_ibc_rect.obu` (99614 bytes, provenance in
7826 /// `lanes/av1ibc444rect.report.md`) is a lossless `--profile=1 --i444
7827 /// --enable-intrabc=1` key frame. r1 pinned the (then-known) leaf8
7828 /// `palette_window` panic as its alignment witness; with that blocker
7829 /// fixed upstream (lane-av1leaf8oob) the frame decodes to completion and
7830 /// this gate is the FULL-FRAME exact `aomdec` comparison its r1 doc
7831 /// promised, flipped by lane-av1-ibcskip2 -- which also closed the
7832 /// SKIPPED intrabc sub8 chroma cells the r1 measurement called out: a
7833 /// skipped intrabc leaf's chroma is the bare frame copy at the DV
7834 /// (libaom's `av1_build_inter_predictors_sb` runs regardless of `skip`),
7835 /// never the intra-DC push that arm used to run. Fail-before, measured on
7836 /// this tree with the DV-copy arm cut back to the intra push: 2794 U +
7837 /// 2830 V samples differ across 180 distinct 4x4 cells, 175 of them
7838 /// exactly this frame's skipped intrabc leaves, luma clean; with the arm,
7839 /// 0 differing samples on every plane.
7840 #[test]
7841 fn a_lossless_444_intrabc_rect_leaf_walks_per_4x4_units() {
7842 const NAME: &str = "a_lossless_444_intrabc_rect_leaf_walks_per_4x4_units";
7843 const FIXTURE_LEN: usize = 99614;
7844 const FIXTURE_FNV: u64 = 0xa1b6_a84e_ac6a_656f;
7845 const W: usize = 320;
7846 const H: usize = 240;
7847 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7848 .join("fixtures/ll444_ibc_rect.obu");
7849 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
7850 panic!(
7851 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
7852 which is a failure, not a skip",
7853 obu.display()
7854 )
7855 });
7856 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
7857 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
7858
7859 let _guard = lock_gate_counters();
7860 crate::decode::reset_ibc444rect_hits();
7861 crate::decode::reset_skipped_intrabc_dv_copy_hits();
7862 let frames = decode_stream(&stream).unwrap_or_else(|e| {
7863 panic!(
7864 "{NAME}: the fixture must decode to completion (the leaf8 \
7865 chroma buffers were fixed upstream): {e}"
7866 )
7867 });
7868 assert_eq!(frames.len(), 1, "{NAME}: shown frame count");
7869 let luma = crate::decode::intrabc_rect8_lossless_luma_hits();
7870 let chroma = crate::decode::intrabc_rect8_lossless_chroma_hits();
7871 assert_eq!(
7872 (luma, chroma),
7873 (339, 339),
7874 "{NAME}: the per-4x4 walk must fire on the fixture's full unskipped \
7875 intrabc rect census (got luma {luma}, chroma {chroma}) -- zero \
7876 means the fixture no longer reaches the fixed body (class \
7877 gate-blind-to-feature), more means the entropy desynced and \
7878 garbage blocks read as intrabc rect leaves"
7879 );
7880 let dv_skips = crate::decode::skipped_intrabc_dv_copy_hits();
7881 assert_eq!(
7882 dv_skips, 150,
7883 "{NAME}: the skipped-intrabc DV-copy chroma arm must fire on every \
7884 one of the fixture's 150 skipped intrabc leaves (got {dv_skips}) \
7885 -- zero means the arm is unreachable (class gate-blind-to-feature)"
7886 );
7887
7888 // The oracle aomdec, rawvideo out: one concatenated yuv444p frame.
7889 if aomdec_path().is_file() {
7890 let dir = std::env::temp_dir().join(format!("ec-av1-ibcskip2-{}", std::process::id()));
7891 let _ = std::fs::remove_dir_all(&dir);
7892 std::fs::create_dir_all(&dir).expect("scratch dir");
7893 let raw = dir.join("aomdec.raw");
7894 let out = Command::new(aomdec_path())
7895 .args(["--codec=av1", "--rawvideo", "-o"])
7896 .arg(&raw)
7897 .arg(&obu)
7898 .stdin(Stdio::null())
7899 .stdout(Stdio::piped())
7900 .stderr(Stdio::piped())
7901 .output()
7902 .expect("aomdec failed to run");
7903 assert!(
7904 out.status.success(),
7905 "{NAME}: the oracle aomdec refused the stream: {}",
7906 String::from_utf8_lossy(&out.stderr)
7907 );
7908 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
7909 let _ = std::fs::remove_dir_all(&dir);
7910 assert_eq!(ref_raw.len(), W * H * 3, "{NAME}: aomdec raw size");
7911 let f = &frames[0];
7912 for (plane, off, p) in [
7913 (&f.y, 0usize, "Y"),
7914 (&f.u, W * H, "U"),
7915 (&f.v, 2 * W * H, "V"),
7916 ] {
7917 let want = &ref_raw[off..off + W * H];
7918 let bad = plane
7919 .iter()
7920 .zip(want)
7921 .filter(|&(&a, &b)| a as u8 != b)
7922 .count();
7923 assert_eq!(
7924 bad, 0,
7925 "{NAME}: aomdec plane {p}: {bad} samples differ -- a \
7926 regression here reopens the skipped-intrabc sub8 chroma \
7927 predictor or the rect walk"
7928 );
7929 }
7930 } else {
7931 eprintln!(
7932 "SKIP {NAME} aomdec arm: no oracle aomdec at {}",
7933 aomdec_path().display()
7934 );
7935 }
7936 eprintln!(
7937 "{NAME}: frame sample-exact vs oracle aomdec; {luma}+{chroma} rect \
7938 walks, {dv_skips} skipped-intrabc DV copies"
7939 );
7940 }
7941
7942 /// lane-dkey: the palette-neighbour-band gate. A palette-Y block's size and
7943 /// colours used to stay standing in the mi-granular above/left bands after a
7944 /// sub-8x8 group was decoded next to it -- the sub-8x8 readers published
7945 /// skip/lf/mode state but no palette state, while libaom's mi grid carries
7946 /// `palette_size == 0` in exactly those cells (`av1_allow_palette` needs
7947 /// BLOCK_8X8 and up). The next intra block then read `palette_y_mode` off
7948 /// CDF row 1 where libaom reads row 0 (class `cdf-row-held-constant`),
7949 /// decoded a palette libaom never coded, and skipped the `use_filter_intra`
7950 /// symbol a palette block has none of: one symbol short, tile desynced.
7951 ///
7952 /// Measured on the instrumented aomdec at KEY-frame block mi(76,88) of this
7953 /// very stream (`EC_PALSYN_AOM ... ctx=0 y=0` against our `mode_ctx=1`).
7954 /// Without the fix every one of the 12 frames differs from ffmpeg's decode
7955 /// from luma sample 491904 on.
7956 ///
7957 /// The source is SYNTHETIC (no film sample lives in `fixtures`): the dark,
7958 /// near-flat background libaom's own screen-content detector counts as
7959 /// screen content (2..=4 distinct luma values per 16x16 block), which is
7960 /// what turns palette on, plus one textured patch at a HALF-PEL position on
7961 /// half the frames so the encoder splits that region down to 4x4 groups
7962 /// beside its palette blocks.
7963 #[test]
7964 fn a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact() {
7965 const NAME: &str =
7966 "a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact";
7967 if !have_ffmpeg() {
7968 eprintln!("SKIP {NAME}: no ffmpeg");
7969 return;
7970 }
7971 let (w, h, frames) = (1920usize, 1024usize, 12usize);
7972 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
7973 for f in 0..frames {
7974 let mut y = vec![0u8; w * h];
7975 for row in 0..h {
7976 for col in 0..w {
7977 y[row * w + col] =
7978 16 + ((col / 32 + row / 32) % 5) as u8 + ((col / 4 + row / 4) % 3) as u8;
7979 }
7980 }
7981 // 2.5 px per pair of frames: integer on one pair, half a pixel off
7982 // on the next (linear interpolation), so the patch's edges land
7983 // mid-sample and the encoder splits there.
7984 let x0 = 200.0 + 2.5 * (f / 2) as f64;
7985 let (fx, ix) = (x0.fract(), x0.floor() as usize);
7986 for row in 300..428 {
7987 for col in 0..192 {
7988 let tex = |u: f64| -> f64 {
7989 let v = (row - 300) as f64;
7990 30.0 + 100.0 * (0.5 + 0.5 * ((u * 0.35).sin() * (v * 0.21).cos()))
7991 };
7992 let s = tex(col as f64) * (1.0 - fx) + tex(col as f64 - 1.0) * fx;
7993 y[row * w + ix + col] = s.round().clamp(0.0, 255.0) as u8;
7994 }
7995 }
7996 raw.extend_from_slice(&y);
7997 raw.extend(std::iter::repeat_n(128u8, w * h / 2));
7998 }
7999 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
8000 let src = std::env::temp_dir().join(format!("ec-av1-palsub8-{}.yuv", std::process::id()));
8001 std::fs::write(&src, &raw).expect("raw source");
8002 let out = Command::new("ffmpeg")
8003 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
8004 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
8005 .arg(&src)
8006 .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"])
8007 .args([
8008 "-cpu-used",
8009 "6",
8010 "-b:v",
8011 "0",
8012 "-crf",
8013 "35",
8014 "-f",
8015 "obu",
8016 "-",
8017 ])
8018 .stdin(Stdio::null())
8019 .stdout(Stdio::piped())
8020 .stderr(Stdio::piped())
8021 .output()
8022 .expect("ffmpeg failed to run");
8023 let _ = std::fs::remove_file(&src);
8024 if !out.status.success() {
8025 eprintln!(
8026 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
8027 String::from_utf8_lossy(&out.stderr)
8028 );
8029 return;
8030 }
8031 let stream = out.stdout;
8032 let ours = decode_stream(&stream).expect("libaom screen-content stream decodes");
8033 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
8034 assert_eq!(ours.len(), frames, "{NAME}: shown frame count");
8035 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
8036 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
8037 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
8038 assert!(
8039 first.is_none(),
8040 "{NAME}: frame {i} plane {plane} differs from ffmpeg at sample {}",
8041 first.unwrap()
8042 );
8043 }
8044 }
8045 }
8046
8047 /// Hardened past the report-only test above: a real libaom-av1 gradients
8048 /// stream, pinned deterministic (`gradients`' own `seed=`, plus
8049 /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search
8050 /// cannot pick a different mode set run to run) and with CDEF turned off
8051 /// (this decoder's tile path never applies that in-loop filter -- see
8052 /// `cdef_is_active` in `decode_stream` -- so a stream that leaves it on
8053 /// decodes-but-wrong instead of refusing at cdef_bits==0; ffmpeg's
8054 /// `-enable-cdef 0` keeps this fixture out of that gap rather than this
8055 /// test working around it). Asserts pixel-exact against ffmpeg's own
8056 /// decode of the identical bytes, not just "decoded without error".
8057 #[test]
8058 fn a_real_libaom_gradients_stream_decodes_pixel_exact() {
8059 if !have_ffmpeg() {
8060 eprintln!("SKIP a_real_libaom_gradients_stream_decodes_pixel_exact: no ffmpeg");
8061 return;
8062 }
8063 let (width, height) = (64, 64);
8064 let stream = libaom_encode_with(
8065 &gradients_source(42, width, height, "rate=1"),
8066 width,
8067 height,
8068 15,
8069 &[
8070 "-threads",
8071 "1",
8072 "-row-mt",
8073 "0",
8074 "-tile-columns",
8075 "0",
8076 "-tile-rows",
8077 "0",
8078 "-enable-cdef",
8079 "0",
8080 ],
8081 )
8082 .expect("ffmpeg encode");
8083 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
8084 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
8085 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
8086 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
8087 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
8088 }
8089
8090 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but at
8091 /// 32x32 (below `is_cfl_allowed`'s 32x32 luma bound as a *single*
8092 /// undivided block, spec 5.11.5) rather than 64x64 -- a whole 64x64 SB
8093 /// is never CFL-eligible itself, only its <=32x32 partitions, and
8094 /// `testsrc2`/`gradients` at 64x64 with rect/ab/1to4/angle-delta search
8095 /// disabled reliably pick a whole-SB `PARTITION_NONE` (probed
8096 /// lane-av1real r2), so no fixture at that size exercises CfL at all.
8097 /// A 32x32 frame is exactly the whole-block, CFL-allowed case, and
8098 /// lane-av1real r2 found `gradients` there reliably selects
8099 /// `UV_CFL_PRED` (`uv_mode=13`) across a crf sweep -- `testsrc2` there
8100 /// stays DC. Proves the CfL port this round added, not just DC-chroma
8101 /// decode: pixel-exact against ffmpeg's own decode, not just "decoded".
8102 ///
8103 #[test]
8104 fn a_real_libaom_cfl_stream_decodes_pixel_exact() {
8105 if !have_ffmpeg() {
8106 eprintln!("SKIP a_real_libaom_cfl_stream_decodes_pixel_exact: no ffmpeg");
8107 return;
8108 }
8109 let (width, height) = (32, 32);
8110 let stream = libaom_encode_with(
8111 &gradients_source(42, width, height, "rate=1"),
8112 width,
8113 height,
8114 15,
8115 &[
8116 "-threads",
8117 "1",
8118 "-row-mt",
8119 "0",
8120 "-tile-columns",
8121 "0",
8122 "-tile-rows",
8123 "0",
8124 "-enable-cdef",
8125 "0",
8126 ],
8127 )
8128 .expect("ffmpeg encode");
8129 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
8130 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
8131 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
8132 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
8133 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
8134 }
8135
8136 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves
8137 /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
8138 /// proves `apply_cdef` itself, not just that this decoder still works
8139 /// when the filter never fires. Gradient content at a low crf reliably
8140 /// gives libaom something to dering. If a run happens to land on
8141 /// `cdef_bits > 0` (per-64x64 `cdef_idx`, still unimplemented -- see the
8142 /// refusal in `decode_stream`) the stream is skipped rather than failed:
8143 /// that gap is named by the refusal's own error text, not silently
8144 /// swallowed here.
8145 #[test]
8146 fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
8147 if !have_ffmpeg() {
8148 eprintln!(
8149 "SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: no ffmpeg"
8150 );
8151 return;
8152 }
8153 let (width, height) = (64, 64);
8154 let stream = libaom_encode_with(
8155 &gradients_source(42, width, height, "rate=1"),
8156 width,
8157 height,
8158 30,
8159 &[
8160 "-threads",
8161 "1",
8162 "-row-mt",
8163 "0",
8164 "-tile-columns",
8165 "0",
8166 "-tile-rows",
8167 "0",
8168 ],
8169 )
8170 .expect("ffmpeg encode");
8171 match decode_stream(&stream) {
8172 Ok(frames) => {
8173 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
8174 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (CDEF on)");
8175 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (CDEF on)");
8176 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (CDEF on)");
8177 }
8178 Err(e) => {
8179 eprintln!("SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: {e}");
8180 }
8181 }
8182 }
8183
8184 /// Path to a real `aomenc` build carrying the reference options this
8185 /// fixture needs (`--max-partition-size`, `--enable-tx-size-search`,
8186 /// `--loopfilter-control`) -- this box's `ffmpeg` links a libaom too old
8187 /// to expose `enable-tx-size-search`/`loopfilter-control` through its
8188 /// own `-aom-params` passthrough (probed live: "Cannot find aom
8189 /// option"), so [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]
8190 /// shells out to the standalone binary instead of ffmpeg's libaom-av1
8191 /// wrapper every other test here uses. `EC_AV1_AOMENC` overrides the
8192 /// default dev-build path; the test skips (not fails) when neither this
8193 /// nor `ffmpeg` is present.
8194 fn aomenc_path() -> std::path::PathBuf {
8195 if let Some(p) = std::env::var_os("EC_AV1_AOMENC") {
8196 return std::path::PathBuf::from(p);
8197 }
8198 // The oracle used to live only under `/tmp`, which this box's tmpfs
8199 // guard reclaims -- when it did, all 20 aomenc gates below went
8200 // silently vacuous (SKIP, suite still green). The durable location
8201 // is provisioned by `scripts/build-aom-oracle.sh`; the `/tmp` path
8202 // stays last as a legacy fallback.
8203 let mut candidates = Vec::new();
8204 if let Some(home) = std::env::var_os("HOME") {
8205 candidates.push(std::path::PathBuf::from(&home).join(".cache/aom-oracle/build/aomenc"));
8206 }
8207 candidates.push("/tmp/libaom-src/build/encoder/aomenc".into());
8208 candidates
8209 .iter()
8210 .find(|p| p.is_file())
8211 .cloned()
8212 .unwrap_or_else(|| candidates.remove(0))
8213 }
8214
8215 /// Whether the aomenc oracle is present. Absence normally SKIPs (a
8216 /// checkout without the oracle should still run the rest of the suite),
8217 /// but `EC_AV1_REQUIRE_AOMENC=1` turns it into a hard failure so a batch
8218 /// run cannot report green off 20 skipped gates.
8219 /// Where a pinned stream lives. `fixtures/` is a symlink to a durable
8220 /// directory outside the repo, so a pin captured in one session is still
8221 /// there in the next; a session scratchpad is not (tmpfs reaps it, and
8222 /// four pins were silently dead because of that).
8223 fn pin_dir() -> std::path::PathBuf {
8224 if let Some(p) = std::env::var_os("EC_AV1_PIN_DIR") {
8225 return std::path::PathBuf::from(p);
8226 }
8227 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8228 .join("../../fixtures")
8229 .canonicalize()
8230 .unwrap_or_else(|_| std::path::PathBuf::from("fixtures"))
8231 }
8232
8233 fn have_aomenc() -> bool {
8234 let present = aomenc_path().is_file();
8235 assert!(
8236 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
8237 "EC_AV1_REQUIRE_AOMENC is set but no aomenc at {} -- run scripts/build-aom-oracle.sh",
8238 aomenc_path().display()
8239 );
8240 present
8241 }
8242
8243 /// The instrumented `aomdec` beside the `aomenc` oracle
8244 /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`).
8245 fn aomdec_path() -> std::path::PathBuf {
8246 if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") {
8247 return std::path::PathBuf::from(p);
8248 }
8249 aomenc_path().with_file_name("aomdec")
8250 }
8251
8252 /// Decodes `stream` with both this decoder and the instrumented oracle
8253 /// `aomdec`, and compares EVERY decoded frame in DECODE order --
8254 /// including the hidden (`show_frame == 0`) alt-ref frames no other gate
8255 /// in this repo can see, because `decode_stream` only pushes shown
8256 /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames
8257 /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces
8258 /// only as drift on some later shown frame, if at all).
8259 ///
8260 /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it
8261 /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in
8262 /// `decode_stream`, the oracle's in rung 12 of
8263 /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as
8264 /// u16 LE. Returns `(frames_decoded, hidden_frames)`.
8265 fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) {
8266 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
8267 let _ = std::fs::remove_dir_all(&dir);
8268 std::fs::create_dir_all(&dir).expect("scratch dir");
8269 let obu = dir.join("in.obu");
8270 std::fs::write(&obu, stream).expect("writing the stream");
8271 let aom_prefix = dir.join("aom");
8272 let out = Command::new(aomdec_path())
8273 .args(["--codec=av1", "-o"])
8274 .arg(dir.join("out.y4m"))
8275 .arg(&obu)
8276 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
8277 .stdin(Stdio::null())
8278 .stdout(Stdio::piped())
8279 .stderr(Stdio::piped())
8280 .output()
8281 .expect("aomdec failed to run");
8282 assert!(
8283 out.status.success(),
8284 "{name}: the oracle aomdec refused the stream: {}",
8285 String::from_utf8_lossy(&out.stderr)
8286 );
8287 let count_dumps = |prefix: &std::path::Path| -> usize {
8288 let mut n = 0usize;
8289 while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() {
8290 n += 1;
8291 }
8292 n
8293 };
8294 let oracle_frames = count_dumps(&aom_prefix);
8295 assert!(
8296 oracle_frames > 0,
8297 "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \
8298 scripts/instrument-aom-oracle.sh is missing from {}",
8299 aomdec_path().display()
8300 );
8301 let ours_prefix = dir.join("ours");
8302 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
8303 let decoded = decode_stream(stream);
8304 set_final_dump_prefix(None);
8305 let shown = decoded
8306 .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}"))
8307 .len();
8308 let our_frames = count_dumps(&ours_prefix);
8309 assert_eq!(
8310 our_frames, oracle_frames,
8311 "{name}: decoded {our_frames} frames in decode order, the oracle decoded \
8312 {oracle_frames}"
8313 );
8314 for i in 0..oracle_frames {
8315 let want =
8316 std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
8317 let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
8318 assert_eq!(
8319 got.len(),
8320 want.len(),
8321 "{name}: decode-order frame {i} is {} bytes, the oracle's is {}",
8322 got.len(),
8323 want.len()
8324 );
8325 if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) {
8326 let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count();
8327 panic!(
8328 "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \
8329 hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \
8330 bytes differ -- stream pinned at {}",
8331 oracle_frames - shown,
8332 got[at],
8333 want[at],
8334 obu.display()
8335 );
8336 }
8337 }
8338 let hidden = oracle_frames - shown;
8339 let _ = std::fs::remove_dir_all(&dir);
8340 (oracle_frames, hidden)
8341 }
8342
8343 /// lane-hidden r2: the `--arnr-maxframes=0` SECOND ARM of an existing
8344 /// gate -- the gate's own recipe is never changed, this re-encodes the
8345 /// same fixture with libaom's temporal alt-ref filter switched off and
8346 /// runs [`decode_all_frames_vs_oracle`] on the result. Measured: with
8347 /// the filter at its default EVERY alt-ref recipe in this file emits
8348 /// ZERO hidden frames (the candidates are filtered away), so the
8349 /// hidden-frame compare on the gate's own stream is vacuous; this arm
8350 /// is what actually puts `show_frame == 0` frames on the wire.
8351 ///
8352 /// Runs at most once per gate name per process (the loop gates sweep
8353 /// dozens of attempts and each arm costs a full encode + two decodes).
8354 /// A stream this decoder refuses BY NAME skips the arm -- the arm is
8355 /// about hidden frames, not about that capability gap -- while a pixel
8356 /// mismatch is a hard failure raised inside the compare.
8357 fn hidden_arnr_arm(name: &str, y4m: &[u8], args: &[&str]) -> Option<(usize, usize)> {
8358 static ARMED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
8359 std::sync::OnceLock::new();
8360 if !ARMED
8361 .get_or_init(Default::default)
8362 .lock()
8363 .unwrap()
8364 .insert(name.to_string())
8365 {
8366 return None;
8367 }
8368 let mut arm: Vec<&str> = vec!["--arnr-maxframes=0"];
8369 arm.extend_from_slice(args);
8370 let out = run_with_stdin(Command::new(aomenc_path()).args(&arm), &y4m);
8371 assert!(
8372 out.status.success(),
8373 "{name} HIDDEN-ARM: aomenc refused its own recipe plus --arnr-maxframes=0: {}",
8374 String::from_utf8_lossy(&out.stderr)
8375 );
8376 let stream = out.stdout;
8377 match decode_stream(&stream) {
8378 Err(e) => {
8379 let msg = e.to_string();
8380 assert!(
8381 msg.contains("unsupported"),
8382 "{name} HIDDEN-ARM failed outright: {msg}"
8383 );
8384 eprintln!("{name} HIDDEN-ARM: skipped on a named refusal: {msg}");
8385 None
8386 }
8387 Ok(_) => Some(decode_all_frames_vs_oracle(
8388 &stream,
8389 &format!("{name}-arnr0"),
8390 )),
8391 }
8392 }
8393
8394 /// The repo's first hidden-frame pixel gate. Every other aomenc gate
8395 /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and
8396 /// both sides emit SHOWN frames only -- so an alt-ref frame that is
8397 /// decoded, stored into a reference slot and never displayed was, until
8398 /// this gate, never compared to anything (class
8399 /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the
8400 /// default `--lag-in-frames`, so they are full of exactly these frames.
8401 ///
8402 /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc
8403 /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's
8404 /// temporal filter on, this fixture's alt-ref candidates get filtered
8405 /// away and the encoder emits ZERO hidden frames (measured: 0 hidden
8406 /// with the filter on, 3 with it off), which would have made the gate
8407 /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so
8408 /// a recipe that stops producing hidden frames fails rather than skips.
8409 #[test]
8410 fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() {
8411 const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact";
8412 let _gate_lock = lock_gate_counters();
8413 if !have_ffmpeg() {
8414 eprintln!("SKIP {NAME}: no ffmpeg");
8415 return;
8416 }
8417 if !have_aomenc() {
8418 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8419 return;
8420 }
8421 for bit_depth in [8u32, 10u32] {
8422 let (width, height, frames) = (64usize, 64usize, 40usize);
8423 let duration = frames as f64 / 25.0;
8424 let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25");
8425 let pix_fmt = if bit_depth == 10 {
8426 "yuv420p10le"
8427 } else {
8428 "yuv420p"
8429 };
8430 let y4m = Command::new("ffmpeg")
8431 .args([
8432 "-v",
8433 "error",
8434 "-f",
8435 "lavfi",
8436 "-i",
8437 &source,
8438 "-t",
8439 &duration.to_string(),
8440 "-pix_fmt",
8441 pix_fmt,
8442 "-strict",
8443 "-1",
8444 "-f",
8445 "yuv4mpegpipe",
8446 "-",
8447 ])
8448 .stdin(Stdio::null())
8449 .stdout(Stdio::piped())
8450 .stderr(Stdio::piped())
8451 .output()
8452 .expect("ffmpeg failed to run");
8453 assert!(
8454 y4m.status.success(),
8455 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
8456 String::from_utf8_lossy(&y4m.stderr)
8457 );
8458 let depth_arg = format!("--bit-depth={bit_depth}");
8459 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
8460 let out = run_with_stdin(
8461 Command::new(aomenc_path()).args([
8462 // lane-defon r1: the repo's only gate that decodes hidden
8463 // frames is also the only place a FORWARD KEYFRAME can be
8464 // proven -- a KEY frame with `show_frame == 0`, which is
8465 // exactly the shape this gate already compares in decode
8466 // order. On-values go before the base list (aomenc keeps
8467 // the FIRST occurrence of a repeated flag).
8468 "--enable-fwd-kf=1",
8469 "--fwd-kf-dist=8",
8470 "--codec=av1",
8471 "--passes=1",
8472 "--end-usage=q",
8473 "--cq-level=45",
8474 "--cpu-used=0",
8475 "--threads=1",
8476 "--row-mt=0",
8477 "--kf-max-dist=1000",
8478 "--enable-order-hint=1",
8479 "--auto-alt-ref=1",
8480 "--lag-in-frames=25",
8481 "--arnr-maxframes=0",
8482 &depth_arg,
8483 &input_depth_arg,
8484 // The same tool set every sibling inter gate pins -- the
8485 // open capability gaps (rect/AB partitions, warped/OBMC,
8486 // masked compound, palette, ...) are other lanes' work;
8487 // this gate is about hidden frames, not about them.
8488 "--enable-warped-motion=0",
8489 // OBMC stays off HERE (this gate is about hidden frames);
8490 // the tool's own coverage is the `obmc*` gates and, on a
8491 // 16x8/8x16 leaf, the `--enable-obmc=1` arm of
8492 // `..._with_a_16_level_rect_leaf_...` (lane-inter4 r4).
8493 "--enable-obmc=0",
8494 "--enable-masked-comp=0",
8495 "--enable-interintra-comp=0",
8496 "--enable-onesided-comp=0",
8497 "--enable-interintra-wedge=0",
8498 "--enable-smooth-interintra=0",
8499 "--enable-rect-partitions=0",
8500 "--enable-ab-partitions=0",
8501 "--enable-1to4-partitions=0",
8502 "--enable-filter-intra=0",
8503 "--enable-smooth-intra=0",
8504 "--enable-paeth-intra=0",
8505 "--enable-directional-intra=0",
8506 "--enable-angle-delta=0",
8507 "--enable-tx-size-search=0",
8508 "--enable-cdef=0",
8509 "--enable-restoration=0",
8510 "--max-partition-size=32",
8511 "--min-partition-size=32",
8512 "--enable-palette=0",
8513 "--enable-intrabc=0",
8514 "--enable-cfl-intra=0",
8515 "--enable-ref-frame-mvs=0",
8516 "--obu",
8517 "-o",
8518 "-",
8519 "-",
8520 ]),
8521 &y4m.stdout,
8522 );
8523 assert!(
8524 out.status.success(),
8525 "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}",
8526 String::from_utf8_lossy(&out.stderr)
8527 );
8528 let stream = out.stdout;
8529 let fwd_kf_before = crate::decode::fwd_kf_hits();
8530 let (total, hidden) =
8531 decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit"));
8532 let fwd_kf = crate::decode::fwd_kf_hits() - fwd_kf_before;
8533 assert!(
8534 hidden >= 2,
8535 "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \
8536 {total} decoded -- the gate would be vacuous (class \
8537 gate-blind-to-hidden-frames)"
8538 );
8539 // lane-defon r1: `--enable-fwd-kf=1` is spelled on this recipe, so
8540 // a KEY frame with `show_frame == 0` must actually have been
8541 // decoded -- otherwise the on-value proves nothing.
8542 assert!(
8543 fwd_kf > 0,
8544 "{NAME}: the {bit_depth}-bit recipe decoded {total} frames ({hidden} hidden) but \
8545 zero forward keyframes -- --enable-fwd-kf=1 --fwd-kf-dist=8 never reached the \
8546 bitstream"
8547 );
8548 eprintln!(
8549 "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, {fwd_kf} \
8550 forward keyframes, all pixel-exact vs the oracle in decode order"
8551 );
8552 }
8553 }
8554
8555 /// A real `aomenc` filter-intra fixture: every other intra mode disabled
8556 /// (smooth/paeth/directional/angle-delta) and
8557 /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s
8558 /// <=32x32 bound means `use_filter_intra` never reads at all, spec
8559 /// 5.11.14), so the only way this frame codes is `DC_PRED` with filter
8560 /// intra on top -- `--loopfilter-control=0` is required too: this
8561 /// decoder has no in-loop deblocking filter at all, and libaom's default
8562 /// (on) smooths every block-boundary column, which first looked like a
8563 /// filter-intra math bug (mismatches straddling the 32-pixel block
8564 /// seam) until the recipe without it round-tripped byte-exact. Checks
8565 /// [`decode::filter_intra_hits`] actually moved (a process-global
8566 /// counter, so before/after rather than an absolute value) to prove the
8567 /// symbol fired, then pixel-exactness against ffmpeg's own decode of the
8568 /// identical bytes on every plane.
8569 #[test]
8570 fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {
8571 if !have_ffmpeg() {
8572 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no ffmpeg");
8573 return;
8574 }
8575 if !have_aomenc() {
8576 eprintln!(
8577 "SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no aomenc at {}",
8578 aomenc_path().display()
8579 );
8580 return;
8581 }
8582 let (width, height) = (64usize, 64usize);
8583 // Recipe-search hooks: with the encoder pinned to one thread the
8584 // stream is a deterministic function of (seed, cq), so a firing recipe
8585 // can be searched for without a rebuild.
8586 let fi_seed: u32 = std::env::var("EC_FI_SEED")
8587 .ok()
8588 .and_then(|v| v.parse().ok())
8589 .unwrap_or(42);
8590 let fi_source = gradients_source(fi_seed, 64, 64, "duration=0.04:rate=25");
8591 let fi_cq = std::env::var("EC_FI_CQ").unwrap_or_else(|_| "40".to_string());
8592 let fi_cq_arg = format!("--cq-level={fi_cq}");
8593 let y4m = Command::new("ffmpeg")
8594 .args([
8595 "-v",
8596 "error",
8597 "-f",
8598 "lavfi",
8599 "-i",
8600 &fi_source,
8601 "-pix_fmt",
8602 "yuv420p",
8603 "-f",
8604 "yuv4mpegpipe",
8605 "-",
8606 ])
8607 .stdin(Stdio::null())
8608 .stdout(Stdio::piped())
8609 .stderr(Stdio::piped())
8610 .output()
8611 .expect("ffmpeg failed to run");
8612 assert!(
8613 y4m.status.success(),
8614 "ffmpeg refused to generate the y4m fixture: {}",
8615 String::from_utf8_lossy(&y4m.stderr)
8616 );
8617 let out = run_with_stdin(
8618 Command::new(aomenc_path()).args([
8619 "--codec=av1",
8620 "--passes=1",
8621 "--end-usage=q",
8622 &fi_cq_arg,
8623 "--cpu-used=0",
8624 // Every sibling gate pins these; this one did not, and a
8625 // multi-threaded aomenc is not deterministic, so each run
8626 // encoded a slightly different stream and the gate flaked
8627 // against whichever features that run happened to pick.
8628 // Pinning them makes seed 42 mean one stream (class
8629 // `parallel-flake-is-attempt-selection`).
8630 "--threads=1",
8631 "--row-mt=0",
8632 "--enable-filter-intra=1",
8633 "--enable-smooth-intra=0",
8634 "--enable-paeth-intra=0",
8635 "--enable-directional-intra=0",
8636 "--enable-angle-delta=0",
8637 "--enable-tx-size-search=0",
8638 "--enable-cdef=0",
8639 "--max-partition-size=32",
8640 "--loopfilter-control=0",
8641 "--enable-palette=0",
8642 "--enable-intrabc=0",
8643 "--obu",
8644 "-o",
8645 "-",
8646 "-",
8647 ]),
8648 &y4m.stdout,
8649 );
8650 assert!(
8651 out.status.success(),
8652 "aomenc refused the fixture: {}",
8653 String::from_utf8_lossy(&out.stderr)
8654 );
8655 let stream = out.stdout;
8656 let before = decode::filter_intra_hits();
8657 // `screen_content_tools_determination` (libaom encoder_utils.c) is a
8658 // real internal trial-encode/PSNR comparison, not a flag this CLI
8659 // exposes a knob for -- on this flat gradient fixture it lands on
8660 // `allow_screen_content_tools=0` most runs but occasionally trips
8661 // over its 0.9 dB threshold the other way even with palette/intrabc
8662 // both disabled. That is a genuine separate gap (`decode_stream`
8663 // never reads `intrabc`/`palette_mode_info`), not a filter-intra
8664 // regression, so it is skipped here exactly as
8665 // `a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact`
8666 // above skips its own still-unsupported-gap runs.
8667 let frames = match decode_stream(&stream) {
8668 Ok(frames) => frames,
8669 Err(e) => {
8670 eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: {e}");
8671 return;
8672 }
8673 };
8674 assert!(
8675 decode::filter_intra_hits() > before,
8676 "use_filter_intra never fired decoding this stream"
8677 );
8678 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
8679 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
8680 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
8681 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
8682 }
8683
8684 /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`
8685 /// (SMPTE colour bars -- a handful of large flat luma regions, exactly
8686 /// the "flat, few-colour, repetitive" content `av1_choose_palette_map`'s
8687 /// RD trial rewards) with `hue=s=0` to flatten chroma to one constant
8688 /// value, so `DC_PRED` already nails every chroma block with zero
8689 /// residual and the encoder's own RD never has a reason to spend bits on
8690 /// a *UV* palette too (a real symbol this decoder still refuses --
8691 /// lane-palette r3's own scope is Y only). `smptebars` has no seed to
8692 /// vary, so the fixture is deterministic by construction; hashed twice
8693 /// below to prove it rather than assert it. `--enable-rect-partitions=0`
8694 /// / `-ab-` / `-1to4-` keep every intra block square, sidestepping the
8695 /// rect-strip screen-content refusal at `read_intra_mode_rect`
8696 /// (decode.rs ~2226) -- that refusal is this lane's own next milestone,
8697 /// not this gate's. `--sb-size=64` and `--threads=1 --row-mt=0` are the
8698 /// sibling-lane facts this charter paid for: a single 64x64 frame is one
8699 /// superblock either way, but pinning them keeps the recipe identical to
8700 /// every other gate in this file. HARD-asserts
8701 /// [`decode::palette_hits`] moved -- a stream that never reads a real
8702 /// palette block would refuse (or not) by construction without proving
8703 /// this milestone at all.
8704 ///
8705 /// lane-palette r4/r6/r7: r3/r4 found that this fixture's reconstructed
8706 /// pixels did not match ffmpeg's decode of the same bytes even though
8707 /// every symbol read by `decode_color_index_map` checked line-for-line
8708 /// against the oracle and matched. r6's range trace (`compare-range-not-tell`)
8709 /// pinned the real cause: `decode_color_index_map` was called from the
8710 /// wrong syntax position -- inline right after the Y colours, instead of
8711 /// after the whole mode-info read (UV palette mode_info + `filter_intra`,
8712 /// `av1_visit_palette`'s real call order). r7 ported the UV palette
8713 /// mode_info read and moved the colour-index-map decode after
8714 /// `filter_intra`; this gate now asserts a real pixel match instead of
8715 /// the old named refusal.
8716 #[test]
8717 fn a_real_aomenc_stream_with_palette_y_decodes_pixel_exact() {
8718 const NAME: &str = "a_real_aomenc_stream_with_palette_y_decodes_pixel_exact";
8719 if !have_ffmpeg() {
8720 eprintln!("SKIP {NAME}: no ffmpeg");
8721 return;
8722 }
8723 if !have_aomenc() {
8724 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8725 return;
8726 }
8727 let source = "smptebars=size=64x64:rate=25";
8728 fn render(source: &str) -> Vec<u8> {
8729 Command::new("ffmpeg")
8730 .args([
8731 "-v",
8732 "error",
8733 "-f",
8734 "lavfi",
8735 "-i",
8736 source,
8737 "-vf",
8738 "hue=s=0",
8739 "-pix_fmt",
8740 "yuv420p",
8741 "-t",
8742 "0.04",
8743 "-f",
8744 "yuv4mpegpipe",
8745 "-",
8746 ])
8747 .stdin(Stdio::null())
8748 .stdout(Stdio::piped())
8749 .stderr(Stdio::piped())
8750 .output()
8751 .expect("ffmpeg failed to run")
8752 .stdout
8753 }
8754 let y4m_a = render(source);
8755 let y4m_b = render(source);
8756 assert_eq!(
8757 y4m_a, y4m_b,
8758 "smptebars must render byte-identical across two runs"
8759 );
8760 let y4m = y4m_a;
8761 let out = run_with_stdin(
8762 Command::new(aomenc_path()).args([
8763 "--codec=av1",
8764 "--passes=1",
8765 "--end-usage=q",
8766 "--cq-level=30",
8767 "--cpu-used=0",
8768 "--threads=1",
8769 "--row-mt=0",
8770 "--sb-size=64",
8771 "--tune-content=screen",
8772 "--enable-palette=1",
8773 "--enable-intrabc=0",
8774 "--enable-rect-partitions=0",
8775 "--enable-ab-partitions=0",
8776 "--enable-1to4-partitions=0",
8777 "--min-partition-size=32",
8778 "--max-partition-size=32",
8779 "--enable-filter-intra=0",
8780 "--enable-smooth-intra=0",
8781 "--enable-paeth-intra=0",
8782 "--enable-directional-intra=0",
8783 "--enable-angle-delta=0",
8784 "--enable-cfl-intra=0",
8785 "--enable-cdef=0",
8786 "--enable-restoration=0",
8787 "--enable-tx-size-search=0",
8788 "--loopfilter-control=0",
8789 "--obu",
8790 "-o",
8791 "-",
8792 "-",
8793 ]),
8794 &y4m,
8795 );
8796 assert!(
8797 out.status.success(),
8798 "aomenc refused the fixture: {}",
8799 String::from_utf8_lossy(&out.stderr)
8800 );
8801 let stream = out.stdout;
8802 let before = decode::palette_hits();
8803 let frames = match decode_stream(&stream) {
8804 Ok(frames) => frames,
8805 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
8806 };
8807 assert!(
8808 decode::palette_hits() > before,
8809 "palette_y_mode never fired decoding this stream -- gate is vacuous"
8810 );
8811 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1);
8812 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
8813 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
8814 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
8815 }
8816
8817 /// lane-kf900 r3: the palette colour reader at BOTH bit depths.
8818 ///
8819 /// `read_palette_colors_y`/`_uv` (decode.rs, mirroring `decodemv.c:478`
8820 /// and `:509`) size every raw literal they read by the sequence's
8821 /// `bit_depth`: the first colour is `bit_depth` bits, `min_bits` is
8822 /// `bit_depth - 3` (Y/U) or `bit_depth - 4` (V), `range` starts at
8823 /// `1 << bit_depth`, and the clamp/wrap bound is `(1 << bit_depth) - 1`.
8824 /// Ours hardcoded 8, so every 10-bit palette block read TWO BITS TOO FEW
8825 /// per transmitted colour and silently decoded the rest of the tile from
8826 /// the wrong bit position.
8827 ///
8828 /// It was silent because raw literals are EQUIPROBABLE: at the ranges
8829 /// this content reaches an equiprobable read maps the msac range onto
8830 /// itself (62728 -> 31364 -> renormalised 62728), so a cross-decoder
8831 /// RANGE ladder stays bit-identical straight through the miscount and
8832 /// only the decoded VALUE moves. Pinned on a 256x192 10-bit
8833 /// `--cq-level=59` stream whose first block is a 32x16 palette: aomdec's
8834 /// `EC_PAL` ladder and ours agreed on every range and disagreed on the
8835 /// very first colour index (0 vs 1); after the fix all 1024 `EC_PAL`
8836 /// lines of that block match aomdec line for line.
8837 ///
8838 /// The recipe is the 8-bit `..._with_palette_y_...` gate's, with the
8839 /// depth as the only variable, so a failure here is the depth and
8840 /// nothing else. HARD-asserts [`decode::palette_hits`] moved on each arm
8841 /// (a stream with no real palette block would prove nothing) and
8842 /// compares all three planes against ffmpeg's decode of the same bytes.
8843 #[test]
8844 fn a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit() {
8845 const NAME: &str = "a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit";
8846 if !have_ffmpeg() {
8847 eprintln!("SKIP {NAME}: no ffmpeg");
8848 return;
8849 }
8850 if !have_aomenc() {
8851 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8852 return;
8853 }
8854 let (width, height) = (64usize, 64usize);
8855 for depth in [8usize, 10] {
8856 let pix_fmt = if depth == 10 {
8857 "yuv420p10le"
8858 } else {
8859 "yuv420p"
8860 };
8861 let render = || {
8862 Command::new("ffmpeg")
8863 .args([
8864 "-v",
8865 "error",
8866 "-f",
8867 "lavfi",
8868 "-i",
8869 "smptebars=size=64x64:rate=25",
8870 "-vf",
8871 "hue=s=0",
8872 "-pix_fmt",
8873 pix_fmt,
8874 "-strict",
8875 "-1",
8876 "-t",
8877 "0.04",
8878 "-f",
8879 "yuv4mpegpipe",
8880 "-",
8881 ])
8882 .stdin(Stdio::null())
8883 .stdout(Stdio::piped())
8884 .stderr(Stdio::piped())
8885 .output()
8886 .expect("ffmpeg failed to run")
8887 .stdout
8888 };
8889 let y4m_a = render();
8890 let y4m_b = render();
8891 assert_eq!(
8892 y4m_a, y4m_b,
8893 "{NAME}: smptebars must render byte-identical across two runs at {depth}-bit"
8894 );
8895 let y4m = y4m_a;
8896 let depth_arg = format!("--bit-depth={depth}");
8897 let input_depth_arg = format!("--input-bit-depth={depth}");
8898 let out = run_with_stdin(
8899 Command::new(aomenc_path())
8900 .args([
8901 "--codec=av1",
8902 "--passes=1",
8903 "--end-usage=q",
8904 "--cq-level=30",
8905 "--cpu-used=0",
8906 "--threads=1",
8907 "--row-mt=0",
8908 "--sb-size=64",
8909 "--tune-content=screen",
8910 "--enable-palette=1",
8911 "--enable-intrabc=0",
8912 "--enable-rect-partitions=0",
8913 "--enable-ab-partitions=0",
8914 "--enable-1to4-partitions=0",
8915 "--min-partition-size=32",
8916 "--max-partition-size=32",
8917 "--enable-filter-intra=0",
8918 "--enable-smooth-intra=0",
8919 "--enable-paeth-intra=0",
8920 "--enable-directional-intra=0",
8921 "--enable-angle-delta=0",
8922 "--enable-cfl-intra=0",
8923 "--enable-cdef=0",
8924 "--enable-restoration=0",
8925 "--enable-tx-size-search=0",
8926 "--loopfilter-control=0",
8927 "--limit=1",
8928 ])
8929 // Per-arm overrides go AFTER the base recipe: aomenc keeps the
8930 // LAST occurrence of a repeated flag.
8931 .args([&depth_arg, &input_depth_arg])
8932 .args(["--obu", "-o", "-", "-"]),
8933 &y4m,
8934 );
8935 assert!(
8936 out.status.success(),
8937 "{NAME}: aomenc refused the {depth}-bit fixture: {}",
8938 String::from_utf8_lossy(&out.stderr)
8939 );
8940 let stream = out.stdout;
8941 let before = decode::palette_hits();
8942 let frames = match decode_stream(&stream) {
8943 Ok(frames) => frames,
8944 Err(e) => panic!("{NAME}: decode_stream refused the {depth}-bit stream: {e}"),
8945 };
8946 assert!(
8947 decode::palette_hits() > before,
8948 "{NAME}: no real palette block at {depth}-bit -- gate is vacuous"
8949 );
8950 let ffmpeg_frames = if depth == 10 {
8951 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
8952 } else {
8953 ffmpeg_decode_sequence(&stream, width, height, 1)
8954 };
8955 assert_eq!(
8956 frames[0].y, ffmpeg_frames[0].y,
8957 "{NAME}: luma at {depth}-bit"
8958 );
8959 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U at {depth}-bit");
8960 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V at {depth}-bit");
8961 }
8962 }
8963
8964 /// lane-pal8 r1, the gate for a palette on a SQUARE 8x8 LEAF.
8965 ///
8966 /// `read_palette_mode_info` (decodemv.c:567) reads `palette_y_mode` for
8967 /// every `DC_PRED` block whose `av1_get_palette_bsize_ctx`
8968 /// (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`, 0 at 8x8) exists, and
8969 /// `av1_decode_palette_tokens` (decodeframe.c:1135, `av1_visit_palette`)
8970 /// reads the colour-index map after the WHOLE mode-info read. Ours passed
8971 /// `None`/`&[]` from [`decode::decode_leaf8`], reading the mode symbol off
8972 /// CDF row 0 and refusing "a block that actually uses a palette (Y) --
8973 /// reconstruction is out of scope" the moment it fired -- and at 8 bit
8974 /// aomenc palettes SQUARE blocks, so with `--min-partition-size=8` every
8975 /// 8-bit screen-content stream stopped there (lane-kf900 r4's measurement).
8976 ///
8977 /// Sweeps both bit depths x cq 30/40/55 x `--enable-tx-size-search` 0/1 x
8978 /// two lavfi sources (+ a `--tile-columns=1` arm, per the neighbour-map
8979 /// rule: the palette bands are per-mi and tile-guarded). Key frame only
8980 /// (`--limit=1`): the inter frames of these recipes stop on OTHER lanes'
8981 /// open refusals (8x8 inter leaf chroma mode, inter 1:4 partitions).
8982 /// HARD-asserts the 8x8-leaf palette counter moved on the compared arms
8983 /// and that no arm mismatched, in or out of scope.
8984 #[test]
8985 fn a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact() {
8986 const NAME: &str = "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact";
8987 if !have_ffmpeg() {
8988 eprintln!("SKIP {NAME}: no ffmpeg");
8989 return;
8990 }
8991 if !have_aomenc() {
8992 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
8993 return;
8994 }
8995 let (width, height) = (128usize, 128usize);
8996 let (mut leaf8_total, mut fired_arms, mut compared, mut frames_compared) =
8997 (0usize, 0u32, 0u32, 0usize);
8998 let (mut out_of_scope, mut out_of_scope_mismatch, mut refusals) = (0u32, 0u32, 0u32);
8999 let (mut sb_strip_total, mut sb_strip_arms) = (0usize, 0u32);
9000 // lane-t900 r34 LIFTED this shape; the counter stays so the gate
9001 // fails loudly if the refusal ever comes back.
9002 let mut sb_strip_refusals = 0u32;
9003 for src in ["testsrc2", "smptebars"] {
9004 for depth in [8usize, 10usize] {
9005 for cq in [30usize, 40, 55] {
9006 for txs in [0usize, 1] {
9007 for tiles in [0usize, 1] {
9008 let arm = format!("{src}-{depth}bit-cq{cq}-txs{txs}-tc{tiles}");
9009 let pix_fmt = if depth == 10 {
9010 "yuv420p10le"
9011 } else {
9012 "yuv420p"
9013 };
9014 let size = format!("{src}=size={width}x{height}:rate=25");
9015 let render = || {
9016 let out = Command::new("ffmpeg")
9017 .args([
9018 "-v",
9019 "error",
9020 "-f",
9021 "lavfi",
9022 "-i",
9023 &size,
9024 "-t",
9025 "0.04",
9026 "-pix_fmt",
9027 pix_fmt,
9028 "-strict",
9029 "-1",
9030 "-f",
9031 "yuv4mpegpipe",
9032 "-",
9033 ])
9034 .stdin(Stdio::null())
9035 .stdout(Stdio::piped())
9036 .stderr(Stdio::piped())
9037 .output()
9038 .expect("ffmpeg failed to run");
9039 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
9040 out.stdout
9041 };
9042 let y4m_a = render();
9043 let y4m_b = render();
9044 assert_eq!(
9045 y4m_a, y4m_b,
9046 "{NAME}: {arm} must render byte-identical across two runs"
9047 );
9048 let y4m = y4m_a;
9049 let depth_arg = format!("--bit-depth={depth}");
9050 let input_depth_arg = format!("--input-bit-depth={depth}");
9051 let cq_arg = format!("--cq-level={cq}");
9052 let txs_arg = format!("--enable-tx-size-search={txs}");
9053 let tiles_arg = format!("--tile-columns={tiles}");
9054 let out = run_with_stdin(
9055 Command::new(aomenc_path())
9056 .args([
9057 "--codec=av1",
9058 "--passes=1",
9059 "--end-usage=q",
9060 "--cpu-used=0",
9061 "--threads=1",
9062 "--row-mt=0",
9063 "--lag-in-frames=0",
9064 "--limit=1",
9065 "--sb-size=64",
9066 "--tune-content=screen",
9067 "--enable-palette=1",
9068 "--enable-intrabc=0",
9069 "--min-partition-size=8",
9070 "--enable-cdef=0",
9071 "--enable-restoration=0",
9072 "--loopfilter-control=0",
9073 ])
9074 // aomenc keeps the LAST occurrence of a repeated flag,
9075 // so per-arm overrides go after the base recipe.
9076 .args([
9077 &depth_arg,
9078 &input_depth_arg,
9079 &cq_arg,
9080 &txs_arg,
9081 &tiles_arg,
9082 ])
9083 .args(["--obu", "-o", "-", "-"]),
9084 &y4m,
9085 );
9086 assert!(
9087 out.status.success(),
9088 "{NAME}: aomenc refused {arm}: {}",
9089 String::from_utf8_lossy(&out.stderr)
9090 );
9091 let stream = out.stdout;
9092 decode::reset_palette_leaf8_hits();
9093 decode::reset_palette_sb_strip_hits();
9094 let decoded = decode_stream(&stream);
9095 let leaf8 = decode::palette_leaf8_hits();
9096 let sb_strip = decode::palette_sb_strip_hits();
9097 leaf8_total += leaf8;
9098 sb_strip_total += sb_strip;
9099 match decoded {
9100 Ok(frames) => {
9101 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
9102 let theirs = if depth == 10 {
9103 ffmpeg_decode_sequence_10bit(
9104 &stream,
9105 width,
9106 height,
9107 frames.len(),
9108 )
9109 } else {
9110 ffmpeg_decode_sequence(&stream, width, height, frames.len())
9111 };
9112 assert_eq!(
9113 frames.len(),
9114 theirs.len(),
9115 "{NAME}: {arm} frame count"
9116 );
9117 let mut same = true;
9118 for (i, (ours, ref_f)) in
9119 frames.iter().zip(theirs.iter()).enumerate()
9120 {
9121 let ok = ours.y == ref_f.y
9122 && ours.u == ref_f.u
9123 && ours.v == ref_f.v;
9124 if !ok {
9125 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
9126 }
9127 same &= ok;
9128 frames_compared += 1;
9129 }
9130 compared += 1;
9131 if sb_strip > 0 {
9132 sb_strip_arms += 1;
9133 assert!(
9134 same,
9135 "{NAME}: {arm} decoded {sb_strip} non-skip palette \
9136 block(s) on a superblock-level strip and did not \
9137 match ffmpeg"
9138 );
9139 }
9140 if leaf8 > 0 || sb_strip > 0 {
9141 fired_arms += 1;
9142 assert!(
9143 same,
9144 "{NAME}: {arm} decoded {leaf8} 8x8-leaf palette \
9145 block(s) and did not match ffmpeg"
9146 );
9147 } else {
9148 out_of_scope += 1;
9149 if !same {
9150 out_of_scope_mismatch += 1;
9151 }
9152 }
9153 eprintln!(
9154 "{NAME}: {arm} {} frame(s), {leaf8} 8x8-leaf palette \
9155 block(s), {sb_strip} superblock-strip palette \
9156 block(s), exact={same}",
9157 frames.len()
9158 );
9159 }
9160 Err(e) => {
9161 let msg = e.to_string();
9162 assert!(
9163 msg.contains("unsupported"),
9164 "{NAME}: {arm} decode failed: {e}"
9165 );
9166 // Named, counted, never turned into a skip.
9167 if msg.contains("superblock-level HORZ/VERT strip") {
9168 sb_strip_refusals += 1;
9169 }
9170 eprintln!("{NAME}: {arm} REFUSED: {e}");
9171 refusals += 1;
9172 }
9173 }
9174 }
9175 }
9176 }
9177 }
9178 }
9179 eprintln!(
9180 "{NAME}: {leaf8_total} 8x8-leaf palette block(s) across {fired_arms} arm(s), \
9181 {compared} arms compared ({frames_compared} frames), {sb_strip_total} \
9182 superblock-strip palette block(s) across {sb_strip_arms} arm(s), \
9183 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
9184 {refusals} refused ({sb_strip_refusals} superblock-strip palette)"
9185 );
9186 assert!(
9187 leaf8_total > 0 && fired_arms > 0,
9188 "{NAME}: gate is vacuous -- no compared arm decoded an 8x8-leaf palette block"
9189 );
9190 assert_eq!(
9191 sb_strip_refusals, 0,
9192 "{NAME}: the superblock-strip palette refusal is back (lane-t900 r34 lifted it)"
9193 );
9194 assert!(
9195 sb_strip_arms > 0 && sb_strip_total > 0,
9196 "{NAME}: no arm decoded a non-skip palette block on a superblock-level strip -- \
9197 the shape r34 lifted is no longer exercised"
9198 );
9199 assert_eq!(
9200 out_of_scope_mismatch, 0,
9201 "{NAME}: an out-of-scope arm mismatched ffmpeg -- a defect, never a skip"
9202 );
9203 assert!(
9204 frames_compared > 0,
9205 "{NAME}: no frame was compared pixel-exact"
9206 );
9207 }
9208
9209 /// lane-kf900 r5, the gate for the rect-strip `use_intrabc` read.
9210 ///
9211 /// `av1_allow_intrabc` is a FRAME-level test (`decodemv.c:892`,
9212 /// `read_intra_frame_mode_info`): on an intra frame whose header set
9213 /// `allow_intrabc`, EVERY intra block reads a `use_intrabc` symbol right
9214 /// after `skip`/`cdef`/`delta_q` and before `mbmi->mode`. There is no
9215 /// block-shape term, so rect strips read it exactly like square leaves --
9216 /// `read_intra_mode_rect` never did, and the arithmetic decoder desynced
9217 /// at the FIRST symbol of the first rect block of every
9218 /// `--tune-content=screen` key frame (measured: `testsrc2` 256x192 cq59
9219 /// 8-bit decoded "OK" with all 49152 luma samples wrong).
9220 ///
9221 /// Arm 0 is that recipe at cq50 without palette: its rect strips really do
9222 /// use intrabc. lane-av1-rect14 reconstructs those strips (2:1 and the
9223 /// 16x4/4x16 pair), so the arm must now decode pixel-exact -- and it must
9224 /// still have read the symbol. The named refusal remains only for a
9225 /// 128-superblock strip (`decode_block_128rect`), which this sb64 recipe
9226 /// does not reach.
9227 /// Arm 1 is the same recipe without palette and without tx-size search --
9228 /// it decodes the whole frame, reading the symbol dozens of times.
9229 /// Arm 2 is a screen-tools key frame whose header does NOT set
9230 /// `allow_intrabc` (cq63): it stays pixel-exact, proving the new read is
9231 /// not taken when libaom does not write it.
9232 ///
9233 /// PIXEL RESIDUE (open, lane-kf900 r5): arm 1's frame is entropy-exact
9234 /// against the instrumented aomdec for 429 mode-ladder elements and then
9235 /// diverges inside the DV read of a SQUARE intrabc block at mi(32,44), so
9236 /// its pixels are not compared here. That is a separate defect in
9237 /// `read_intrabc_dv`, not in the read this gate covers.
9238 #[test]
9239 fn a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips() {
9240 const NAME: &str = "a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips";
9241 if !have_ffmpeg() {
9242 eprintln!("SKIP {NAME}: no ffmpeg");
9243 return;
9244 }
9245 if !have_aomenc() {
9246 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9247 return;
9248 }
9249 let (width, height) = (256usize, 192usize);
9250 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
9251 // must_read_use_intrabc)
9252 const TS: &str = "testsrc2=s=256x192:r=25";
9253 const SB: &str = "smptebars=size=256x192:rate=25";
9254 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
9255 // must_read_use_intrabc_on_a_rect_strip)
9256 let arms: [(&str, &str, &[&str], bool, bool); 8] = [
9257 // lane-av1-intrabc (2026-09-20): this arm used to REFUSE here -- the
9258 // 16x8 rect strip it decodes is the first block on main that reaches
9259 // `decode_intrabc_rect`, so the whole arm stopped at a named refusal.
9260 // Reconstruction is ported now, so the arm decodes pixel-exact and
9261 // the `rect_total` assert below keeps it from quietly falling back
9262 // to an ordinary-intra decode of the same block.
9263 (
9264 "testsrc2-cq50-txs0",
9265 TS,
9266 &[
9267 "--cq-level=50",
9268 "--enable-palette=0",
9269 "--enable-tx-size-search=0",
9270 ],
9271 false,
9272 true,
9273 ),
9274 (
9275 "smptebars-cq40-txs0",
9276 SB,
9277 &[
9278 "--cq-level=40",
9279 "--enable-palette=0",
9280 "--enable-tx-size-search=0",
9281 ],
9282 false,
9283 false,
9284 ),
9285 (
9286 "smptebars-cq45-txs0",
9287 SB,
9288 &[
9289 "--cq-level=45",
9290 "--enable-palette=0",
9291 "--enable-tx-size-search=0",
9292 ],
9293 false,
9294 true,
9295 ),
9296 (
9297 "smptebars-cq45-txs1",
9298 SB,
9299 &[
9300 "--cq-level=45",
9301 "--enable-palette=0",
9302 "--enable-tx-size-search=1",
9303 ],
9304 false,
9305 false,
9306 ),
9307 (
9308 "smptebars-cq50-txs1",
9309 SB,
9310 &[
9311 "--cq-level=50",
9312 "--enable-palette=0",
9313 "--enable-tx-size-search=1",
9314 ],
9315 false,
9316 false,
9317 ),
9318 (
9319 "smptebars-cq55-txs0",
9320 SB,
9321 &[
9322 "--cq-level=55",
9323 "--enable-palette=0",
9324 "--enable-tx-size-search=0",
9325 ],
9326 false,
9327 false,
9328 ),
9329 (
9330 "testsrc2-cq63-txs1",
9331 TS,
9332 &[
9333 "--cq-level=63",
9334 "--enable-palette=0",
9335 "--enable-tx-size-search=1",
9336 ],
9337 false,
9338 false,
9339 ),
9340 // lane-kf900 r7: the 8x8-LEAF intrabc arm. Rect and 1:4
9341 // partitions off (so no rect strip refuses first), palette on,
9342 // `TxMode::Largest`: aomenc puts exactly one `use_intrabc` block
9343 // on a `BLOCK_8X8` leaf here, the shape `decode_leaf8` decoded as
9344 // ordinary intra before this round.
9345 (
9346 "testsrc2-cq55-leaf8",
9347 TS,
9348 &[
9349 "--cq-level=55",
9350 "--enable-palette=1",
9351 "--enable-tx-size-search=0",
9352 "--enable-rect-partitions=0",
9353 "--enable-1to4-partitions=0",
9354 ],
9355 false,
9356 false,
9357 ),
9358 ];
9359 let (mut reads_total, mut refused, mut frames_compared) = (0usize, 0u32, 0usize);
9360 let (mut blocks_total, mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) =
9361 (0usize, 0u32, 0u32, 0u32);
9362 let mut leaf8_total = 0usize;
9363 let mut rect_total = 0usize;
9364 for (arm, src, extra, expect_refusal, must_read) in &arms {
9365 let render = || {
9366 let out = Command::new("ffmpeg")
9367 .args([
9368 "-v",
9369 "error",
9370 "-f",
9371 "lavfi",
9372 "-i",
9373 *src,
9374 "-t",
9375 "0.2",
9376 "-pix_fmt",
9377 "yuv420p",
9378 "-strict",
9379 "-1",
9380 "-f",
9381 "yuv4mpegpipe",
9382 "-",
9383 ])
9384 .stdin(Stdio::null())
9385 .stdout(Stdio::piped())
9386 .stderr(Stdio::piped())
9387 .output()
9388 .expect("ffmpeg failed to run");
9389 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
9390 out.stdout
9391 };
9392 let y4m_a = render();
9393 let y4m_b = render();
9394 assert_eq!(
9395 y4m_a, y4m_b,
9396 "{NAME}: {arm} must render byte-identical across two runs"
9397 );
9398 let y4m = y4m_a;
9399 let out = run_with_stdin(
9400 Command::new(aomenc_path())
9401 .args([
9402 "--codec=av1",
9403 "--bit-depth=8",
9404 "--input-bit-depth=8",
9405 "--passes=1",
9406 "--end-usage=q",
9407 "--cpu-used=0",
9408 "--lag-in-frames=0",
9409 "--kf-max-dist=1",
9410 "--limit=1",
9411 "--threads=1",
9412 "--tile-columns=0",
9413 "--enable-rect-partitions=1",
9414 "--enable-1to4-partitions=1",
9415 "--min-partition-size=8",
9416 "--max-partition-size=32",
9417 "--sb-size=64",
9418 // `allow_screen_content_tools` (and with it the frame
9419 // header's `allow_intrabc` bit) comes from here.
9420 "--tune-content=screen",
9421 // Spelled so `gate_coverage` counts the tool as exercised
9422 // rather than defaulted (class `tool-disabled-in-every-gate`).
9423 "--enable-intrabc=1",
9424 ])
9425 // aomenc keeps the LAST occurrence of a repeated flag.
9426 .args(*extra)
9427 .args(["--obu", "-o", "-", "-"]),
9428 &y4m,
9429 );
9430 assert!(
9431 out.status.success(),
9432 "{NAME}: aomenc refused {arm}: {}",
9433 String::from_utf8_lossy(&out.stderr)
9434 );
9435 let stream = out.stdout;
9436 decode::reset_rect_intrabc_reads();
9437 crate::decode::reset_intrabc_hits();
9438 crate::decode::reset_leaf8_intrabc_hits();
9439 crate::decode::reset_intrabc_rect_hits();
9440 let decoded = decode_stream(&stream);
9441 let reads = decode::rect_intrabc_reads();
9442 // Blocks that decoded `use_intrabc == 1` (square path), i.e. that
9443 // read a DV and predicted from the current frame -- distinct from
9444 // `reads`, which counts rect strips that merely READ the flag.
9445 let blocks = crate::decode::intrabc_hits();
9446 reads_total += reads;
9447 blocks_total += blocks;
9448 // The 8x8-leaf shape has its own counter: without it this gate's
9449 // other arms (all rect/32x32 intrabc) would stay green while the
9450 // leaf path decoded an intrabc block as ordinary intra (class
9451 // `gate-blind-to-feature`).
9452 let leaf8 = crate::decode::leaf8_intrabc_hits();
9453 leaf8_total += leaf8;
9454 rect_total += crate::decode::intrabc_rect_hits();
9455 if *arm == "testsrc2-cq55-leaf8" {
9456 assert!(
9457 leaf8 > 0,
9458 "{NAME}: {arm} decoded no intrabc block at an 8x8 leaf -- the arm no longer exercises `decode_leaf8`'s intrabc path"
9459 );
9460 }
9461 if *must_read {
9462 assert!(
9463 reads > 0,
9464 "{NAME}: {arm} read no use_intrabc symbol on a rect strip -- the \
9465 arm no longer exercises the fix (allow_intrabc not set?)"
9466 );
9467 }
9468 match decoded {
9469 Ok(frames) => {
9470 assert!(
9471 !*expect_refusal,
9472 "{NAME}: {arm} decoded a frame whose rect strips use intrabc -- \
9473 reconstruction is not ported, it must refuse by name"
9474 );
9475 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
9476 let ffmpeg_frames =
9477 ffmpeg_decode_sequence(&stream, width, height, frames.len());
9478 assert_eq!(
9479 frames.len(),
9480 ffmpeg_frames.len(),
9481 "{NAME}: {arm} frame count"
9482 );
9483 // EVERY frame is compared; an arm whose decode never hit an
9484 // intrabc block proves nothing about the DV/prediction path,
9485 // so it is counted OUT OF SCOPE -- but a mismatch there is
9486 // still a failure (`out_of_scope_mismatch == 0`), never a skip.
9487 let mut same = true;
9488 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
9489 let ok = ours.y == theirs.y && ours.u == theirs.u && ours.v == theirs.v;
9490 if !ok {
9491 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
9492 }
9493 same &= ok;
9494 frames_compared += 1;
9495 }
9496 if blocks > 0 {
9497 fired_arms += 1;
9498 assert!(
9499 same,
9500 "{NAME}: {arm} decoded {blocks} intrabc block(s) and did not match ffmpeg"
9501 );
9502 } else {
9503 out_of_scope += 1;
9504 if !same {
9505 out_of_scope_mismatch += 1;
9506 }
9507 }
9508 eprintln!(
9509 "{NAME}: {arm} {} frame(s), {reads} rect use_intrabc reads, \
9510 {blocks} intrabc block(s), exact={same}",
9511 frames.len()
9512 );
9513 }
9514 Err(e) => {
9515 let msg = e.to_string();
9516 assert!(
9517 msg.contains("unsupported"),
9518 "{NAME}: {arm} decode failed: {e}"
9519 );
9520 assert!(
9521 *expect_refusal,
9522 "{NAME}: {arm} was expected to decode, it refused: {e}"
9523 );
9524 assert!(
9525 msg.contains("intra block copy") || msg.contains("intrabc"),
9526 "{NAME}: {arm} refused for an unrelated reason: {e}"
9527 );
9528 eprintln!("{NAME}: {arm} REFUSED (expected): {e}");
9529 refused += 1;
9530 }
9531 }
9532 }
9533 eprintln!(
9534 "{NAME}: {reads_total} rect-strip use_intrabc symbol(s) read, \
9535 {blocks_total} intrabc block(s) decoded across {fired_arms} arm(s), \
9536 {refused} refused by name, {frames_compared} frames compared, \
9537 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched)"
9538 );
9539 eprintln!(
9540 "{NAME}: {rect_total} intrabc block(s) on a HORZ/VERT rect strip (decode_intrabc_rect)"
9541 );
9542 assert!(
9543 reads_total > 0,
9544 "{NAME}: gate is vacuous -- no arm read the symbol"
9545 );
9546 assert!(
9547 leaf8_total > 0,
9548 "{NAME}: no arm decoded an intrabc block at an 8x8 leaf -- lane-kf900 r7's fix is untested"
9549 );
9550 assert!(
9551 blocks_total > 0 && fired_arms > 0,
9552 "{NAME}: gate is vacuous -- no compared arm actually decoded an intrabc block"
9553 );
9554 assert!(
9555 rect_total > 0,
9556 "{NAME}: no arm decoded an intrabc block on a HORZ/VERT rect strip -- \
9557 `decode_intrabc_rect` is untested"
9558 );
9559 // lane-av1-intrabc: this used to be exactly one -- the 2:1 rect strips
9560 // now reconstruct. The 1:4 pair strips (`decode_rect4_16_strip` et al.)
9561 // still refuse by name, but no arm HERE reaches that shape; it stays
9562 // pinned by `refusal_inventory`'s own gate.
9563 assert_eq!(refused, 0, "{NAME}: an arm still refuses by name");
9564 assert!(
9565 frames_compared > 0,
9566 "{NAME}: no frame was compared pixel-exact"
9567 );
9568 assert_eq!(
9569 out_of_scope_mismatch, 0,
9570 "{NAME}: an arm without an intrabc block still mismatched ffmpeg"
9571 );
9572 }
9573
9574 /// lane-av1-rect14: the 16x4/4x16 intrabc pair. libaom codes the pair's
9575 /// chroma on the odd-mi strip only (`is_chroma_reference`,
9576 /// av1_common_int.h:1454). The witness is the report recipe: testsrc2
9577 /// 640x480 cq60 palette, txs off, which places a 16x4 intrabc strip at
9578 /// mi(76,108). Pre-fix this refused by name. VERT_4 was not produced by
9579 /// any fully-decoded recipe tried here (the allintra stream codes four
9580 /// `PARTITION_VERT_4` at bsize 6 and then stops on the unrelated var-tx
9581 /// mixed-leaf refusal); the VERT arm is the same body with the axes
9582 /// swapped.
9583 #[test]
9584 fn a_16x4_intrabc_pair_strip_decodes_pixel_exact() {
9585 const NAME: &str = "a_16x4_intrabc_pair_strip_decodes_pixel_exact";
9586 if !have_ffmpeg() || !have_aomenc() {
9587 eprintln!("SKIP {NAME}: ffmpeg/aomenc missing");
9588 return;
9589 }
9590 let (width, height) = (640usize, 480usize);
9591 let y4m = Command::new("ffmpeg")
9592 .args([
9593 "-v",
9594 "error",
9595 "-f",
9596 "lavfi",
9597 "-i",
9598 "testsrc2=s=640x480:r=25",
9599 "-frames:v",
9600 "1",
9601 "-pix_fmt",
9602 "yuv420p",
9603 "-strict",
9604 "-1",
9605 "-f",
9606 "yuv4mpegpipe",
9607 "-",
9608 ])
9609 .output()
9610 .expect("ffmpeg")
9611 .stdout;
9612 let out = run_with_stdin(
9613 Command::new(aomenc_path()).args([
9614 "--codec=av1",
9615 "--bit-depth=8",
9616 "--input-bit-depth=8",
9617 "--passes=1",
9618 "--end-usage=q",
9619 "--cpu-used=0",
9620 "--lag-in-frames=0",
9621 "--kf-max-dist=1",
9622 "--limit=1",
9623 "--threads=1",
9624 "--tile-columns=0",
9625 "--enable-rect-partitions=1",
9626 "--enable-1to4-partitions=1",
9627 "--min-partition-size=4",
9628 "--max-partition-size=64",
9629 "--sb-size=64",
9630 "--tune-content=screen",
9631 "--enable-intrabc=1",
9632 "--cq-level=60",
9633 "--enable-palette=1",
9634 "--enable-tx-size-search=0",
9635 "--obu",
9636 "-o",
9637 "-",
9638 "-",
9639 ]),
9640 &y4m,
9641 );
9642 assert!(out.status.success(), "{NAME}: aomenc failed");
9643 crate::decode::reset_rect4_16_pair_hits();
9644 let frames = decode_stream(&out.stdout).unwrap_or_else(|e| panic!("{NAME}: {e}"));
9645 assert!(
9646 crate::decode::rect4_16_intrabc_hits() > 0,
9647 "{NAME}: no 16x4/4x16 intrabc strip -- the pair body was not reached"
9648 );
9649 let refs = ffmpeg_decode_sequence(&out.stdout, width, height, frames.len());
9650 assert_eq!(frames.len(), 1);
9651 assert_eq!(frames[0].y, refs[0].y, "{NAME}: luma");
9652 assert_eq!(frames[0].u, refs[0].u, "{NAME}: u");
9653 assert_eq!(frames[0].v, refs[0].v, "{NAME}: v");
9654 }
9655
9656 /// lane-av1-rect14: lossless 16x4/4x16 chroma is two TX_4X4s, not one
9657 /// TX_8X4. The measured site is luma col 108 of a 320x240 sb128 lossless
9658 /// key frame (lanes/av1lossless128.report.md §6). Rows 0-127 of that
9659 /// frame -- the first superblock row, which contains the site -- must
9660 /// match ffmpeg. A later mismatch is the pre-existing 64x64 square
9661 /// lossless residue (base fails at byte 108; this lane's first remaining
9662 /// mismatch is row 128). The gate fails if that residue moves back into
9663 /// the repaired region.
9664 #[test]
9665 fn a_lossless_16x4_chroma_pair_repairs_the_measured_site() {
9666 const NAME: &str = "a_lossless_16x4_chroma_pair_repairs_the_measured_site";
9667 if !have_ffmpeg() || !have_aomenc() {
9668 eprintln!("SKIP {NAME}: ffmpeg/aomenc missing");
9669 return;
9670 }
9671 let (width, height) = (320usize, 240usize);
9672 let y4m = Command::new("ffmpeg")
9673 .args([
9674 "-v",
9675 "error",
9676 "-f",
9677 "lavfi",
9678 "-i",
9679 "testsrc2=s=320x240:r=25",
9680 "-frames:v",
9681 "1",
9682 "-pix_fmt",
9683 "yuv420p",
9684 "-strict",
9685 "-1",
9686 "-f",
9687 "yuv4mpegpipe",
9688 "-",
9689 ])
9690 .output()
9691 .expect("ffmpeg")
9692 .stdout;
9693 let out = run_with_stdin(
9694 Command::new(aomenc_path()).args([
9695 "--codec=av1",
9696 "--cpu-used=0",
9697 "--lossless=1",
9698 "--sb-size=128",
9699 "--lag-in-frames=0",
9700 "--kf-max-dist=1",
9701 "--limit=1",
9702 "--threads=1",
9703 "--passes=1",
9704 "--enable-1to4-partitions=1",
9705 "--min-partition-size=4",
9706 "--enable-rect-partitions=1",
9707 "--obu",
9708 "-o",
9709 "-",
9710 "-",
9711 ]),
9712 &y4m,
9713 );
9714 assert!(out.status.success(), "{NAME}: aomenc failed");
9715 crate::decode::reset_rect4_16_pair_hits();
9716 let frames = decode_stream(&out.stdout).unwrap_or_else(|e| panic!("{NAME}: {e}"));
9717 assert!(
9718 crate::decode::rect4_16_lossless_chroma_hits() > 0,
9719 "{NAME}: no lossless 16x4/4x16 chroma pair -- the walk was not reached"
9720 );
9721 let refs = ffmpeg_decode_sequence(&out.stdout, width, height, frames.len());
9722 let repaired = 128 * width;
9723 assert_eq!(
9724 &frames[0].y[..repaired],
9725 &refs[0].y[..repaired],
9726 "{NAME}: luma rows 0-127 (the measured col-108 site) diverged"
9727 );
9728 let chroma_rows = 64 * (width / 2);
9729 assert_eq!(
9730 &frames[0].u[..chroma_rows],
9731 &refs[0].u[..chroma_rows],
9732 "{NAME}: u"
9733 );
9734 assert_eq!(
9735 &frames[0].v[..chroma_rows],
9736 &refs[0].v[..chroma_rows],
9737 "{NAME}: v"
9738 );
9739 // The col-108 byte specifically, so a shift of the old site still fails
9740 // even if some other prefix sample happens to match.
9741 assert_eq!(
9742 frames[0].y[108], refs[0].y[108],
9743 "{NAME}: measured byte 108"
9744 );
9745 }
9746 /// lane-av1-intrabc r4: the reviewer's unblock witness for the rect-strip
9747 /// reconstruction -- a CODED `use_intrabc` block (so its residual reader
9748 /// runs, not just the prediction copy) on a 2:1 strip in BOTH
9749 /// orientations, plus the `TX_MODE_SELECT` (var-tx) shape, every arm
9750 /// byte-exact against ffmpeg.
9751 ///
9752 /// The orientation counters (`intrabc_rect_coded_hits`) are the
9753 /// non-vacuity instrument: [`intrabc_rect_hits`] counts neither the skip
9754 /// flag nor the orientation, so an arm that silently became an all-skip
9755 /// stream (or a stream with only one orientation) would keep the old gate
9756 /// green while the coded residual path went untested
9757 /// (class `gate-blind-to-feature`).
9758 ///
9759 /// # The VERT arm is also the DV-PREDICTOR regression witness
9760 ///
9761 /// The 512x384 arm is the stream that exposed r4's defect: 528 of 294912
9762 /// luma samples were wrong, all inside one `skip == 1` intrabc copy at
9763 /// `mi(84,104)`. Its coded diff was identical to aomdec's and the post-read
9764 /// range matched exactly (`rng=33207` both), so nothing was misread -- the
9765 /// DV PREDICTOR differed. libaom picks `nearestmv` (`-520`) from the
9766 /// `INTRA_FRAME` MV stack; this decoder picked `-512`, one stack entry
9767 /// lower, because the scan that builds that stack walked further than
9768 /// libaom's. The scans step by the candidate BLOCK's own width
9769 /// (`mi_size_wide[bsize]`) over `xd->mi[]`, which holds an entry for every
9770 /// coded block; this decoder's MV grid held only the intrabc blocks, so a
9771 /// non-intrabc neighbour read as uncovered and the scan advanced that cell
9772 /// by one instead of by its real width. See `MiGrid::cover` for the
9773 /// measured walk. A stream that decodes the DV predictor from the wrong
9774 /// stack entry cannot pass this arm's pixel comparison.
9775 #[test]
9776 fn a_coded_rect_intrabc_block_reconstructs_in_both_orientations() {
9777 const NAME: &str = "a_coded_rect_intrabc_block_reconstructs_in_both_orientations";
9778 if !have_ffmpeg() {
9779 eprintln!("SKIP {NAME}: no ffmpeg");
9780 return;
9781 }
9782 if !have_aomenc() {
9783 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9784 return;
9785 }
9786 const TS256: &str = "testsrc2=s=256x192:r=25";
9787 const TS512: &str = "testsrc2=s=512x384:r=25";
9788 // (arm, source, width, height, per-arm overrides, the coded orientation
9789 // this arm must exercise, and whether the frame must code
9790 // `TX_MODE_SELECT` with `allow_intrabc` still set)
9791 let arms: [(&str, &str, usize, usize, &[&str], u8, bool); 3] = [
9792 // HORZ (16x8) coded strip -- the shape the in-gate witness above
9793 // already reconstructs, pinned here with its own orientation counter.
9794 (
9795 "horz-coded-256-cq45-pal0-txs0",
9796 TS256,
9797 256,
9798 192,
9799 &[
9800 "--cq-level=45",
9801 "--enable-palette=0",
9802 "--enable-tx-size-search=0",
9803 ],
9804 0,
9805 false,
9806 ),
9807 // VERT (8x16) coded strip AND the DV-predictor regression stream.
9808 (
9809 "vert-coded-512-cq45-pal1-txs0",
9810 TS512,
9811 512,
9812 384,
9813 &[
9814 "--cq-level=45",
9815 "--enable-palette=1",
9816 "--enable-tx-size-search=0",
9817 ],
9818 1,
9819 false,
9820 ),
9821 // The `TX_MODE_SELECT` (stream A) shape: `--enable-tx-size-search=1`
9822 // makes the frame code `tx_mode == Select`, so the intrabc block's
9823 // transform size comes off the INTER var-tx tree.
9824 (
9825 "txmode-select-256-cq45-pal0-txs1",
9826 TS256,
9827 256,
9828 192,
9829 &[
9830 "--cq-level=45",
9831 "--enable-palette=0",
9832 "--enable-tx-size-search=1",
9833 ],
9834 0,
9835 true,
9836 ),
9837 ];
9838 let mut coded_total = [0usize; 2];
9839 let mut frames_compared = 0usize;
9840 for (arm, src, width, height, extra, want_orient, want_select) in &arms {
9841 let render = || {
9842 let out = Command::new("ffmpeg")
9843 .args([
9844 "-v",
9845 "error",
9846 "-f",
9847 "lavfi",
9848 "-i",
9849 *src,
9850 "-t",
9851 "0.2",
9852 "-pix_fmt",
9853 "yuv420p",
9854 "-strict",
9855 "-1",
9856 "-f",
9857 "yuv4mpegpipe",
9858 "-",
9859 ])
9860 .stdin(Stdio::null())
9861 .stdout(Stdio::piped())
9862 .stderr(Stdio::piped())
9863 .output()
9864 .expect("ffmpeg failed to run");
9865 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
9866 out.stdout
9867 };
9868 let y4m = render();
9869 let out = run_with_stdin(
9870 Command::new(aomenc_path())
9871 .args([
9872 "--codec=av1",
9873 "--bit-depth=8",
9874 "--input-bit-depth=8",
9875 "--passes=1",
9876 "--end-usage=q",
9877 "--cpu-used=0",
9878 "--lag-in-frames=0",
9879 "--kf-max-dist=1",
9880 "--limit=1",
9881 "--threads=1",
9882 "--tile-columns=0",
9883 "--enable-rect-partitions=1",
9884 "--enable-1to4-partitions=1",
9885 "--min-partition-size=8",
9886 "--max-partition-size=32",
9887 "--sb-size=64",
9888 "--tune-content=screen",
9889 "--enable-intrabc=1",
9890 ])
9891 // aomenc keeps the LAST occurrence of a repeated flag.
9892 .args(*extra)
9893 .args(["--obu", "-o", "-", "-"]),
9894 &y4m,
9895 );
9896 assert!(
9897 out.status.success(),
9898 "{NAME}: aomenc refused {arm}: {}",
9899 String::from_utf8_lossy(&out.stderr)
9900 );
9901 let stream = out.stdout;
9902 if *want_select {
9903 let (select, premise) = tx_select_and_intrabc_frames(&stream);
9904 assert!(
9905 select > 0 && premise > 0,
9906 "{NAME}: {arm} no longer codes a frame with both tx_mode == Select and \
9907 allow_intrabc (select={select} premise={premise}), so the TX_MODE_SELECT \
9908 shape is untested here"
9909 );
9910 }
9911 crate::decode::reset_intrabc_rect_hits();
9912 let frames =
9913 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {arm} refused: {e}"));
9914 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
9915 let coded = crate::decode::intrabc_rect_coded_hits();
9916 coded_total[0] += coded[0];
9917 coded_total[1] += coded[1];
9918 assert!(
9919 coded[*want_orient as usize] > 0,
9920 "{NAME}: {arm} reconstructed no CODED ({}) rect intrabc block -- the residual \
9921 reader for this orientation is untested (coded horz/vert = {coded:?})",
9922 if *want_orient == 0 { "HORZ" } else { "VERT" }
9923 );
9924 let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len());
9925 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
9926 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
9927 assert!(
9928 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
9929 "{NAME}: {arm} frame {i} does not match ffmpeg"
9930 );
9931 frames_compared += 1;
9932 }
9933 eprintln!(
9934 "{NAME}: {arm} {} frame(s) exact, coded rect intrabc horz={} vert={}",
9935 frames.len(),
9936 coded[0],
9937 coded[1]
9938 );
9939 }
9940 assert!(
9941 coded_total[0] > 0 && coded_total[1] > 0,
9942 "{NAME}: gate is vacuous -- coded rect intrabc blocks seen: horz={} vert={}",
9943 coded_total[0],
9944 coded_total[1]
9945 );
9946 assert!(
9947 frames_compared > 0,
9948 "{NAME}: no frame was compared pixel-exact"
9949 );
9950
9951 // lane-av1-intrabc r5: the SKIPPED VERT 2:1 strip -- the arm the
9952 // reviewer's sweep panicked on (a skipped 8x32 strip passed a
9953 // `bw * bh`-sized ZERO_RESIDUAL slice at stride `side`, and
9954 // `reconstruct_mc_rect` indexed `row * side + w` past its end).
9955 // Skip-heavy recipes (low cq, palette off AND on), each decoded
9956 // byte-exact vs ffmpeg on BOTH the default single-threaded path
9957 // (`EC_AV1_RECON_THREADS == 1`, the inline ReconPlanes arm that
9958 // panicked pre-fix) AND the wavefront path. The skipped-orientation
9959 // counter is asserted per arm (`gate-blind-to-feature`): a recipe
9960 // that stops producing a skipped VERT strip fails instead of passing
9961 // vacuously. `lock_gate_counters` because `set_recon_threads` is a
9962 // process-wide knob.
9963 let _par_lock = lock_gate_counters();
9964 let skip_arms: [(&str, &str, usize, usize, &[&str]); 2] = [
9965 (
9966 "vert-skip-512-cq30-pal0-txs0",
9967 TS512,
9968 512,
9969 384,
9970 &[
9971 "--cq-level=30",
9972 "--enable-palette=0",
9973 "--enable-tx-size-search=0",
9974 ],
9975 ),
9976 (
9977 "vert-skip-512-cq30-pal1-txs0",
9978 TS512,
9979 512,
9980 384,
9981 &[
9982 "--cq-level=30",
9983 "--enable-palette=1",
9984 "--enable-tx-size-search=0",
9985 ],
9986 ),
9987 ];
9988 for (arm, src, width, height, extra) in &skip_arms {
9989 let y4m = {
9990 let out = Command::new("ffmpeg")
9991 .args([
9992 "-v",
9993 "error",
9994 "-f",
9995 "lavfi",
9996 "-i",
9997 *src,
9998 "-t",
9999 "0.2",
10000 "-pix_fmt",
10001 "yuv420p",
10002 "-strict",
10003 "-1",
10004 "-f",
10005 "yuv4mpegpipe",
10006 "-",
10007 ])
10008 .stdin(Stdio::null())
10009 .stdout(Stdio::piped())
10010 .stderr(Stdio::piped())
10011 .output()
10012 .expect("ffmpeg failed to run");
10013 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
10014 out.stdout
10015 };
10016 let out = run_with_stdin(
10017 Command::new(aomenc_path())
10018 .args([
10019 "--codec=av1",
10020 "--bit-depth=8",
10021 "--input-bit-depth=8",
10022 "--passes=1",
10023 "--end-usage=q",
10024 "--cpu-used=0",
10025 "--lag-in-frames=0",
10026 "--kf-max-dist=1",
10027 "--limit=1",
10028 "--threads=1",
10029 "--tile-columns=0",
10030 "--enable-rect-partitions=1",
10031 "--enable-1to4-partitions=1",
10032 "--min-partition-size=8",
10033 "--max-partition-size=32",
10034 "--sb-size=64",
10035 "--tune-content=screen",
10036 "--enable-intrabc=1",
10037 ])
10038 // aomenc keeps the LAST occurrence of a repeated flag.
10039 .args(*extra)
10040 .args(["--obu", "-o", "-", "-"]),
10041 &y4m,
10042 );
10043 assert!(
10044 out.status.success(),
10045 "{NAME}: aomenc refused {arm}: {}",
10046 String::from_utf8_lossy(&out.stderr)
10047 );
10048 let stream = out.stdout;
10049 // Default single-threaded path first (the arm that panicked
10050 // pre-fix), then the wavefront path; both must match ffmpeg.
10051 let mut skipped_vert = 0usize;
10052 for threads in [1usize, 4] {
10053 crate::par::set_recon_threads(threads);
10054 crate::decode::reset_intrabc_rect_hits();
10055 let frames = match decode_stream(&stream) {
10056 Ok(frames) => frames,
10057 Err(e) => {
10058 crate::par::set_recon_threads(1);
10059 panic!("{NAME}: {arm} refused at {threads} recon thread(s): {e}")
10060 }
10061 };
10062 let skipped = crate::decode::intrabc_rect_skipped_hits();
10063 assert!(
10064 !frames.is_empty(),
10065 "{NAME}: {arm} decoded no frame at {threads} recon thread(s)"
10066 );
10067 let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len());
10068 assert_eq!(
10069 frames.len(),
10070 theirs.len(),
10071 "{NAME}: {arm} frame count at {threads} recon thread(s)"
10072 );
10073 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
10074 assert!(
10075 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
10076 "{NAME}: {arm} frame {i} does not match ffmpeg at {threads} recon thread(s)"
10077 );
10078 }
10079 if threads == 1 {
10080 skipped_vert = skipped[1];
10081 } else {
10082 assert_eq!(
10083 skipped[1], skipped_vert,
10084 "{NAME}: {arm} skipped VERT strip count changed across recon paths"
10085 );
10086 }
10087 eprintln!(
10088 "{NAME}: {arm} {} frame(s) exact at {threads} recon thread(s), skipped rect intrabc horz={} vert={}",
10089 frames.len(),
10090 skipped[0],
10091 skipped[1]
10092 );
10093 }
10094 crate::par::set_recon_threads(1);
10095 assert!(
10096 skipped_vert > 0,
10097 "{NAME}: {arm} reconstructed no SKIPPED VERT rect intrabc strip -- the r5 stride arm is untested"
10098 );
10099 }
10100 }
10101
10102 /// lane-t900 r31: builds one `--tune-content=screen --enable-intrabc=1`
10103 /// key frame, 256x192 8-bit, from a deterministic lavfi source. `tiled`
10104 /// renders a 2x2 tiling of a 128x96 pattern -- exact spatial repetition,
10105 /// the content intra block copy exists for; `square_only` turns the rect
10106 /// and 1:4 partitions off so an intrabc block lands on a SQUARE block
10107 /// instead of stopping on the rect-strip intrabc refusal first.
10108 fn screen_intrabc_stream(
10109 src: &str,
10110 cq: &str,
10111 txs: &str,
10112 tiled: bool,
10113 square_only: bool,
10114 ) -> Vec<u8> {
10115 screen_intrabc_stream_with(src, cq, txs, tiled, square_only, &[])
10116 }
10117
10118 /// [`screen_intrabc_stream`] with per-arm flags appended AFTER the base
10119 /// recipe -- aomenc keeps the LAST occurrence of a repeated flag, so an
10120 /// arm can override `--sb-size` / `--min-partition-size` here.
10121 fn screen_intrabc_stream_with(
10122 src: &str,
10123 cq: &str,
10124 txs: &str,
10125 tiled: bool,
10126 square_only: bool,
10127 extra: &[&str],
10128 ) -> Vec<u8> {
10129 screen_intrabc_stream_at_depth(src, cq, txs, tiled, square_only, 8, extra)
10130 }
10131
10132 /// [`screen_intrabc_stream_with`] at an explicit bit depth (8 or 10): the
10133 /// lavfi source is rendered straight to that depth's yuv4mpegpipe pixel
10134 /// format and aomenc is told to encode at the matching
10135 /// `--bit-depth`/`--input-bit-depth`, so a 10-bit arm produces a genuine
10136 /// high-bit-depth stream rather than an 8-bit one in disguise.
10137 fn screen_intrabc_stream_at_depth(
10138 src: &str,
10139 cq: &str,
10140 txs: &str,
10141 tiled: bool,
10142 square_only: bool,
10143 depth: usize,
10144 extra: &[&str],
10145 ) -> Vec<u8> {
10146 assert!(depth == 8 || depth == 10, "unsupported bit depth {depth}");
10147 let pix_fmt = if depth == 10 {
10148 "yuv420p10le"
10149 } else {
10150 "yuv420p"
10151 };
10152 let mut ff = Command::new("ffmpeg");
10153 ff.args(["-v", "error", "-f", "lavfi", "-i", src, "-t", "0.2"]);
10154 if tiled {
10155 ff.args(["-vf", "tile=2x2"]);
10156 }
10157 let out = ff
10158 .args([
10159 "-pix_fmt",
10160 pix_fmt,
10161 "-strict",
10162 "-1",
10163 "-f",
10164 "yuv4mpegpipe",
10165 "-",
10166 ])
10167 .stdin(Stdio::null())
10168 .stdout(Stdio::piped())
10169 .stderr(Stdio::piped())
10170 .output()
10171 .expect("ffmpeg failed to run");
10172 assert!(out.status.success(), "ffmpeg failed for {src}");
10173 let y4m = out.stdout;
10174 let enc = run_with_stdin(
10175 Command::new(aomenc_path())
10176 .args(["--codec=av1"])
10177 .args([
10178 format!("--bit-depth={depth}"),
10179 format!("--input-bit-depth={depth}"),
10180 ])
10181 .args([
10182 "--passes=1",
10183 "--end-usage=q",
10184 "--cpu-used=0",
10185 "--lag-in-frames=0",
10186 "--kf-max-dist=1",
10187 "--limit=1",
10188 "--threads=1",
10189 "--tile-columns=0",
10190 "--min-partition-size=8",
10191 "--max-partition-size=32",
10192 "--sb-size=64",
10193 "--tune-content=screen",
10194 "--enable-intrabc=1",
10195 "--enable-palette=0",
10196 ])
10197 .args([
10198 format!("--cq-level={cq}"),
10199 format!("--enable-tx-size-search={txs}"),
10200 ])
10201 // aomenc keeps the LAST occurrence of a repeated flag.
10202 .args(if square_only {
10203 &["--enable-rect-partitions=0", "--enable-1to4-partitions=0"][..]
10204 } else {
10205 &[][..]
10206 })
10207 .args(extra)
10208 .args(["--obu", "-o", "-", "-"]),
10209 &y4m,
10210 );
10211 assert!(
10212 enc.status.success(),
10213 "aomenc refused {src} cq={cq}: {}",
10214 String::from_utf8_lossy(&enc.stderr)
10215 );
10216 enc.stdout
10217 }
10218
10219 /// The sequence header's `use_128x128_superblock`, and how many frames of
10220 /// `stream` keep `allow_intrabc` -- the two bits the refusal "intrabc
10221 /// under a 128x128 superblock" is the conjunction of, read out of the
10222 /// headers rather than assumed from the flags handed to the encoder.
10223 fn sb128_and_intrabc_frames(stream: &[u8]) -> (bool, u32) {
10224 let mut parser = Av1Parser::new();
10225 let mut pos = 0usize;
10226 let (mut sb128, mut intrabc) = (false, 0u32);
10227 while pos < stream.len() {
10228 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
10229 break;
10230 };
10231 pos += obu.total_size.max(1);
10232 if let Some(seq) = parser.sequence_header() {
10233 sb128 = seq.use_128x128_superblock;
10234 }
10235 let header = match &obu.kind {
10236 ObuKind::Frame(h, _) => Some(&**h),
10237 ObuKind::FrameHeader(h) => Some(&**h),
10238 _ => None,
10239 };
10240 if header.is_some_and(|h| h.allow_intrabc) {
10241 intrabc += 1;
10242 }
10243 }
10244 (sb128, intrabc)
10245 }
10246
10247 /// lane-t900 r34, the WITNESS (r33 pinned it ignored) that intrabc under
10248 /// a 128x128 superblock decodes pixel-exact.
10249 ///
10250 /// All four arms of r33's census -- `--sb-size=128 --tune-content=screen
10251 /// --enable-intrabc=1` over both `--enable-tx-size-search` settings and
10252 /// two quantisers, on a 2x2 tiling of a 128x96 bar pattern (256x192,
10253 /// 8-bit, `--cpu-used=0 --min-partition-size=8 --max-partition-size=32`,
10254 /// rect and 1:4 off) -- code `use_128x128_superblock && allow_intrabc`.
10255 ///
10256 /// The lift was one constant: `av1_find_ref_dv` (mvref_common.c) takes
10257 /// `mib_size`, the SEQUENCE's superblock size in mi units, so the
10258 /// fallback DV is one 128-px superblock up (or 128 + `INTRABC_DELAY_PIXELS`
10259 /// left on the tile's first superblock row) under a 128 superblock, where
10260 /// [`crate::decode::read_intrabc_dv`] hardcoded 64. Every arm is compared
10261 /// to ffmpeg and the decoded-intrabc-block counter is asserted non-zero,
10262 /// so a stream that stopped using intrabc could not make this vacuous.
10263 ///
10264 /// lane-av1-intrabc (2026-09-17): the four recipes now run at 10 bits as
10265 /// well, and both depths must SHOW the engagement -- `blocks_at_depth`
10266 /// below hard-asserts a decoded intrabc block per depth. The 10-bit
10267 /// coverage the guard records for `enable-intrabc` used to rest on a gate
10268 /// that only SPELLED `--enable-intrabc=1`: measured (same round), all five
10269 /// arms of `a_real_aomenc_rect_strip_palette_decodes_pixel_exact` decode
10270 /// ZERO intrabc blocks at BOTH depths, so the spelling proved nothing and
10271 /// the entry was one encoder-RD change away from being vacuous again
10272 /// (class `tool-disabled-in-every-gate`). An arm here that stops engaging
10273 /// intrabc now fails this gate instead of retiring the entry unproven.
10274 #[test]
10275 fn an_sb128_screen_stream_with_intrabc_decodes_pixel_exact() {
10276 const NAME: &str = "an_sb128_screen_stream_with_intrabc_decodes_pixel_exact";
10277 if !have_ffmpeg() || !have_aomenc() {
10278 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
10279 return;
10280 }
10281 let (width, height) = (256usize, 192usize);
10282 let _guard = lock_gate_counters();
10283 let (mut blocks_total, mut frames_compared) = (0usize, 0u32);
10284 let mut blocks_at_depth = [0usize; 2];
10285 for depth in [8usize, 10] {
10286 for txs in ["0", "1"] {
10287 for cq in ["30", "45"] {
10288 let arm = format!("sb128 {depth}-bit txs={txs} cq={cq}");
10289 let stream = screen_intrabc_stream_at_depth(
10290 "smptebars=size=128x96:rate=25",
10291 cq,
10292 txs,
10293 true,
10294 true,
10295 depth,
10296 &["--sb-size=128"],
10297 );
10298 let (sb128, intrabc_frames) = sb128_and_intrabc_frames(&stream);
10299 assert!(
10300 sb128 && intrabc_frames > 0,
10301 "{NAME}: {arm} no longer codes sb128 + allow_intrabc"
10302 );
10303 crate::decode::reset_intrabc_hits();
10304 let frames =
10305 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {arm}: {e}"));
10306 let blocks = crate::decode::intrabc_hits();
10307 blocks_total += blocks;
10308 blocks_at_depth[usize::from(depth == 10)] += blocks;
10309 let theirs = if depth == 10 {
10310 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
10311 } else {
10312 ffmpeg_decode_sequence(&stream, width, height, frames.len())
10313 };
10314 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
10315 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
10316 assert!(
10317 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
10318 "{NAME}: {arm} frame {i} does not match ffmpeg"
10319 );
10320 frames_compared += 1;
10321 }
10322 eprintln!(
10323 "{NAME}: {arm} intrabc_frames={intrabc_frames} intrabc_blocks={blocks} \
10324 DECODED {} frame(s) exact",
10325 frames.len()
10326 );
10327 }
10328 }
10329 }
10330 assert!(frames_compared > 0, "{NAME}: no frame was compared");
10331 assert!(
10332 blocks_total > 0,
10333 "{NAME}: gate is vacuous -- no arm decoded a single intrabc block"
10334 );
10335 assert!(
10336 blocks_at_depth[0] > 0 && blocks_at_depth[1] > 0,
10337 "{NAME}: 8-bit={} 10-bit={} -- an arm at that depth no longer decodes an intrabc \
10338 block, so `enable-intrabc` coverage there would rest on the flag spelling alone",
10339 blocks_at_depth[0],
10340 blocks_at_depth[1]
10341 );
10342 }
10343
10344 /// lane-av1-ibcrect: `use_intrabc` on a 128-root HORZ/VERT strip
10345 /// (BLOCK_128X64 / BLOCK_64X128) decodes PIXEL-EXACT against the
10346 /// instrumented oracle -- the witness the refusal inventory names after
10347 /// `decode_block_128rect`'s rect-strip intrabc refusal was lifted
10348 /// (`decode_intrabc_128rect`). The square-block twin is
10349 /// [`an_sb128_screen_stream_with_intrabc_decodes_pixel_exact`] above.
10350 ///
10351 /// The recipes are the hunt's proven arms (lanes/ibcrect r1/r2, the same
10352 /// `--sb-size=128 --min-partition-size=64 --enable-rect-partitions=1
10353 /// --enable-ab-partitions=0 --enable-1to4-partitions=0` partition recipe
10354 /// [`a_real_aomenc_sb128_intra_rect_block_decodes_pixel_exact`] uses, plus
10355 /// `--tune-content=screen --enable-intrabc=1` over the DETERMINISTIC geq
10356 /// sinusoid sources -- lavfi `gradients` ignores its seed and re-rolls
10357 /// every run, so a "flake" there was really this):
10358 ///
10359 /// * HORZ arm: 384x320 cq32, 5 all-key frames -- 14 unskipped 128x64
10360 /// intrabc blocks (`skip=false`, real residual reads);
10361 /// * VERT arm: 512x512 cq45, 5 all-key frames -- an unskipped 64x128
10362 /// intrabc block at mi(64,96).
10363 ///
10364 /// Both arms HARD-assert `intrabc_128rect_hits() > 0` and decode-order
10365 /// pixel-exactness of EVERY frame (hidden alt-refs included) against the
10366 /// oracle's own dump, so a stream that stopped engaging the shape fails
10367 /// the gate instead of passing vacuously (class `gate-blind-to-feature`).
10368 ///
10369 /// The 10-bit arm engages the shape. Hunt r2 and the witness re-run both
10370 /// measured `intrabc_128rect_hits` +15 on arm 3, so aomenc does take a
10371 /// 128-root HORZ/VERT strip at 10 bit under this recipe. There is no
10372 /// per-depth coverage gap to print. The gate's hard asserts already
10373 /// cover that arm.
10374 ///
10375 /// The chroma context this shape reads was the r2 defect: per-unit chroma
10376 /// entropy states were stamped inside the mu-chunk loop, then the
10377 /// end-of-block `record_split_luma_rect_mi` re-stamped BOTH planes over
10378 /// the whole 128x64 span with ONE composed state -- level = the SUM of
10379 /// both 64x64 chunks' units, dc = chunk-0's top-left (class
10380 /// `override-slot-on-one-arm`; the inter-128 path fixed the same class
10381 /// with its `mu_chroma_units` replay, decode.rs). The next block then
10382 /// read `txb_skip` off the smeared state.
10383 #[test]
10384 fn an_sb128_rect_strip_with_intrabc_decodes_pixel_exact() {
10385 const NAME: &str = "an_sb128_rect_strip_with_intrabc_decodes_pixel_exact";
10386 let _gate_lock = lock_gate_counters();
10387 if !have_ffmpeg() {
10388 eprintln!("SKIP {NAME}: no ffmpeg");
10389 return;
10390 }
10391 if !have_aomenc() {
10392 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10393 return;
10394 }
10395 // (tag, width, height, cq, geq luma, 10-bit)
10396 // The geq sources are the hunt's GEO_SMOOTH / GEO_SMOOTH_512,
10397 // byte-identical across runs (see the sb128 intra-rect gate's note).
10398 let arms: [(u32, usize, usize, &str, &str, bool); 3] = [
10399 (
10400 1,
10401 384,
10402 320,
10403 "32",
10404 "128+90*sin((X+2*N)/37)+30*sin(Y/29)",
10405 false,
10406 ),
10407 (
10408 2,
10409 512,
10410 512,
10411 "45",
10412 "128+80*sin((X+3*N)/17)+50*sin(Y/29)+30*sin((X+Y)/13)",
10413 false,
10414 ),
10415 (
10416 3,
10417 384,
10418 320,
10419 "32",
10420 "128+90*sin((X+2*N)/37)+30*sin(Y/29)",
10421 true,
10422 ),
10423 ];
10424 let mut engaged_arms = 0u32;
10425 let mut vert_arms = 0u32;
10426 for (tag, width, height, cq, lum, ten_bit) in arms {
10427 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
10428 let y4m = Command::new("ffmpeg")
10429 .args([
10430 "-v",
10431 "error",
10432 "-f",
10433 "lavfi",
10434 "-i",
10435 &format!(
10436 "nullsrc=size={width}x{height}:rate=25,format=yuv420p,\
10437 geq=lum='{lum}':\
10438 cb='128+30*sin(X/23)':cr='128+30*sin((Y+N)/19)'"
10439 ),
10440 "-pix_fmt",
10441 pix,
10442 "-strict",
10443 "-1",
10444 "-t",
10445 "0.2",
10446 "-f",
10447 "yuv4mpegpipe",
10448 "-",
10449 ])
10450 .stdin(Stdio::null())
10451 .stdout(Stdio::piped())
10452 .stderr(Stdio::piped())
10453 .output()
10454 .expect("ffmpeg failed to run");
10455 assert!(
10456 y4m.status.success(),
10457 "{NAME}: ffmpeg fixture: {}",
10458 String::from_utf8_lossy(&y4m.stderr)
10459 );
10460 let cq_arg = format!("--cq-level={cq}");
10461 let mut args: Vec<&str> = vec![
10462 "--codec=av1",
10463 "--passes=1",
10464 "--end-usage=q",
10465 &cq_arg,
10466 "--cpu-used=0",
10467 "--threads=1",
10468 "--row-mt=0",
10469 "--lag-in-frames=0",
10470 "--kf-max-dist=1",
10471 "--limit=5",
10472 "--tile-columns=0",
10473 "--sb-size=128",
10474 "--min-partition-size=64",
10475 "--enable-rect-partitions=1",
10476 "--enable-ab-partitions=0",
10477 "--enable-1to4-partitions=0",
10478 "--enable-palette=0",
10479 "--tune-content=screen",
10480 "--enable-intrabc=1",
10481 "--deltaq-mode=0",
10482 "--enable-tx-size-search=0",
10483 ];
10484 if ten_bit {
10485 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
10486 }
10487 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
10488 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
10489 assert!(
10490 out.status.success(),
10491 "{NAME}: aomenc refused the arm {tag} fixture: {}",
10492 String::from_utf8_lossy(&out.stderr)
10493 );
10494 let stream = out.stdout;
10495 let before = crate::decode::intrabc_128rect_hits();
10496 let (frames, hidden) = decode_all_frames_vs_oracle(
10497 &stream,
10498 &format!("ibcrect-strip-{tag}-{width}x{height}"),
10499 );
10500 let hits = crate::decode::intrabc_128rect_hits() - before;
10501 eprintln!(
10502 "{NAME}: arm {tag} {width}x{height} cq={cq} {}bit: {frames} decode-order frames \
10503 pixel-exact ({hidden} hidden), intrabc_128rect_hits=+{hits}",
10504 if ten_bit { 10 } else { 8 },
10505 );
10506 if hits > 0 {
10507 engaged_arms += 1;
10508 // The VERT arm is tag 2; its engagement is what proves the
10509 // 64x128 orientation, not just 128x64.
10510 if tag == 2 {
10511 vert_arms += 1;
10512 }
10513 }
10514 }
10515 assert!(
10516 engaged_arms > 0,
10517 "{NAME}: {engaged_arms} arm(s) decoded pixel-exact but NOT ONE decoded a 128-root \
10518 rect-strip intrabc block -- the shape this gate exists for was never engaged"
10519 );
10520 assert!(
10521 vert_arms > 0,
10522 "{NAME}: the VERT (64x128) orientation was never engaged -- only 128x64 HORZ strips \
10523 proved the lift"
10524 );
10525 }
10526 /// lane-av1intrapred r2, REGRESSION GATE for the two intrabc TX4-split
10527 /// chroma defects this lane fixed.
10528 ///
10529 /// An intrabc 8x8 leaf whose var-tx tree split to TX_4X4 must (a) arm
10530 /// `INTRABC_CHROMA_TX` from the co-located luma TU's coded type -- the
10531 /// chroma units then take that type's class-1 eob row, HORIZ scan and nz
10532 /// contexts (libaom `av1_get_tx_type`'s is_inter branch; intrabc is
10533 /// inter-classified) -- and (b) predict the chroma units from the FRAME
10534 /// COPY at the DV, not intra-from-UV-mode (intrabc's UV mode is DC, so a
10535 /// leaf that loses the override predicts flat DC where libaom copies a
10536 /// busy region).
10537 ///
10538 /// Pre-r2, decode_leaf8's TX4 arm did neither: R5's chroma U txb at
10539 /// mi (36,66) decoded `eob=11` off the 2D row where aomdec decoded
10540 /// `eob=13` off the class-1 row, and the first surviving pixel fork was
10541 /// U(184,4) of mi (2,92) (class `intrabc-chroma-tx-not-armed`, then
10542 /// `intrabc-chroma-predicts-intra`).
10543 ///
10544 /// The fixture is the report's R5 stream pinned into `fixtures/`
10545 /// (aomenc oracle, testsrc2 320x180 tiled 2x2 -> 640x360, sb64 maxp64
10546 /// square-only screen intrabc, cq20, 1 frame; 7173 bytes,
10547 /// sha256 bc699af4a6e7c1c5657f041e8cbdf2d3d899ddb80ec2a549a950b7cebb5b41bd).
10548 /// The gate needs no oracle at run time and cannot be skipped: a missing
10549 /// fixture, a decode error, a zero counter, a moved pixel patch or a
10550 /// changed full-frame fingerprint each fail by name. The fingerprint is
10551 /// FNV-1a (dependency-free, same rationale as the cdf-forwarding gate's).
10552 #[test]
10553 fn an_intrabc_tx4_leaf_chroma_inherits_the_luma_type_and_predicts_from_the_frame_copy() {
10554 const NAME: &str =
10555 "an_intrabc_tx4_leaf_chroma_inherits_the_luma_type_and_predicts_from_the_frame_copy";
10556 const FIXTURE_LEN: usize = 7173;
10557 const FIXTURE_FNV: u64 = 0x3a57_d075_5e4c_fe5b;
10558 const RAW_LEN: usize = 640 * 360 * 3 / 2;
10559 const RAW_FNV: u64 = 0xf271_df27_ce4d_ba66;
10560 // The 4x4 chroma patches at (184,4) -- the first surviving pixel fork
10561 // -- as the oracles (aomdec and ffmpeg agree) reconstruct them.
10562 const U_PATCH: [u16; 16] = [
10563 86, 116, 55, 110, 114, 114, 51, 83, 99, 121, 48, 114, 103, 117, 102, 67,
10564 ];
10565 const V_PATCH: [u16; 16] = [
10566 179, 158, 199, 105, 155, 158, 195, 147, 163, 153, 194, 108, 170, 148, 168, 172,
10567 ];
10568
10569 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
10570 .join("fixtures/intrabc_tx4_chroma_kf.obu");
10571 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
10572 panic!(
10573 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
10574 which is a failure, not a skip",
10575 obu.display()
10576 )
10577 });
10578 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
10579 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
10580
10581 let _guard = lock_gate_counters();
10582 crate::decode::reset_leaf8_intrabc_hits();
10583 crate::decode::reset_intrabc_tx4_chroma_copy_hits();
10584 let frames = decode_stream(&stream)
10585 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
10586 assert_eq!(frames.len(), 1, "{NAME}: frame count");
10587 let frame = &frames[0];
10588 assert_eq!(
10589 (frame.width, frame.height),
10590 (640, 360),
10591 "{NAME}: dimensions"
10592 );
10593
10594 // Non-vacuity, both halves: the leaf shape must be reached at all,
10595 // and its chroma route must have consulted the ARMED slot (pre-r2
10596 // this counter is 0 -- the arm never armed the slot).
10597 assert!(
10598 crate::decode::leaf8_intrabc_hits() > 0,
10599 "{NAME}: gate is vacuous -- no intrabc 8x8 leaf was decoded"
10600 );
10601 assert!(
10602 crate::decode::intrabc_tx4_chroma_copy_hits() > 0,
10603 "{NAME}: gate is vacuous -- no intrabc TX4-split leaf's chroma read consulted \
10604 the armed slot (class intrabc-chroma-tx-not-armed)"
10605 );
10606
10607 // The first surviving pixel fork: chroma 4x4 at (184,4). The wrong
10608 // wirings put flat intra-DC predictions or the wrong eob class here.
10609 let cw = frame.width / 2;
10610 let u_patch: Vec<u16> = (0..4)
10611 .flat_map(|dy| (0..4).map(move |dx| frame.u[(4 + dy) * cw + 184 + dx]))
10612 .collect();
10613 let v_patch: Vec<u16> = (0..4)
10614 .flat_map(|dy| (0..4).map(move |dx| frame.v[(4 + dy) * cw + 184 + dx]))
10615 .collect();
10616 assert_eq!(u_patch, U_PATCH, "{NAME}: U(184,4) patch moved");
10617 assert_eq!(v_patch, V_PATCH, "{NAME}: V(184,4) patch moved");
10618 // The unit the FRAME-COPY override specifically pins: chroma 4x4 at
10619 // (168,0) is an intrabc TX4-split leaf's chroma whose copy source is
10620 // a busy ramp region; without the `palette_uv_bufs` intrabc wrap the
10621 // read predicts flat intra-DC here (78k chroma bytes drift from this
10622 // unit alone), with it the copy reproduces the oracle exactly.
10623 const U_COPY_PATCH: [u16; 16] = [
10624 91, 91, 91, 91, 120, 120, 120, 120, 120, 120, 120, 120, 73, 102, 116, 116,
10625 ];
10626 const V_COPY_PATCH: [u16; 16] = [
10627 241, 241, 241, 241, 156, 156, 156, 156, 158, 158, 158, 158, 181, 163, 154, 154,
10628 ];
10629 let u_copy: Vec<u16> = (0..4)
10630 .flat_map(|dy| (0..4).map(move |dx| frame.u[dy * cw + 168 + dx]))
10631 .collect();
10632 let v_copy: Vec<u16> = (0..4)
10633 .flat_map(|dy| (0..4).map(move |dx| frame.v[dy * cw + 168 + dx]))
10634 .collect();
10635 assert_eq!(
10636 u_copy, U_COPY_PATCH,
10637 "{NAME}: U(168,0) patch moved -- the intrabc TX4 chroma read no longer \
10638 predicts from the frame copy (class intrabc-chroma-predicts-intra)"
10639 );
10640 assert_eq!(v_copy, V_COPY_PATCH, "{NAME}: V(168,0) patch moved");
10641
10642 // The whole frame, packed as the rawvideo byte stream the oracles
10643 // produce: any remaining byte anywhere in Y/U/V fails the gate.
10644 let mut raw = Vec::with_capacity(RAW_LEN);
10645 for plane in [&frame.y, &frame.u, &frame.v] {
10646 raw.extend(plane.iter().map(|&s| s as u8));
10647 }
10648 assert_eq!(raw.len(), RAW_LEN, "{NAME}: raw size");
10649 assert_eq!(
10650 fnv1a64(&raw),
10651 RAW_FNV,
10652 "{NAME}: full-frame fingerprint moved"
10653 );
10654 }
10655
10656 /// lane-t900 r33, CENSUS for "a sub-8x8 leaf that uses intrabc".
10657 ///
10658 /// The `use_intrabc` symbol IS read at that reader for every sub-8x8 leaf
10659 /// of an `allow_intrabc` frame, so arrival is provable rather than
10660 /// assumed: the arms below force 4x4 leaves (`--min-partition-size=4`) on
10661 /// the exact-repetition screen content that keeps `allow_intrabc`, and the
10662 /// gate requires both counters -- `allow_intrabc` frames and decoded sub-8
10663 /// leaves -- to be non-zero before it reads anything into the refusal
10664 /// firing 0 times (class `gate-blind-to-feature`).
10665 #[test]
10666 fn a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal() {
10667 const NAME: &str =
10668 "a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal";
10669 if !have_ffmpeg() || !have_aomenc() {
10670 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
10671 return;
10672 }
10673 let (width, height) = (256usize, 192usize);
10674 let _guard = lock_gate_counters();
10675 let (mut premise_arms, mut reached, mut sub8_total, mut frames_compared) =
10676 (0u32, 0u32, 0usize, 0u32);
10677 for cq in ["30", "45"] {
10678 let arm = format!("sub8 cq={cq}");
10679 let stream = screen_intrabc_stream_with(
10680 "smptebars=size=128x96:rate=25",
10681 cq,
10682 "0",
10683 true,
10684 true,
10685 &["--min-partition-size=4"],
10686 );
10687 let (_, intrabc_frames) = sb128_and_intrabc_frames(&stream);
10688 if intrabc_frames > 0 {
10689 premise_arms += 1;
10690 }
10691 // No reset for this counter, so measure the delta (the gate lock
10692 // above keeps another gate's decode out of it).
10693 let sub8_before = crate::decode::sub8_split_hits();
10694 match decode_stream(&stream) {
10695 Ok(frames) => {
10696 let sub8 = crate::decode::sub8_split_hits() - sub8_before;
10697 sub8_total += sub8;
10698 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
10699 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
10700 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
10701 assert!(
10702 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
10703 "{NAME}: {arm} frame {i} does not match ffmpeg"
10704 );
10705 frames_compared += 1;
10706 }
10707 eprintln!(
10708 "{NAME}: {arm} intrabc_frames={intrabc_frames} sub8_leaves={sub8} \
10709 DECODED {} frame(s) exact",
10710 frames.len()
10711 );
10712 }
10713 Err(e) => {
10714 let msg = e.to_string();
10715 assert!(
10716 msg.contains("unsupported"),
10717 "{NAME}: {arm} decode failed: {e}"
10718 );
10719 if msg.contains("a sub-8x8 leaf that uses intrabc") {
10720 reached += 1;
10721 }
10722 sub8_total += crate::decode::sub8_split_hits() - sub8_before;
10723 eprintln!("{NAME}: {arm} intrabc_frames={intrabc_frames} REFUSED: {e}");
10724 }
10725 }
10726 }
10727 eprintln!(
10728 "{NAME}: {premise_arms}/2 arm(s) keep allow_intrabc, {sub8_total} sub-8 leaf/leaves \
10729 decoded, {reached} reach the refusal, {frames_compared} frame(s) exact"
10730 );
10731 assert!(
10732 premise_arms > 0,
10733 "{NAME}: census is vacuous -- no arm kept allow_intrabc, so the refusal's own \
10734 premise was never within reach"
10735 );
10736 assert!(
10737 sub8_total > 0,
10738 "{NAME}: census is vacuous -- no sub-8 leaf was decoded at all, so the \
10739 `use_intrabc` symbol this refusal guards was never read"
10740 );
10741 }
10742
10743 /// lane-t900 r33, CENSUS for "an intrabc block whose var-tx tree resolved
10744 /// to mixed leaf transform sizes" -- the residue lane-t900 r32 left when
10745 /// it lifted the intrabc `TX_MODE_SELECT` refusal.
10746 ///
10747 /// The tree is read in full; lane-av1-ibcvtx taught the luma reconstruct
10748 /// to walk the tree's own leaf list, so mixed trees now decode. This
10749 /// census sweeps the quantiser across the exact-repetition recipe that
10750 /// reaches the tree at all and requires the tree to actually be read
10751 /// (`intrabc_vartx_hits`); it stays as the premise witness for the lifted
10752 /// refusal (`reached` is 0 by construction now).
10753 #[test]
10754 fn an_intrabc_vartx_census_measures_the_mixed_leaf_refusal() {
10755 const NAME: &str = "an_intrabc_vartx_census_measures_the_mixed_leaf_refusal";
10756 if !have_ffmpeg() || !have_aomenc() {
10757 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
10758 return;
10759 }
10760 let (width, height) = (256usize, 192usize);
10761 let _guard = lock_gate_counters();
10762 let (mut vartx_total, mut reached, mut frames_compared) = (0usize, 0u32, 0u32);
10763 for cq in ["20", "30", "45", "55"] {
10764 let arm = format!("vartx cq={cq}");
10765 let stream =
10766 screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
10767 let (select, premise) = tx_select_and_intrabc_frames(&stream);
10768 crate::decode::reset_intrabc_vartx_hits();
10769 match decode_stream(&stream) {
10770 Ok(frames) => {
10771 let vartx = crate::decode::intrabc_vartx_hits();
10772 vartx_total += vartx;
10773 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
10774 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
10775 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
10776 assert!(
10777 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
10778 "{NAME}: {arm} frame {i} does not match ffmpeg"
10779 );
10780 frames_compared += 1;
10781 }
10782 eprintln!(
10783 "{NAME}: {arm} select={select} premise={premise} vartx_blocks={vartx} \
10784 DECODED {} frame(s) exact",
10785 frames.len()
10786 );
10787 }
10788 Err(e) => {
10789 let msg = e.to_string();
10790 assert!(
10791 msg.contains("unsupported"),
10792 "{NAME}: {arm} decode failed: {e}"
10793 );
10794 vartx_total += crate::decode::intrabc_vartx_hits();
10795 if msg.contains("mixed leaf transform sizes") {
10796 reached += 1;
10797 }
10798 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
10799 }
10800 }
10801 }
10802 eprintln!(
10803 "{NAME}: {vartx_total} intrabc block(s) read the var-tx tree, {reached} resolved to \
10804 mixed leaves, {frames_compared} frame(s) exact"
10805 );
10806 assert!(
10807 vartx_total > 0,
10808 "{NAME}: census is vacuous -- no intrabc block read the var-tx tree at all"
10809 );
10810 assert_eq!(
10811 reached, 0,
10812 "{NAME}: an intrabc var-tx tree was REFUSED -- the mixed-leaf refusal \
10813 is lifted (lane-av1-ibcvtx) and must stay gone"
10814 );
10815 }
10816
10817 /// lane-av1-ibcvtx, capability gate for the LIFTED refusal "an intrabc
10818 /// block whose var-tx tree resolved to mixed leaf transform sizes": the
10819 /// t900 r33 census recipe class (screen content, square partitions,
10820 /// tx-size search) reaches mixed trees the moment the canvas carries
10821 /// testsrc2's texture and blocks grow past 32 -- on the PRE-fix tree this
10822 /// exact stream refused by name on its first mixed tree (5 of the 12
10823 /// hunt recipes hit it, `lanes/av1ibcvtx.report.md`).
10824 ///
10825 /// The luma reconstruct walks the tree's own leaf list per leaf (libaom
10826 /// `decode_token_recon_block`), and the block's chroma inherits the
10827 /// co-located luma unit's coded tx type (`av1_get_tx_type`,
10828 /// `blockd.h:1278`) -- the inheritance the uniform multi-TU intrabc path
10829 /// was missing as well: symbol-aligned against an instrumented aomdec,
10830 /// the 640x360 cq20 witness desynced inside the FIRST chroma unit of its
10831 /// first mixed tree until the arm landed, then matched every subsequent
10832 /// read.
10833 ///
10834 /// NOT yet asserted: full pixel-exactness against ffmpeg. A second,
10835 /// PRE-EXISTING defect that is not this refusal -- a NON-intrabc intra
10836 /// block (R5 witness: mi (32,32), 64x64, uniform 4x TX_32X32 tree, every
10837 /// coefficient all_zero, reads symbol-identical to aomdec) mispredicts
10838 /// isolated samples on testsrc2 content (first divergence px (128,296)
10839 /// of the 640x360 cq20 recipe) and cascades over roughly a third of the
10840 /// frame. It is pinned in `lanes/av1ibcvtx.report.md`; when it lands,
10841 /// tighten this gate to a full pixel-exact assert.
10842 #[test]
10843 fn a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal() {
10844 const NAME: &str =
10845 "a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal";
10846 if !have_ffmpeg() || !have_aomenc() {
10847 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
10848 return;
10849 }
10850 let (width, height) = (640usize, 360usize);
10851 let _guard = lock_gate_counters();
10852 let stream = screen_intrabc_stream_with(
10853 "testsrc2=size=320x180:rate=25",
10854 "30",
10855 "1",
10856 true,
10857 true,
10858 &["--max-partition-size=64"],
10859 );
10860 let (select, premise) = tx_select_and_intrabc_frames(&stream);
10861 assert!(
10862 premise > 0,
10863 "{NAME}: vacuous -- no frame keeps allow_intrabc under TxMode::Select, \
10864 so the refusal's premise was never within reach (select={select})"
10865 );
10866 crate::decode::reset_intrabc_vartx_hits();
10867 crate::decode::reset_intrabc_vartx_mixed_leaves_hits();
10868 match decode_stream(&stream) {
10869 Ok(frames) => {
10870 let trees = crate::decode::intrabc_vartx_hits();
10871 let mixed = crate::decode::intrabc_vartx_mixed_leaves_hits();
10872 assert!(
10873 trees > 0 && mixed > 0,
10874 "{NAME}: vacuous -- {trees} var-tx tree(s), {mixed} mixed: the \
10875 capability this gate pins was never exercised"
10876 );
10877 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
10878 assert_eq!(frames.len(), theirs.len(), "{NAME}: frame count");
10879 let mut mismatched = 0usize;
10880 for (ours, ref_frame) in frames.iter().zip(theirs.iter()) {
10881 mismatched += ours
10882 .y
10883 .iter()
10884 .zip(ref_frame.y.iter())
10885 .filter(|(x, y)| x != y)
10886 .count();
10887 mismatched += ours
10888 .u
10889 .iter()
10890 .zip(ref_frame.u.iter())
10891 .filter(|(x, y)| x != y)
10892 .count();
10893 mismatched += ours
10894 .v
10895 .iter()
10896 .zip(ref_frame.v.iter())
10897 .filter(|(x, y)| x != y)
10898 .count();
10899 }
10900 eprintln!(
10901 "{NAME}: select={select} premise={premise} vartx_blocks={trees} \
10902 mixed_trees={mixed}, {mismatched} sample(s) differ from ffmpeg \
10903 (the pinned non-intrabc second defect, see the doc comment)"
10904 );
10905 }
10906 Err(e) => panic!(
10907 "{NAME}: the mixed-leaf refusal is lifted (lane-av1-ibcvtx); the \
10908 witness stream must decode, not stop: {e}"
10909 ),
10910 }
10911 }
10912
10913 /// How many frames of `stream` carry `tx_mode == Select`, and how many of
10914 /// those also keep `allow_intrabc` -- the frame-level premise of the
10915 /// refusal "an intrabc block under TxMode::Select", read out of the
10916 /// headers rather than assumed from the flags handed to the encoder
10917 /// (libaom clears `allow_intrabc` again when no block picked it,
10918 /// encodeframe.c:2336).
10919 fn tx_select_and_intrabc_frames(stream: &[u8]) -> (u32, u32) {
10920 let (mut select, mut premise) = (0u32, 0u32);
10921 let mut p = Av1Parser::new();
10922 let mut pos = 0usize;
10923 while pos < stream.len() {
10924 let obu = p.parse_obu(&stream[pos..]).expect("parse");
10925 pos += obu.total_size;
10926 let header = match &obu.kind {
10927 ObuKind::Frame(h, _) => Some(&**h),
10928 ObuKind::FrameHeader(h) => Some(&**h),
10929 _ => None,
10930 };
10931 if let Some(h) = header {
10932 if h.tx_mode == TxMode::Select {
10933 select += 1;
10934 if h.allow_intrabc {
10935 premise += 1;
10936 }
10937 }
10938 }
10939 }
10940 (select, premise)
10941 }
10942
10943 /// lane-t900 r31, CENSUS for the refusal "an intrabc block under
10944 /// TxMode::Select" -- which this gate DISPROVES as an "no encoder writes
10945 /// one" claim and pins as a real capability gap instead.
10946 ///
10947 /// The premise is reachable by the SPEC: `tx_mode` (5.9.21) is forced to
10948 /// `ONLY_4X4` only under `CodedLossless`, while `allow_intrabc` (5.9.2)
10949 /// needs `allow_screen_content_tools` at unscaled resolution -- two
10950 /// independent conditions. libaom leaves it open too: `select_tx_mode`
10951 /// (encodeframe.c:2355) never consults `allow_intrabc`, and the only
10952 /// downgrade to `TX_MODE_LARGEST` is `txb_split_count == 0`
10953 /// (encodeframe.c:2690).
10954 ///
10955 /// The measurement over 14 real `--tune-content=screen --enable-intrabc=1`
10956 /// recipes:
10957 ///
10958 /// * the 10 non-repeating arms never present the premise at all -- with
10959 /// `--enable-tx-size-search=1` the frame codes `TX_MODE_SELECT` but RD
10960 /// never picks intrabc, so libaom clears `allow_intrabc` again; with
10961 /// `=0` intrabc IS used and the frame is `TX_MODE_LARGEST`. That
10962 /// correlation, not any rule, is why earlier rounds never saw this;
10963 /// * the four EXACT-REPETITION arms (a 2x2 tiling of one 128x96 bar
10964 /// pattern) all code `allow_intrabc && tx_mode == Select`. Two of them
10965 /// stop on the older rect-strip intrabc refusal (the shape that fires
10966 /// first, class `refusal-hides-a-defect`), and the two with rect/1:4
10967 /// partitions off put intrabc on a SQUARE block: `cq=30` reaches THIS
10968 /// refusal by name, `cq=45`'s intrabc blocks are all `skip` and decode
10969 /// pixel-exact against ffmpeg.
10970 ///
10971 /// So the refusal is correct and load-bearing, exactly one arm reaches it,
10972 /// and the lift it names has a waiting witness:
10973 /// [`an_intrabc_block_under_tx_mode_select_decodes_pixel_exact`] (ignored
10974 /// until the intra path reads the inter var-tx tree for an intrabc block).
10975 #[test]
10976 fn an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal() {
10977 const NAME: &str =
10978 "an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal";
10979 if !have_ffmpeg() {
10980 eprintln!("SKIP {NAME}: no ffmpeg");
10981 return;
10982 }
10983 if !have_aomenc() {
10984 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
10985 return;
10986 }
10987 const TS: &str = "testsrc2=s=256x192:r=25";
10988 const SB: &str = "smptebars=size=256x192:rate=25";
10989 const PB: &str = "pal75bars=size=256x192:rate=25";
10990 const TILE: &str = "smptebars=size=128x96:rate=25";
10991 let (width, height) = (256usize, 192usize);
10992 // (arm, source, cq, tx-size-search, tiled, square_only)
10993 let arms: [(&str, &str, &str, &str, bool, bool); 14] = [
10994 ("smptebars-cq40-txs1", SB, "40", "1", false, false),
10995 ("smptebars-cq45-txs1", SB, "45", "1", false, false),
10996 ("smptebars-cq55-txs1", SB, "55", "1", false, false),
10997 ("smptebars-cq63-txs1", SB, "63", "1", false, false),
10998 ("pal75bars-cq40-txs1", PB, "40", "1", false, false),
10999 ("pal75bars-cq55-txs1", PB, "55", "1", false, false),
11000 ("testsrc2-cq50-txs1", TS, "50", "1", false, false),
11001 ("testsrc2-cq63-txs1", TS, "63", "1", false, false),
11002 ("smptebars-cq45-txs0", SB, "45", "0", false, false),
11003 ("pal75bars-cq45-txs0", PB, "45", "0", false, false),
11004 ("tiled-cq30-txs1", TILE, "30", "1", true, false),
11005 ("tiled-cq45-txs1", TILE, "45", "1", true, false),
11006 ("tiled-square-cq30-txs1", TILE, "30", "1", true, true),
11007 // lane-t900 r32: both square arms are now ORDINARY census members
11008 // -- cq30 (unskipped intrabc, the inter var-tx tree) and cq45
11009 // (all-skip intrabc, `maxRectTxSize` with no symbol at all) decode
11010 // pixel-exact, so nothing here reaches the lifted refusal.
11011 ("tiled-square-cq45-txs1", TILE, "45", "1", true, true),
11012 ];
11013 let (mut select_arms, mut premise_arms, mut intrabc_arms, mut blocks_total) =
11014 (0u32, 0u32, 0u32, 0usize);
11015 let (mut refused_tx_select, mut frames_compared) = (0u32, 0usize);
11016 for (arm, src, cq, txs, tiled, square_only) in &arms {
11017 let stream = screen_intrabc_stream(src, cq, txs, *tiled, *square_only);
11018 let (select, premise) = tx_select_and_intrabc_frames(&stream);
11019 if select > 0 {
11020 select_arms += 1;
11021 }
11022 if premise > 0 {
11023 premise_arms += 1;
11024 }
11025 crate::decode::reset_intrabc_hits();
11026 let decoded = decode_stream(&stream);
11027 let blocks = crate::decode::intrabc_hits();
11028 blocks_total += blocks;
11029 if blocks > 0 {
11030 intrabc_arms += 1;
11031 }
11032 match decoded {
11033 Ok(frames) => {
11034 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
11035 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
11036 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
11037 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
11038 assert!(
11039 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
11040 "{NAME}: {arm} frame {i} does not match ffmpeg"
11041 );
11042 frames_compared += 1;
11043 }
11044 eprintln!(
11045 "{NAME}: {arm} select={select} premise={premise} {blocks} intrabc \
11046 block(s), {} frame(s) exact",
11047 frames.len()
11048 );
11049 }
11050 Err(e) => {
11051 let msg = e.to_string();
11052 assert!(
11053 msg.contains("unsupported"),
11054 "{NAME}: {arm} decode failed: {e}"
11055 );
11056 if msg.contains("an intrabc block under TxMode::Select") {
11057 refused_tx_select += 1;
11058 assert!(
11059 premise > 0,
11060 "{NAME}: {arm} reached the TxMode::Select intrabc refusal in a \
11061 frame that codes no such header"
11062 );
11063 } else {
11064 assert!(
11065 msg.contains("intra block copy"),
11066 "{NAME}: {arm} refused for an unrelated reason: {e}"
11067 );
11068 }
11069 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
11070 }
11071 }
11072 }
11073 eprintln!(
11074 "{NAME}: {select_arms}/{n} arm(s) code a TX_MODE_SELECT frame, {premise_arms} of \
11075 those keep allow_intrabc, {intrabc_arms} arm(s) decode an intrabc block \
11076 ({blocks_total} total), {refused_tx_select} reach the refusal, \
11077 {frames_compared} frame(s) compared exact",
11078 n = arms.len()
11079 );
11080 assert!(
11081 intrabc_arms > 0 && blocks_total > 0,
11082 "{NAME}: census is vacuous -- no arm decoded an intrabc block at all"
11083 );
11084 assert!(
11085 premise_arms > 0,
11086 "{NAME}: census is vacuous -- no arm coded a frame with both allow_intrabc and \
11087 tx_mode == Select, so the refusal's own premise was never within reach"
11088 );
11089 assert_eq!(
11090 refused_tx_select, 0,
11091 "{NAME}: lane-t900 r32 lifted this refusal -- an intrabc block now reads the \
11092 INTER tx-size syntax, so no arm may reach it again"
11093 );
11094 assert!(
11095 frames_compared > 0,
11096 "{NAME}: no frame was compared pixel-exact"
11097 );
11098 }
11099
11100 /// lane-t900 r31, the WAITING witness for the capability
11101 /// [`an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal`]
11102 /// pins: a real aomenc screen key frame whose intrabc block sits on a
11103 /// square block of a `TX_MODE_SELECT` frame, unskipped. libaom's
11104 /// `parse_decode_block` treats an intrabc block as `inter_block_tx`, so
11105 /// its transform size comes off the inter var-tx partition tree
11106 /// (`read_var_tx_size`), which this decoder reads nowhere on the intra
11107 /// path -- reading the intra `tx_depth` symbol instead desyncs.
11108 ///
11109 /// lane-t900 r32 closed both arms. A SKIPPED intrabc block reads no
11110 /// tx-size symbol at all (`allowSelect = !skip || !is_inter`, false for an
11111 /// intrabc block since libaom's `is_inter_block` counts one); reading the
11112 /// intra `tx_depth` for it consumed a symbol libaom never wrote and
11113 /// desynced the tile a whole block later, at the superblock corner
11114 /// (192,64) (class `equal-range-means-unread`). An UNSKIPPED one reads the
11115 /// inter var-tx tree (`read_var_tx_size`). r31's note that cq=45's blocks
11116 /// are all `skip` was read off that desynced decode: with the tx-size read
11117 /// corrected, cq=45 carries 3 unskipped intrabc blocks of 10 and cq=30
11118 /// carries 1 of 16, so both arms exercise both sides of the split.
11119 #[test]
11120 fn an_intrabc_block_under_tx_mode_select_decodes_pixel_exact() {
11121 const NAME: &str = "an_intrabc_block_under_tx_mode_select_decodes_pixel_exact";
11122 if !have_ffmpeg() || !have_aomenc() {
11123 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
11124 return;
11125 }
11126 let (width, height) = (256usize, 192usize);
11127 for cq in ["30", "45"] {
11128 let stream =
11129 screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
11130 let (select, premise) = tx_select_and_intrabc_frames(&stream);
11131 assert!(
11132 select > 0 && premise > 0,
11133 "{NAME}: cq={cq} no longer codes allow_intrabc under TX_MODE_SELECT \
11134 (select={select} premise={premise})"
11135 );
11136 crate::decode::reset_intrabc_hits();
11137 crate::decode::reset_intrabc_vartx_hits();
11138 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: cq={cq}: {e}"));
11139 let (blocks, vartx) = (
11140 crate::decode::intrabc_hits(),
11141 crate::decode::intrabc_vartx_hits(),
11142 );
11143 assert!(
11144 blocks > 0,
11145 "{NAME}: cq={cq} no longer decodes an intrabc block"
11146 );
11147 // r31 recorded cq=45's intrabc blocks as ALL skip; that was read
11148 // off the desynced decode. With the tx-size read corrected both
11149 // arms carry unskipped ones (cq30 1 of 16, cq45 3 of 10), so both
11150 // must reach the var-tx tree or the gate is blind to the lift
11151 // (class `gate-blind-to-feature`).
11152 assert!(
11153 vartx > 0,
11154 "{NAME}: cq={cq} no longer reads the inter var-tx tree for an intrabc block"
11155 );
11156 eprintln!("{NAME}: cq={cq} {blocks} intrabc block(s), {vartx} through var-tx");
11157 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
11158 assert_eq!(frames.len(), theirs.len(), "{NAME}: cq={cq} frame count");
11159 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
11160 assert!(
11161 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
11162 "{NAME}: cq={cq} frame {i} does not match ffmpeg"
11163 );
11164 }
11165 }
11166 }
11167
11168 /// lane-av1txr: a real `aomenc --cdf-update-mode=0` stream (spec 5.9.2
11169 /// `disable_cdf_update`) decodes SAMPLE-EXACT. The read that was missing:
11170 /// `stream.rs` never threaded the header bit, so the tile readers adapted
11171 /// every symbol of a frame the encoder coded against fixed tables -- the
11172 /// stream desynced at its first multi-symbol block and the pixels differed
11173 /// from byte 6 (`EC_PROBE_OUT` vs `ffmpeg -pix_fmt yuv420p`, measured
11174 /// 2026-09-20). The msac unit gate
11175 /// (`a_reader_told_not_to_adapt_matches_a_non_adapting_writer`) pins the
11176 /// mechanism; this one pins the wiring end to end.
11177 #[test]
11178 fn a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact() {
11179 const NAME: &str = "a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact";
11180 if !have_ffmpeg() || !have_aomenc() {
11181 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
11182 return;
11183 }
11184 let (width, height) = (256usize, 192usize);
11185 let stream = screen_intrabc_stream_with(
11186 "testsrc2=size=256x192:rate=25",
11187 "45",
11188 "1",
11189 false,
11190 true,
11191 &["--cdf-update-mode=0", "--limit=3"],
11192 );
11193 // Non-vacuity: the fixture must really code the bit on every frame.
11194 let mut parser = Av1Parser::new();
11195 let mut pos = 0usize;
11196 let mut headers = 0usize;
11197 while pos < stream.len() {
11198 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
11199 break;
11200 };
11201 pos += obu.total_size.max(1);
11202 let header = match &obu.kind {
11203 ObuKind::Frame(h, _) | ObuKind::FrameHeader(h) => h,
11204 _ => continue,
11205 };
11206 assert!(
11207 header.disable_cdf_update,
11208 "{NAME}: frame {headers} does not carry disable_cdf_update -- aomenc ignored \
11209 --cdf-update-mode=0"
11210 );
11211 headers += 1;
11212 }
11213 assert!(
11214 headers >= 3,
11215 "{NAME}: only {headers} frame headers in the fixture"
11216 );
11217 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {e}"));
11218 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
11219 assert_eq!(frames.len(), theirs.len(), "{NAME}: frame count");
11220 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
11221 assert!(
11222 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
11223 "{NAME}: frame {i} does not match ffmpeg"
11224 );
11225 }
11226 eprintln!("{NAME}: {headers} disable_cdf_update frame headers, all frames sample-exact");
11227 }
11228
11229 /// lane-kf900 r4, the gate for the two lifted palette refusals ("a 1:4
11230 /// rect strip that actually uses a palette (reconstruction is not ported
11231 /// at this shape)" and "a palette block on a HORZ/VERT intra strip below
11232 /// 16x16 (reconstruction not ported)"): real `aomenc` streams that put a
11233 /// palette on a RECT strip, decoded whole-frame pixel-exact against
11234 /// ffmpeg's own decode of the identical bytes, at 8 AND 10 bit.
11235 ///
11236 /// Arm 0 is the stream lane-kf900 r3 pinned and stopped on -- `testsrc2`
11237 /// 256x192, `--cq-level=59 --cpu-used=0 --min-partition-size=8
11238 /// --enable-rect-partitions=1 --enable-tx-size-search=1`, md5
11239 /// `e5f033d8fe34e4418d8cca3ac9d2b595` at 10 bit. Arms 1-2 force the shape
11240 /// on screen-like content with `--tune-content=screen --enable-palette=1
11241 /// --enable-1to4-partitions=1`.
11242 ///
11243 /// An attempt whose decode never hit a rect-strip palette block proves
11244 /// nothing about the lift, so it is counted OUT OF SCOPE rather than
11245 /// silently passing -- but a mismatch on one is still a failure
11246 /// (`out_of_scope_mismatch == 0`), and at least one attempt must fire the
11247 /// counter or the gate is vacuous.
11248 #[test]
11249 fn a_real_aomenc_rect_strip_palette_decodes_pixel_exact() {
11250 const NAME: &str = "a_real_aomenc_rect_strip_palette_decodes_pixel_exact";
11251 if !have_ffmpeg() {
11252 eprintln!("SKIP {NAME}: no ffmpeg");
11253 return;
11254 }
11255 if !have_aomenc() {
11256 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11257 return;
11258 }
11259 let (width, height) = (256usize, 192usize);
11260 let screen: &[&str] = &[
11261 "--tune-content=screen",
11262 "--enable-palette=1",
11263 "--enable-1to4-partitions=1",
11264 "--min-partition-size=8",
11265 ];
11266 // lane-kf900 r6: arms 3-4 are the palette + `--enable-tx-size-search=1`
11267 // shape whose neighbour palette lookup was SUB-granular -- a 16x8 strip
11268 // pair shares one 16px cell, so strip 1 read strip 0's palette size and
11269 // the colour cache came out short. Both were whole-frame wrong before
11270 // the mi-granular fix (`$HOME/.cache/kf900-r6/sweep.log`: smptebars
11271 // cq40/cq55 txs=1 pal=1 = DIFF).
11272 let screen_txs: &[&str] = &[
11273 "--tune-content=screen",
11274 "--enable-palette=1",
11275 "--enable-1to4-partitions=1",
11276 "--min-partition-size=8",
11277 "--max-partition-size=32",
11278 "--sb-size=64",
11279 "--enable-intrabc=1",
11280 "--enable-tx-size-search=1",
11281 ];
11282 let cq40: Vec<&str> = screen_txs
11283 .iter()
11284 .copied()
11285 .chain(["--cq-level=40"])
11286 .collect();
11287 let cq55: Vec<&str> = screen_txs
11288 .iter()
11289 .copied()
11290 .chain(["--cq-level=55"])
11291 .collect();
11292 let arms: [(&str, String, &[&str]); 5] = [
11293 (
11294 "testsrc2-pinned",
11295 "testsrc2=s=256x192:r=25".to_string(),
11296 &[],
11297 ),
11298 (
11299 "testsrc2-screen",
11300 "testsrc2=s=256x192:r=25".to_string(),
11301 screen,
11302 ),
11303 (
11304 "smptebars-screen",
11305 "smptebars=size=256x192:rate=25".to_string(),
11306 screen,
11307 ),
11308 (
11309 "smptebars-screen-txs-cq40",
11310 "smptebars=size=256x192:rate=25".to_string(),
11311 &cq40,
11312 ),
11313 (
11314 "smptebars-screen-txs-cq55",
11315 "smptebars=size=256x192:rate=25".to_string(),
11316 &cq55,
11317 ),
11318 ];
11319 let (mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32, 0u32);
11320 let mut refused = 0u32;
11321 let mut fired_at_depth = [0u32; 2];
11322 let mut frames_compared = 0usize;
11323 for (arm, src, extra) in &arms {
11324 for depth in [8usize, 10] {
11325 let pix_fmt = if depth == 10 {
11326 "yuv420p10le"
11327 } else {
11328 "yuv420p"
11329 };
11330 let render = || {
11331 let out = Command::new("ffmpeg")
11332 .args([
11333 "-v",
11334 "error",
11335 "-f",
11336 "lavfi",
11337 "-i",
11338 src.as_str(),
11339 "-t",
11340 "0.2",
11341 "-pix_fmt",
11342 pix_fmt,
11343 "-strict",
11344 "-1",
11345 "-f",
11346 "yuv4mpegpipe",
11347 "-",
11348 ])
11349 .stdin(Stdio::null())
11350 .stdout(Stdio::piped())
11351 .stderr(Stdio::piped())
11352 .output()
11353 .expect("ffmpeg failed to run");
11354 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
11355 out.stdout
11356 };
11357 let y4m_a = render();
11358 let y4m_b = render();
11359 assert_eq!(
11360 y4m_a, y4m_b,
11361 "{NAME}: {arm} must render byte-identical across two runs at {depth}-bit"
11362 );
11363 let y4m = y4m_a;
11364 let depth_arg = format!("--bit-depth={depth}");
11365 let in_depth_arg = format!("--input-bit-depth={depth}");
11366 let out = run_with_stdin(
11367 Command::new(aomenc_path())
11368 .args(["--codec=av1"])
11369 .args([&depth_arg, &in_depth_arg])
11370 .args([
11371 "--passes=1",
11372 "--end-usage=q",
11373 "--cq-level=59",
11374 "--cpu-used=0",
11375 "--lag-in-frames=0",
11376 "--kf-max-dist=1",
11377 "--limit=1",
11378 "--threads=1",
11379 "--tile-columns=0",
11380 "--enable-tx-size-search=1",
11381 "--min-partition-size=8",
11382 "--enable-rect-partitions=1",
11383 ])
11384 // Per-arm overrides go AFTER the base recipe: aomenc keeps
11385 // the LAST occurrence of a repeated flag.
11386 .args(*extra)
11387 // The 8-bit twin of the pinned recipe picks a 128-root
11388 // HORZ partition, which this decoder still refuses by name
11389 // ("a 128x128 superblock HORZ/VERT or AB partition") --
11390 // an open refusal of another lane, unrelated to palette.
11391 // Pinning the superblock to 64 keeps the 8-bit arm on the
11392 // shape this gate is about; the 10-bit arms are the
11393 // untouched pinned recipe.
11394 .args(if depth == 8 {
11395 &["--sb-size=64"][..]
11396 } else {
11397 &[][..]
11398 })
11399 .args(["--obu", "-o", "-", "-"]),
11400 &y4m,
11401 );
11402 assert!(
11403 out.status.success(),
11404 "{NAME}: aomenc refused {arm} at {depth}-bit: {}",
11405 String::from_utf8_lossy(&out.stderr)
11406 );
11407 let stream = out.stdout;
11408 let before = decode::rect4_palette_hits();
11409 let frames = match decode_stream(&stream) {
11410 Ok(frames) => frames,
11411 // A NAMED refusal is another lane's open shape (here: a
11412 // palette on an 8x8 SQUARE leaf, still out of scope), never
11413 // a pass -- the attempt is counted out of scope and the
11414 // per-depth firing assert below keeps the gate honest.
11415 Err(e) if e.to_string().contains("unsupported") => {
11416 eprintln!("{NAME}: {arm} {depth}-bit REFUSED: {e}");
11417 refused += 1;
11418 continue;
11419 }
11420 Err(e) => panic!("{NAME}: decode failed on {arm} at {depth}-bit: {e}"),
11421 };
11422 let fired = decode::rect4_palette_hits() - before;
11423 let ffmpeg_frames = if depth == 10 {
11424 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
11425 } else {
11426 ffmpeg_decode_sequence(&stream, width, height, frames.len())
11427 };
11428 assert_eq!(
11429 frames.len(),
11430 ffmpeg_frames.len(),
11431 "{NAME}: {arm} at {depth}-bit -- frame count"
11432 );
11433 assert!(
11434 !frames.is_empty(),
11435 "{NAME}: {arm} at {depth}-bit decoded no frame"
11436 );
11437 // EVERY decode-order frame, all three planes.
11438 let mut exact = true;
11439 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
11440 if ours.y != theirs.y || ours.u != theirs.u || ours.v != theirs.v {
11441 exact = false;
11442 eprintln!("{NAME}: {arm} {depth}-bit frame {i} differs");
11443 }
11444 frames_compared += 1;
11445 }
11446 if fired > 0 {
11447 fired_arms += 1;
11448 fired_at_depth[usize::from(depth == 10)] += 1;
11449 assert!(
11450 exact,
11451 "{NAME}: {arm} at {depth}-bit has {fired} rect-strip palette block(s) \
11452 and does NOT decode pixel-exact"
11453 );
11454 } else {
11455 out_of_scope += 1;
11456 if !exact {
11457 out_of_scope_mismatch += 1;
11458 }
11459 }
11460 }
11461 }
11462 eprintln!(
11463 "{NAME}: {fired_arms} attempt(s) with a rect-strip palette block, \
11464 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
11465 {refused} refused, {frames_compared} frames compared, \
11466 fired 8-bit={} 10-bit={}",
11467 fired_at_depth[0], fired_at_depth[1]
11468 );
11469 // MEASURED 2026-09-02, every 8-bit attempt of these recipes: aomenc
11470 // puts its palettes on SQUARE blocks at 8 bit and every 8-bit stream
11471 // that reaches a rect strip with one lands on a palette shape still
11472 // out of scope (8x8 square leaf, or a 64x32/32x64 superblock strip
11473 // with a real transform). So the 8-bit arms here prove the DECODE
11474 // path, not the lift -- `fired_at_depth[0] == 0` is a known, reported
11475 // coverage gap and not a silent pass: the counter is printed.
11476 assert!(
11477 fired_at_depth[1] > 0,
11478 "{NAME}: no attempt put a palette on a rect strip \
11479 (8-bit={}, 10-bit={}) -- gate is vacuous",
11480 fired_at_depth[0],
11481 fired_at_depth[1]
11482 );
11483 assert!(fired_arms > 0, "{NAME}: gate is vacuous");
11484 assert_eq!(
11485 out_of_scope_mismatch, 0,
11486 "{NAME}: {out_of_scope_mismatch} attempt(s) without a rect-strip palette block \
11487 still mismatched -- an unrelated defect, not a SKIP"
11488 );
11489 }
11490
11491 /// lane-hbd r5: a real `aomenc --bit-depth=10` stream, decoded through
11492 /// this crate's own 10-bit planes (`Picture` widened to `u16` in an
11493 /// earlier round) and checked pixel-exact against ffmpeg's own decode of
11494 /// the identical bytes via [`ffmpeg_decode_sequence_10bit`]. Confirms
11495 /// (hard-asserts, not just trusts) the sequence header this stream
11496 /// actually parses to says `bit_depth == 10` before trusting any pixel
11497 /// match -- a stream that silently fell back to 8-bit would still
11498 /// "match" trivially.
11499 // -------------------------------------------------------------------
11500 // lane-av112bit: the 12-bit gate battery. The blanket refusal is lifted
11501 // for what these gates witness byte-exact against ffmpeg on real
11502 // `aomenc --bit-depth=12 --profile=2` streams: the full intra stack,
11503 // dequant/transforms at the 12-bit dequant tables, deblock, CDEF, loop
11504 // restoration (Wiener AND SGR), and translational subpel motion
11505 // compensation through the bit-depth-parameterised `round_0`/`round_1`
11506 // (libaom `convolve.h:81..86`). Everything else stays refused by name:
11507 // warp and screen content tools (palette/intrabc) at the frame level,
11508 // each with its own real-stream refusal gate below.
11509 // lane-av112bitc: compound joined the witnessed set (refusal gate became
11510 // the six-frame compound witness).
11511 // lane-av112bitg: film grain joined the witnessed set (refusal gate became
11512 // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
11513 // -------------------------------------------------------------------
11514
11515 /// The 12-bit witness source, byte-identical to the lane's committed
11516 /// fixture recipe: 160x128 C420p12, a gradient + fine-texture base with a
11517 /// 24x20 box that travels 1.25 px/frame horizontally and 0.75 px/frame
11518 /// vertically with linear edge coverage -- sub-pixel true motion, so an
11519 /// inter frame over it cannot be coded whole-pel-only.
11520 fn y4m_12bit_subpel_source(frames: usize) -> Vec<u8> {
11521 const W: usize = 160;
11522 const H: usize = 128;
11523 let cov = |a: f64, b: f64, i: i64| (b.min(i as f64 + 1.0) - a.max(i as f64)).max(0.0);
11524 let mut y4m = format!("YUV4MPEG2 W{W} H{H} F30:1 Ip A1:1 C420p12\n").into_bytes();
11525 for t in 0..frames {
11526 let (ax, ay) = (12.0 + 1.25 * t as f64, 10.0 + 0.75 * t as f64);
11527 let (bx, by) = (ax + 24.0, ay + 20.0);
11528 y4m.extend_from_slice(b"FRAME\n");
11529 for j in 0..H as i64 {
11530 for i in 0..W as i64 {
11531 let g = (i * 190) / W as i64 + (j * 150) / H as i64;
11532 let mut v = (g * 12
11533 + if (i * 5 + j * 3 + t as i64) % 7 < 3 {
11534 90
11535 } else {
11536 220
11537 }
11538 + if (60..110).contains(&i) && (70..110).contains(&j) {
11539 640
11540 } else {
11541 0
11542 }) as f64;
11543 let c = cov(ax, bx, i) * cov(ay, by, j);
11544 if c > 0.0 {
11545 v = v * (1.0 - c) + 3500.0 * c;
11546 }
11547 y4m.extend_from_slice(&(v.min(4095.0) as u16).to_le_bytes());
11548 }
11549 }
11550 for (base, fx) in [(1900usize, 0usize), (2100, 1)] {
11551 for j in 0..H / 2 {
11552 for i in 0..W / 2 {
11553 let v = if fx == 0 {
11554 base + (((i / 5 + t * 2) % 7) * 120 + (j * 60) / H)
11555 } else {
11556 base + (((j / 4 + t) % 5) * 140 + (i * 40) / W)
11557 };
11558 y4m.extend_from_slice(&(v.min(4095) as u16).to_le_bytes());
11559 }
11560 }
11561 }
11562 }
11563 y4m
11564 }
11565
11566 /// lane-av1gwarp12 fixture: rotating + uniformly zooming mandelbrot as a
11567 /// C420p12 y4m. Rotation composed with a UNIFORM scale is a similarity
11568 /// transform -- exactly the family a 4-parameter ROTZOOM global model
11569 /// expresses (the affine gate needs the anisotropic stretch to force
11570 /// 6 parameters; this lane needs the model vanilla aomenc actually
11571 /// searches, ROTZOOM).
11572 fn y4m_12bit_rotzoom_gm_source(frames: usize) -> Vec<u8> {
11573 const W: usize = 128;
11574 const H: usize = 128;
11575 let source = format!(
11576 "mandelbrot=size=192x192:rate=25,rotate=a=0.12*t:c=black,\
11577 scale=w='ceil(192*(1+0.04*n)/2)*2':h='ceil(192*(1+0.04*n)/2)*2':eval=frame,\
11578 crop={W}:{H}"
11579 );
11580 let duration = (frames as f64 / 25.0).to_string();
11581 let ff_args: Vec<&str> = vec![
11582 "-v",
11583 "error",
11584 "-f",
11585 "lavfi",
11586 "-i",
11587 &source,
11588 "-pix_fmt",
11589 "yuv420p12le",
11590 // y4m has no official 12-bit tag, same as the 10-bit gate.
11591 "-strict",
11592 "-1",
11593 "-t",
11594 &duration,
11595 "-f",
11596 "yuv4mpegpipe",
11597 "-",
11598 ];
11599 let out = Command::new("ffmpeg")
11600 .args(&ff_args)
11601 .stdin(Stdio::null())
11602 .stdout(Stdio::piped())
11603 .stderr(Stdio::piped())
11604 .output()
11605 .expect("ffmpeg failed to run");
11606 assert!(
11607 out.status.success(),
11608 "ffmpeg fixture: {}",
11609 String::from_utf8_lossy(&out.stderr)
11610 );
11611 out.stdout
11612 }
11613
11614 /// The 12-bit coding recipe shared by the witness gates (cpu-used=0 so
11615 /// every search runs; explicit CDEF/restoration ON). Warp/global-motion
11616 /// are deliberately NOT spelled here: this aomenc honours the LAST
11617 /// occurrence of these flags (measured), so a base pin plus an override
11618 /// would silently take the base value -- each gate spells what it needs
11619 /// exactly once.
11620 fn encode_12bit(y4m: &[u8], frames: usize, extra: &[&str]) -> Vec<u8> {
11621 let limit = format!("--limit={frames}");
11622 let mut args: Vec<&str> = vec![
11623 "--codec=av1",
11624 "--profile=2",
11625 "--passes=1",
11626 "--end-usage=q",
11627 "--cq-level=20",
11628 "--cpu-used=0",
11629 "--threads=1",
11630 "--row-mt=0",
11631 "--sb-size=64",
11632 "--lag-in-frames=0",
11633 "--auto-alt-ref=0",
11634 "--kf-max-dist=1000",
11635 "--input-bit-depth=12",
11636 "--bit-depth=12",
11637 "--enable-cdef=1",
11638 "--enable-restoration=1",
11639 "--obu",
11640 "-o",
11641 "-",
11642 "-",
11643 &limit,
11644 ];
11645 // AOMENC FLAG PRECEDENCE (COMMON): aomenc keeps the FIRST occurrence
11646 // of a flag, so the per-arm override goes BEFORE the base list.
11647 args.splice(1..1, extra.iter().copied());
11648 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m);
11649 assert!(
11650 out.status.success(),
11651 "aomenc refused the 12-bit fixture: {}",
11652 String::from_utf8_lossy(&out.stderr)
11653 );
11654 out.stdout
11655 }
11656
11657 /// Asserts the stream's sequence header really says 12-bit before any
11658 /// pixel comparison is trusted.
11659 fn assert_12bit_sequence_header(stream: &[u8], name: &str) {
11660 let mut probe = Av1Parser::new();
11661 let mut pos = 0usize;
11662 while pos < stream.len() && probe.sequence_header().is_none() {
11663 let obu = probe.parse_obu(&stream[pos..]).unwrap();
11664 pos += obu.total_size;
11665 }
11666 let seq = probe
11667 .sequence_header()
11668 .expect("stream has a sequence header OBU");
11669 assert_eq!(
11670 seq.color_config.bit_depth, 12,
11671 "{name}: aomenc did not actually write a 12-bit sequence header"
11672 );
11673 }
11674
11675 fn ffmpeg_decode_sequence_12bit(
11676 stream: &[u8],
11677 width: usize,
11678 height: usize,
11679 frames: usize,
11680 ) -> Vec<Pic> {
11681 let out = run_with_stdin(
11682 Command::new("ffmpeg").args([
11683 "-v",
11684 "error",
11685 "-f",
11686 "obu",
11687 "-i",
11688 "-",
11689 "-f",
11690 "rawvideo",
11691 "-pix_fmt",
11692 "yuv420p12le",
11693 "-",
11694 ]),
11695 stream,
11696 );
11697 assert!(
11698 out.status.success(),
11699 "ffmpeg refused the 12-bit stream: {}",
11700 String::from_utf8_lossy(&out.stderr)
11701 );
11702 let (luma, chroma) = (width * height, width * height / 4);
11703 let frame_bytes = (luma + 2 * chroma) * 2;
11704 assert_eq!(
11705 out.stdout.len(),
11706 frame_bytes * frames,
11707 "expected {frames} 4:2:0 12-bit frames, ffmpeg said: {}",
11708 String::from_utf8_lossy(&out.stderr)
11709 );
11710 fn le16(bytes: &[u8]) -> Vec<u16> {
11711 bytes
11712 .chunks_exact(2)
11713 .map(|c| u16::from_le_bytes([c[0], c[1]]))
11714 .collect()
11715 }
11716 (0..frames)
11717 .map(|i| {
11718 let base = i * frame_bytes;
11719 Pic {
11720 width,
11721 height,
11722 y: le16(&out.stdout[base..base + luma * 2]),
11723 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
11724 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
11725 }
11726 })
11727 .collect()
11728 }
11729
11730 /// The 12-bit KEY witness: CDEF and loop restoration ON, grain off.
11731 /// Byte-exact against ffmpeg, and the 12-bit-sensitive pixel paths hard-
11732 /// assert fired: a CDEF index literal read (bits > 0) and at least one
11733 /// Wiener or SGR restoration unit. Gauntlet for the parameterised
11734 /// rounding sites: MC/Wiener round pairs, `coeff_shift = bd - 8` CDEF,
11735 /// the 12-bit dequant tables, bd-scaled SGR box sums.
11736 #[test]
11737 fn a_real_aomenc_12bit_stream_decodes_pixel_exact() {
11738 const NAME: &str = "a_real_aomenc_12bit_stream_decodes_pixel_exact";
11739 let _gate_lock = lock_gate_counters();
11740 if !have_ffmpeg() {
11741 eprintln!("SKIP {NAME}: no ffmpeg");
11742 return;
11743 }
11744 if !have_aomenc() {
11745 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11746 return;
11747 }
11748 let y4m = y4m_12bit_subpel_source(1);
11749 let stream = encode_12bit(
11750 &y4m,
11751 1,
11752 &["--enable-warped-motion=0", "--enable-global-motion=0"],
11753 );
11754 assert_12bit_sequence_header(&stream, NAME);
11755 let before_cdef = decode::cdef_idx_hits();
11756 let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
11757 let frames = decode_stream(&stream).unwrap_or_else(|e| {
11758 panic!("{NAME}: decode_stream refused a real 12-bit key frame: {e}")
11759 });
11760 assert_eq!(frames.len(), 1);
11761 assert!(
11762 decode::cdef_idx_hits() > before_cdef,
11763 "{NAME}: no CDEF index literal was read -- CDEF is not exercised"
11764 );
11765 assert!(
11766 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
11767 "{NAME}: no loop restoration unit was decoded -- LR is not exercised"
11768 );
11769 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 1);
11770 assert_eq!(
11771 frames[0].y, ffmpeg_frames[0].y,
11772 "luma vs ffmpeg (12-bit key)"
11773 );
11774 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (12-bit key)");
11775 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (12-bit key)");
11776 }
11777
11778 /// The 12-bit INTER witness: a key frame plus one P frame over sub-pixel
11779 /// true motion. Byte-exact against ffmpeg; hard-asserts the two-pass
11780 /// SUBPEL prediction path ran (`MC_SUBPEL_HITS`), so the frame's own
11781 /// `round_0`/`round_1` -- 5/9 at 12 bits, the whole point of the mc.rs
11782 /// parameterisation -- really executed, and asserts
11783 /// `compound_mode_hits` UNCHANGED (this recipe offers no divergent
11784 /// second reference, so no compound mode symbol is read -- the lane's
11785 /// compound witness is the six-frame gate below).
11786 #[test]
11787 fn a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact() {
11788 const NAME: &str = "a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact";
11789 let _gate_lock = lock_gate_counters();
11790 if !have_ffmpeg() {
11791 eprintln!("SKIP {NAME}: no ffmpeg");
11792 return;
11793 }
11794 if !have_aomenc() {
11795 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11796 return;
11797 }
11798 let y4m = y4m_12bit_subpel_source(2);
11799 let stream = encode_12bit(
11800 &y4m,
11801 2,
11802 &["--enable-warped-motion=0", "--enable-global-motion=0"],
11803 );
11804 assert_12bit_sequence_header(&stream, NAME);
11805 let before_subpel = crate::mc::mc_subpel_hits();
11806 let before_compound = decode::compound_mode_hits();
11807 let frames = decode_stream(&stream).unwrap_or_else(|e| {
11808 panic!("{NAME}: decode_stream refused a real 12-bit inter stream: {e}")
11809 });
11810 assert_eq!(frames.len(), 2);
11811 assert!(
11812 crate::mc::mc_subpel_hits() > before_subpel,
11813 "{NAME}: no subpel inter prediction decoded -- the 12-bit round pair is unexercised"
11814 );
11815 assert_eq!(
11816 decode::compound_mode_hits(),
11817 before_compound,
11818 "{NAME}: a compound mode symbol was read -- the single-reference premise is gone"
11819 );
11820 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2);
11821 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11822 assert_eq!(
11823 ours.y, reference.y,
11824 "frame {i} luma vs ffmpeg (12-bit inter)"
11825 );
11826 assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit inter)");
11827 assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit inter)");
11828 }
11829 }
11830
11831 /// The 12-bit WARP witness (lane-av112bitw): the same source and recipe
11832 /// with the warp tools ON -- aomenc picks warp models on this content
11833 /// (measured pre-lift: the warp model fires at the third frame, and the
11834 /// decode refused by name at exactly that block) -- now decodes
11835 /// BYTE-EXACT against ffmpeg. The warp filter's shifts are the bumped
11836 /// `conv_params->round_0` (`warp::warp_round_0`, 5 at 12 bits, feeding
11837 /// `reduce_bits_horiz`, the derived non-compound
11838 /// `reduce_bits_vert = 2*FILTER_BITS - round_0` and both `offset_bits`),
11839 /// the whole libaom `get_conv_params_no_round` 12-bit bump.
11840 ///
11841 /// Non-vacuous: the same recipe refused by name before the lift, the
11842 /// gate hard-asserts a warp predictor was really resolved (a warpless
11843 /// stream would pass the pixel compare and prove nothing), and every
11844 /// plane of every frame compares against ffmpeg's decode.
11845 #[test]
11846 fn a_12bit_warped_motion_stream_decodes_pixel_exact() {
11847 const NAME: &str = "a_12bit_warped_motion_stream_decodes_pixel_exact";
11848 let _gate_lock = lock_gate_counters();
11849 if !have_ffmpeg() {
11850 eprintln!("SKIP {NAME}: no ffmpeg");
11851 return;
11852 }
11853 if !have_aomenc() {
11854 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11855 return;
11856 }
11857 let y4m = y4m_12bit_subpel_source(6);
11858 // Exactly the recipe measured to refuse at warp pre-lift: warp ON,
11859 // global motion NOT spelled (spelling it ON drives a GLOBAL_GLOBALMV
11860 // compound block into the compound-warp arm -- see the compound gate
11861 // below), six frames -- the warp model fires at the third frame.
11862 let stream = encode_12bit(&y4m, 6, &["--enable-warped-motion=1"]);
11863 assert_12bit_sequence_header(&stream, NAME);
11864 let (before_selected, before_warp8, before_affine) = (
11865 decode::warp_selected_hits(),
11866 decode::warp_hits_8(),
11867 decode::affine_gm_hits(),
11868 );
11869 let frames = decode_stream(&stream).unwrap_or_else(|e| {
11870 panic!("{NAME}: decode_stream refused a real 12-bit warp stream: {e}")
11871 });
11872 assert_eq!(frames.len(), 6);
11873 let (delta_selected, delta_warp8, delta_affine) = (
11874 decode::warp_selected_hits() - before_selected,
11875 decode::warp_hits_8() - before_warp8,
11876 decode::affine_gm_hits() - before_affine,
11877 );
11878 eprintln!(
11879 "{NAME}: warp_engagement selected(16x16+ symbol)={delta_selected} \
11880 warped8(usable 8x8 model)={delta_warp8} affine_gm(6-param model)={delta_affine}"
11881 );
11882 assert!(
11883 delta_selected + delta_warp8 + delta_affine > 0,
11884 "{NAME}: no warp predictor was resolved -- the stream carries no \
11885 warp model and the pixel compare would prove nothing"
11886 );
11887 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6);
11888 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11889 assert_eq!(
11890 ours.y, reference.y,
11891 "frame {i} luma vs ffmpeg (12-bit warp)"
11892 );
11893 assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit warp)");
11894 assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit warp)");
11895 }
11896 }
11897
11898 /// The 12-bit COMPOUND witness (lane-av112bitc): the parent's source
11899 /// and recipe with warp pinned OFF -- with six frames LAST diverges
11900 /// from GOLDEN from frame 2 on and aomenc codes compound inter blocks
11901 /// (pre-lift measurement: the decode refused at the compound mode
11902 /// read). Two arms: the default recipe (dist-weighted average
11903 /// combines live) and `--enable-dist-wtd-comp=0` (pushes compound AND
11904 /// the masked choice harder: 6 diffwtd blends). Both byte-exact
11905 /// against ffmpeg; each hard-asserts compound mode symbols and
11906 /// masked-diffwtd blends really ran, so the parameterised combine
11907 /// rounds (`INTER_POST_ROUND - delta`, diffwtd `+ (bd-8) - delta` at
11908 /// 12 bits) and the ffmpeg-pinned pixel path genuinely executed.
11909 #[test]
11910 fn a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact() {
11911 const NAME: &str = "a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact";
11912 let _gate_lock = lock_gate_counters();
11913 if !have_ffmpeg() {
11914 eprintln!("SKIP {NAME}: no ffmpeg");
11915 return;
11916 }
11917 if !have_aomenc() {
11918 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11919 return;
11920 }
11921 let y4m = y4m_12bit_subpel_source(6);
11922 for (arm, extra) in [
11923 ("dist-wtd", &["--enable-warped-motion=0"][..]),
11924 (
11925 "plain-masked",
11926 &["--enable-warped-motion=0", "--enable-dist-wtd-comp=0"][..],
11927 ),
11928 ] {
11929 let stream = encode_12bit(&y4m, 6, &extra);
11930 assert_12bit_sequence_header(&stream, NAME);
11931 let before_compound = decode::compound_mode_hits();
11932 let before_masked = decode::masked_compound_hits();
11933 let before_diffwtd = decode::diffwtd_hits();
11934 let before_wedge = decode::wedge_hits();
11935 let frames = decode_stream(&stream).unwrap_or_else(|e| {
11936 panic!("{NAME} [{arm}]: decode_stream refused a real 12-bit compound stream: {e}")
11937 });
11938 assert_eq!(frames.len(), 6, "{NAME} [{arm}]: frame count");
11939 let (comp, masked, diffwtd, wedge) = (
11940 decode::compound_mode_hits() - before_compound,
11941 decode::masked_compound_hits() - before_masked,
11942 decode::diffwtd_hits() - before_diffwtd,
11943 decode::wedge_hits() - before_wedge,
11944 );
11945 eprintln!(
11946 "{NAME} [{arm}]: compound blocks={comp} masked={masked} diffwtd={diffwtd} wedge={wedge}"
11947 );
11948 assert!(
11949 comp > 0,
11950 "{NAME} [{arm}]: no compound mode symbol was read -- the compound path is unexercised"
11951 );
11952 assert!(
11953 masked > 0,
11954 "{NAME} [{arm}]: no masked compound block ran -- the masked combine is unexercised"
11955 );
11956 assert!(
11957 diffwtd > 0,
11958 "{NAME} [{arm}]: no diffwtd blend ran -- the diffwtd combine is unexercised"
11959 );
11960 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6);
11961 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
11962 assert_eq!(
11963 ours.y, reference.y,
11964 "{NAME} [{arm}] frame {i} luma vs ffmpeg"
11965 );
11966 assert_eq!(ours.u, reference.u, "{NAME} [{arm}] frame {i} U vs ffmpeg");
11967 assert_eq!(ours.v, reference.v, "{NAME} [{arm}] frame {i} V vs ffmpeg");
11968 }
11969 }
11970 }
11971
11972 /// lane-av112bitg: the 12-bit film grain witness. A real
11973 /// `aomenc --bit-depth=12 --profile=2 --film-grain-test=5` stream -- grain
11974 /// params present AND applied (2 luma + 9 cb + 9 cr scaling points,
11975 /// overlap blending on, clip-to-restricted-range on; the second frame is
11976 /// an INTER frame that inherits the params via `update_grain = 0`) --
11977 /// decoded byte-exact against ffmpeg's own 12-bit decode of the identical
11978 /// bytes (ffmpeg synthesizes grain by default; no grain-disable flag is
11979 /// passed anywhere in this file). Proves the bit-depth-generic grain path
11980 /// at 12 bits: `grain_range`'s ±(128 << 4) AR clamp and overlap-blend
11981 /// clamp, the `gauss_sec_shift = 12 - bd` Gaussian shift, the 4096-entry
11982 /// expanded scaling-LUT interpolation, and the `<< (bit_depth - 8)`
11983 /// chroma offsets and legal-range clamps. HARD-asserts the parsed headers
11984 /// really carry that coverage and `film_grain::grain_hits()` fired, so
11985 /// neither a params-without-apply stream nor a silently-skipped synthesis
11986 /// can pass vacuously.
11987 #[test]
11988 fn a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact() {
11989 const NAME: &str = "a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact";
11990 let _gate_lock = lock_gate_counters();
11991 if !have_ffmpeg() {
11992 eprintln!("SKIP {NAME}: no ffmpeg");
11993 return;
11994 }
11995 if !have_aomenc() {
11996 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11997 return;
11998 }
11999 let y4m = y4m_12bit_subpel_source(2);
12000 // Warp stays refused at 12 bits (lane-av112bitg lifts GRAIN only), so
12001 // the arm pins both motion tools off exactly once each -- aomenc
12002 // otherwise picks warped motion on this fixture's sub-pel motion.
12003 let stream = encode_12bit(
12004 &y4m,
12005 2,
12006 &[
12007 "--film-grain-test=5",
12008 "--enable-warped-motion=0",
12009 "--enable-global-motion=0",
12010 ],
12011 );
12012 assert_12bit_sequence_header(&stream, NAME);
12013 // The arm is only honest if the stream itself carries the coverage:
12014 // grain applied on every frame, scaling points on all three planes,
12015 // overlap blending and restricted-range clipping on.
12016 let mut probe = Av1Parser::new();
12017 let mut pos = 0usize;
12018 let mut grain_frames = 0usize;
12019 while pos < stream.len() {
12020 let obu = probe.parse_obu(&stream[pos..]).unwrap();
12021 pos += obu.total_size;
12022 if let ObuKind::Frame(header, _) = obu.kind {
12023 let fg = &header.film_grain;
12024 assert!(
12025 fg.apply_grain,
12026 "{NAME}: frame without apply_grain -- aomenc emitted params it does not apply"
12027 );
12028 assert!(
12029 fg.num_y_points > 0 && fg.num_cb_points > 0 && fg.num_cr_points > 0,
12030 "{NAME}: grain without all three planes' scaling points -- the bit-depth \
12031 LUT math would not be exercised"
12032 );
12033 assert!(
12034 fg.overlap_flag,
12035 "{NAME}: overlap off -- the grain_min/grain_max blend clamp is not exercised"
12036 );
12037 assert!(
12038 fg.clip_to_restricted_range,
12039 "{NAME}: clip_to_restricted_range off -- the << (bd - 8) legal-range clamps \
12040 are not exercised"
12041 );
12042 grain_frames += 1;
12043 }
12044 }
12045 assert_eq!(grain_frames, 2, "{NAME}: expected grain on both frames");
12046 let before = crate::film_grain::grain_hits();
12047 let frames = decode_stream(&stream).unwrap_or_else(|e| {
12048 panic!("{NAME}: decode_stream refused a real 12-bit grain stream: {e}")
12049 });
12050 assert_eq!(frames.len(), 2);
12051 assert!(
12052 crate::film_grain::grain_hits() > before,
12053 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
12054 );
12055 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2);
12056 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12057 assert_eq!(
12058 ours.y, theirs.y,
12059 "{NAME}: luma vs ffmpeg (12-bit grain, frame {i})"
12060 );
12061 assert_eq!(
12062 ours.u, theirs.u,
12063 "{NAME}: U vs ffmpeg (12-bit grain, frame {i})"
12064 );
12065 assert_eq!(
12066 ours.v, theirs.v,
12067 "{NAME}: V vs ffmpeg (12-bit grain, frame {i})"
12068 );
12069 }
12070 eprintln!(
12071 "{NAME}: byte-exact, grain_hits={}",
12072 crate::film_grain::grain_hits()
12073 );
12074 }
12075
12076 /// The 12-bit screen-content refusal: a real `--tune-content=screen
12077 /// --enable-palette=1 --enable-intrabc=1` frame carries
12078 /// `allow_screen_content_tools = 1` and is refused by name at the frame
12079 /// gate -- palette and intrabc have no 12-bit witness.
12080 #[test]
12081 fn a_12bit_screen_content_stream_is_refused_by_name() {
12082 const NAME: &str = "a_12bit_screen_content_stream_is_refused_by_name";
12083 let _gate_lock = lock_gate_counters();
12084 if !have_ffmpeg() {
12085 eprintln!("SKIP {NAME}: no ffmpeg");
12086 return;
12087 }
12088 if !have_aomenc() {
12089 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12090 return;
12091 }
12092 let y4m = Command::new("ffmpeg")
12093 .args([
12094 "-v",
12095 "error",
12096 "-f",
12097 "lavfi",
12098 "-i",
12099 "smptebars=s=128x128:r=25",
12100 "-pix_fmt",
12101 "yuv420p12le",
12102 "-strict",
12103 "-1",
12104 "-frames:v",
12105 "2",
12106 "-f",
12107 "yuv4mpegpipe",
12108 "-",
12109 ])
12110 .stdin(Stdio::null())
12111 .stdout(Stdio::piped())
12112 .stderr(Stdio::piped())
12113 .output()
12114 .expect("ffmpeg failed to run");
12115 assert!(
12116 y4m.status.success(),
12117 "ffmpeg failed to render the 12-bit screen fixture: {}",
12118 String::from_utf8_lossy(&y4m.stderr)
12119 );
12120 let stream = encode_12bit(
12121 &y4m.stdout,
12122 1,
12123 &[
12124 "--tune-content=screen",
12125 "--enable-palette=1",
12126 "--enable-intrabc=1",
12127 ],
12128 );
12129 let err = decode_stream(&stream).unwrap_err().to_string();
12130 assert!(
12131 err.contains(
12132 "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)"
12133 ),
12134 "{NAME}: expected the 12-bit screen content refusal, got: {err}"
12135 );
12136 }
12137
12138 #[test]
12139 fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {
12140 const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact";
12141 if !have_ffmpeg() {
12142 eprintln!("SKIP {NAME}: no ffmpeg");
12143 return;
12144 }
12145 if !have_aomenc() {
12146 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12147 return;
12148 }
12149 let (width, height) = (64usize, 64usize);
12150 let y4m = Command::new("ffmpeg")
12151 .args([
12152 "-v",
12153 "error",
12154 "-f",
12155 "lavfi",
12156 "-i",
12157 &gradients_source(42, width, height, "duration=0.04:rate=25"),
12158 "-pix_fmt",
12159 "yuv420p10le",
12160 "-strict",
12161 "-1",
12162 "-t",
12163 "0.04",
12164 "-f",
12165 "yuv4mpegpipe",
12166 "-",
12167 ])
12168 .stdin(Stdio::null())
12169 .stdout(Stdio::piped())
12170 .stderr(Stdio::piped())
12171 .output()
12172 .expect("ffmpeg failed to run");
12173 assert!(
12174 y4m.status.success(),
12175 "ffmpeg failed to render the 10-bit fixture: {}",
12176 String::from_utf8_lossy(&y4m.stderr)
12177 );
12178 let out = run_with_stdin(
12179 Command::new(aomenc_path()).args([
12180 "--codec=av1",
12181 "--passes=1",
12182 "--end-usage=q",
12183 "--cq-level=30",
12184 "--cpu-used=0",
12185 "--threads=1",
12186 "--row-mt=0",
12187 "--sb-size=64",
12188 "--input-bit-depth=10",
12189 "--bit-depth=10",
12190 "--limit=1",
12191 "--obu",
12192 "-o",
12193 "-",
12194 "-",
12195 ]),
12196 &y4m.stdout,
12197 );
12198 assert!(
12199 out.status.success(),
12200 "aomenc refused the 10-bit fixture: {}",
12201 String::from_utf8_lossy(&out.stderr)
12202 );
12203 let stream = out.stdout;
12204 // Confirm the sequence header this stream actually parses to before
12205 // trusting any pixel comparison below.
12206 let mut probe = Av1Parser::new();
12207 let mut pos = 0usize;
12208 while pos < stream.len() && probe.sequence_header().is_none() {
12209 let obu = probe.parse_obu(&stream[pos..]).unwrap();
12210 pos += obu.total_size;
12211 }
12212 let seq = probe
12213 .sequence_header()
12214 .expect("stream has a sequence header OBU");
12215 assert_eq!(
12216 seq.color_config.bit_depth, 10,
12217 "{NAME}: aomenc did not actually write a 10-bit sequence header"
12218 );
12219 let frames = match decode_stream(&stream) {
12220 Ok(frames) => frames,
12221 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit stream: {e}"),
12222 };
12223 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
12224 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (10-bit)");
12225 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (10-bit)");
12226 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
12227 }
12228
12229 /// The 10-bit *inter* counterpart of the gate above: a real `aomenc`
12230 /// `yuv420p10le` sequence whose non-key frames are plain forward
12231 /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0
12232 /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate),
12233 /// decoded pixel-exact on every frame. 10-bit intra was proven exact by
12234 /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated.
12235 #[test]
12236 fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() {
12237 const NAME: &str = "a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact";
12238 let _gate_lock = lock_gate_counters();
12239 if !have_ffmpeg() {
12240 eprintln!("SKIP {NAME}: no ffmpeg");
12241 return;
12242 }
12243 if !have_aomenc() {
12244 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12245 return;
12246 }
12247 let (width, height, frame_count) = (128usize, 64usize, 16usize);
12248 let y4m = Command::new("ffmpeg")
12249 .args([
12250 "-v",
12251 "error",
12252 "-f",
12253 "lavfi",
12254 "-i",
12255 &gradients_source(42, width, height, "duration=0.64:rate=25"),
12256 "-pix_fmt",
12257 "yuv420p10le",
12258 "-strict",
12259 "-1",
12260 "-t",
12261 "0.64",
12262 "-f",
12263 "yuv4mpegpipe",
12264 "-",
12265 ])
12266 .stdin(Stdio::null())
12267 .stdout(Stdio::piped())
12268 .stderr(Stdio::piped())
12269 .output()
12270 .expect("ffmpeg failed to run");
12271 assert!(
12272 y4m.status.success(),
12273 "ffmpeg failed to render the 10-bit fixture: {}",
12274 String::from_utf8_lossy(&y4m.stderr)
12275 );
12276 let out = run_with_stdin(
12277 Command::new(aomenc_path()).args([
12278 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
12279 // occurrence, so overrides go before the base list).
12280 "--loopfilter-control=1",
12281 "--codec=av1",
12282 "--passes=1",
12283 "--end-usage=q",
12284 "--cq-level=15",
12285 "--cpu-used=0",
12286 "--threads=1",
12287 "--row-mt=0",
12288 "--sb-size=64",
12289 "--input-bit-depth=10",
12290 "--bit-depth=10",
12291 "--lag-in-frames=0",
12292 "--auto-alt-ref=0",
12293 "--kf-max-dist=1000",
12294 "--error-resilient=1",
12295 "--aq-mode=0",
12296 "--deltaq-mode=0",
12297 "--enable-cdef=0",
12298 "--enable-rect-partitions=0",
12299 "--enable-ab-partitions=0",
12300 "--enable-1to4-partitions=0",
12301 "--enable-filter-intra=0",
12302 "--enable-smooth-intra=0",
12303 "--enable-paeth-intra=0",
12304 "--enable-directional-intra=0",
12305 "--enable-angle-delta=0",
12306 "--enable-tx-size-search=0",
12307 "--enable-cdef=1",
12308 "--enable-restoration=1",
12309 "--min-partition-size=16",
12310 "--max-partition-size=32",
12311 "--enable-palette=0",
12312 "--enable-intrabc=0",
12313 "--enable-cfl-intra=0",
12314 "--enable-ref-frame-mvs=0",
12315 "--obu",
12316 "-o",
12317 "-",
12318 "-",
12319 ]),
12320 &y4m.stdout,
12321 );
12322 assert!(
12323 out.status.success(),
12324 "aomenc refused the 10-bit fixture: {}",
12325 String::from_utf8_lossy(&out.stderr)
12326 );
12327 let stream = out.stdout;
12328 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
12329 std::fs::write(dump, &stream).expect("dump stream");
12330 }
12331 let mut probe = Av1Parser::new();
12332 let mut pos = 0usize;
12333 while pos < stream.len() && probe.sequence_header().is_none() {
12334 let obu = probe.parse_obu(&stream[pos..]).unwrap();
12335 pos += obu.total_size;
12336 }
12337 assert_eq!(
12338 probe
12339 .sequence_header()
12340 .expect("stream has a sequence header OBU")
12341 .color_config
12342 .bit_depth,
12343 10,
12344 "{NAME}: aomenc did not actually write a 10-bit sequence header"
12345 );
12346 let before_deblock = decode::deblock_hits();
12347 let before_inter = decode::inter_pred_hits();
12348 let before_lr = crate::restoration::wiener_hits()
12349 + crate::restoration::sgrproj_hits()
12350 + crate::restoration::switchable_hits();
12351 let frames = match decode_stream(&stream) {
12352 Ok(frames) => frames,
12353 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"),
12354 };
12355 assert!(
12356 decode::inter_pred_hits() > before_inter,
12357 "{NAME}: no inter-predicted block decoded -- the gate proves nothing"
12358 );
12359 assert!(
12360 decode::deblock_hits() > before_deblock,
12361 "{NAME}: no deblocking edge fired -- raise cq-level"
12362 );
12363 // Loop restoration is where the 10-bit inter/intra defect lived
12364 // (lane-hbdinter r1: the self-guided box sums were never brought back
12365 // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened
12366 // to pick RESTORE_NONE would pass while proving nothing.
12367 assert!(
12368 crate::restoration::wiener_hits()
12369 + crate::restoration::sgrproj_hits()
12370 + crate::restoration::switchable_hits()
12371 > before_lr,
12372 "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level"
12373 );
12374 eprintln!(
12375 "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}",
12376 decode::inter_pred_hits() - before_inter,
12377 decode::deblock_hits() - before_deblock,
12378 decode::cdef_idx_hits(),
12379 crate::restoration::wiener_hits(),
12380 crate::restoration::sgrproj_hits(),
12381 );
12382 assert_eq!(frames.len(), frame_count);
12383 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count);
12384 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12385 if got.y != want.y || got.u != want.u || got.v != want.v {
12386 let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu");
12387 let _ = std::fs::write(&pin, &stream);
12388 let first = |a: &Vec<u16>, b: &Vec<u16>| {
12389 a.iter()
12390 .zip(b)
12391 .enumerate()
12392 .find(|(_, (x, y))| x != y)
12393 .map(|(k, (x, y))| (k, *x, *y))
12394 };
12395 panic!(
12396 "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}",
12397 first(&got.y, &want.y),
12398 first(&got.u, &want.u),
12399 first(&got.v, &want.v),
12400 pin.display()
12401 );
12402 }
12403 }
12404 }
12405
12406 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1`
12407 /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the
12408 /// identical bytes (ffmpeg synthesizes grain by default -- no
12409 /// grain-disable flag is passed anywhere in this file). Proves the
12410 /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`,
12411 /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather
12412 /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed
12413 /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a
12414 /// silent 8-bit fallback nor a stream aomenc emitted without
12415 /// `apply_grain` can make it pass vacuously.
12416 #[test]
12417 fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() {
12418 const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact";
12419 if !have_ffmpeg() {
12420 eprintln!("SKIP {NAME}: no ffmpeg");
12421 return;
12422 }
12423 if !have_aomenc() {
12424 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12425 return;
12426 }
12427 let (width, height) = (64usize, 64usize);
12428 let stream = encode_10bit_gradients(
12429 NAME,
12430 width,
12431 height,
12432 1,
12433 &["--film-grain-test=1", "--limit=1"],
12434 );
12435 assert_eq!(
12436 parsed_bit_depth(&stream),
12437 10,
12438 "{NAME}: aomenc did not actually write a 10-bit sequence header"
12439 );
12440 let mut probe = Av1Parser::new();
12441 let mut pos = 0usize;
12442 let mut saw_grain = false;
12443 while pos < stream.len() {
12444 let obu = probe.parse_obu(&stream[pos..]).unwrap();
12445 pos += obu.total_size;
12446 if let ObuKind::Frame(header, _) = obu.kind
12447 && header.film_grain.apply_grain
12448 {
12449 // A grain block whose scaling LUT is empty would blend a
12450 // zero delta into every pixel and let this gate pass without
12451 // the bit-depth math mattering at all.
12452 assert!(
12453 header.film_grain.num_y_points > 0,
12454 "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op"
12455 );
12456 saw_grain = true;
12457 }
12458 }
12459 assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain");
12460 let before = crate::film_grain::grain_hits();
12461 let frames = match decode_stream(&stream) {
12462 Ok(frames) => frames,
12463 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
12464 };
12465 assert!(
12466 crate::film_grain::grain_hits() > before,
12467 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
12468 );
12469 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
12470 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
12471 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
12472 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
12473 eprintln!(
12474 "{NAME}: pixel-exact, grain_hits={}",
12475 crate::film_grain::grain_hits()
12476 );
12477 }
12478
12479 /// lane-t900 r29: `fixtures/superres_kf_cdef_lr_64x64.obu` is a real
12480 /// aomenc key frame (64x64 upscaled from a coded 43x64,
12481 /// `--superres-mode=1 --superres-denominator=12 --cpu-used=0 --sb-size=64
12482 /// --enable-cdef=1 --enable-restoration=1 --cq-level=32`) -- the first
12483 /// stream in this repo that runs BOTH in-loop filters under superres.
12484 ///
12485 /// The defect it pins: spec 7.16's upscale runs between CDEF and loop
12486 /// restoration (libaom `superres_post_decode`, `decodeframe.c`, called
12487 /// between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`),
12488 /// but this decoder ran the whole filter chain on the DOWNSCALED frame
12489 /// and upscaled last, in `stream.rs`. Loop restoration therefore filtered
12490 /// downscaled pixels with a unit grid sized from the downscaled width
12491 /// (1873 wrong samples, max 7, on this very stream). Class
12492 /// `wrong-stage-width`: every plane width in the filter chain is either
12493 /// the downscaled one (deblock, CDEF, and the mi grid all three walk) or
12494 /// the upscaled one (loop restoration's `av1_get_upsampled_plane_size`
12495 /// unit grid, `av1_loop_restoration_corners_in_sb`'s `mi_to_num_x`
12496 /// superres arm, and the pixel filters themselves); the sweep is every
12497 /// caller of `apply_deblock`/`apply_cdef`/`apply_loop_restoration` plus
12498 /// `RestorationGrid::new` and `read_lr`.
12499 #[test]
12500 fn a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact() {
12501 const NAME: &str =
12502 "a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact";
12503 let _gate_lock = lock_gate_counters();
12504 if !have_ffmpeg() {
12505 eprintln!("SKIP {NAME}: no ffmpeg");
12506 return;
12507 }
12508 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12509 .join("fixtures/superres_kf_cdef_lr_64x64.obu");
12510 let stream = std::fs::read(&path)
12511 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
12512 let (width, height) = (64usize, 64usize);
12513 let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
12514 let frames = match decode_stream(&stream) {
12515 Ok(frames) => frames,
12516 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
12517 };
12518 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
12519 assert_eq!((frames[0].width, frames[0].height), (width, height));
12520 // class `gate-blind-to-feature`: the stream must actually upscale and
12521 // actually run a real restoration filter, or this gate proves nothing.
12522 assert!(
12523 crate::superres::superres_hits() > 0,
12524 "{NAME}: zero superres_hits -- the frame was never upscaled"
12525 );
12526 assert!(
12527 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
12528 "{NAME}: zero restoration units fired -- LR never ran under superres"
12529 );
12530 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
12531 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
12532 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
12533 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
12534 }
12535
12536 /// lane-filt1: `EC_AV1_FILTER_THREADS` splits every in-frame filter stage
12537 /// -- deblock (row bands for the vertical-edge pass, column bands for the
12538 /// horizontal one), CDEF (mi row bands), loop restoration (RU row bands)
12539 /// and film grain (32-pixel block rows) -- across scoped worker threads.
12540 /// A split is only legal if it is BYTE-EXACT, so this gate decodes two
12541 /// real aomenc streams at 1 and at 4 filter threads and compares every
12542 /// output frame's three planes.
12543 ///
12544 /// Between them the fixtures fire all four stages, and the firing
12545 /// counters are asserted rather than assumed (class `gate-blind-to-feature`):
12546 /// `superres_alltools_sb128_320x180.obu` is the 10-bit CDEF + loop
12547 /// restoration stream, `grain_cdef_lr_128x128.obu` a 128x128
12548 /// `--denoise-noise-level=25` stream whose frames carry film grain
12549 /// parameters (small enough that 4 bands is one block row each, which is
12550 /// what exercises the grain band's one-row `prelude` replay).
12551 /// lane-wave1 step (ii): the superblock-row wavefront
12552 /// (`EC_AV1_RECON_THREADS`) reconstructs every output frame byte for
12553 /// byte as the inline path does, on a hidden-ARF 10-bit stream (no-show
12554 /// frames, CfL, 128 superblocks) and on the two screen-content streams
12555 /// whose palette/intrabc blocks READ the current frame's pixels while
12556 /// parsing -- the sites that make the workers barrier.
12557 #[test]
12558 fn a_real_stream_reconstructs_identically_with_one_and_four_recon_threads() {
12559 const NAME: &str = "a_real_stream_reconstructs_identically_with_one_and_four_recon_threads";
12560 let _gate_lock = lock_gate_counters();
12561 for fixture in [
12562 "reelb_arf_witness.obu",
12563 "palette_screen_witness.obu",
12564 "palette_screen_witness_10bit.obu",
12565 // lane-av1wavefront: the 4:4:4 inter witness. The wavefront's
12566 // replay-side chroma (`mv_to_q4(.., ss_x(fctx))` in the deferred
12567 // builds, `exec_intra`'s CfL AC) used to read the worker's fresh
12568 // `FrameCtx` 4:2:0 DEFAULT instead of the frame's subsampling --
12569 // invisible on the three 4:2:0 streams above, chroma-only loss on
12570 // this one (f1 U 17504 / V 3, f2 U 25472 / V 1472 at PREFILT).
12571 "444_sb128rect_lr_witness.obu",
12572 ] {
12573 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12574 .join("fixtures")
12575 .join(fixture);
12576 let stream = std::fs::read(&path)
12577 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
12578 crate::par::set_recon_threads(1);
12579 let one = match decode_stream(&stream) {
12580 Ok(frames) => frames,
12581 Err(e) => panic!("{NAME}: {fixture} refused at 1 recon thread: {e}"),
12582 };
12583 crate::par::set_recon_threads(4);
12584 let four = match decode_stream(&stream) {
12585 Ok(frames) => frames,
12586 Err(e) => {
12587 crate::par::set_recon_threads(1);
12588 panic!("{NAME}: {fixture} refused at 4 recon threads: {e}")
12589 }
12590 };
12591 crate::par::set_recon_threads(1);
12592 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
12593 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
12594 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
12595 assert_eq!(
12596 a.y, b.y,
12597 "{NAME}: {fixture} frame {i} luma differs at 4 recon threads"
12598 );
12599 assert_eq!(
12600 a.u, b.u,
12601 "{NAME}: {fixture} frame {i} U differs at 4 recon threads"
12602 );
12603 assert_eq!(
12604 a.v, b.v,
12605 "{NAME}: {fixture} frame {i} V differs at 4 recon threads"
12606 );
12607 }
12608 }
12609 }
12610
12611 /// lane-memfix: the pool grows to the peak of `busy + queued` over the
12612 /// job tree and stops there. Before, a job running on a pool worker
12613 /// opened a SECOND pool on that worker's own thread-local -- one level
12614 /// per pipeline stage, none of them ever shrinking -- which is how a 4K
12615 /// decode at `(16, 4, 2)` reached 1038 live threads. Two decodes of the
12616 /// same stream: the count stays inside the composed setting and the
12617 /// second decode adds nothing (the ratchet is what cost the memory).
12618 #[test]
12619 fn the_worker_pool_stays_bounded_across_repeated_threaded_decodes() {
12620 const NAME: &str = "the_worker_pool_stays_bounded_across_repeated_threaded_decodes";
12621 let _gate_lock = lock_gate_counters();
12622 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12623 .join("fixtures")
12624 .join("superres_alltools_sb128_320x180.obu");
12625 let stream = std::fs::read(&path)
12626 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
12627 crate::par::set_filter_threads(4);
12628 crate::par::set_recon_threads(2);
12629 let mut counts = [0usize; 2];
12630 let mut frames = [0usize; 2];
12631 for (i, slot) in counts.iter_mut().enumerate() {
12632 let mut n = 0usize;
12633 let r = decode_stream_with_threads(&stream, 4, |_, _, _| {
12634 n += 1;
12635 Ok(())
12636 });
12637 if let Err(e) = r {
12638 crate::par::set_filter_threads(1);
12639 crate::par::set_recon_threads(1);
12640 panic!("{NAME}: refused on decode {i}: {e}");
12641 }
12642 frames[i] = n;
12643 *slot = crate::par::pool_threads();
12644 }
12645 crate::par::set_filter_threads(1);
12646 crate::par::set_recon_threads(1);
12647 assert!(
12648 frames[0] > 1,
12649 "{NAME}: the fixture decoded {} frames, so nothing was threaded",
12650 frames[0]
12651 );
12652 // 4 frame workers x (recon 2 + filter 4) plus the two in-flight
12653 // slots `stream.rs` allows over the thread count, with room for the
12654 // show jobs -- 1038 was three orders past this.
12655 assert!(
12656 counts[1] <= 4 * (2 + 4) + 2 * 4,
12657 "{NAME}: the pool grew to {} threads at 4 frame / 4 filter / 2 recon",
12658 counts[1]
12659 );
12660 // The pool grows to `busy + queued`, so a loaded box can queue one
12661 // more job than an idle one did (seen: 9 -> 10 at load 62). The
12662 // bound above is the structural claim; here only a runaway counts.
12663 assert!(
12664 counts[1] <= counts[0] + 4,
12665 "{NAME}: a second decode of the same stream grew the pool from {} to {} threads",
12666 counts[0],
12667 counts[1]
12668 );
12669 }
12670
12671 #[test]
12672 fn a_real_stream_filters_identically_with_one_and_four_filter_threads() {
12673 const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads";
12674 let _gate_lock = lock_gate_counters();
12675 for (fixture, wants_lr, wants_grain) in [
12676 ("superres_alltools_sb128_320x180.obu", true, false),
12677 ("grain_cdef_lr_128x128.obu", false, true),
12678 ] {
12679 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12680 .join("fixtures")
12681 .join(fixture);
12682 let stream = std::fs::read(&path)
12683 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
12684 let before = (
12685 crate::decode::deblock_hits(),
12686 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
12687 crate::film_grain::grain_hits(),
12688 );
12689 crate::par::set_filter_threads(1);
12690 let one = match decode_stream(&stream) {
12691 Ok(frames) => frames,
12692 Err(e) => panic!("{NAME}: {fixture} refused at 1 filter thread: {e}"),
12693 };
12694 let after = (
12695 crate::decode::deblock_hits(),
12696 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
12697 crate::film_grain::grain_hits(),
12698 );
12699 crate::par::set_filter_threads(4);
12700 let four = match decode_stream(&stream) {
12701 Ok(frames) => frames,
12702 Err(e) => {
12703 crate::par::set_filter_threads(1);
12704 panic!("{NAME}: {fixture} refused at 4 filter threads: {e}")
12705 }
12706 };
12707 crate::par::set_filter_threads(1);
12708 assert!(
12709 after.0 > before.0,
12710 "{NAME}: {fixture} deblocked no edge at all"
12711 );
12712 if wants_lr {
12713 assert!(
12714 after.1 > before.1,
12715 "{NAME}: {fixture} ran no restoration unit"
12716 );
12717 }
12718 if wants_grain {
12719 assert!(
12720 after.2 > before.2,
12721 "{NAME}: {fixture} applied no film grain"
12722 );
12723 }
12724 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
12725 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
12726 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
12727 assert_eq!(
12728 a.y, b.y,
12729 "{NAME}: {fixture} frame {i} luma differs at 4 filter threads"
12730 );
12731 assert_eq!(
12732 a.u, b.u,
12733 "{NAME}: {fixture} frame {i} U differs at 4 filter threads"
12734 );
12735 assert_eq!(
12736 a.v, b.v,
12737 "{NAME}: {fixture} frame {i} V differs at 4 filter threads"
12738 );
12739 }
12740 }
12741 }
12742
12743 /// lane-t900 r30b: `fixtures/superres_alltools_sb128_320x180.obu` is 10
12744 /// frames of `--cpu-used=4 --sb-size=128 --superres-mode=1
12745 /// --superres-denominator=12 --cq-level=32` with every tool aomenc turns
12746 /// on by default (CDEF, loop restoration, OBMC, compound, warp) -- the
12747 /// first stream here that deblocks CHROMA across a group of 4x4 luma
12748 /// blocks.
12749 ///
12750 /// The defect it pins (fixed at this commit, `decode.rs`'s
12751 /// `plane_to_mi`/`edge_params`): `set_lpf_parameters`
12752 /// (`av1_loopfilter.c:245`) indexes the mi grid for a CHROMA edge at
12753 /// `scale | ((coord << scale) >> MI_SIZE_LOG2)` -- the BOTTOM/RIGHT mi of
12754 /// the co-located 8x8 luma group, the same cell that donates the group's
12755 /// chroma prediction. This decoder dropped that `| 1` and read the
12756 /// group's top-left mi, stepped to the previous cell by one mi instead of
12757 /// `1 << ss`, and priced `pu_edge` by comparing mi origins rather than
12758 /// the edge coordinate against the block size in the FILTERED plane's own
12759 /// pixels (chroma bottoms out at 4). All three are invisible while every
12760 /// block is 8x8 or larger (all four mi of a group carry the same tx size,
12761 /// ref frame, skip flag and delta_lf) and wrong the moment cpu-used=4
12762 /// splits a group into 4x4 blocks: on this stream one U sample of frame 2
12763 /// took a filter level of 12 where libaom's neighbouring 4x4 block gives
12764 /// 8, and the error compounded through the reference chain to 280 U + 331
12765 /// V samples (max 9) by frame 9. Class `context-read-from-one-cell`.
12766 ///
12767 /// Post-deblock, this stream is now byte-exact against the instrumented
12768 /// libaom (`EC_AV1_POSTDEBLOCK_DUMP`) in all 10 frames, and the final
12769 /// output matches ffmpeg's.
12770 #[test]
12771 fn a_superres_all_tools_sb128_stream_decodes_pixel_exact() {
12772 const NAME: &str = "a_superres_all_tools_sb128_stream_decodes_pixel_exact";
12773 let _gate_lock = lock_gate_counters();
12774 if !have_ffmpeg() {
12775 eprintln!("SKIP {NAME}: no ffmpeg");
12776 return;
12777 }
12778 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12779 .join("fixtures/superres_alltools_sb128_320x180.obu");
12780 let stream = std::fs::read(&path)
12781 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
12782 let (width, height, count) = (320usize, 180usize, 10usize);
12783 let frames = match decode_stream(&stream) {
12784 Ok(frames) => frames,
12785 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
12786 };
12787 assert_eq!(frames.len(), count, "{NAME}: frame count");
12788 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, count);
12789 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
12790 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
12791 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
12792 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
12793 }
12794 }
12795
12796 /// lane-golomb r1: THE FILM ITSELF. `crates/ec-av1/fixtures/reelb_head_key_frame.obu`
12797 /// is the first frame of the user's ReelB AV1 release (3840x1608
12798 /// yuv420p10le, `ffmpeg -i <mkv> -c copy -frames:v 1 -f obu`, 147 bytes) --
12799 /// a real 10-bit key frame whose height is NOT a multiple of the 64-pixel
12800 /// superblock, so its last superblock row (mi_row=400 of 402) carries the
12801 /// edge partition symbol this lane fixed: libaom's `ec_read_partition_impl`
12802 /// returns `PARTITION_HORZ` when the gathered `split_or_horz` bit is 0, and
12803 /// this decoder used to READ that bit and throw it away, forcing SPLIT
12804 /// (class `parsed-then-discarded`). The desync surfaced two rows later as
12805 /// "a Golomb tail longer than this decoder reads" -- a refusal naming the
12806 /// symptom, never the cause.
12807 #[test]
12808 fn the_reelb_head_key_frame_decodes_pixel_exact() {
12809 const NAME: &str = "the_reelb_head_key_frame_decodes_pixel_exact";
12810 if !have_ffmpeg() {
12811 eprintln!("SKIP {NAME}: no ffmpeg");
12812 return;
12813 }
12814 let path =
12815 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_head_key_frame.obu");
12816 let stream = std::fs::read(&path)
12817 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
12818 let (width, height) = (3840usize, 1608usize);
12819 let frames = match decode_stream(&stream) {
12820 Ok(frames) => frames,
12821 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
12822 };
12823 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
12824 assert_eq!((frames[0].width, frames[0].height), (width, height));
12825 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
12826 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
12827 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
12828 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
12829 }
12830 /// lane-reelckf r2: `crates/ec-av1/fixtures/reelc_kf2700.obu` is a 1920x792
12831 /// 10-bit AV1 key frame taken out of one of the user's own films
12832 /// (`ffmpeg -ss 2700 -c:v copy -f obu`, then truncated to its first temporal
12833 /// unit, 36 kB) -- the ONLY stream in this repo that contains a SKIPPED
12834 /// `UV_CFL_PRED` block. 30 aomenc recipes (r1's 20 plus r2's chroma-correlated
12835 /// `geq` sweep, cq 40..63, cpu-used 0..2, min/max-partition 4..64, 8 and
12836 /// 10 bit) never made the encoder pick one, so the counter can only be
12837 /// hard-asserted against a real film frame. The instrumented oracle agrees:
12838 /// `EC_TRACE_MODE=1 aomdec` prints 5 `EC_IMODE_VAL ... uv_mode=13 skip=1`
12839 /// lines for this frame.
12840 ///
12841 /// The defect it pins (fixed at 29cd53f, `decode.rs:7719`/`:10528`/`:10891`):
12842 /// a skipped intra block must still PREDICT with CfL -- libaom's
12843 /// `predict_and_reconstruct_intra_block` predicts every plane and guards only
12844 /// the residual on `skip_txfm`. Before the fix this frame had 499 wrong
12845 /// chroma samples (U rows 48..79 cols 464..492); after it, zero.
12846 ///
12847 /// The ffmpeg reference is `ffmpeg -f obu -i <fixture> -f rawvideo
12848 /// -pix_fmt yuv420p10le -` (what `ffmpeg_decode_sequence_10bit` runs).
12849 #[test]
12850 fn a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact() {
12851 const NAME: &str = "a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact";
12852 let path =
12853 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelc_kf2700.obu");
12854 let stream = std::fs::read(&path)
12855 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
12856 let (width, height) = (1920usize, 792usize);
12857 let before = crate::decode::reelc_chroma_counters();
12858 let frames = match decode_stream(&stream) {
12859 Ok(frames) => frames,
12860 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
12861 };
12862 let after = crate::decode::reelc_chroma_counters();
12863 let skip_cfl = after.0 - before.0;
12864 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
12865 assert_eq!((frames[0].width, frames[0].height), (width, height));
12866 // Asserted before the ffmpeg compare so an absent ffmpeg cannot make the
12867 // gate vacuous: the skipped-CfL path is exercised on every run.
12868 assert!(
12869 skip_cfl > 0,
12870 "{NAME}: zero skipped-CfL blocks -- the fixture no longer exercises defect 1"
12871 );
12872 if !have_ffmpeg() {
12873 eprintln!("SKIP {NAME} pixel compare: no ffmpeg (skipped_cfl={skip_cfl})");
12874 return;
12875 }
12876 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
12877 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
12878 assert_eq!(
12879 frames[0].u, ffmpeg_frames[0].u,
12880 "{NAME}: U vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
12881 );
12882 assert_eq!(
12883 frames[0].v, ffmpeg_frames[0].v,
12884 "{NAME}: V vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
12885 );
12886 eprintln!("{NAME}: pixel-exact, skipped_cfl={skip_cfl}");
12887 }
12888
12889 /// lane-kf1200 r2: the same film's `-ss 300` key frame, pinned because no
12890 /// aomenc recipe reaches its shape -- a SKIPPED sub-8x8 chroma block whose
12891 /// `uv_mode` is `UV_CFL_PRED`. (lane-reelckf r1 burned 20 recipes across cq
12892 /// 40..63 and nine lavfi sources hunting exactly this block and never got
12893 /// one; ledger dead-end "never produced a SKIPPED 1:4 or sub-8x8 CfL
12894 /// block".) Before the fix the two sub-8x8 skip arms passed `None` for the
12895 /// CfL argument, so the block reconstructed as flat DC and 463 bytes of
12896 /// this frame's chroma were wrong. HARD-asserts `skip_cfl_hits` moved, so
12897 /// the fixture cannot silently stop exercising the arm.
12898 #[test]
12899 fn the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact() {
12900 const NAME: &str = "the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact";
12901 if !have_ffmpeg() {
12902 eprintln!("SKIP {NAME}: no ffmpeg");
12903 return;
12904 }
12905 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12906 .join("fixtures/reelb_ss300_key_frame.obu");
12907 let stream = std::fs::read(&path)
12908 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
12909 let (width, height) = (3840usize, 1608usize);
12910 let before = crate::decode::skip_cfl_hits();
12911 let frames = match decode_stream(&stream) {
12912 Ok(frames) => frames,
12913 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
12914 };
12915 let skipped_cfl = crate::decode::skip_cfl_hits() - before;
12916 assert!(
12917 skipped_cfl > 0,
12918 "{NAME}: zero skipped sub-8x8 CfL blocks -- the fixture no longer \
12919 exercises the arm this test exists for"
12920 );
12921 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
12922 assert_eq!((frames[0].width, frames[0].height), (width, height));
12923 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
12924 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
12925 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
12926 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
12927 eprintln!("{NAME}: {skipped_cfl} skipped sub-8x8 CfL chroma blocks, frame pixel-exact");
12928 }
12929
12930 /// lane-kf900 r2: the film's key frame at -ss 900, one frame
12931 /// (`crates/ec-av1/fixtures/reelb_kf900.obu`, 484640 bytes, sha256
12932 /// `a273ae99328388be14a1ff8fa1c5a6d391a9948159eaef120e1b50e02015eb83`,
12933 /// extracted twice from independent
12934 /// `ffmpeg -ss 900 -t 2 -i <2160p AV1 HDR10 mkv> -c:v copy -f obu` runs and
12935 /// truncated to the first frame; both extracts hashed identically).
12936 ///
12937 /// This is the ONLY stream that reaches the r1 defect: a SKIPPED 8x8 intra
12938 /// leaf whose `tx_depth` symbol resolved to `TX_4X4` still publishes 4 --
12939 /// not its 8-pixel block side -- to the next block's `get_tx_size_context`
12940 /// (`set_txfm_ctxs(mbmi->tx_size, bw, bh, skip_txfm && is_inter_block(...))`,
12941 /// `decodemv.c`; the skip term is 0 for intra). It fires 15 times here and
12942 /// zero times across 108 measured aomenc recipes, so the counter is
12943 /// asserted against the film rather than against a synthesised stream.
12944 ///
12945 /// LUMA only. U/V still differ (open residue, lane-kf900 r2: 221 U and
12946 /// 47912 V samples, max |d| 23/2, first at chroma (195, 640) -- chroma
12947 /// RESIDUAL, the prediction there is bit-exact against aomdec's
12948 /// `EC_PREDOUT`), so this gate pins what is proven and no more.
12949 #[test]
12950 fn a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact()
12951 {
12952 const NAME: &str = "a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact";
12953 if !have_ffmpeg() {
12954 eprintln!("SKIP {NAME}: no ffmpeg");
12955 return;
12956 }
12957 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_kf900.obu");
12958 let stream = std::fs::read(&path)
12959 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
12960 let (width, height) = (3840usize, 1608usize);
12961 crate::decode::reset_skip_split_tx_hits();
12962 let frames = match decode_stream(&stream) {
12963 Ok(frames) => frames,
12964 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
12965 };
12966 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
12967 assert_eq!((frames[0].width, frames[0].height), (width, height));
12968 assert!(
12969 crate::decode::skip_split_tx_hits() >= 15,
12970 "{NAME}: skip_split_tx_hits() == {} -- the stream that carries the tx-context \
12971 defect stopped carrying it, so this gate proves nothing",
12972 crate::decode::skip_split_tx_hits()
12973 );
12974 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
12975 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
12976 }
12977
12978 /// lane-kf1200 r3: the same film's `-ss 600` key frame (3840x1608, one
12979 /// 8-px partial bottom superblock row), pinned because no aomenc recipe
12980 /// reaches its shape -- a SKIPPED 8x8 intra leaf whose `tx_depth` resolved
12981 /// to TX_4X4. (80 recipes swept this round: 4 frame shapes x 2 sources x
12982 /// cq 32..63 x cpu-used 0/3 x 8/10-bit, all with
12983 /// `--enable-tx-size-search=1 --enable-filter-intra=1`; every one came
12984 /// back with `skip_split_tx_hits == 0`, `lanes/kf1200-r3.report.md`.)
12985 /// An intra block reads `tx_depth` whether or not it is skipped, so the
12986 /// leaf must record its resolved 4 -- not its 8x8 side -- in the txfm
12987 /// context; recording 8 gave the NEXT block's `tx_depth` symbol the wrong
12988 /// `tx_size_cdf` row (ctx 2 where libaom reads 1) and desynced the
12989 /// entropy stream at mi (400,46). HARD-asserts `skip_split_tx_hits` moved.
12990 #[test]
12991 fn the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact() {
12992 const NAME: &str = "the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact";
12993 if !have_ffmpeg() {
12994 eprintln!("SKIP {NAME}: no ffmpeg");
12995 return;
12996 }
12997 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
12998 .join("fixtures/reelb_ss600_key_frame.obu");
12999 let stream = std::fs::read(&path)
13000 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
13001 let (width, height) = (3840usize, 1608usize);
13002 crate::decode::reset_skip_split_tx_hits();
13003 let frames = match decode_stream(&stream) {
13004 Ok(frames) => frames,
13005 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
13006 };
13007 let skipped_split_tx = crate::decode::skip_split_tx_hits();
13008 assert!(
13009 skipped_split_tx > 0,
13010 "{NAME}: zero skipped 8x8 leaves with a split transform -- the fixture no longer \
13011 exercises the arm this test exists for"
13012 );
13013 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
13014 assert_eq!((frames[0].width, frames[0].height), (width, height));
13015 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
13016 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
13017 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
13018 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
13019 eprintln!("{NAME}: {skipped_split_tx} skipped 8x8 TX_4X4 leaves, frame pixel-exact");
13020 }
13021
13022 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1
13023 /// --superres-denominator=12` key frame, decoded pixel-exact against
13024 /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s
13025 /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit
13026 /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts
13027 /// `bit_depth == 10` and `superres_hits > 0`.
13028 #[test]
13029 fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() {
13030 const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact";
13031 if !have_ffmpeg() {
13032 eprintln!("SKIP {NAME}: no ffmpeg");
13033 return;
13034 }
13035 if !have_aomenc() {
13036 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13037 return;
13038 }
13039 let (width, height) = (64usize, 64usize);
13040 let stream = encode_10bit_gradients(
13041 NAME,
13042 width,
13043 height,
13044 1,
13045 &[
13046 "--limit=1",
13047 "--kf-max-dist=0",
13048 "--superres-mode=1",
13049 "--superres-denominator=12",
13050 "--superres-kf-denominator=12",
13051 "--enable-rect-partitions=0",
13052 "--enable-ab-partitions=0",
13053 "--enable-1to4-partitions=0",
13054 "--enable-filter-intra=0",
13055 "--enable-smooth-intra=0",
13056 "--enable-paeth-intra=0",
13057 "--enable-directional-intra=0",
13058 "--enable-angle-delta=0",
13059 "--enable-tx-size-search=0",
13060 "--enable-cdef=0",
13061 "--enable-restoration=0",
13062 "--max-partition-size=32",
13063 "--min-partition-size=32",
13064 "--enable-palette=0",
13065 "--enable-intrabc=0",
13066 "--enable-cfl-intra=0",
13067 ],
13068 );
13069 assert_eq!(
13070 parsed_bit_depth(&stream),
13071 10,
13072 "{NAME}: aomenc did not actually write a 10-bit sequence header"
13073 );
13074 let before = crate::superres::superres_hits();
13075 let frames = match decode_stream(&stream) {
13076 Ok(frames) => frames,
13077 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
13078 };
13079 assert!(
13080 crate::superres::superres_hits() > before,
13081 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
13082 );
13083 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
13084 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
13085 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
13086 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
13087 eprintln!(
13088 "{NAME}: pixel-exact, superres_hits={}",
13089 crate::superres::superres_hits()
13090 );
13091 }
13092
13093 /// lane-hbdgates r1: drive one 10-bit aomenc recipe over `seeds`, decode
13094 /// every attempt and pixel-compare every SHOWN frame against ffmpeg's own
13095 /// 10-bit decode of the identical bytes. Per-tool firing counters are
13096 /// sampled PER ATTEMPT and summed only over attempts that decoded *and*
13097 /// compared -- a stream that hit a named refusal contributes nothing
13098 /// (class `counter-from-refused-stream`). Named refusals are tolerated
13099 /// and reported; a pixel mismatch is a hard failure, never a SKIP.
13100 fn ten_bit_tool_gate(
13101 name: &str,
13102 width: usize,
13103 height: usize,
13104 frames: usize,
13105 extra: &[&str],
13106 seeds: &[u32],
13107 counters: &[(&str, fn() -> usize)],
13108 ) {
13109 fn first_diff(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
13110 ours.iter()
13111 .zip(theirs.iter())
13112 .position(|(a, b)| a != b)
13113 .map(|i| {
13114 format!(
13115 "first diff at index {i} (row {}, col {}): ours {} vs ffmpeg {}",
13116 i / width,
13117 i % width,
13118 ours[i],
13119 theirs[i]
13120 )
13121 })
13122 }
13123 let mut totals = vec![0usize; counters.len()];
13124 let mut refusals: Vec<String> = Vec::new();
13125 let mut compared = 0usize;
13126 for &seed in seeds {
13127 let stream = encode_10bit_gradients_seed(name, seed, width, height, frames, extra);
13128 assert_eq!(
13129 parsed_bit_depth(&stream),
13130 10,
13131 "{name}: aomenc did not write a 10-bit sequence header (seed {seed})"
13132 );
13133 let before: Vec<usize> = counters.iter().map(|(_, f)| f()).collect();
13134 let decoded = match decode_stream(&stream) {
13135 Ok(frames) => frames,
13136 Err(e) => {
13137 refusals.push(format!("seed {seed}: {e}"));
13138 continue;
13139 }
13140 };
13141 // Deltas are read BEFORE the pixel compare so a mismatch report
13142 // says whether the tool under test actually fired on the failing
13143 // stream (a mismatch with a zero delta is some other defect).
13144 let deltas: Vec<usize> = counters
13145 .iter()
13146 .zip(before.iter())
13147 .map(|((_, f), b)| f() - b)
13148 .collect();
13149 let fired: Vec<String> = counters
13150 .iter()
13151 .zip(deltas.iter())
13152 .map(|((label, _), d)| format!("{label}={d}"))
13153 .collect();
13154 let fired = fired.join(" ");
13155 let reference = ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len());
13156 assert_eq!(
13157 decoded.len(),
13158 reference.len(),
13159 "{name}: seed {seed}: shown-frame count vs ffmpeg"
13160 );
13161 for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() {
13162 for (plane, (a, b), w) in [
13163 ("Y", (&ours.y, &theirs.y), width),
13164 ("U", (&ours.u, &theirs.u), width / 2),
13165 ("V", (&ours.v, &theirs.v), width / 2),
13166 ] {
13167 if let Some(d) = first_diff(a, b, w) {
13168 panic!("{name}: seed {seed} frame {i} plane {plane}: {d} [{fired}]");
13169 }
13170 }
13171 }
13172 compared += 1;
13173 for (i, d) in deltas.iter().enumerate() {
13174 totals[i] += d;
13175 }
13176 }
13177 assert!(
13178 compared > 0,
13179 "{name}: every attempt hit a named refusal:\n{}",
13180 refusals.join("\n")
13181 );
13182 for (i, (label, _)) in counters.iter().enumerate() {
13183 assert!(
13184 totals[i] > 0,
13185 "{name}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
13186 the gate would prove nothing about that tool. refusals:\n{}",
13187 refusals.join("\n")
13188 );
13189 }
13190 let summary: Vec<String> = counters
13191 .iter()
13192 .zip(totals.iter())
13193 .map(|((label, _), t)| format!("{label}={t}"))
13194 .collect();
13195 eprintln!(
13196 "{name}: {compared}/{} attempts pixel-exact, {}",
13197 seeds.len(),
13198 summary.join(" ")
13199 );
13200 }
13201
13202 /// lane-hbdgates r1: the four intra tools that had an 8-bit gate and no
13203 /// 10-bit one (`filter-intra`, `smooth-intra`, `paeth-intra`,
13204 /// `intra-edge-filter`) on ONE real 10-bit `aomenc` key frame, each with
13205 /// its own hard-asserted counter. His two films are yuv420p10le, so an
13206 /// 8-bit-only gate for these tools proves nothing about the streams that
13207 /// matter (lane-covbd r1).
13208 #[test]
13209 fn a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact() {
13210 const NAME: &str = "a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact";
13211 if !have_ffmpeg() {
13212 eprintln!("SKIP {NAME}: no ffmpeg");
13213 return;
13214 }
13215 if !have_aomenc() {
13216 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13217 return;
13218 }
13219 ten_bit_tool_gate(
13220 NAME,
13221 64,
13222 64,
13223 1,
13224 &[
13225 "--limit=1",
13226 "--kf-max-dist=0",
13227 "--enable-filter-intra=1",
13228 "--enable-smooth-intra=1",
13229 "--enable-paeth-intra=1",
13230 "--enable-intra-edge-filter=1",
13231 "--enable-directional-intra=1",
13232 "--enable-angle-delta=0",
13233 "--enable-rect-partitions=0",
13234 "--enable-ab-partitions=0",
13235 "--enable-1to4-partitions=0",
13236 "--enable-tx-size-search=0",
13237 "--enable-cdef=0",
13238 "--enable-restoration=0",
13239 "--max-partition-size=32",
13240 "--min-partition-size=16",
13241 "--enable-palette=0",
13242 "--enable-intrabc=0",
13243 "--enable-cfl-intra=0",
13244 "--enable-ref-frame-mvs=0",
13245 ],
13246 &[42, 7, 11, 23, 31, 57],
13247 &[
13248 ("filter_intra_hits", decode::filter_intra_hits),
13249 ("smooth_pred_hits", crate::intra::smooth_pred_hits),
13250 ("paeth_pred_hits", crate::intra::paeth_pred_hits),
13251 (
13252 "intra_edge_filter_hits",
13253 crate::intra::intra_edge_filter_hits,
13254 ),
13255 ],
13256 );
13257 }
13258
13259 /// lane-hbdgates r1: `--enable-restoration=1` at 10 bits. Every earlier
13260 /// bit-depth gate ran `--enable-restoration=0`, which is exactly why two
13261 /// high-bit-depth loop-restoration defects survived to 2026-09-01
13262 /// (SGR box sums unscaled, Wiener clamp at the 8-bit bound). Same recipe
13263 /// as the 8-bit LR gate, at 10 bits.
13264 // Written `#[ignore]`d on lane-hbdgates (the branch lacked lane-hbdinter's
13265 // 10-bit LR fix and failed at seed 42, frame 0, Y index 122: ours 351 vs
13266 // ffmpeg 350). Un-ignored on the merge into main 2026-09-01, where the
13267 // SGR box-sum scaling and the Wiener clamp are fixed: 16/16 attempts
13268 // pixel-exact, lr_hits=28.
13269 #[test]
13270 fn a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact() {
13271 const NAME: &str = "a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact";
13272 if !have_ffmpeg() {
13273 eprintln!("SKIP {NAME}: no ffmpeg");
13274 return;
13275 }
13276 if !have_aomenc() {
13277 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13278 return;
13279 }
13280 // 192x128 = 3x2 superblocks, so `read_lr` is re-entered per SB
13281 // (the 8-bit LR gate's own trap warning); cq-level=15 because
13282 // aomenc's RD only picks a non-RESTORE_NONE frame type at low cq.
13283 ten_bit_tool_gate(
13284 NAME,
13285 192,
13286 128,
13287 1,
13288 &[
13289 "--limit=1",
13290 "--kf-max-dist=0",
13291 "--cq-level=15",
13292 "--enable-restoration=1",
13293 "--enable-cdef=0",
13294 "--enable-rect-partitions=0",
13295 "--enable-ab-partitions=0",
13296 "--enable-1to4-partitions=0",
13297 "--enable-filter-intra=0",
13298 "--enable-smooth-intra=0",
13299 "--enable-paeth-intra=0",
13300 "--enable-tx-size-search=0",
13301 "--max-partition-size=32",
13302 "--min-partition-size=16",
13303 "--enable-palette=0",
13304 "--enable-intrabc=0",
13305 "--enable-cfl-intra=0",
13306 "--enable-ref-frame-mvs=0",
13307 ],
13308 &LR_SEEDS,
13309 &[("lr_hits", ten_bit_lr_hits)],
13310 );
13311 }
13312
13313 /// Seeds swept by the 10-bit LR gate (the 8-bit gate needs ~40 attempts
13314 /// to land a non-RESTORE_NONE frame; every attempt here still has to
13315 /// decode pixel-exact).
13316 /// lane-obmcrec r1: the `LR_SEEDS` members whose 1:4-partition stream both
13317 /// fires `obmc_pair_filter_hits` and decodes every frame pixel-exact.
13318 /// Measured over seeds 42..=73 (32 encodes): 43/46/47/65/66 fire and are
13319 /// exact; 70 and 73 fire and mismatch, but mismatch IDENTICALLY with
13320 /// `--enable-obmc=0` (seed 73 frame 1 luma, seed 70 frame 16), so their
13321 /// defect is in the `--min-partition-size=4` recipe, not in OBMC -- kept
13322 /// out of this gate rather than papered over, and reported as open.
13323 const OBMC_PAIR_SEEDS: [u32; 5] = [43, 46, 47, 65, 66];
13324
13325 const LR_SEEDS: [u32; 16] = [
13326 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
13327 ];
13328
13329 /// Wiener + SGR + switchable loop-restoration firings, summed.
13330 fn ten_bit_lr_hits() -> usize {
13331 crate::restoration::wiener_hits()
13332 + crate::restoration::sgrproj_hits()
13333 + crate::restoration::switchable_hits()
13334 }
13335
13336 /// lane-reelckf2 r1: loop restoration on frame sizes whose LAST stripe is
13337 /// partial, with 128-sample superblocks -- the two stripe shapes whose
13338 /// boundary substitution is special (`filter_restoration_unit`: the first
13339 /// stripe is 8 rows short and takes its above boundary from the frame's
13340 /// own top rows, the last one is truncated and takes its below boundary
13341 /// from the frame's own bottom row) had no gate at all: every earlier LR
13342 /// size (192x128, 160x96) is a whole multiple of 64 rows and ran at
13343 /// `--sb-size=64`. 152 = 2*64+24 and 216 = 3*64+24 both leave a 32-row
13344 /// tail stripe, mirroring the 792-row 10-bit film that made this lane.
13345 /// `lr_stripe0_hits`/`lr_last_stripe_hits` are hard-asserted per attempt
13346 /// by [`ten_bit_tool_gate`], so an RD that picked RESTORE_NONE on either
13347 /// stripe cannot pass.
13348 #[test]
13349 fn a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact() {
13350 const NAME: &str =
13351 "a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact";
13352 if !have_ffmpeg() {
13353 eprintln!("SKIP {NAME}: no ffmpeg");
13354 return;
13355 }
13356 if !have_aomenc() {
13357 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13358 return;
13359 }
13360 // `--sb-size=128` goes in `extra`, which the helper appends AFTER its
13361 // own `--sb-size=64` (aomenc keeps the LAST occurrence of a repeated
13362 // flag, measured 2026-09-02); `--max-partition-size=32` keeps the 128
13363 // root on SPLIT, the only 128-root partition decoded today.
13364 for (width, height, cq) in [
13365 (256usize, 152usize, "15"),
13366 (384, 216, "15"),
13367 (256, 152, "25"),
13368 ] {
13369 ten_bit_tool_gate(
13370 &format!("{NAME} {width}x{height} cq{cq}"),
13371 width,
13372 height,
13373 1,
13374 &[
13375 "--limit=1",
13376 "--kf-max-dist=0",
13377 &format!("--cq-level={cq}"),
13378 "--sb-size=128",
13379 "--enable-restoration=1",
13380 "--enable-cdef=0",
13381 "--enable-rect-partitions=0",
13382 "--enable-ab-partitions=0",
13383 "--enable-1to4-partitions=0",
13384 "--enable-filter-intra=0",
13385 "--enable-smooth-intra=0",
13386 "--enable-paeth-intra=0",
13387 "--enable-tx-size-search=0",
13388 "--max-partition-size=32",
13389 "--min-partition-size=16",
13390 "--enable-palette=0",
13391 "--enable-intrabc=0",
13392 "--enable-cfl-intra=0",
13393 "--enable-ref-frame-mvs=0",
13394 ],
13395 &LR_SEEDS,
13396 &[
13397 ("lr_hits", ten_bit_lr_hits),
13398 ("lr_stripe0_hits", crate::restoration::lr_stripe0_hits),
13399 (
13400 "lr_last_stripe_hits",
13401 crate::restoration::lr_last_stripe_hits,
13402 ),
13403 ],
13404 );
13405 }
13406 }
13407
13408 /// lane-hbdgates r1: `--enable-rect-partitions=1 --enable-ab-partitions=1`
13409 /// at 10 bits, one intra stream, one counter per tool
13410 /// (`rect_partition_hits`, `partab_hits`) so a stream that only fired the
13411 /// rect arms cannot stand in for AB.
13412 #[test]
13413 fn a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact() {
13414 const NAME: &str = "a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact";
13415 if !have_ffmpeg() {
13416 eprintln!("SKIP {NAME}: no ffmpeg");
13417 return;
13418 }
13419 if !have_aomenc() {
13420 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13421 return;
13422 }
13423 // The 8-bit free-partition/AB recipe, verbatim, at 10 bits: AB
13424 // splits are an INTER dispatch here (intra-frame AB is still a named
13425 // refusal), so the stream needs alt-refs and 24 frames, not one key
13426 // frame.
13427 ten_bit_tool_gate(
13428 NAME,
13429 64,
13430 64,
13431 24,
13432 &[
13433 "--cq-level=45",
13434 "--kf-max-dist=1000",
13435 "--auto-alt-ref=1",
13436 "--lag-in-frames=16",
13437 "--enable-fwd-kf=0",
13438 "--enable-order-hint=1",
13439 "--enable-warped-motion=1",
13440 "--enable-obmc=1",
13441 "--tune-content=default",
13442 "--enable-masked-comp=0",
13443 "--enable-interintra-comp=0",
13444 "--enable-onesided-comp=0",
13445 "--enable-interintra-wedge=0",
13446 "--enable-smooth-interintra=0",
13447 "--enable-rect-partitions=1",
13448 "--enable-ab-partitions=1",
13449 "--enable-1to4-partitions=0",
13450 "--enable-filter-intra=0",
13451 "--enable-smooth-intra=0",
13452 "--enable-paeth-intra=0",
13453 "--enable-directional-intra=0",
13454 "--enable-angle-delta=0",
13455 "--enable-tx-size-search=0",
13456 "--enable-cdef=0",
13457 "--enable-restoration=0",
13458 "--max-partition-size=32",
13459 "--min-partition-size=16",
13460 "--enable-palette=0",
13461 "--enable-intrabc=0",
13462 "--enable-cfl-intra=0",
13463 "--enable-ref-frame-mvs=0",
13464 ],
13465 &LR_SEEDS,
13466 &[
13467 ("rect_partition_hits", decode::rect_partition_hits),
13468 ("partab_hits", decode::partab_hits),
13469 ],
13470 );
13471 }
13472
13473 /// lane-obmcrec r1: OBMC whose above/left neighbour is a 4-wide/4-tall
13474 /// 1:4-partition strip -- the shape the three 1080p 10-bit film cuts
13475 /// refused on ("an OBMC neighbour whose switchable interp filter was never
13476 /// recorded"). `overlappable_above`/`_left` snap such a neighbour to the
13477 /// chroma pair's SECOND mi but used to read its interp filter from the
13478 /// FIRST one, a different block whose filter record is the intra
13479 /// `[3, 3]` sentinel whenever that half is intra. `obmc_pair_filter_hits`
13480 /// counts exactly that neighbour shape, so a stream without 1:4 strips
13481 /// next to an OBMC block cannot stand in for it.
13482 #[test]
13483 fn a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact() {
13484 const NAME: &str =
13485 "a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact";
13486 if !have_ffmpeg() {
13487 eprintln!("SKIP {NAME}: no ffmpeg");
13488 return;
13489 }
13490 if !have_aomenc() {
13491 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13492 return;
13493 }
13494 ten_bit_tool_gate(
13495 NAME,
13496 128,
13497 128,
13498 24,
13499 &[
13500 "--ec-fixture-noise",
13501 "--cq-level=45",
13502 "--kf-max-dist=1000",
13503 "--auto-alt-ref=1",
13504 "--lag-in-frames=16",
13505 "--enable-fwd-kf=0",
13506 "--enable-order-hint=1",
13507 "--enable-warped-motion=0",
13508 "--enable-obmc=1",
13509 "--tune-content=default",
13510 "--enable-masked-comp=0",
13511 "--enable-interintra-comp=0",
13512 "--enable-onesided-comp=0",
13513 "--enable-interintra-wedge=0",
13514 "--enable-smooth-interintra=0",
13515 "--enable-rect-partitions=1",
13516 "--enable-ab-partitions=0",
13517 "--enable-1to4-partitions=1",
13518 "--enable-filter-intra=0",
13519 "--enable-smooth-intra=0",
13520 "--enable-paeth-intra=0",
13521 "--enable-directional-intra=0",
13522 "--enable-angle-delta=0",
13523 "--enable-tx-size-search=0",
13524 "--enable-cdef=0",
13525 "--enable-restoration=0",
13526 "--max-partition-size=32",
13527 "--min-partition-size=4",
13528 "--enable-palette=0",
13529 "--enable-intrabc=0",
13530 "--enable-cfl-intra=0",
13531 "--enable-ref-frame-mvs=0",
13532 ],
13533 &OBMC_PAIR_SEEDS,
13534 &[("obmc_pair_filter_hits", decode::obmc_pair_filter_hits)],
13535 );
13536 }
13537
13538 /// `bit_depth` of the first sequence header in `stream`.
13539 fn parsed_bit_depth(stream: &[u8]) -> u8 {
13540 let mut probe = Av1Parser::new();
13541 let mut pos = 0usize;
13542 while pos < stream.len() && probe.sequence_header().is_none() {
13543 let obu = probe.parse_obu(&stream[pos..]).unwrap();
13544 pos += obu.total_size;
13545 }
13546 probe
13547 .sequence_header()
13548 .expect("stream has a sequence header OBU")
13549 .color_config
13550 .bit_depth
13551 }
13552
13553 /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and
13554 /// encode it with a real 10-bit `aomenc`, returning the OBU stream.
13555 /// `extra` carries the tool flags under test.
13556 fn encode_10bit_gradients(
13557 name: &str,
13558 width: usize,
13559 height: usize,
13560 frames: usize,
13561 extra: &[&str],
13562 ) -> Vec<u8> {
13563 encode_10bit_gradients_seed(name, 42, width, height, frames, extra)
13564 }
13565
13566 /// As [`encode_10bit_gradients`], but with the fixture seed exposed --
13567 /// lane-hbdgates r1 sweeps seeds so a tool that aomenc's RD declines on
13568 /// one fixture still gets a firing stream.
13569 fn encode_10bit_gradients_seed(
13570 name: &str,
13571 seed: u32,
13572 width: usize,
13573 height: usize,
13574 frames: usize,
13575 extra: &[&str],
13576 ) -> Vec<u8> {
13577 let duration = frames as f64 / 25.0;
13578 // lane-ab32 r1: `--ec-fixture-noise` is not an aomenc flag -- it is a
13579 // fixture request, consumed (and stripped) here: the smooth gradients
13580 // source codes as PARTITION_NONE everywhere, so a partition gate needs
13581 // seeded noise on top of it to give the RD a reason to split.
13582 let noisy = extra.contains(&"--ec-fixture-noise");
13583 let stripped: Vec<&str> = extra
13584 .iter()
13585 .copied()
13586 .filter(|a| *a != "--ec-fixture-noise")
13587 .collect();
13588 let extra: &[&str] = &stripped;
13589 let base = gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
13590 let source = if noisy {
13591 format!("{base},noise=alls=40:all_seed={seed}")
13592 } else {
13593 base
13594 };
13595 let y4m = Command::new("ffmpeg")
13596 .args([
13597 "-v",
13598 "error",
13599 "-f",
13600 "lavfi",
13601 "-i",
13602 &source,
13603 "-pix_fmt",
13604 "yuv420p10le",
13605 "-strict",
13606 "-1",
13607 "-t",
13608 &format!("{duration}"),
13609 "-f",
13610 "yuv4mpegpipe",
13611 "-",
13612 ])
13613 .stdin(Stdio::null())
13614 .stdout(Stdio::piped())
13615 .stderr(Stdio::piped())
13616 .output()
13617 .expect("ffmpeg failed to run");
13618 assert!(
13619 y4m.status.success(),
13620 "{name}: ffmpeg failed to render the 10-bit fixture: {}",
13621 String::from_utf8_lossy(&y4m.stderr)
13622 );
13623 let mut args: Vec<&str> = vec!["--codec=av1", "--passes=1", "--end-usage=q"];
13624 // lane-hbdgates r1: a caller-supplied `--cq-level` REPLACES the
13625 // default rather than being appended after it -- two `--cq-level`
13626 // flags on one aomenc line is a coin flip on which one lands.
13627 if !extra.iter().any(|a| a.starts_with("--cq-level=")) {
13628 args.push("--cq-level=30");
13629 }
13630 args.extend_from_slice(&[
13631 "--cpu-used=0",
13632 "--threads=1",
13633 "--row-mt=0",
13634 "--sb-size=64",
13635 "--input-bit-depth=10",
13636 "--bit-depth=10",
13637 ]);
13638 args.extend_from_slice(extra);
13639 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
13640 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
13641 assert!(
13642 out.status.success(),
13643 "{name}: aomenc refused the 10-bit fixture: {}",
13644 String::from_utf8_lossy(&out.stderr)
13645 );
13646 out.stdout
13647 }
13648
13649 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
13650 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
13651 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
13652 /// which flattened chroma to a single value specifically to avoid
13653 /// exercising this path). Same square-only recipe as the palette-Y gate
13654 /// (`--enable-rect-partitions=0`/`-ab-`/`-1to4-`, fixed 32x32 partition)
13655 /// so a UV palette block never lands inside the still-refused HORZ/VERT
13656 /// screen-content strip. HARD-asserts [`decode::palette_uv_hits`] moved
13657 /// -- a stream that never reads a real UV palette block would decode (or
13658 /// not) by construction without proving this milestone at all
13659 /// ([[gate-blind-to-feature]]).
13660 #[test]
13661 fn a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact() {
13662 const NAME: &str = "a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact";
13663 if !have_ffmpeg() {
13664 eprintln!("SKIP {NAME}: no ffmpeg");
13665 return;
13666 }
13667 if !have_aomenc() {
13668 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13669 return;
13670 }
13671 let source = "testsrc2=size=64x64:rate=25";
13672 fn render(source: &str) -> Vec<u8> {
13673 Command::new("ffmpeg")
13674 .args([
13675 "-v",
13676 "error",
13677 "-f",
13678 "lavfi",
13679 "-i",
13680 source,
13681 "-pix_fmt",
13682 "yuv420p",
13683 "-t",
13684 "0.16",
13685 "-f",
13686 "yuv4mpegpipe",
13687 "-",
13688 ])
13689 .stdin(Stdio::null())
13690 .stdout(Stdio::piped())
13691 .stderr(Stdio::piped())
13692 .output()
13693 .expect("ffmpeg failed to run")
13694 .stdout
13695 }
13696 let y4m_a = render(source);
13697 let y4m_b = render(source);
13698 assert_eq!(
13699 y4m_a, y4m_b,
13700 "testsrc2 must render byte-identical across two runs"
13701 );
13702 let y4m = y4m_a;
13703 let out = run_with_stdin(
13704 Command::new(aomenc_path()).args([
13705 "--codec=av1",
13706 "--passes=1",
13707 "--end-usage=q",
13708 "--cq-level=30",
13709 "--cpu-used=0",
13710 "--threads=1",
13711 "--row-mt=0",
13712 "--sb-size=64",
13713 "--tune-content=screen",
13714 "--enable-palette=1",
13715 "--enable-intrabc=0",
13716 "--enable-rect-partitions=0",
13717 "--enable-ab-partitions=0",
13718 "--enable-1to4-partitions=0",
13719 "--min-partition-size=32",
13720 "--max-partition-size=32",
13721 "--enable-filter-intra=0",
13722 "--enable-cdef=0",
13723 "--enable-restoration=0",
13724 "--enable-tx-size-search=0",
13725 "--loopfilter-control=0",
13726 "--obu",
13727 "-o",
13728 "-",
13729 "-",
13730 ]),
13731 &y4m,
13732 );
13733 assert!(
13734 out.status.success(),
13735 "aomenc refused the fixture: {}",
13736 String::from_utf8_lossy(&out.stderr)
13737 );
13738 let stream = out.stdout;
13739 let before = decode::palette_uv_hits();
13740 let frames = match decode_stream(&stream) {
13741 Ok(frames) => frames,
13742 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
13743 };
13744 assert!(
13745 decode::palette_uv_hits() > before,
13746 "palette_uv_mode never fired decoding this stream -- gate is vacuous"
13747 );
13748 let frame_count = frames.len();
13749 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, frame_count);
13750 for i in 0..frame_count {
13751 assert_eq!(frames[i].y, ffmpeg_frames[i].y, "luma vs ffmpeg, frame {i}");
13752 assert_eq!(frames[i].u, ffmpeg_frames[i].u, "U vs ffmpeg, frame {i}");
13753 assert_eq!(frames[i].v, ffmpeg_frames[i].v, "V vs ffmpeg, frame {i}");
13754 }
13755 }
13756
13757 /// A real `aomenc` fixture that lands palette syntax on a HORZ/VERT
13758 /// intra strip (lane-palette2 r5, gating r4's `read_intra_mode_rect`
13759 /// wiring). `smptebars`/`rgbtestsrc` at plain default settings both hit a
13760 /// SQUARE palette refusal or an unrelated 32x32 `HORZ_A`/`VERT_A`/etc
13761 /// partition FIRST on every size/cq combo probed -- `--enable-ab-
13762 /// partitions=0` measurably does not stop aomenc choosing one at this
13763 /// screen-content tune (byte-identical output with `=0` vs `=1`, same
13764 /// aomenc quirk as `[[lane-sbpart-r2]]`'s SB-level AB). Forcing
13765 /// `--min/max-partition-size=64` sidesteps that whole 32x32-level code
13766 /// path: the only choices left at the (single, key-frame) superblock are
13767 /// NONE/SPLIT/HORZ/VERT/AB/1to4 straight from [`decode_block_rect64`],
13768 /// and a size/cq sweep (measured live this round) reliably lands
13769 /// PARTITION_HORZ/VERT with a real (non-split-tx) palette block on both
13770 /// sources. Drives `decode_stream` directly (below any refusal) and
13771 /// HARD-asserts [`decode::palette_rect_hits`] moved on every attempt that
13772 /// didn't refuse, before comparing pixels ([[gate-blind-to-feature]]) --
13773 /// a decode that never lands a rect palette block is not a match.
13774 #[test]
13775 fn a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact() {
13776 const NAME: &str = "a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact";
13777 let _gate_lock = lock_gate_counters();
13778 if !have_ffmpeg() {
13779 eprintln!("SKIP {NAME}: no ffmpeg");
13780 return;
13781 }
13782 if !have_aomenc() {
13783 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13784 return;
13785 }
13786 let mut matched = 0u32;
13787 let mut uncounted_exact = 0u32;
13788 let mut named_refusals = 0u32;
13789 let mut attempts = 0u32;
13790 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
13791 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
13792 for src_name in ["smptebars", "rgbtestsrc"] {
13793 for (width, height) in sizes {
13794 for cq in cqs {
13795 attempts += 1;
13796 let source = format!("{src_name}=size={width}x{height}:rate=25");
13797 let y4m = Command::new("ffmpeg")
13798 .args([
13799 "-v",
13800 "error",
13801 "-f",
13802 "lavfi",
13803 "-i",
13804 &source,
13805 "-pix_fmt",
13806 "yuv420p",
13807 "-t",
13808 "0.04",
13809 "-f",
13810 "yuv4mpegpipe",
13811 "-",
13812 ])
13813 .stdin(Stdio::null())
13814 .stdout(Stdio::piped())
13815 .stderr(Stdio::piped())
13816 .output()
13817 .expect("ffmpeg failed to run");
13818 assert!(
13819 y4m.status.success(),
13820 "ffmpeg fixture: {}",
13821 String::from_utf8_lossy(&y4m.stderr)
13822 );
13823 let cq_arg = format!("--cq-level={cq}");
13824 let out = run_with_stdin(
13825 Command::new(aomenc_path()).args([
13826 "--codec=av1",
13827 "--passes=1",
13828 "--end-usage=q",
13829 &cq_arg,
13830 "--cpu-used=4",
13831 "--threads=1",
13832 "--row-mt=0",
13833 "--sb-size=64",
13834 "--enable-palette=1",
13835 "--min-partition-size=16",
13836 "--max-partition-size=64",
13837 "--obu",
13838 "-o",
13839 "-",
13840 "-",
13841 ]),
13842 &y4m.stdout,
13843 );
13844 assert!(
13845 out.status.success(),
13846 "aomenc refused the fixture ({source} cq={cq}): {}",
13847 String::from_utf8_lossy(&out.stderr)
13848 );
13849 let stream = out.stdout;
13850 let before = crate::decode::palette_rect_hits();
13851 let frames = match decode_stream(&stream) {
13852 Err(e) => {
13853 let msg = e.to_string();
13854 assert!(
13855 msg.contains("unsupported"),
13856 "{NAME} failed outright, not a named refusal \
13857 ({source} cq={cq}): {msg}"
13858 );
13859 named_refusals += 1;
13860 eprintln!("{source} cq={cq}: refusal: {msg}");
13861 continue;
13862 }
13863 Ok(frames) => frames,
13864 };
13865 // A successful decode is ALWAYS pixel-compared; the hit
13866 // counter only decides whether the attempt counts toward
13867 // the hit-asserting total (class
13868 // [[gate-skips-on-its-own-failure]]: the old `continue`
13869 // here let 16/70 decoded attempts past without any pixel
13870 // check at all).
13871 let counted = crate::decode::palette_rect_hits() != before;
13872 if !counted {
13873 eprintln!(
13874 "{NAME}: {source} cq={cq} decoded without ever landing a rect \
13875 palette block (palette_rect_hits unchanged) -- pixel-compared, \
13876 not counted toward the hit assertion"
13877 );
13878 }
13879 let frame_count = frames.len();
13880 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
13881 if frames
13882 .iter()
13883 .zip(&ffmpeg_frames)
13884 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v)
13885 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
13886 {
13887 std::fs::write(&path, &stream).expect("writing pinned stream");
13888 eprintln!(
13889 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
13890 );
13891 }
13892 for i in 0..frame_count {
13893 assert_eq!(
13894 frames[i].y, ffmpeg_frames[i].y,
13895 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
13896 );
13897 assert_eq!(
13898 frames[i].u, ffmpeg_frames[i].u,
13899 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
13900 );
13901 assert_eq!(
13902 frames[i].v, ffmpeg_frames[i].v,
13903 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
13904 );
13905 }
13906 if counted {
13907 matched += 1;
13908 } else {
13909 uncounted_exact += 1;
13910 }
13911 }
13912 }
13913 }
13914 assert!(
13915 matched > 0,
13916 "{NAME}: no attempt out of {attempts} ever landed a matching rect palette \
13917 block ({named_refusals} named refusals) -- palette_rect_hits never proven \
13918 pixel-exact"
13919 );
13920 eprintln!(
13921 "{NAME}: {matched}/{attempts} attempts matched pixel-exact, \
13922 {uncounted_exact} decoded-and-pixel-exact but uncounted, {named_refusals} \
13923 named refusals, palette_rect_hits={}",
13924 crate::decode::palette_rect_hits()
13925 );
13926 }
13927
13928 /// The BROAD case (lane-palette2 r6, per its charter): a HORZ/VERT intra
13929 /// strip in a screen-content-tools frame that does NOT necessarily use a
13930 /// palette. This is what the refusal r4 removed actually guarded --
13931 /// [`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`] above
13932 /// gates the rarer "and picks a palette" case, which r5 measured RD
13933 /// almost never chooses -- 39/70 of that same sweep DID land here (a
13934 /// clean rect-strip decode with `palette_rect_hits` unchanged), just
13935 /// uncounted by r5's narrower assertion. Same `--min/max-partition-size=64`
13936 /// recipe r5 measured live to dodge the 32x32-level AB-partition quirk
13937 /// ([[lane-sbpart-r2]]), single key frame, size/cq sweep. HARD-asserts
13938 /// [`decode::rect_screen_content_hits`] moved -- proof this stream
13939 /// actually ran [`read_intra_mode_rect`]'s screen-content-tools branch --
13940 /// before comparing pixels.
13941 #[test]
13942 fn a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact() {
13943 const NAME: &str = "a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact";
13944 let _gate_lock = lock_gate_counters();
13945 if !have_ffmpeg() {
13946 eprintln!("SKIP {NAME}: no ffmpeg");
13947 return;
13948 }
13949 if !have_aomenc() {
13950 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13951 return;
13952 }
13953 let mut matched = 0u32;
13954 // Blocks that reconstructed a palette-Y prediction through a SPLIT
13955 // luma transform (lane-palette2 r7's lifted refusal): the same
13956 // screen-content streams exercise it, so this gate proves both.
13957 let mut split_palette_matched = 0u32;
13958 let mut uncounted_exact = 0u32;
13959 let mut named_refusals = 0u32;
13960 let mut attempts = 0u32;
13961 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
13962 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
13963 for src_name in ["smptebars", "rgbtestsrc"] {
13964 for (width, height) in sizes {
13965 for cq in cqs {
13966 attempts += 1;
13967 let source = format!("{src_name}=size={width}x{height}:rate=25");
13968 let y4m = Command::new("ffmpeg")
13969 .args([
13970 "-v",
13971 "error",
13972 "-f",
13973 "lavfi",
13974 "-i",
13975 &source,
13976 "-pix_fmt",
13977 "yuv420p",
13978 "-t",
13979 "0.04",
13980 "-f",
13981 "yuv4mpegpipe",
13982 "-",
13983 ])
13984 .stdin(Stdio::null())
13985 .stdout(Stdio::piped())
13986 .stderr(Stdio::piped())
13987 .output()
13988 .expect("ffmpeg failed to run");
13989 assert!(
13990 y4m.status.success(),
13991 "ffmpeg fixture: {}",
13992 String::from_utf8_lossy(&y4m.stderr)
13993 );
13994 let cq_arg = format!("--cq-level={cq}");
13995 let out = run_with_stdin(
13996 Command::new(aomenc_path()).args([
13997 "--codec=av1",
13998 "--passes=1",
13999 "--end-usage=q",
14000 &cq_arg,
14001 "--cpu-used=4",
14002 "--threads=1",
14003 "--row-mt=0",
14004 "--sb-size=64",
14005 "--enable-palette=1",
14006 "--min-partition-size=16",
14007 "--max-partition-size=64",
14008 "--obu",
14009 "-o",
14010 "-",
14011 "-",
14012 ]),
14013 &y4m.stdout,
14014 );
14015 assert!(
14016 out.status.success(),
14017 "aomenc refused the fixture ({source} cq={cq}): {}",
14018 String::from_utf8_lossy(&out.stderr)
14019 );
14020 let stream = out.stdout;
14021 let before = crate::decode::rect_screen_content_hits();
14022 let split_before = crate::decode::palette_split_tx_hits();
14023 let frames = match decode_stream(&stream) {
14024 Err(e) => {
14025 let msg = e.to_string();
14026 assert!(
14027 msg.contains("unsupported"),
14028 "{NAME} failed outright, not a named refusal \
14029 ({source} cq={cq}): {msg}"
14030 );
14031 named_refusals += 1;
14032 eprintln!("{source} cq={cq}: refusal: {msg}");
14033 continue;
14034 }
14035 Ok(frames) => frames,
14036 };
14037 // Same integrity rule as the palette gate above: decoded
14038 // means pixel-compared, counter or no counter.
14039 let counted = crate::decode::rect_screen_content_hits() != before;
14040 if !counted {
14041 eprintln!(
14042 "{NAME}: {source} cq={cq} decoded without ever running the rect \
14043 screen-content path (rect_screen_content_hits unchanged) -- \
14044 pixel-compared, not counted toward the hit assertion"
14045 );
14046 }
14047 let frame_count = frames.len();
14048 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
14049 if frames
14050 .iter()
14051 .zip(&ffmpeg_frames)
14052 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v)
14053 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
14054 {
14055 std::fs::write(&path, &stream).expect("writing pinned stream");
14056 eprintln!(
14057 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
14058 );
14059 }
14060 for i in 0..frame_count {
14061 assert_eq!(
14062 frames[i].y, ffmpeg_frames[i].y,
14063 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
14064 );
14065 assert_eq!(
14066 frames[i].u, ffmpeg_frames[i].u,
14067 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
14068 );
14069 assert_eq!(
14070 frames[i].v, ffmpeg_frames[i].v,
14071 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
14072 );
14073 }
14074 if counted {
14075 matched += 1;
14076 } else {
14077 uncounted_exact += 1;
14078 }
14079 if counted && crate::decode::palette_split_tx_hits() > split_before {
14080 split_palette_matched += 1;
14081 }
14082 }
14083 }
14084 }
14085 assert!(
14086 split_palette_matched > 0,
14087 "{NAME}: no pixel-exact attempt ever reconstructed a palette block with a \
14088 split luma transform -- the lifted refusal is ungated"
14089 );
14090 assert!(
14091 matched > 0,
14092 "{NAME}: no attempt out of {attempts} ever landed a matching rect \
14093 screen-content block ({named_refusals} named refusals) -- \
14094 rect_screen_content_hits never proven pixel-exact"
14095 );
14096 eprintln!(
14097 "{NAME}: {matched}/{attempts} attempts matched pixel-exact \
14098 ({split_palette_matched} of them through a split-transform palette block), \
14099 {uncounted_exact} decoded-and-pixel-exact but uncounted, \
14100 {named_refusals} named refusals, rect_screen_content_hits={}, \
14101 palette_split_tx_hits={}",
14102 crate::decode::rect_screen_content_hits(),
14103 crate::decode::palette_split_tx_hits()
14104 );
14105 }
14106
14107 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s
14108 /// harness, but with the deblocking filter left *on* (no
14109 /// `--loopfilter-control=0`) at a crf high enough that libaom actually
14110 /// picks a nonzero level -- proves `apply_deblock` itself, not just that
14111 /// this decoder still works when every edge lands on level 0. CDEF
14112 /// stays off so a pixel mismatch can only come from the loop filter.
14113 #[test]
14114 fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() {
14115 if !have_ffmpeg() {
14116 eprintln!(
14117 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no ffmpeg"
14118 );
14119 return;
14120 }
14121 if !have_aomenc() {
14122 eprintln!(
14123 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no aomenc at {}",
14124 aomenc_path().display()
14125 );
14126 return;
14127 }
14128 let (width, height) = (64usize, 64usize);
14129 let source = gradients_source(42, width, height, "duration=0.04:rate=25");
14130 let y4m = Command::new("ffmpeg")
14131 .args(["-v", "error", "-f", "lavfi", "-i"])
14132 .arg(&source)
14133 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
14134 .stdin(Stdio::null())
14135 .stdout(Stdio::piped())
14136 .stderr(Stdio::piped())
14137 .output()
14138 .expect("ffmpeg failed to run");
14139 assert!(
14140 y4m.status.success(),
14141 "ffmpeg fixture: {}",
14142 String::from_utf8_lossy(&y4m.stderr)
14143 );
14144 let out = run_with_stdin(
14145 Command::new(aomenc_path()).args([
14146 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
14147 // occurrence, so overrides go before the base list).
14148 "--loopfilter-control=1",
14149 "--codec=av1",
14150 "--passes=1",
14151 "--end-usage=q",
14152 "--cq-level=55",
14153 "--cpu-used=0",
14154 "--enable-filter-intra=0",
14155 "--enable-smooth-intra=0",
14156 "--enable-paeth-intra=0",
14157 "--enable-directional-intra=0",
14158 "--enable-angle-delta=0",
14159 "--enable-tx-size-search=0",
14160 "--enable-cdef=0",
14161 // Loop restoration is a named refusal (aomenc's RD picks
14162 // Sgrproj on this kind of content) -- off in every recipe
14163 // whose test targets a different surface.
14164 "--enable-restoration=0",
14165 "--max-partition-size=32",
14166 "--enable-palette=0",
14167 "--enable-intrabc=0",
14168 "--enable-cfl-intra=0",
14169 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
14170 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
14171 "--enable-ref-frame-mvs=0",
14172 "--obu",
14173 "-o",
14174 "-",
14175 "-",
14176 ]),
14177 &y4m.stdout,
14178 );
14179 assert!(
14180 out.status.success(),
14181 "aomenc refused the fixture: {}",
14182 String::from_utf8_lossy(&out.stderr)
14183 );
14184 let stream = out.stdout;
14185 let before = decode::deblock_hits();
14186 let frames = match decode_stream(&stream) {
14187 Ok(frames) => frames,
14188 Err(e) => {
14189 eprintln!(
14190 "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: {e}"
14191 );
14192 return;
14193 }
14194 };
14195 assert!(
14196 decode::deblock_hits() > before,
14197 "no deblocking edge fired decoding this stream -- raise cq-level"
14198 );
14199 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
14200 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
14201 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
14202 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
14203 }
14204
14205 /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`],
14206 /// but WITHOUT `--enable-tx-size-search=0` -- the one flag every other
14207 /// recipe in this file pins off specifically to keep the stream on
14208 /// `TxMode::Largest`. Dropped, aomenc's RD is free to pick
14209 /// `TxMode::Select` and split some blocks' luma transform below their own
14210 /// side (spec 5.11.16), which is what this test's `tx_depth_hits()`
14211 /// counter proves actually happened -- a stream that resolves every
14212 /// `tx_depth` to 0 would pixel-match by construction (identical to
14213 /// `TxMode::Largest`) without exercising the new split-TU decode path at
14214 /// all. Same multi-seed retry shape as
14215 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]:
14216 /// aomenc's own RD is free (with tx-size search on) to also occasionally
14217 /// pick `allow_screen_content_tools` on this content, a separate,
14218 /// already-named refusal -- try several seeds, and the first stream that
14219 /// both decodes AND actually split a transform must be pixel-exact.
14220 #[test]
14221 fn a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact() {
14222 if !have_ffmpeg() {
14223 eprintln!(
14224 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no ffmpeg"
14225 );
14226 return;
14227 }
14228 if !have_aomenc() {
14229 eprintln!(
14230 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no aomenc at {}",
14231 aomenc_path().display()
14232 );
14233 return;
14234 }
14235 let (width, height) = (64usize, 64usize);
14236 let mut refusals = Vec::new();
14237 let mut uncounted_exact = 0u32;
14238 for attempt in 0..40u32 {
14239 let seed = 42 + attempt;
14240 // A flat gradient never has enough local detail for the RD
14241 // search to prefer a split transform over the block's own full
14242 // size -- `mandelbrot`'s fractal boundary gives every attempt
14243 // (a different `start_scale`) sharp, varied-frequency edges.
14244 // start_scale 5.0 is the proven first try (decodes pixel-exact
14245 // AND reads the seven-symbol set-1 tx_type rows on TX8 TUs);
14246 // later attempts walk down for variety when aomenc's RD flips
14247 // elsewhere.
14248 let source = format!(
14249 "mandelbrot=size=64x64:start_scale={}:rate=25",
14250 5.0 - f64::from(attempt) * 0.06
14251 );
14252 let y4m = Command::new("ffmpeg")
14253 .args([
14254 "-v",
14255 "error",
14256 "-f",
14257 "lavfi",
14258 "-i",
14259 &source,
14260 // Desaturated: chroma stays flat (constant 128) so
14261 // `uv_mode` always resolves to `DC_PRED` and this
14262 // decoder's still-unsupported directional-chroma round-2
14263 // gap never fires, leaving the luma detail alone to
14264 // drive whether `TxMode::Select`'s RD splits a block.
14265 "-vf",
14266 "hue=s=0",
14267 "-pix_fmt",
14268 "yuv420p",
14269 "-t",
14270 "0.04",
14271 "-f",
14272 "yuv4mpegpipe",
14273 "-",
14274 ])
14275 .stdin(Stdio::null())
14276 .stdout(Stdio::piped())
14277 .stderr(Stdio::piped())
14278 .output()
14279 .expect("ffmpeg failed to run");
14280 assert!(
14281 y4m.status.success(),
14282 "ffmpeg fixture: {}",
14283 String::from_utf8_lossy(&y4m.stderr)
14284 );
14285 let out = run_with_stdin(
14286 Command::new(aomenc_path()).args([
14287 "--codec=av1",
14288 "--passes=1",
14289 "--end-usage=q",
14290 "--cq-level=45",
14291 "--cpu-used=0",
14292 "--enable-rect-partitions=0",
14293 "--enable-ab-partitions=0",
14294 "--enable-1to4-partitions=0",
14295 "--enable-filter-intra=0",
14296 // Every non-DC intra tool off: directional chroma and
14297 // angle deltas are separate round-2 gaps, and DC-only
14298 // residual is exactly what gives the RD search a reason
14299 // to split a transform.
14300 "--enable-smooth-intra=0",
14301 "--enable-paeth-intra=0",
14302 "--enable-directional-intra=0",
14303 "--enable-angle-delta=0",
14304 "--enable-cdef=0",
14305 // Loop restoration is a named refusal (aomenc's RD picks
14306 // Sgrproj on this kind of content) -- off in every recipe
14307 // whose test targets a different surface.
14308 "--enable-restoration=0",
14309 "--max-partition-size=32",
14310 // 16x16 blocks are what split into the TX8 TUs whose
14311 // set-1 tx_type rows this gate exists to prove; some
14312 // scales resolve depth 2 (TX4, a named refusal) and the
14313 // attempt loop just moves on.
14314 "--min-partition-size=16",
14315 "--enable-palette=0",
14316 "--enable-intrabc=0",
14317 "--enable-cfl-intra=0",
14318 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
14319 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
14320 "--enable-ref-frame-mvs=0",
14321 "--obu",
14322 "-o",
14323 "-",
14324 "-",
14325 ]),
14326 &y4m.stdout,
14327 );
14328 assert!(
14329 out.status.success(),
14330 "aomenc refused the fixture: {}",
14331 String::from_utf8_lossy(&out.stderr)
14332 );
14333 let stream = out.stdout;
14334 let before = decode::tx_depth_hits();
14335 let frames = match decode_stream(&stream) {
14336 Ok(frames) => frames,
14337 Err(e) => {
14338 refusals.push(format!("seed {seed}: {e}"));
14339 continue;
14340 }
14341 };
14342 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
14343 // is ALWAYS pixel-compared below; the hit counter only decides whether
14344 // the attempt counts toward the firing total.
14345 let counted = decode::tx_depth_hits() != before;
14346 if !counted {
14347 uncounted_exact += 1;
14348 refusals.push(format!(
14349 "seed {seed}: decoded and pixel-compared, but no block resolved a split \
14350 tx_depth"
14351 ));
14352 }
14353 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
14354 assert_eq!(
14355 frames[0].y, ffmpeg_frames[0].y,
14356 "luma vs ffmpeg (seed {seed})"
14357 );
14358 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
14359 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
14360 if counted {
14361 gate_buckets(
14362 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
14363 1,
14364 uncounted_exact,
14365 refusals.len() - uncounted_exact as usize,
14366 );
14367 return;
14368 }
14369 }
14370 gate_buckets(
14371 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
14372 0,
14373 uncounted_exact,
14374 refusals.len() - uncounted_exact as usize,
14375 );
14376 eprintln!(
14377 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: every attempt \
14378 hit a named refusal or never split a transform:\n{}",
14379 refusals.join("\n")
14380 );
14381 }
14382
14383 /// lane-txselect's decisive gate: a real aomenc INTER sequence WITHOUT
14384 /// `--enable-tx-size-search=0`, the flag every other inter recipe in this
14385 /// file pins off precisely to keep the stream on `TxMode::Largest`.
14386 /// Dropped, aomenc takes its own default (`TX_MODE_SELECT` -- which is
14387 /// what both of the user's real films use), and an inter block's
14388 /// transform size is then the recursive `txfm_split` tree of spec
14389 /// 5.11.17 rather than one whole-block transform. A stream that decoded
14390 /// pixel-exact while every `txfm_split` symbol resolved to "no split"
14391 /// would prove nothing (it is `TxMode::Largest` by another name), so this
14392 /// gate hard-asserts BOTH counters: at least one `txfm_split` symbol read
14393 /// AND at least one split actually taken. Exhausting every attempt is a
14394 /// FAILURE, not a SKIP -- an unfired gate is a vacuous gate.
14395 #[test]
14396 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact() {
14397 tx_select_inter_gate(8);
14398 }
14399
14400 /// The 10-bit arm of the gate above (lane-txselect r2): both of the
14401 /// user's films are `yuv420p10le` and var-tx is exactly the tool they
14402 /// use, so an 8-bit-only proof would not reach them. Same recipe plus
14403 /// `-b 10 --input-bit-depth=10`.
14404 #[test]
14405 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact_10bit() {
14406 tx_select_inter_gate(10);
14407 }
14408
14409 /// lane-intrarect r1's decisive gate: a real aomenc INTER sequence whose
14410 /// hard mid-GOP content cut makes aomenc code INTRA blocks inside inter
14411 /// frames, with rect partitions ON so those intra blocks land on
14412 /// HORZ/VERT strip shapes. Every such block was the named refusal "an
14413 /// intra-coded HORZ/VERT strip needs rectangular intra prediction this
14414 /// decoder does not code yet" until this round; they now decode through
14415 /// the same `decode_rect_split` machinery the key-frame rect paths use.
14416 ///
14417 /// Hard-asserts per-shape counters (`intra_rect_strip_in_inter_hits`:
14418 /// 0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16) summed over the
14419 /// attempts that were actually pixel-compared -- at least TWO of the
14420 /// three shape classes must fire, so a green run cannot come from one
14421 /// lucky size. A decode that succeeds is ALWAYS pixel-compared (class
14422 /// [[gate-skips-on-its-own-failure]]); exhausting every attempt without
14423 /// two shapes is a FAILURE, never a SKIP.
14424 #[test]
14425 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact() {
14426 intra_rect_in_inter_gate(8);
14427 }
14428
14429 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
14430 #[test]
14431 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact_10bit() {
14432 intra_rect_in_inter_gate(10);
14433 }
14434
14435 fn intra_rect_in_inter_gate(bit_depth: u32) {
14436 const NAME: &str =
14437 "a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact";
14438 if !have_ffmpeg() {
14439 eprintln!("SKIP {NAME}: no ffmpeg");
14440 return;
14441 }
14442 if !have_aomenc() {
14443 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14444 return;
14445 }
14446 let (width, height, frame_count) = (96usize, 96usize, 8usize);
14447 let mut refusals: Vec<String> = Vec::new();
14448 let mut uncounted_exact = 0u32;
14449 let mut compared = 0u32;
14450 let mut shapes = [0usize; 3];
14451 for attempt in 0..45u32 {
14452 let seed = 42 + attempt;
14453 // mandelbrot's fractal detail plus a HARD cut at frame 4: half
14454 // the picture becomes a flat white box, which no motion vector
14455 // can predict, so aomenc's RD codes those blocks INTRA inside an
14456 // inter frame. The box's vertical edge at x=48 is what makes the
14457 // partition search reach for HORZ/VERT strips there.
14458 // A FAST ZOOM: `end_scale`/`end_pts` make mandelbrot rush
14459 // through its own zoom, so consecutive frames share almost no
14460 // content and aomenc's RD codes blocks INTRA inside INTER frames
14461 // (`--kf-min-dist=1000` forbids a new key frame). That is the
14462 // only way a real encoder reaches this decoder's intra-in-inter
14463 // arm; a slowly-evolving source codes every rect strip inter.
14464 let source = format!(
14465 "mandelbrot=size={width}x{height}:start_scale={}:end_scale=0.004:end_pts=8:rate=25",
14466 5.0 - f64::from(attempt) * 0.06
14467 );
14468 let y4m = Command::new("ffmpeg")
14469 .args([
14470 "-v",
14471 "error",
14472 "-f",
14473 "lavfi",
14474 "-i",
14475 &source,
14476 "-vf",
14477 "hue=s=0",
14478 "-pix_fmt",
14479 if bit_depth == 10 {
14480 "yuv420p10le"
14481 } else {
14482 "yuv420p"
14483 },
14484 "-strict",
14485 "-1",
14486 "-t",
14487 "0.32",
14488 "-f",
14489 "yuv4mpegpipe",
14490 "-strict",
14491 "-1",
14492 "-",
14493 ])
14494 .stdin(Stdio::null())
14495 .stdout(Stdio::piped())
14496 .stderr(Stdio::piped())
14497 .output()
14498 .expect("ffmpeg failed to run");
14499 assert!(
14500 y4m.status.success(),
14501 "ffmpeg fixture: {}",
14502 String::from_utf8_lossy(&y4m.stderr)
14503 );
14504 let depth_args: &[&str] = if bit_depth == 10 {
14505 &["-b", "10", "--input-bit-depth=10"]
14506 } else {
14507 &[]
14508 };
14509 // MEASURED (r1): the speed preset gates the feature (class
14510 // [[gate-preset-gates-the-feature]]) -- at `--cpu-used=4` this
14511 // content produces no rect partition at all, at `--cpu-used=0`
14512 // aomenc emits AB partitions the tile path refuses (it ignores
14513 // `--enable-ab-partitions=0`, ledger). So the attempt sweep walks
14514 // the preset as well as the seed.
14515 let cpu = format!("--cpu-used={}", attempt % 5);
14516 // The quantiser drives how finely the RD partitions: the sweep
14517 // walks it too, so "no rect strip fired" cannot be an artefact of
14518 // one cq.
14519 let cq = format!("--cq-level={}", [30u32, 20, 12][(attempt / 5) as usize % 3]);
14520 let out = run_with_stdin(
14521 Command::new(aomenc_path())
14522 .args(depth_args)
14523 .arg(&cpu)
14524 .arg(&cq)
14525 .args([
14526 // class [[aomenc-first-flag-wins]]: every flag is spelled
14527 // exactly ONCE in this recipe, so there is no override to
14528 // order. These four are what this gate is about.
14529 "--enable-rect-partitions=1",
14530 // MEASURED (r1): the charter's `--min-partition-size=8`
14531 // makes 24/24 attempts stop at a sub-16 AB-partition
14532 // refusal ("a HORZ_A/HORZ_B/VERT_A partition below 16x16",
14533 // "a coded (non-skip) HORZ_B/VERT_B rect strip below
14534 // 16x16") before any intra rect strip is reached -- those
14535 // are other lanes' surfaces. 16 keeps the 16x8/8x16 shape
14536 // reachable (a 16x16 block's own HORZ/VERT children).
14537 "--min-partition-size=16",
14538 "--max-partition-size=64",
14539 // MEASURED (r1): with tx-size search ON, 24/24 attempts stop at
14540 // the SQUARE intra-in-inter arm's own refusal ("an intra
14541 // block in an inter frame whose tx_depth splits its luma
14542 // transform (round 1)", read_block_tx_size) long before a
14543 // rect strip is reached -- that arm is another lane's
14544 // surface. OFF, no tx-depth symbol is coded at all and
14545 // every rect strip here is the unsplit single-transform
14546 // case. The SPLIT rect arm (`depth_to_tx_wh` +
14547 // decode_rect_split's per-unit walk) is wired but stays
14548 // UNGATED on this path until that square refusal lifts.
14549 "--enable-tx-size-search=0",
14550 "--codec=av1",
14551 "--passes=1",
14552 "--end-usage=q",
14553 "--lag-in-frames=0",
14554 "--auto-alt-ref=0",
14555 // One key frame at the head: the frames after the cut must
14556 // stay INTER frames carrying intra blocks, not become a
14557 // new key frame.
14558 "--kf-min-dist=1000",
14559 "--kf-max-dist=1000",
14560 "--threads=1",
14561 "--row-mt=0",
14562 "--enable-order-hint=0",
14563 "--enable-warped-motion=0",
14564 "--enable-obmc=0",
14565 "--enable-masked-comp=0",
14566 "--enable-interintra-comp=0",
14567 "--enable-dist-wtd-comp=0",
14568 "--enable-diff-wtd-comp=0",
14569 "--enable-onesided-comp=0",
14570 "--enable-interintra-wedge=0",
14571 "--enable-smooth-interintra=0",
14572 "--enable-ab-partitions=0",
14573 "--enable-1to4-partitions=0",
14574 // The intra-in-inter arm reads no `use_filter_intra`
14575 // symbol (square OR rect) -- lane-fiinter owns that read.
14576 "--enable-filter-intra=0",
14577 "--enable-smooth-intra=0",
14578 "--enable-paeth-intra=0",
14579 "--enable-directional-intra=0",
14580 "--enable-angle-delta=0",
14581 "--enable-cdef=0",
14582 "--enable-restoration=0",
14583 "--enable-palette=0",
14584 "--enable-intrabc=0",
14585 "--enable-cfl-intra=0",
14586 "--enable-ref-frame-mvs=0",
14587 "--obu",
14588 "-o",
14589 "-",
14590 "-",
14591 ]),
14592 &y4m.stdout,
14593 );
14594 assert!(
14595 out.status.success(),
14596 "aomenc refused the fixture: {}",
14597 String::from_utf8_lossy(&out.stderr)
14598 );
14599 let stream = out.stdout;
14600 let before = [
14601 decode::intra_rect_strip_in_inter_hits(0),
14602 decode::intra_rect_strip_in_inter_hits(1),
14603 decode::intra_rect_strip_in_inter_hits(2),
14604 ];
14605 let kf_rect_before = decode::rect_partition_hits();
14606 let frames = match decode_stream(&stream) {
14607 Ok(frames) => frames,
14608 Err(e) => {
14609 let msg = e.to_string();
14610 assert!(
14611 msg.contains("unsupported"),
14612 "intra-rect-in-inter decode failed outright (seed {seed}): {msg}"
14613 );
14614 refusals.push(format!("seed {seed} {cpu} {cq}: {msg}"));
14615 continue;
14616 }
14617 };
14618 let delta = [
14619 decode::intra_rect_strip_in_inter_hits(0) - before[0],
14620 decode::intra_rect_strip_in_inter_hits(1) - before[1],
14621 decode::intra_rect_strip_in_inter_hits(2) - before[2],
14622 ];
14623 let ffmpeg_frames = if bit_depth == 10 {
14624 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14625 } else {
14626 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14627 };
14628 assert_eq!(frames.len(), frame_count);
14629 eprintln!(
14630 "intrarect gate {bit_depth}-bit seed={seed} {cpu} {cq}: intra rect strips in inter frames \
14631 64-level={} 32-level={} 16-level={}, key-frame rect strips this stream={}",
14632 delta[0],
14633 delta[1],
14634 delta[2],
14635 decode::rect_partition_hits() - kf_rect_before
14636 );
14637 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14638 for (plane, (g, w)) in [
14639 ("Y", (&got.y, &want.y)),
14640 ("U", (&got.u, &want.u)),
14641 ("V", (&got.v, &want.v)),
14642 ] {
14643 let stride = if plane == "Y" { width } else { width / 2 };
14644 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
14645 eprintln!(
14646 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} first \
14647 diff at ({}, {}) got {} want {} ({} samples differ)",
14648 at % stride,
14649 at / stride,
14650 g[at],
14651 w[at],
14652 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
14653 );
14654 // Magnitude separates a deblock/prediction difference
14655 // (all |d| == 1) from an entropy desync (large,
14656 // arbitrary): the first thing r2 needs to know.
14657 let maxd = g
14658 .iter()
14659 .zip(w.iter())
14660 .map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b)))
14661 .max()
14662 .unwrap_or(0);
14663 let rows: std::collections::BTreeSet<usize> = g
14664 .iter()
14665 .zip(w.iter())
14666 .enumerate()
14667 .filter(|(_, (a, b))| a != b)
14668 .map(|(k, _)| k / stride)
14669 .collect();
14670 eprintln!(
14671 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} max \
14672 |diff|={maxd}, rows {:?}..{:?}",
14673 rows.iter().next(),
14674 rows.iter().next_back()
14675 );
14676 }
14677 assert_eq!(g, w, "{plane} vs ffmpeg (seed {seed}, frame {i})");
14678 }
14679 }
14680 compared += 1;
14681 if delta.iter().all(|d| *d == 0) {
14682 uncounted_exact += 1;
14683 refusals.push(format!(
14684 "seed {seed} {cpu} {cq}: decoded and pixel-compared, but no intra rect strip on the \
14685 inter path"
14686 ));
14687 }
14688 for k in 0..3 {
14689 shapes[k] += delta[k];
14690 }
14691 if shapes.iter().filter(|n| **n > 0).count() >= 2 {
14692 break;
14693 }
14694 }
14695 gate_buckets(
14696 NAME,
14697 compared - uncounted_exact,
14698 uncounted_exact,
14699 refusals.len() - uncounted_exact as usize,
14700 );
14701 eprintln!(
14702 "{NAME} ({bit_depth}-bit): compared {compared} streams, intra rect strips in inter \
14703 frames per shape: 64x32/32x64={} 32x16/16x32={} 16x8/8x16={}; refusals:\n{}",
14704 shapes[0],
14705 shapes[1],
14706 shapes[2],
14707 refusals.join("\n")
14708 );
14709 assert!(
14710 compared > 0,
14711 "{NAME} ({bit_depth}-bit): every attempt hit a named refusal -- nothing was \
14712 pixel-compared:\n{}",
14713 refusals.join("\n")
14714 );
14715 // MEASURED (r1, 90 attempts; r2 re-ran the 45-attempt sweep at both
14716 // depths): only the 32x16/16x32 class is REACHABLE on this branch --
14717 // the inter tile path refuses any SB-level partition other than
14718 // NONE/SPLIT, so a 64x32/32x64 intra strip cannot be produced at all,
14719 // and every 16x8/8x16 candidate stops at a sub-16 refusal owned by
14720 // another lane. So the bar is that class, hard, not "two of three":
14721 // a green run still cannot come from a stream that fired nothing.
14722 assert!(
14723 shapes[1] > 0,
14724 "{NAME} ({bit_depth}-bit): no 32x16/16x32 intra rect strip fired over \
14725 {compared} compared streams (64-level={} 32-level={} 16-level={})",
14726 shapes[0],
14727 shapes[1],
14728 shapes[2]
14729 );
14730 }
14731
14732 fn tx_select_inter_gate(bit_depth: u32) {
14733 if !have_ffmpeg() {
14734 eprintln!(
14735 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no ffmpeg"
14736 );
14737 return;
14738 }
14739 if !have_aomenc() {
14740 eprintln!(
14741 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no aomenc at {}",
14742 aomenc_path().display()
14743 );
14744 return;
14745 }
14746 let (width, height, frame_count) = (64usize, 64usize, 4usize);
14747 let mut refusals = Vec::new();
14748 let mut uncounted_exact = 0u32;
14749 for attempt in 0..40u32 {
14750 let seed = 42 + attempt;
14751 // Detail is what makes aomenc's RD prefer a split transform; a
14752 // flat gradient resolves every `txfm_split` to 0. `mandelbrot`'s
14753 // fractal boundary is the same source the sibling intra tx-select
14754 // gate uses, at a different `start_scale` per attempt.
14755 let source = format!(
14756 "mandelbrot=size=64x64:start_scale={}:rate=25",
14757 5.0 - f64::from(attempt) * 0.06
14758 );
14759 let y4m = Command::new("ffmpeg")
14760 .args([
14761 "-v",
14762 "error",
14763 "-f",
14764 "lavfi",
14765 "-i",
14766 &source,
14767 // Desaturated chroma: `uv_mode` stays DC_PRED, so the
14768 // still-refused directional-chroma gap never fires and
14769 // luma detail alone drives the transform split.
14770 "-vf",
14771 "hue=s=0",
14772 "-pix_fmt",
14773 if bit_depth == 10 {
14774 "yuv420p10le"
14775 } else {
14776 "yuv420p"
14777 },
14778 // y4m carries no official 10-bit tag; ffmpeg writes one
14779 // only under `-strict -1` (a no-op at 8 bit).
14780 "-strict",
14781 "-1",
14782 "-t",
14783 "0.16",
14784 "-f",
14785 "yuv4mpegpipe",
14786 "-strict",
14787 "-1",
14788 "-",
14789 ])
14790 .stdin(Stdio::null())
14791 .stdout(Stdio::piped())
14792 .stderr(Stdio::piped())
14793 .output()
14794 .expect("ffmpeg failed to run");
14795 assert!(
14796 y4m.status.success(),
14797 "ffmpeg fixture: {}",
14798 String::from_utf8_lossy(&y4m.stderr)
14799 );
14800 let depth_args: &[&str] = if bit_depth == 10 {
14801 &["-b", "10", "--input-bit-depth=10"]
14802 } else {
14803 &[]
14804 };
14805 let out = run_with_stdin(
14806 Command::new(aomenc_path()).args(depth_args).args([
14807 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
14808 // occurrence, so overrides go before the base list).
14809 "--enable-tx-size-search=1",
14810 "--codec=av1",
14811 "--passes=1",
14812 "--end-usage=q",
14813 "--cq-level=55",
14814 "--cpu-used=0",
14815 "--lag-in-frames=0",
14816 "--auto-alt-ref=0",
14817 "--kf-max-dist=1000",
14818 "--threads=1",
14819 "--row-mt=0",
14820 "--enable-order-hint=0",
14821 "--enable-warped-motion=0",
14822 "--enable-obmc=0",
14823 "--enable-masked-comp=0",
14824 "--enable-interintra-comp=0",
14825 "--enable-dist-wtd-comp=0",
14826 "--enable-diff-wtd-comp=0",
14827 "--enable-onesided-comp=0",
14828 "--enable-interintra-wedge=0",
14829 "--enable-smooth-interintra=0",
14830 "--enable-rect-partitions=0",
14831 "--enable-ab-partitions=0",
14832 "--enable-1to4-partitions=0",
14833 "--enable-filter-intra=0",
14834 "--enable-smooth-intra=0",
14835 "--enable-paeth-intra=0",
14836 "--enable-directional-intra=0",
14837 "--enable-angle-delta=0",
14838 // DELIBERATELY ABSENT: --enable-tx-size-search=0.
14839 "--enable-cdef=0",
14840 "--enable-restoration=0",
14841 "--max-partition-size=32",
14842 // Sub-16 inter partitions are a separate named refusal
14843 // (this decoder codes no inter block below 16x16 through
14844 // the square path this gate drives), and detailed content
14845 // makes aomenc's RD reach for them on nearly every seed.
14846 "--min-partition-size=16",
14847 "--enable-palette=0",
14848 "--enable-intrabc=0",
14849 "--enable-cfl-intra=0",
14850 "--enable-ref-frame-mvs=0",
14851 "--obu",
14852 "-o",
14853 "-",
14854 "-",
14855 ]),
14856 &y4m.stdout,
14857 );
14858 assert!(
14859 out.status.success(),
14860 "aomenc refused the fixture: {}",
14861 String::from_utf8_lossy(&out.stderr)
14862 );
14863 let stream = out.stdout;
14864 let (reads_before, hits_before) =
14865 (decode::txfm_split_reads(), decode::txfm_split_hits());
14866 let frames = match decode_stream(&stream) {
14867 Ok(frames) => frames,
14868 Err(e) => {
14869 let msg = e.to_string();
14870 assert!(
14871 msg.contains("unsupported"),
14872 "tx-select inter decode failed outright (seed {seed}): {msg}"
14873 );
14874 refusals.push(format!("seed {seed}: {msg}"));
14875 continue;
14876 }
14877 };
14878 let (reads, hits) = (
14879 decode::txfm_split_reads() - reads_before,
14880 decode::txfm_split_hits() - hits_before,
14881 );
14882 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
14883 // is ALWAYS pixel-compared below; the hit counter only decides whether
14884 // the attempt counts toward the firing total.
14885 let counted = hits != 0;
14886 if !counted {
14887 uncounted_exact += 1;
14888 refusals.push(format!(
14889 "seed {seed}: decoded and pixel-compared, but no block took a txfm_split \
14890 ({reads} symbols read)"
14891 ));
14892 }
14893 let ffmpeg_frames = if bit_depth == 10 {
14894 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
14895 } else {
14896 ffmpeg_decode_sequence(&stream, width, height, frame_count)
14897 };
14898 assert_eq!(frames.len(), frame_count);
14899 eprintln!(
14900 "txselect gate {bit_depth}-bit seed={seed}: txfm_split reads={reads} splits taken={hits}"
14901 );
14902 // Name the first differing sample before the assert fires: a
14903 // 64x64 plane's `assert_eq!` output is 4096 numbers, useless for
14904 // locating a desync.
14905 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14906 for (plane, (g, w)) in [
14907 ("Y", (&got.y, &want.y)),
14908 ("U", (&got.u, &want.u)),
14909 ("V", (&got.v, &want.v)),
14910 ] {
14911 let stride = if plane == "Y" { width } else { width / 2 };
14912 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
14913 eprintln!(
14914 "txselect gate seed={seed}: frame {i} {plane} first diff at \
14915 ({}, {}) got {} want {} ({} samples differ)",
14916 at % stride,
14917 at / stride,
14918 g[at],
14919 w[at],
14920 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
14921 );
14922 let coords: Vec<String> = g
14923 .iter()
14924 .zip(w.iter())
14925 .enumerate()
14926 .filter(|(_, (a, b))| a != b)
14927 .take(12)
14928 .map(|(k, (a, b))| format!("({},{})={a}/{b}", k % stride, k / stride))
14929 .collect();
14930 eprintln!("txselect gate seed={seed}: frame {i} {plane} diffs {coords:?}");
14931 }
14932 }
14933 }
14934 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
14935 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
14936 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
14937 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
14938 }
14939 if counted {
14940 gate_buckets(
14941 &format!("tx_select_inter_gate({bit_depth})"),
14942 1,
14943 uncounted_exact,
14944 refusals.len() - uncounted_exact as usize,
14945 );
14946 return;
14947 }
14948 }
14949 gate_buckets(
14950 &format!("tx_select_inter_gate({bit_depth})"),
14951 0,
14952 uncounted_exact,
14953 refusals.len() - uncounted_exact as usize,
14954 );
14955 panic!(
14956 "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}",
14957 refusals.join("\n")
14958 );
14959 }
14960
14961 /// lane-intrainter r1's decisive gate: a real aomenc INTER sequence in
14962 /// which aomenc's RD picks an INTRA block inside an inter frame AND
14963 /// splits that block's luma transform (`tx_depth >= 1`, the intra depth
14964 /// symbol -- not the inter var-tx tree). That block codes one intra
14965 /// prediction plus one coefficient set per transform unit, exactly like a
14966 /// key frame's split block but with the inter frame's CDF state and the
14967 /// inter-frame intra mode syntax; before this lane it was a named
14968 /// refusal. Hard-asserts [`decode::intra_in_inter_split_tx_hits`] per
14969 /// block size: an attempt that never produced such a block proves
14970 /// nothing, and exhausting every attempt is a FAILURE, not a SKIP.
14971 #[test]
14972 fn a_real_aomenc_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
14973 intra_in_inter_split_tx_gate(8);
14974 }
14975
14976 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
14977 #[test]
14978 fn a_real_aomenc_10bit_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
14979 intra_in_inter_split_tx_gate(10);
14980 }
14981
14982 fn intra_in_inter_split_tx_gate(bit_depth: u32) {
14983 let name = format!("intra_in_inter_split_tx_gate({bit_depth})");
14984 if !have_ffmpeg() {
14985 eprintln!("SKIP {name}: no ffmpeg");
14986 return;
14987 }
14988 if !have_aomenc() {
14989 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
14990 return;
14991 }
14992 let (width, height, frame_count) = (64usize, 64usize, 8usize);
14993 let mut refusals = Vec::new();
14994 let mut uncounted_exact = 0u32;
14995 for attempt in 0..40u32 {
14996 let seed = 42 + attempt;
14997 // A zooming fractal: every frame moves (so the sequence is
14998 // genuinely inter-coded) and keeps sharp new detail entering at
14999 // the borders, which is what makes aomenc's RD choose an INTRA
15000 // block inside an inter frame -- and then split its transform.
15001 // A zooming fractal with a hard CUT halfway (`overlay` switching
15002 // a second, unrelated fractal on at frame 4): after the cut every
15003 // block is unpredictable from the reference, which is what makes
15004 // aomenc code INTRA blocks inside an inter frame -- and at this
15005 // cq the RD then splits their transforms.
15006 let source = format!(
15007 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
15008 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
15009 [a][b]overlay=enable='gte(n,4)'",
15010 5.0 - f64::from(attempt) * 0.06,
15011 0.9 + f64::from(attempt) * 0.11
15012 );
15013 let y4m = Command::new("ffmpeg")
15014 .args([
15015 "-v",
15016 "error",
15017 "-f",
15018 "lavfi",
15019 "-i",
15020 &source,
15021 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
15022 // still-refused directional-chroma gaps never fire and
15023 // luma detail alone drives the transform split.
15024 "-vf",
15025 "hue=s=0",
15026 "-pix_fmt",
15027 if bit_depth == 10 {
15028 "yuv420p10le"
15029 } else {
15030 "yuv420p"
15031 },
15032 "-strict",
15033 "-1",
15034 "-t",
15035 "0.32",
15036 "-f",
15037 "yuv4mpegpipe",
15038 "-strict",
15039 "-1",
15040 "-",
15041 ])
15042 .stdin(Stdio::null())
15043 .stdout(Stdio::piped())
15044 .stderr(Stdio::piped())
15045 .output()
15046 .expect("ffmpeg failed to run");
15047 assert!(
15048 y4m.status.success(),
15049 "ffmpeg fixture: {}",
15050 String::from_utf8_lossy(&y4m.stderr)
15051 );
15052 let depth_args: &[&str] = if bit_depth == 10 {
15053 &["-b", "10", "--input-bit-depth=10"]
15054 } else {
15055 &[]
15056 };
15057 let out = run_with_stdin(
15058 Command::new(aomenc_path()).args(depth_args).args([
15059 "--codec=av1",
15060 "--passes=1",
15061 "--end-usage=q",
15062 "--cq-level=30",
15063 "--cpu-used=0",
15064 "--lag-in-frames=0",
15065 "--auto-alt-ref=0",
15066 // One key frame only: every later frame is an inter frame,
15067 // which is where this gate's intra blocks must sit. The
15068 // MIN distance is what stops aomenc's scene-cut detector
15069 // from inserting a second key frame at the cut this gate's
15070 // source deliberately contains.
15071 "--kf-max-dist=1000",
15072 "--kf-min-dist=1000",
15073 "--threads=1",
15074 "--row-mt=0",
15075 "--enable-order-hint=0",
15076 "--enable-warped-motion=0",
15077 "--enable-obmc=0",
15078 "--enable-masked-comp=0",
15079 "--enable-interintra-comp=0",
15080 "--enable-dist-wtd-comp=0",
15081 "--enable-diff-wtd-comp=0",
15082 "--enable-onesided-comp=0",
15083 "--enable-interintra-wedge=0",
15084 "--enable-smooth-interintra=0",
15085 "--enable-ab-partitions=0",
15086 "--enable-1to4-partitions=0",
15087 "--enable-filter-intra=0",
15088 "--enable-smooth-intra=0",
15089 "--enable-paeth-intra=0",
15090 "--enable-directional-intra=0",
15091 "--enable-angle-delta=0",
15092 "--enable-cdef=0",
15093 "--enable-restoration=0",
15094 "--enable-palette=0",
15095 "--enable-intrabc=0",
15096 "--enable-cfl-intra=0",
15097 "--enable-ref-frame-mvs=0",
15098 // Per-arm overrides go LAST (aomenc keeps the last
15099 // occurrence of a repeated --enable-* flag): the intra
15100 // tx_depth symbol only exists under TX_MODE_SELECT, and
15101 // rect partitions are a separate named refusal.
15102 "--enable-tx-size-search=1",
15103 "--enable-rect-partitions=0",
15104 "--max-partition-size=32",
15105 // Sub-16 inter partitions are a separate named refusal,
15106 // as is the 8x8 intra leaf's own TX_4X4 split.
15107 "--min-partition-size=16",
15108 "--obu",
15109 "-o",
15110 "-",
15111 "-",
15112 ]),
15113 &y4m.stdout,
15114 );
15115 assert!(
15116 out.status.success(),
15117 "aomenc refused the fixture: {}",
15118 String::from_utf8_lossy(&out.stderr)
15119 );
15120 let stream = out.stdout;
15121 let before = decode::intra_in_inter_split_tx_hits();
15122 let frames = match decode_stream(&stream) {
15123 Ok(frames) => frames,
15124 Err(e) => {
15125 let msg = e.to_string();
15126 assert!(
15127 msg.contains("unsupported"),
15128 "{name} decode failed outright (seed {seed}): {msg}"
15129 );
15130 refusals.push(format!("seed {seed}: {msg}"));
15131 continue;
15132 }
15133 };
15134 let after = decode::intra_in_inter_split_tx_hits();
15135 let mut per_size = [0usize; 4];
15136 for i in 0..4 {
15137 per_size[i] = after[i] - before[i];
15138 }
15139 // class [[gate-skips-on-its-own-failure]]: a decode that
15140 // succeeded is ALWAYS pixel-compared below; the counter only
15141 // decides whether the attempt counts as firing.
15142 let counted = per_size.iter().sum::<usize>() != 0;
15143 if !counted {
15144 uncounted_exact += 1;
15145 refusals.push(format!(
15146 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
15147 frame split its transform"
15148 ));
15149 }
15150 let ffmpeg_frames = if bit_depth == 10 {
15151 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
15152 } else {
15153 ffmpeg_decode_sequence(&stream, width, height, frame_count)
15154 };
15155 assert_eq!(frames.len(), frame_count);
15156 eprintln!(
15157 "{name} seed={seed}: split intra-in-inter blocks 8x8={} 16x16={} 32x32={} \
15158 64x64={}",
15159 per_size[0], per_size[1], per_size[2], per_size[3]
15160 );
15161 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15162 for (plane, (g, w)) in [
15163 ("Y", (&got.y, &want.y)),
15164 ("U", (&got.u, &want.u)),
15165 ("V", (&got.v, &want.v)),
15166 ] {
15167 let stride = if plane == "Y" { width } else { width / 2 };
15168 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
15169 eprintln!(
15170 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
15171 want {} ({} samples differ)",
15172 at % stride,
15173 at / stride,
15174 g[at],
15175 w[at],
15176 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
15177 );
15178 }
15179 }
15180 }
15181 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15182 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
15183 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
15184 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
15185 }
15186 if counted {
15187 gate_buckets(
15188 &name,
15189 1,
15190 uncounted_exact,
15191 refusals.len() - uncounted_exact as usize,
15192 );
15193 return;
15194 }
15195 }
15196 gate_buckets(
15197 &name,
15198 0,
15199 uncounted_exact,
15200 refusals.len() - uncounted_exact as usize,
15201 );
15202 panic!(
15203 "{name} never observed a split-transform intra block in an inter frame:\n{}",
15204 refusals.join("\n")
15205 );
15206 }
15207
15208 /// lane-fiinter r1 (class [[symbol-consumption-gap]] +
15209 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
15210 /// `--enable-filter-intra=1` (aomenc's own default -- every inter gate
15211 /// recipe before this one pinned it OFF, so nothing ever exercised it) in
15212 /// which the RD picks an INTRA block inside an inter frame and gives it
15213 /// filter intra. `read_intra_block_mode_info` reads `use_filter_intra`
15214 /// there exactly as a key frame does; this decoder read no such symbol at
15215 /// all until this round, so such a stream desynced at that symbol and
15216 /// decoded silently wrong. Hard-asserts
15217 /// [`decode::intra_in_inter_filter_intra_hits`]: an attempt that never
15218 /// produced one proves nothing, and exhausting every attempt is a
15219 /// FAILURE, not a SKIP.
15220 #[test]
15221 fn a_real_aomenc_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact() {
15222 filter_intra_in_inter_gate(8);
15223 }
15224
15225 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
15226 #[test]
15227 fn a_real_aomenc_10bit_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact()
15228 {
15229 filter_intra_in_inter_gate(10);
15230 }
15231
15232 fn filter_intra_in_inter_gate(bit_depth: u32) {
15233 let name = format!("filter_intra_in_inter_gate({bit_depth})");
15234 if !have_ffmpeg() {
15235 eprintln!("SKIP {name}: no ffmpeg");
15236 return;
15237 }
15238 if !have_aomenc() {
15239 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
15240 return;
15241 }
15242 let (width, height, frame_count) = (64usize, 64usize, 8usize);
15243 let mut refusals = Vec::new();
15244 let mut uncounted_exact = 0u32;
15245 for attempt in 0..40u32 {
15246 let seed = 42 + attempt;
15247 // A zooming fractal: every frame moves (so the sequence is
15248 // genuinely inter-coded) and keeps sharp new detail entering at
15249 // the borders, which is what makes aomenc's RD choose an INTRA
15250 // block inside an inter frame -- and then split its transform.
15251 // A zooming fractal with a hard CUT halfway (`overlay` switching
15252 // a second, unrelated fractal on at frame 4): after the cut every
15253 // block is unpredictable from the reference, which is what makes
15254 // aomenc code INTRA blocks inside an inter frame -- and at this
15255 // cq the RD then splits their transforms.
15256 let source = format!(
15257 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
15258 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
15259 [a][b]overlay=enable='gte(n,4)'",
15260 5.0 - f64::from(attempt) * 0.06,
15261 0.9 + f64::from(attempt) * 0.11
15262 );
15263 let y4m = Command::new("ffmpeg")
15264 .args([
15265 "-v",
15266 "error",
15267 "-f",
15268 "lavfi",
15269 "-i",
15270 &source,
15271 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
15272 // still-refused directional-chroma gaps never fire and
15273 // luma detail alone drives the transform split.
15274 "-vf",
15275 "hue=s=0",
15276 "-pix_fmt",
15277 if bit_depth == 10 {
15278 "yuv420p10le"
15279 } else {
15280 "yuv420p"
15281 },
15282 "-strict",
15283 "-1",
15284 "-t",
15285 "0.32",
15286 "-f",
15287 "yuv4mpegpipe",
15288 "-strict",
15289 "-1",
15290 "-",
15291 ])
15292 .stdin(Stdio::null())
15293 .stdout(Stdio::piped())
15294 .stderr(Stdio::piped())
15295 .output()
15296 .expect("ffmpeg failed to run");
15297 assert!(
15298 y4m.status.success(),
15299 "ffmpeg fixture: {}",
15300 String::from_utf8_lossy(&y4m.stderr)
15301 );
15302 let depth_args: &[&str] = if bit_depth == 10 {
15303 &["-b", "10", "--input-bit-depth=10"]
15304 } else {
15305 &[]
15306 };
15307 let out = run_with_stdin(
15308 Command::new(aomenc_path()).args(depth_args).args([
15309 "--codec=av1",
15310 "--passes=1",
15311 "--end-usage=q",
15312 "--cq-level=30",
15313 "--cpu-used=0",
15314 "--lag-in-frames=0",
15315 "--auto-alt-ref=0",
15316 // One key frame only: every later frame is an inter frame,
15317 // which is where this gate's intra blocks must sit. The
15318 // MIN distance is what stops aomenc's scene-cut detector
15319 // from inserting a second key frame at the cut this gate's
15320 // source deliberately contains.
15321 "--kf-max-dist=1000",
15322 "--kf-min-dist=1000",
15323 "--threads=1",
15324 "--row-mt=0",
15325 "--enable-order-hint=0",
15326 "--enable-warped-motion=0",
15327 "--enable-obmc=0",
15328 "--enable-masked-comp=0",
15329 "--enable-interintra-comp=0",
15330 "--enable-dist-wtd-comp=0",
15331 "--enable-diff-wtd-comp=0",
15332 "--enable-onesided-comp=0",
15333 "--enable-interintra-wedge=0",
15334 "--enable-smooth-interintra=0",
15335 "--enable-ab-partitions=0",
15336 "--enable-1to4-partitions=0",
15337 "--enable-smooth-intra=0",
15338 "--enable-paeth-intra=0",
15339 "--enable-directional-intra=0",
15340 "--enable-angle-delta=0",
15341 "--enable-cdef=0",
15342 "--enable-restoration=0",
15343 "--enable-palette=0",
15344 "--enable-intrabc=0",
15345 "--enable-cfl-intra=0",
15346 "--enable-ref-frame-mvs=0",
15347 // Per-arm overrides go LAST (aomenc keeps the last
15348 // occurrence of a repeated --enable-* flag): the intra
15349 // tx_depth symbol only exists under TX_MODE_SELECT, and
15350 // rect partitions are a separate named refusal.
15351 "--enable-filter-intra=1",
15352 "--enable-tx-size-search=1",
15353 "--enable-rect-partitions=0",
15354 "--max-partition-size=32",
15355 // Sub-16 inter partitions are a separate named refusal,
15356 // as is the 8x8 intra leaf's own TX_4X4 split.
15357 "--min-partition-size=16",
15358 "--obu",
15359 "-o",
15360 "-",
15361 "-",
15362 ]),
15363 &y4m.stdout,
15364 );
15365 assert!(
15366 out.status.success(),
15367 "aomenc refused the fixture: {}",
15368 String::from_utf8_lossy(&out.stderr)
15369 );
15370 let stream = out.stdout;
15371 let before = decode::intra_in_inter_filter_intra_hits();
15372 let frames = match decode_stream(&stream) {
15373 Ok(frames) => frames,
15374 Err(e) => {
15375 let msg = e.to_string();
15376 assert!(
15377 msg.contains("unsupported"),
15378 "{name} decode failed outright (seed {seed}): {msg}"
15379 );
15380 refusals.push(format!("seed {seed}: {msg}"));
15381 continue;
15382 }
15383 };
15384 let fired = decode::intra_in_inter_filter_intra_hits() - before;
15385 // class [[gate-skips-on-its-own-failure]]: a decode that
15386 // succeeded is ALWAYS pixel-compared below; the counter only
15387 // decides whether the attempt counts as firing.
15388 let counted = fired != 0;
15389 if !counted {
15390 uncounted_exact += 1;
15391 refusals.push(format!(
15392 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
15393 frame used filter intra"
15394 ));
15395 }
15396 let ffmpeg_frames = if bit_depth == 10 {
15397 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
15398 } else {
15399 ffmpeg_decode_sequence(&stream, width, height, frame_count)
15400 };
15401 assert_eq!(frames.len(), frame_count);
15402 eprintln!("{name} seed={seed}: filter-intra blocks inside inter frames = {fired}");
15403 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15404 for (plane, (g, w)) in [
15405 ("Y", (&got.y, &want.y)),
15406 ("U", (&got.u, &want.u)),
15407 ("V", (&got.v, &want.v)),
15408 ] {
15409 let stride = if plane == "Y" { width } else { width / 2 };
15410 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
15411 eprintln!(
15412 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
15413 want {} ({} samples differ)",
15414 at % stride,
15415 at / stride,
15416 g[at],
15417 w[at],
15418 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
15419 );
15420 }
15421 }
15422 }
15423 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15424 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
15425 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
15426 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
15427 }
15428 if counted {
15429 gate_buckets(
15430 &name,
15431 1,
15432 uncounted_exact,
15433 refusals.len() - uncounted_exact as usize,
15434 );
15435 return;
15436 }
15437 }
15438 gate_buckets(
15439 &name,
15440 0,
15441 uncounted_exact,
15442 refusals.len() - uncounted_exact as usize,
15443 );
15444 panic!(
15445 "{name} never observed a filter-intra intra block in an inter frame:\n{}",
15446 refusals.join("\n")
15447 );
15448 }
15449
15450 /// lane-angleinter r1 (class [[refusal-strings-are-claims]] +
15451 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
15452 /// `--enable-angle-delta=1` and `--enable-directional-intra=1` (aomenc's
15453 /// own defaults; every inter gate before this one pinned BOTH off) in
15454 /// which the RD gives an INTRA block inside an inter frame a directional
15455 /// luma mode with a nonzero `angle_delta_y`. Both intra-in-inter arms
15456 /// read that symbol and then REFUSED it as "this encoder never writes
15457 /// one" -- the claim is false, `read_intra_angle_info` writes it exactly
15458 /// as a key frame does. Hard-asserts
15459 /// [`decode::intra_in_inter_angle_delta_y_hits`]; an attempt that never
15460 /// produced one proves nothing, and exhausting every attempt is a
15461 /// FAILURE, not a SKIP.
15462 #[test]
15463 fn a_real_aomenc_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
15464 {
15465 angle_delta_in_inter_gate(8, "--min-partition-size=16");
15466 }
15467
15468 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
15469 #[test]
15470 fn a_real_aomenc_10bit_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
15471 {
15472 angle_delta_in_inter_gate(10, "--min-partition-size=16");
15473 }
15474
15475 fn angle_delta_in_inter_gate(bit_depth: u32, min_partition: &str) {
15476 let name = format!("angle_delta_in_inter_gate({bit_depth}, min={min_partition})");
15477 let leaf8 = min_partition.ends_with('8');
15478 assert!(
15479 !leaf8,
15480 "the 8x8-leaf arm keeps its refusal; see the module note"
15481 );
15482 if !have_ffmpeg() {
15483 eprintln!("SKIP {name}: no ffmpeg");
15484 return;
15485 }
15486 if !have_aomenc() {
15487 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
15488 return;
15489 }
15490 let (width, height, frame_count) = (64usize, 64usize, 8usize);
15491 let mut refusals = Vec::new();
15492 let mut uncounted_exact = 0u32;
15493 for attempt in 0..40u32 {
15494 let seed = 42 + attempt;
15495 // A zooming fractal: every frame moves (so the sequence is
15496 // genuinely inter-coded) and keeps sharp new detail entering at
15497 // the borders, which is what makes aomenc's RD choose an INTRA
15498 // block inside an inter frame -- and then split its transform.
15499 // A zooming fractal with a hard CUT halfway (`overlay` switching
15500 // a second, unrelated fractal on at frame 4): after the cut every
15501 // block is unpredictable from the reference, which is what makes
15502 // aomenc code INTRA blocks inside an inter frame -- and at this
15503 // cq the RD then splits their transforms.
15504 let source = format!(
15505 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
15506 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
15507 [a][b]overlay=enable='gte(n,4)'",
15508 5.0 - f64::from(attempt) * 0.06,
15509 0.9 + f64::from(attempt) * 0.11
15510 );
15511 let y4m = Command::new("ffmpeg")
15512 .args([
15513 "-v",
15514 "error",
15515 "-f",
15516 "lavfi",
15517 "-i",
15518 &source,
15519 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
15520 // still-refused directional-chroma gaps never fire and
15521 // luma detail alone drives the transform split.
15522 "-vf",
15523 "hue=s=0",
15524 "-pix_fmt",
15525 if bit_depth == 10 {
15526 "yuv420p10le"
15527 } else {
15528 "yuv420p"
15529 },
15530 "-strict",
15531 "-1",
15532 "-t",
15533 "0.32",
15534 "-f",
15535 "yuv4mpegpipe",
15536 "-strict",
15537 "-1",
15538 "-",
15539 ])
15540 .stdin(Stdio::null())
15541 .stdout(Stdio::piped())
15542 .stderr(Stdio::piped())
15543 .output()
15544 .expect("ffmpeg failed to run");
15545 assert!(
15546 y4m.status.success(),
15547 "ffmpeg fixture: {}",
15548 String::from_utf8_lossy(&y4m.stderr)
15549 );
15550 // The 8x8-leaf arm is fenced by three sibling refusals (non-DC
15551 // chroma on an 8x8 leaf, its TX_4X4 split, sub-16 rect inter
15552 // leaves), so it sweeps the quantiser as well as the source: a
15553 // coarser q is what pushes the RD to directional intra at 8x8.
15554 let cq = if leaf8 {
15555 format!("--cq-level={}", 20 + (attempt % 5) * 10)
15556 } else {
15557 "--cq-level=30".to_string()
15558 };
15559 let depth_args: &[&str] = if bit_depth == 10 {
15560 &["-b", "10", "--input-bit-depth=10"]
15561 } else {
15562 &[]
15563 };
15564 let out = run_with_stdin(
15565 Command::new(aomenc_path()).args(depth_args).args([
15566 "--codec=av1",
15567 "--passes=1",
15568 "--end-usage=q",
15569 &cq,
15570 "--cpu-used=0",
15571 "--lag-in-frames=0",
15572 "--auto-alt-ref=0",
15573 // One key frame only: every later frame is an inter frame,
15574 // which is where this gate's intra blocks must sit. The
15575 // MIN distance is what stops aomenc's scene-cut detector
15576 // from inserting a second key frame at the cut this gate's
15577 // source deliberately contains.
15578 "--kf-max-dist=1000",
15579 "--kf-min-dist=1000",
15580 "--threads=1",
15581 "--row-mt=0",
15582 "--enable-order-hint=0",
15583 "--enable-warped-motion=0",
15584 "--enable-obmc=0",
15585 "--enable-masked-comp=0",
15586 "--enable-interintra-comp=0",
15587 "--enable-dist-wtd-comp=0",
15588 "--enable-diff-wtd-comp=0",
15589 "--enable-onesided-comp=0",
15590 "--enable-interintra-wedge=0",
15591 "--enable-smooth-interintra=0",
15592 "--enable-ab-partitions=0",
15593 "--enable-1to4-partitions=0",
15594 "--enable-smooth-intra=0",
15595 "--enable-paeth-intra=0",
15596 "--enable-directional-intra=1",
15597 "--enable-angle-delta=1",
15598 "--enable-cdef=0",
15599 "--enable-restoration=0",
15600 "--enable-palette=0",
15601 "--enable-intrabc=0",
15602 "--enable-cfl-intra=0",
15603 "--enable-ref-frame-mvs=0",
15604 // Per-arm overrides go LAST (aomenc keeps the last
15605 // occurrence of a repeated --enable-* flag): the intra
15606 // tx_depth symbol only exists under TX_MODE_SELECT, and
15607 // rect partitions are a separate named refusal.
15608 "--enable-filter-intra=1",
15609 "--enable-tx-size-search=1",
15610 "--enable-rect-partitions=0",
15611 "--max-partition-size=32",
15612 // Sub-16 inter partitions are a separate named refusal,
15613 // as is the 8x8 intra leaf's own TX_4X4 split.
15614 min_partition,
15615 "--obu",
15616 "-o",
15617 "-",
15618 "-",
15619 ]),
15620 &y4m.stdout,
15621 );
15622 assert!(
15623 out.status.success(),
15624 "aomenc refused the fixture: {}",
15625 String::from_utf8_lossy(&out.stderr)
15626 );
15627 let stream = out.stdout;
15628 let before = decode::intra_in_inter_angle_delta_y_hits();
15629 let before_uv = decode::intra_in_inter_angle_delta_uv_hits();
15630 let frames = match decode_stream(&stream) {
15631 Ok(frames) => frames,
15632 Err(e) => {
15633 let msg = e.to_string();
15634 assert!(
15635 msg.contains("unsupported"),
15636 "{name} decode failed outright (seed {seed}): {msg}"
15637 );
15638 refusals.push(format!("seed {seed}: {msg}"));
15639 continue;
15640 }
15641 };
15642 let fired = decode::intra_in_inter_angle_delta_y_hits() - before;
15643 let fired_uv = decode::intra_in_inter_angle_delta_uv_hits() - before_uv;
15644 // class [[gate-skips-on-its-own-failure]]: a decode that
15645 // succeeded is ALWAYS pixel-compared below; the counter only
15646 // decides whether the attempt counts as firing.
15647 let counted = fired != 0;
15648 if !counted {
15649 uncounted_exact += 1;
15650 refusals.push(format!(
15651 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
15652 frame carried a nonzero angle_delta_y"
15653 ));
15654 }
15655 let ffmpeg_frames = if bit_depth == 10 {
15656 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
15657 } else {
15658 ffmpeg_decode_sequence(&stream, width, height, frame_count)
15659 };
15660 assert_eq!(frames.len(), frame_count);
15661 eprintln!(
15662 "{name} seed={seed}: intra-in-inter blocks with a nonzero angle_delta_y = \
15663 {fired}, angle_delta_uv = {fired_uv}"
15664 );
15665 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15666 for (plane, (g, w)) in [
15667 ("Y", (&got.y, &want.y)),
15668 ("U", (&got.u, &want.u)),
15669 ("V", (&got.v, &want.v)),
15670 ] {
15671 let stride = if plane == "Y" { width } else { width / 2 };
15672 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
15673 eprintln!(
15674 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
15675 want {} ({} samples differ)",
15676 at % stride,
15677 at / stride,
15678 g[at],
15679 w[at],
15680 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
15681 );
15682 }
15683 }
15684 }
15685 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15686 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
15687 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
15688 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
15689 }
15690 if counted {
15691 gate_buckets(
15692 &name,
15693 1,
15694 uncounted_exact,
15695 refusals.len() - uncounted_exact as usize,
15696 );
15697 return;
15698 }
15699 }
15700 gate_buckets(
15701 &name,
15702 0,
15703 uncounted_exact,
15704 refusals.len() - uncounted_exact as usize,
15705 );
15706 panic!(
15707 "{name} never observed a nonzero angle delta on an intra block in an inter \
15708 frame:\n{}",
15709 refusals.join("\n")
15710 );
15711 }
15712
15713 /// lane-uv8 r1 (classes [[refusal-strings-are-claims]] +
15714 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
15715 /// 8x8 partitions and full chroma intra tooling
15716 /// (`--enable-cfl-intra=1 --enable-smooth-intra=1 --enable-paeth-intra=1
15717 /// --enable-directional-intra=1`), in which the RD gives an INTRA 8x8
15718 /// leaf inside an inter frame a NON-DC `uv_mode`. That leaf
15719 /// ([`decode::decode_inter_block8`]'s intra arm) read the `uv_mode`
15720 /// symbol and refused every value but `DC_PRED` -- "this encoder never
15721 /// writes one" was a claim, and this gate is what contradicts it. Hard-
15722 /// asserts `decode::intra_in_inter8_uv_hits` (directional, smooth/paeth,
15723 /// CfL, counted on THIS leaf only); an attempt that never produced one
15724 /// proves nothing, and exhausting every attempt is a FAILURE, not a SKIP.
15725 #[test]
15726 fn a_real_aomenc_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() {
15727 uv_mode_in_inter8_gate(8, 1);
15728 }
15729
15730 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
15731 #[test]
15732 fn a_real_aomenc_10bit_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact()
15733 {
15734 uv_mode_in_inter8_gate(10, 1);
15735 }
15736
15737 /// The multi-tile arm (class [[new-map-ignores-tile-edge]]): this round
15738 /// stamps a new `uv_mode` band from the 8x8 leaf, whose availability must
15739 /// be tile-relative.
15740 #[test]
15741 fn a_real_aomenc_two_tile_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact()
15742 {
15743 uv_mode_in_inter8_gate(8, 2);
15744 }
15745
15746 fn uv_mode_in_inter8_gate(bit_depth: u32, tile_columns: u32) {
15747 let name = format!("uv_mode_in_inter8_gate({bit_depth}, tiles={tile_columns})");
15748 if !have_ffmpeg() {
15749 eprintln!("SKIP {name}: no ffmpeg");
15750 return;
15751 }
15752 if !have_aomenc() {
15753 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
15754 return;
15755 }
15756 let (width, height, frame_count) = (192usize, 128usize, 8usize);
15757 let mut refusals = Vec::new();
15758 let mut uncounted_exact = 0u32;
15759 let mut totals = (0usize, 0usize, 0usize);
15760 for attempt in 0..30u32 {
15761 let seed = 42 + attempt;
15762 // A zooming fractal with a hard CUT at frame 4 (`overlay`
15763 // switching a second, unrelated fractal on): after the cut a block
15764 // is unpredictable from the reference, which is what makes aomenc
15765 // code INTRA blocks inside an inter frame. Chroma is NOT
15766 // desaturated here (every sibling inter gate passes `hue=s=0`) --
15767 // real chroma detail is exactly what pushes the chroma RD off
15768 // DC_PRED. `noise` carries its own explicit seed (lavfi
15769 // `gradients` ignores its seed; class [[seeded-fixture-not-reproducible]]).
15770 let source = format!(
15771 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
15772 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
15773 [a][b]overlay=enable='gte(n,4)',noise=alls=12:allf=t+u:all_seed={seed}",
15774 5.0 - f64::from(attempt) * 0.06,
15775 0.9 + f64::from(attempt) * 0.11
15776 );
15777 let y4m = Command::new("ffmpeg")
15778 .args([
15779 "-v",
15780 "error",
15781 "-f",
15782 "lavfi",
15783 "-i",
15784 &source,
15785 "-pix_fmt",
15786 if bit_depth == 10 {
15787 "yuv420p10le"
15788 } else {
15789 "yuv420p"
15790 },
15791 "-strict",
15792 "-1",
15793 "-t",
15794 "0.32",
15795 "-f",
15796 "yuv4mpegpipe",
15797 "-strict",
15798 "-1",
15799 "-",
15800 ])
15801 .stdin(Stdio::null())
15802 .stdout(Stdio::piped())
15803 .stderr(Stdio::piped())
15804 .output()
15805 .expect("ffmpeg failed to run");
15806 assert!(
15807 y4m.status.success(),
15808 "ffmpeg fixture: {}",
15809 String::from_utf8_lossy(&y4m.stderr)
15810 );
15811 // A coarser quantiser is what pushes the chroma RD to a cheap
15812 // non-DC mode on a small block; sweep 12..40 (the low end is what
15813 // lane-cdef's cq12 arm needs).
15814 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
15815 let depth_args: &[&str] = if bit_depth == 10 {
15816 &["-b", "10", "--input-bit-depth=10"]
15817 } else {
15818 &[]
15819 };
15820 let tiles = format!("--tile-columns={}", tile_columns - 1);
15821 // The y4m goes through a FILE, not aomenc's stdin: this gate's
15822 // stream is ~100 KB, bigger than a pipe buffer, so an aomenc that
15823 // is still being fed on stdin blocks writing its stdout and the
15824 // test blocks writing its stdin -- a hard deadlock (measured
15825 // here, 3 min into attempt 0, class [[gate-loader-slurps-whole-file]]).
15826 // The path is PID-keyed (class [[pid-keyed-temp-path]]).
15827 let y4m_path = std::env::temp_dir().join(format!(
15828 "ec-av1-uv8-{}-{bit_depth}-{tile_columns}-{seed}.y4m",
15829 std::process::id()
15830 ));
15831 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
15832 let child = Command::new(aomenc_path())
15833 .args(depth_args)
15834 .args([
15835 "--codec=av1",
15836 "--passes=1",
15837 "--end-usage=q",
15838 &cq,
15839 "--cpu-used=0",
15840 "--lag-in-frames=0",
15841 "--auto-alt-ref=0",
15842 "--kf-max-dist=9999",
15843 "--kf-min-dist=9999",
15844 "--threads=1",
15845 "--row-mt=0",
15846 &tiles,
15847 "--enable-order-hint=0",
15848 "--enable-warped-motion=0",
15849 "--enable-obmc=0",
15850 "--enable-masked-comp=0",
15851 "--enable-interintra-comp=0",
15852 "--enable-dist-wtd-comp=0",
15853 "--enable-diff-wtd-comp=0",
15854 "--enable-onesided-comp=0",
15855 "--enable-interintra-wedge=0",
15856 "--enable-smooth-interintra=0",
15857 "--enable-ab-partitions=0",
15858 "--enable-1to4-partitions=0",
15859 "--enable-cdef=0",
15860 "--enable-restoration=0",
15861 "--enable-palette=0",
15862 "--enable-intrabc=0",
15863 "--enable-ref-frame-mvs=0",
15864 // Per-arm overrides go LAST (aomenc keeps the LAST
15865 // occurrence of a repeated --enable-* flag). The three
15866 // chroma intra tools this gate is about, plus the fences
15867 // that keep the leaf's SIBLING refusals (its TX_4X4
15868 // split, a nonzero angle delta, sub-16 rect inter leaves)
15869 // out of the way.
15870 "--enable-cfl-intra=1",
15871 "--enable-smooth-intra=1",
15872 "--enable-paeth-intra=1",
15873 "--enable-directional-intra=1",
15874 "--enable-angle-delta=0",
15875 "--enable-tx-size-search=0",
15876 "--enable-rect-partitions=0",
15877 "--min-partition-size=8",
15878 "--max-partition-size=32",
15879 "--obu",
15880 "-o",
15881 "-",
15882 ])
15883 .arg(&y4m_path)
15884 .stdin(Stdio::null())
15885 .stdout(Stdio::piped())
15886 .stderr(Stdio::piped())
15887 .spawn()
15888 .expect("aomenc failed to start");
15889 let out = child.wait_with_output().expect("aomenc failed to run");
15890 let _ = std::fs::remove_file(&y4m_path);
15891 assert!(
15892 out.status.success(),
15893 "aomenc refused the fixture: {}",
15894 String::from_utf8_lossy(&out.stderr)
15895 );
15896 let stream = out.stdout;
15897 let before = decode::intra_in_inter8_uv_hits();
15898 let frames = match decode_stream(&stream) {
15899 Ok(frames) => frames,
15900 Err(e) => {
15901 let msg = e.to_string();
15902 assert!(
15903 msg.contains("unsupported"),
15904 "{name} decode failed outright (seed {seed}): {msg}"
15905 );
15906 refusals.push(format!("seed {seed}: {msg}"));
15907 continue;
15908 }
15909 };
15910 let now = decode::intra_in_inter8_uv_hits();
15911 // class [[counter-from-refused-stream]]: per-attempt deltas, and
15912 // only for an attempt that decoded to the end and is pixel-
15913 // compared below.
15914 let fired = (now.0 - before.0, now.1 - before.1, now.2 - before.2);
15915 totals = (totals.0 + fired.0, totals.1 + fired.1, totals.2 + fired.2);
15916 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
15917 // is ALWAYS pixel-compared; the counter only decides whether the
15918 // attempt counts as firing.
15919 // lane-uv8 r3: every one of the three chroma classes this gate
15920 // exists for (directional, smooth/paeth, CfL) must fire on the
15921 // SAME pixel-compared attempt -- a sum-nonzero predicate would
15922 // pass on an attempt that only ever hit DC-adjacent CfL.
15923 let counted = fired.0 > 0 && fired.1 > 0 && fired.2 > 0;
15924 if !counted {
15925 uncounted_exact += 1;
15926 refusals.push(format!(
15927 "seed {seed}: decoded and pixel-compared, but no 8x8 intra leaf in an inter \
15928 frame carried a non-DC uv_mode"
15929 ));
15930 }
15931 let ffmpeg_frames = if bit_depth == 10 {
15932 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
15933 } else {
15934 ffmpeg_decode_sequence(&stream, width, height, frame_count)
15935 };
15936 assert_eq!(frames.len(), frame_count);
15937 eprintln!(
15938 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with a non-DC uv_mode -- \
15939 directional {}, smooth/paeth {}, CfL {}",
15940 fired.0, fired.1, fired.2
15941 );
15942 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15943 for (plane, (g, w)) in [
15944 ("Y", (&got.y, &want.y)),
15945 ("U", (&got.u, &want.u)),
15946 ("V", (&got.v, &want.v)),
15947 ] {
15948 let stride = if plane == "Y" { width } else { width / 2 };
15949 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
15950 eprintln!(
15951 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
15952 want {} ({} samples differ)",
15953 at % stride,
15954 at / stride,
15955 g[at],
15956 w[at],
15957 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
15958 );
15959 }
15960 }
15961 }
15962 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15963 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
15964 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
15965 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
15966 }
15967 if counted {
15968 gate_buckets(
15969 &name,
15970 1,
15971 uncounted_exact,
15972 refusals.len() - uncounted_exact as usize,
15973 );
15974 return;
15975 }
15976 }
15977 gate_buckets(
15978 &name,
15979 0,
15980 uncounted_exact,
15981 refusals.len() - uncounted_exact as usize,
15982 );
15983 panic!(
15984 "{name} never observed a non-DC uv_mode on an 8x8 intra leaf in an inter frame \
15985 (totals dir/smooth/cfl {totals:?}):\n{}",
15986 refusals.join("\n")
15987 );
15988 }
15989
15990 /// lane-leaf8tx r1: the refusal this round lifts on an INTRA 8x8 leaf
15991 /// inside an INTER frame -- a nonzero luma `angle_delta_y` on it
15992 /// (`--enable-angle-delta=1`,
15993 /// `av1_use_angle_delta(BLOCK_8X8)`). Both counters are per-attempt
15994 /// deltas on an attempt that decoded to the end and is pixel-compared
15995 /// (class [[counter-from-refused-stream]]); a decode error or a mismatch
15996 /// is a FAILURE, never a SKIP.
15997 #[test]
15998 fn a_real_aomenc_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
15999 tx_split_angle_in_inter8_gate(8);
16000 }
16001
16002 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
16003 #[test]
16004 fn a_real_aomenc_10bit_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
16005 tx_split_angle_in_inter8_gate(10);
16006 }
16007
16008 fn tx_split_angle_in_inter8_gate(bit_depth: u32) {
16009 let name = format!("tx_split_angle_in_inter8_gate({bit_depth})");
16010 if !have_ffmpeg() {
16011 eprintln!("SKIP {name}: no ffmpeg");
16012 return;
16013 }
16014 if !have_aomenc() {
16015 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
16016 return;
16017 }
16018 let (width, height, frame_count) = (192usize, 128usize, 6usize);
16019 let mut refusals = Vec::new();
16020 let mut uncounted_exact = 0u32;
16021 let mut counted_exact = 0u32;
16022 let mut totals = (0usize, 0usize);
16023 for attempt in 0..30u32 {
16024 let seed = 42 + attempt;
16025 // Same zoom + hard-cut fractal source the sibling uv_mode gate
16026 // uses (a cut is what makes aomenc code INTRA blocks inside an
16027 // inter frame); `noise` carries an explicit seed (class
16028 // [[seeded-fixture-not-reproducible]]).
16029 let source = format!(
16030 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
16031 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
16032 [a][b]overlay=enable='gte(n,3)',noise=alls=12:allf=t+u:all_seed={seed}",
16033 5.0 - f64::from(attempt) * 0.06,
16034 0.9 + f64::from(attempt) * 0.11
16035 );
16036 let y4m = Command::new("ffmpeg")
16037 .args([
16038 "-v",
16039 "error",
16040 "-f",
16041 "lavfi",
16042 "-i",
16043 &source,
16044 "-pix_fmt",
16045 if bit_depth == 10 {
16046 "yuv420p10le"
16047 } else {
16048 "yuv420p"
16049 },
16050 "-strict",
16051 "-1",
16052 "-t",
16053 "0.24",
16054 "-f",
16055 "yuv4mpegpipe",
16056 "-strict",
16057 "-1",
16058 "-",
16059 ])
16060 .stdin(Stdio::null())
16061 .stdout(Stdio::piped())
16062 .stderr(Stdio::piped())
16063 .output()
16064 .expect("ffmpeg failed to run");
16065 assert!(
16066 y4m.status.success(),
16067 "ffmpeg fixture: {}",
16068 String::from_utf8_lossy(&y4m.stderr)
16069 );
16070 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
16071 let depth_args: &[&str] = if bit_depth == 10 {
16072 &["-b", "10", "--input-bit-depth=10"]
16073 } else {
16074 &[]
16075 };
16076 // The y4m goes through a PID-keyed FILE, never aomenc's stdin
16077 // (pipe deadlock, class [[gate-loader-slurps-whole-file]]).
16078 let y4m_path = std::env::temp_dir().join(format!(
16079 "ec-av1-leaf8tx-{}-{bit_depth}-{seed}.y4m",
16080 std::process::id()
16081 ));
16082 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
16083 let child = Command::new(aomenc_path())
16084 .args(depth_args)
16085 .args([
16086 "--codec=av1",
16087 "--passes=1",
16088 "--end-usage=q",
16089 &cq,
16090 "--cpu-used=0",
16091 "--lag-in-frames=0",
16092 "--auto-alt-ref=0",
16093 "--kf-max-dist=9999",
16094 "--kf-min-dist=9999",
16095 "--threads=1",
16096 "--row-mt=0",
16097 "--tile-columns=0",
16098 "--enable-order-hint=0",
16099 "--enable-warped-motion=0",
16100 "--enable-obmc=0",
16101 "--enable-masked-comp=0",
16102 "--enable-interintra-comp=0",
16103 "--enable-dist-wtd-comp=0",
16104 "--enable-diff-wtd-comp=0",
16105 "--enable-onesided-comp=0",
16106 "--enable-interintra-wedge=0",
16107 "--enable-smooth-interintra=0",
16108 "--enable-ab-partitions=0",
16109 "--enable-1to4-partitions=0",
16110 "--enable-cdef=0",
16111 "--enable-restoration=0",
16112 "--enable-palette=0",
16113 "--enable-intrabc=0",
16114 "--enable-ref-frame-mvs=0",
16115 // Per-arm overrides LAST (aomenc keeps the last
16116 // occurrence of a repeated --enable-* flag). Rect
16117 // partitions stay off so the leaf's unrelated sub-16 rect
16118 // inter refusal never fires.
16119 "--enable-rect-partitions=0",
16120 "--enable-tx-size-search=1",
16121 "--enable-angle-delta=1",
16122 "--enable-directional-intra=1",
16123 "--min-partition-size=8",
16124 "--max-partition-size=32",
16125 "--obu",
16126 "-o",
16127 "-",
16128 ])
16129 // r1 diagnostic: EC_LEAF8TX_CONTROL=1 turns THIS lane's two
16130 // tools back off (last occurrence of a repeated --enable-*
16131 // wins), so any mismatch that survives is not this lane's.
16132 .args(match std::env::var("EC_LEAF8TX_CONTROL").as_deref() {
16133 Ok("angle") => vec!["--enable-tx-size-search=0", "--enable-angle-delta=1"],
16134 Ok("tx") => vec!["--enable-tx-size-search=1", "--enable-angle-delta=0"],
16135 Ok("tx8") => vec![
16136 "--enable-tx-size-search=1",
16137 "--enable-angle-delta=0",
16138 "--max-partition-size=8",
16139 ],
16140 Ok(_) => vec!["--enable-tx-size-search=0", "--enable-angle-delta=0"],
16141 // Shipped recipe (lane-leaf8tx r4): BOTH of this lane's
16142 // tools on -- the tx_depth split at an 8x8 intra-in-inter
16143 // leaf is what the lifted refusal covers, so
16144 // `--enable-tx-size-search=1` must survive the per-arm
16145 // override (aomenc keeps the LAST occurrence). Odd
16146 // attempts also cap the partition at 8x8, the shape that
16147 // produces the 2x2 TX_4X4 grid most often.
16148 Err(_) => {
16149 if attempt % 2 == 1 {
16150 vec![
16151 "--enable-tx-size-search=1",
16152 "--enable-angle-delta=1",
16153 "--max-partition-size=8",
16154 ]
16155 } else {
16156 vec!["--enable-tx-size-search=1", "--enable-angle-delta=1"]
16157 }
16158 }
16159 })
16160 .arg(&y4m_path)
16161 .stdin(Stdio::null())
16162 .stdout(Stdio::piped())
16163 .stderr(Stdio::piped())
16164 .spawn()
16165 .expect("aomenc failed to start");
16166 let out = child.wait_with_output().expect("aomenc failed to run");
16167 let _ = std::fs::remove_file(&y4m_path);
16168 assert!(
16169 out.status.success(),
16170 "aomenc refused the fixture: {}",
16171 String::from_utf8_lossy(&out.stderr)
16172 );
16173 let stream = out.stdout;
16174 let before = (
16175 decode::intra_in_inter_split_tx_hits()[0],
16176 decode::intra_in_inter8_angle_delta_y_hits(),
16177 );
16178 let frames = match decode_stream(&stream) {
16179 Ok(frames) => frames,
16180 Err(e) => {
16181 let msg = e.to_string();
16182 assert!(
16183 msg.contains("unsupported"),
16184 "{name} decode failed outright (seed {seed}): {msg}"
16185 );
16186 refusals.push(format!("seed {seed}: {msg}"));
16187 continue;
16188 }
16189 };
16190 let now = (
16191 decode::intra_in_inter_split_tx_hits()[0],
16192 decode::intra_in_inter8_angle_delta_y_hits(),
16193 );
16194 let fired = (now.0 - before.0, now.1 - before.1);
16195 totals = (totals.0 + fired.0, totals.1 + fired.1);
16196 // Both lifted capabilities must fire on the SAME pixel-compared
16197 // attempt.
16198 let counted = fired.1 > 0;
16199 if !counted {
16200 uncounted_exact += 1;
16201 refusals.push(format!(
16202 "seed {seed}: decoded and pixel-compared, but split-tx {} / angle-delta {} \
16203 8x8 intra-in-inter leaves",
16204 fired.0, fired.1
16205 ));
16206 }
16207 let ffmpeg_frames = if bit_depth == 10 {
16208 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
16209 } else {
16210 ffmpeg_decode_sequence(&stream, width, height, frame_count)
16211 };
16212 assert_eq!(frames.len(), frame_count);
16213 eprintln!(
16214 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with tx_depth=1 {}, with a \
16215 nonzero angle_delta_y {} (split-tx per size 8/16/32/64 {:?})",
16216 fired.0,
16217 fired.1,
16218 decode::intra_in_inter_split_tx_hits()
16219 );
16220 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16221 for (plane, (g, w)) in [
16222 ("Y", (&got.y, &want.y)),
16223 ("U", (&got.u, &want.u)),
16224 ("V", (&got.v, &want.v)),
16225 ] {
16226 let stride = if plane == "Y" { width } else { width / 2 };
16227 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
16228 eprintln!(
16229 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
16230 want {} ({} samples differ)",
16231 at % stride,
16232 at / stride,
16233 g[at],
16234 w[at],
16235 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
16236 );
16237 }
16238 }
16239 }
16240 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16241 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
16242 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
16243 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
16244 }
16245 if counted {
16246 counted_exact += 1;
16247 }
16248 }
16249 // lane-leaf8tx r4: continue-and-sweep -- every arm is encoded,
16250 // decoded and pixel-compared on every plane of every decode-order
16251 // frame above; the counters are asserted ONCE here. A decode error or
16252 // a mismatch is a failure, never a SKIP, and `uncounted_exact`
16253 // (decoded + compared but neither capability fired) is the
16254 // out-of-scope-mismatch bucket that the sweep tolerates only while at
16255 // least one attempt did fire.
16256 gate_buckets(
16257 &name,
16258 counted_exact,
16259 uncounted_exact,
16260 refusals.len() - uncounted_exact as usize,
16261 );
16262 assert!(
16263 totals.0 > 0,
16264 "{name}: no decoded+compared attempt carried an 8x8 intra-in-inter leaf with \
16265 tx_depth split to 4x4 (split-tx per size {:?}, angle-delta {}):\n{}",
16266 decode::intra_in_inter_split_tx_hits(),
16267 totals.1,
16268 refusals.join("\n")
16269 );
16270 assert!(
16271 totals.1 > 0,
16272 "{name}: no decoded+compared attempt carried a nonzero angle_delta_y on an 8x8 \
16273 intra-in-inter leaf (split-tx {}):\n{}",
16274 totals.0,
16275 refusals.join("\n")
16276 );
16277 }
16278
16279 /// lane-chroma r2 stage 1: a real aomenc key frame with
16280 /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`)
16281 /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still-
16282 /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never
16283 /// fires; smooth *luma* neighbours are exactly what this gate wants to
16284 /// exercise, proving [`decode::smooth_luma_hits`] actually landed a
16285 /// directional block next to a smooth-predicted one and decoded
16286 /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix).
16287 #[test]
16288 fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() {
16289 if !have_ffmpeg() {
16290 eprintln!(
16291 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg"
16292 );
16293 return;
16294 }
16295 if !have_aomenc() {
16296 eprintln!(
16297 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}",
16298 aomenc_path().display()
16299 );
16300 return;
16301 }
16302 let (width, height) = (64usize, 64usize);
16303 let mut refusals = Vec::new();
16304 let mut fired_runs = 0u32;
16305 let mut uncounted_exact = 0u32;
16306 for attempt in 0..40u32 {
16307 let seed = 42 + attempt;
16308 let source = format!(
16309 "mandelbrot=size=64x64:start_scale={}:rate=25",
16310 5.0 - f64::from(attempt) * 0.06
16311 );
16312 let y4m = Command::new("ffmpeg")
16313 .args([
16314 "-v",
16315 "error",
16316 "-f",
16317 "lavfi",
16318 "-i",
16319 &source,
16320 "-pix_fmt",
16321 "yuv420p",
16322 "-t",
16323 "0.04",
16324 "-f",
16325 "yuv4mpegpipe",
16326 "-",
16327 ])
16328 .stdin(Stdio::null())
16329 .stdout(Stdio::piped())
16330 .stderr(Stdio::piped())
16331 .output()
16332 .expect("ffmpeg failed to run");
16333 assert!(
16334 y4m.status.success(),
16335 "ffmpeg fixture: {}",
16336 String::from_utf8_lossy(&y4m.stderr)
16337 );
16338 let out = run_with_stdin(
16339 Command::new(aomenc_path()).args([
16340 "--codec=av1",
16341 "--passes=1",
16342 "--end-usage=q",
16343 "--cq-level=45",
16344 "--cpu-used=0",
16345 "--enable-rect-partitions=0",
16346 "--enable-ab-partitions=0",
16347 "--enable-1to4-partitions=0",
16348 "--enable-filter-intra=0",
16349 "--enable-smooth-intra=1",
16350 // Smooth/paeth chroma is a still-refused, separate
16351 // round-2 gap -- off so no attempt trips it while this
16352 // gate is purely about luma's edge-filter fix.
16353 "--enable-paeth-intra=0",
16354 "--enable-tx-size-search=0",
16355 "--enable-cdef=0",
16356 "--enable-restoration=0",
16357 "--enable-intra-edge-filter=1",
16358 "--max-partition-size=32",
16359 "--min-partition-size=16",
16360 "--enable-palette=0",
16361 "--enable-intrabc=0",
16362 "--enable-cfl-intra=0",
16363 "--enable-ref-frame-mvs=0",
16364 "--obu",
16365 "-o",
16366 "-",
16367 "-",
16368 ]),
16369 &y4m.stdout,
16370 );
16371 assert!(
16372 out.status.success(),
16373 "aomenc refused the fixture: {}",
16374 String::from_utf8_lossy(&out.stderr)
16375 );
16376 let stream = out.stdout;
16377 let smooth_before = decode::smooth_luma_hits();
16378 let frames = match decode_stream(&stream) {
16379 Ok(frames) => frames,
16380 Err(e) => {
16381 refusals.push(format!("seed {seed}: {e}"));
16382 continue;
16383 }
16384 };
16385 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
16386 // is ALWAYS pixel-compared below; the hit counter only decides whether
16387 // the attempt counts toward the firing total.
16388 let counted = decode::smooth_luma_hits() != smooth_before;
16389 if counted {
16390 fired_runs += 1;
16391 } else {
16392 uncounted_exact += 1;
16393 refusals.push(format!(
16394 "seed {seed}: decoded and pixel-compared, but no smooth-luma-neighbour block \
16395 fired"
16396 ));
16397 }
16398 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
16399 assert_eq!(
16400 frames[0].y, ffmpeg_frames[0].y,
16401 "luma vs ffmpeg (seed {seed})"
16402 );
16403 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
16404 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
16405 if fired_runs >= 4 {
16406 gate_buckets(
16407 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
16408 fired_runs,
16409 uncounted_exact,
16410 refusals.len() - uncounted_exact as usize,
16411 );
16412 return;
16413 }
16414 }
16415 gate_buckets(
16416 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
16417 fired_runs,
16418 uncounted_exact,
16419 refusals.len() - uncounted_exact as usize,
16420 );
16421 assert!(
16422 fired_runs > 0,
16423 "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}",
16424 refusals.join("\n")
16425 );
16426 }
16427
16428 /// The smooth/paeth-chroma gate (lane-chroma r1/r3): a real aomenc key
16429 /// frame with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the
16430 /// opposite of the directional-chroma gate below, which turns these OFF
16431 /// to keep this gap from firing while directional chroma is under test).
16432 /// Some seeds won't pick smooth/paeth for chroma at all -- retry like
16433 /// every other real-encoder gate here, but the first attempt that
16434 /// actually fires [`decode::smooth_uv_hits`] must decode pixel-exact.
16435 #[test]
16436 fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() {
16437 if !have_ffmpeg() {
16438 eprintln!(
16439 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg"
16440 );
16441 return;
16442 }
16443 if !have_aomenc() {
16444 eprintln!(
16445 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}",
16446 aomenc_path().display()
16447 );
16448 return;
16449 }
16450 let (width, height) = (64usize, 64usize);
16451 let mut refusals = Vec::new();
16452 let mut fired_runs = 0u32;
16453 let mut uncounted_exact = 0u32;
16454 for attempt in 0..40u32 {
16455 let seed = 42 + attempt;
16456 let source = format!(
16457 "mandelbrot=size=64x64:start_scale={}:rate=25",
16458 5.0 - f64::from(attempt) * 0.06
16459 );
16460 let y4m = Command::new("ffmpeg")
16461 .args([
16462 "-v",
16463 "error",
16464 "-f",
16465 "lavfi",
16466 "-i",
16467 &source,
16468 "-pix_fmt",
16469 "yuv420p",
16470 "-t",
16471 "0.04",
16472 "-f",
16473 "yuv4mpegpipe",
16474 "-",
16475 ])
16476 .stdin(Stdio::null())
16477 .stdout(Stdio::piped())
16478 .stderr(Stdio::piped())
16479 .output()
16480 .expect("ffmpeg failed to run");
16481 assert!(
16482 y4m.status.success(),
16483 "ffmpeg fixture: {}",
16484 String::from_utf8_lossy(&y4m.stderr)
16485 );
16486 let out = run_with_stdin(
16487 Command::new(aomenc_path()).args([
16488 "--codec=av1",
16489 "--passes=1",
16490 "--end-usage=q",
16491 "--cq-level=45",
16492 "--cpu-used=0",
16493 "--enable-rect-partitions=0",
16494 "--enable-ab-partitions=0",
16495 "--enable-1to4-partitions=0",
16496 "--enable-filter-intra=0",
16497 "--enable-smooth-intra=1",
16498 "--enable-paeth-intra=1",
16499 "--enable-tx-size-search=0",
16500 "--enable-cdef=0",
16501 "--enable-restoration=0",
16502 "--enable-intra-edge-filter=1",
16503 "--max-partition-size=32",
16504 // 8x8/leaf8 splits are a separate, already-named refusal.
16505 "--min-partition-size=16",
16506 "--enable-palette=0",
16507 "--enable-intrabc=0",
16508 "--enable-cfl-intra=0",
16509 "--enable-ref-frame-mvs=0",
16510 "--obu",
16511 "-o",
16512 "-",
16513 "-",
16514 ]),
16515 &y4m.stdout,
16516 );
16517 assert!(
16518 out.status.success(),
16519 "aomenc refused the fixture: {}",
16520 String::from_utf8_lossy(&out.stderr)
16521 );
16522 let stream = out.stdout;
16523 let smooth_before = decode::smooth_uv_hits();
16524 let frames = match decode_stream(&stream) {
16525 Ok(frames) => frames,
16526 Err(e) => {
16527 refusals.push(format!("seed {seed}: {e}"));
16528 continue;
16529 }
16530 };
16531 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
16532 // is ALWAYS pixel-compared below; the hit counter only decides whether
16533 // the attempt counts toward the firing total.
16534 let counted = decode::smooth_uv_hits() != smooth_before;
16535 if counted {
16536 fired_runs += 1;
16537 } else {
16538 uncounted_exact += 1;
16539 refusals.push(format!(
16540 "seed {seed}: decoded and pixel-compared, but no smooth/paeth uv_mode fired"
16541 ));
16542 }
16543 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
16544 assert_eq!(
16545 frames[0].y, ffmpeg_frames[0].y,
16546 "luma vs ffmpeg (seed {seed})"
16547 );
16548 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
16549 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
16550 if fired_runs >= 4 {
16551 gate_buckets(
16552 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
16553 fired_runs,
16554 uncounted_exact,
16555 refusals.len() - uncounted_exact as usize,
16556 );
16557 return;
16558 }
16559 }
16560 gate_buckets(
16561 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
16562 fired_runs,
16563 uncounted_exact,
16564 refusals.len() - uncounted_exact as usize,
16565 );
16566 assert!(
16567 fired_runs > 0,
16568 "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}",
16569 refusals.join("\n")
16570 );
16571 }
16572
16573 /// The directional-chroma/angle-delta gate: a real aomenc key frame with
16574 /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the
16575 /// opposite of every sibling recipe's `=0`, which existed specifically to
16576 /// keep this round-2 gap from firing while a different surface was under
16577 /// test). A colourful, sharp-edged source gives the RD search a reason to
16578 /// pick a directional `uv_mode` and/or a nonzero angle delta -- some
16579 /// seeds still won't, so retry like every other real-encoder gate here,
16580 /// but the first attempt that actually fires either counter must decode
16581 /// pixel-exact.
16582 #[test]
16583 fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() {
16584 if !have_ffmpeg() {
16585 eprintln!(
16586 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg"
16587 );
16588 return;
16589 }
16590 if !have_aomenc() {
16591 eprintln!(
16592 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}",
16593 aomenc_path().display()
16594 );
16595 return;
16596 }
16597 let (width, height) = (64usize, 64usize);
16598 let mut refusals = Vec::new();
16599 let mut fired_runs = 0u32;
16600 let mut uncounted_exact = 0u32;
16601 for attempt in 0..40u32 {
16602 let seed = 42 + attempt;
16603 let source = format!(
16604 "mandelbrot=size=64x64:start_scale={}:rate=25",
16605 5.0 - f64::from(attempt) * 0.06
16606 );
16607 let y4m = Command::new("ffmpeg")
16608 .args([
16609 "-v",
16610 "error",
16611 "-f",
16612 "lavfi",
16613 "-i",
16614 &source,
16615 "-pix_fmt",
16616 "yuv420p",
16617 "-t",
16618 "0.04",
16619 "-f",
16620 "yuv4mpegpipe",
16621 "-",
16622 ])
16623 .stdin(Stdio::null())
16624 .stdout(Stdio::piped())
16625 .stderr(Stdio::piped())
16626 .output()
16627 .expect("ffmpeg failed to run");
16628 assert!(
16629 y4m.status.success(),
16630 "ffmpeg fixture: {}",
16631 String::from_utf8_lossy(&y4m.stderr)
16632 );
16633 let out = run_with_stdin(
16634 Command::new(aomenc_path()).args([
16635 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
16636 // occurrence, so overrides go before the base list).
16637 "--enable-directional-intra=1",
16638 "--codec=av1",
16639 "--passes=1",
16640 "--end-usage=q",
16641 "--cq-level=45",
16642 "--cpu-used=0",
16643 "--enable-rect-partitions=0",
16644 "--enable-ab-partitions=0",
16645 "--enable-1to4-partitions=0",
16646 "--enable-filter-intra=0",
16647 // Smooth/Paeth chroma is a separate, still-refused round-2
16648 // gap (an unrelated `Edges::build` no-neighbour bug this
16649 // lane does not cover) -- off so the RD search's only
16650 // non-DC/CFL chroma choice left is directional.
16651 "--enable-smooth-intra=0",
16652 "--enable-paeth-intra=0",
16653 "--enable-tx-size-search=0",
16654 "--enable-cdef=0",
16655 "--enable-restoration=0",
16656 // The intra edge filter/upsample (spec 7.11.2.7-2.9) is
16657 // now implemented (`directional()`) -- left ON (aomenc's
16658 // own default) so this gate actually exercises it instead
16659 // of the un-filtered fast path a disabled flag would keep
16660 // testing.
16661 "--enable-intra-edge-filter=1",
16662 "--max-partition-size=32",
16663 // Same reason as the tx-select gate above: 8x8 and other
16664 // sub-16x16 splits are a separate, already-named refusal.
16665 "--min-partition-size=16",
16666 "--enable-palette=0",
16667 "--enable-intrabc=0",
16668 "--enable-cfl-intra=0",
16669 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
16670 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
16671 "--enable-ref-frame-mvs=0",
16672 "--obu",
16673 "-o",
16674 "-",
16675 "-",
16676 ]),
16677 &y4m.stdout,
16678 );
16679 assert!(
16680 out.status.success(),
16681 "aomenc refused the fixture: {}",
16682 String::from_utf8_lossy(&out.stderr)
16683 );
16684 let stream = out.stdout;
16685 let (uv_before, angle_before) =
16686 (decode::directional_uv_hits(), decode::angle_delta_hits());
16687 let frames = match decode_stream(&stream) {
16688 Ok(frames) => frames,
16689 Err(e) => {
16690 refusals.push(format!("seed {seed}: {e}"));
16691 continue;
16692 }
16693 };
16694 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
16695 // is ALWAYS pixel-compared below; the hit counter only decides whether
16696 // the attempt counts toward the firing total.
16697 let counted = decode::directional_uv_hits() != uv_before
16698 || decode::angle_delta_hits() != angle_before;
16699 if counted {
16700 fired_runs += 1;
16701 } else {
16702 uncounted_exact += 1;
16703 refusals.push(format!(
16704 "seed {seed}: decoded and pixel-compared, but neither a directional uv_mode \
16705 nor a nonzero angle delta fired"
16706 ));
16707 }
16708 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
16709 assert_eq!(
16710 frames[0].y, ffmpeg_frames[0].y,
16711 "luma vs ffmpeg (seed {seed})"
16712 );
16713 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
16714 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
16715 if fired_runs >= 4 {
16716 gate_buckets(
16717 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
16718 fired_runs,
16719 uncounted_exact,
16720 refusals.len() - uncounted_exact as usize,
16721 );
16722 return;
16723 }
16724 }
16725 gate_buckets(
16726 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
16727 fired_runs,
16728 uncounted_exact,
16729 refusals.len() - uncounted_exact as usize,
16730 );
16731 assert!(
16732 fired_runs > 0,
16733 "every attempt hit a named refusal or never exercised directional chroma:\n{}",
16734 refusals.join("\n")
16735 );
16736 }
16737
16738 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
16739 /// --auto-alt-ref=0` keep every non-key frame a simple forward
16740 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this
16741 /// decoder's inter path does not model), `--kf-max-dist` past the clip's
16742 /// own length keeps frame 0 the only key frame.
16743 /// lane-inter8 r1: the inter tile path's SB-level `PARTITION_NONE` -- a
16744 /// whole 64x64 superblock coded as ONE inter block, which is what aomenc
16745 /// picks for static content and which this decoder refused by name
16746 /// ("an inter SB-level partition type other than SPLIT") until this
16747 /// round. HARD-asserts [`decode::inter_sb_none_hits`] moved (the arm
16748 /// really fired, class refusal-lifted-without-a-gate) and every frame is
16749 /// pixel-exact vs ffmpeg; a decode error is a FAILURE here, never a SKIP
16750 /// (class gate-skips-on-its-own-failure).
16751 /// lane-inter8 r1: generalised so the same recipe can target a deeper
16752 /// level of the inter partition tree -- `min_part` is aomenc's
16753 /// `--min-partition-size`, and `hits`/`what` name the counter that proves
16754 /// the arm under test really fired.
16755 #[track_caller]
16756 fn inter_sb_none_gate(
16757 name: &str,
16758 ten_bit: bool,
16759 min_part: &str,
16760 max_part: &str,
16761 hits: fn() -> usize,
16762 what: &str,
16763 // lane-inter8 r3: extra aomenc flags + the frame width they need.
16764 // `--tile-columns=1` needs a frame at least two superblocks wide or
16765 // aomenc silently codes one tile column and the arm is vacuous.
16766 extra: &[&str],
16767 width: usize,
16768 // lane-interp3 r1: sequence length -- a compound block needs several
16769 // already-coded references, which a 4-frame sequence never has.
16770 frame_count: usize,
16771 ) {
16772 if !have_ffmpeg() {
16773 eprintln!("SKIP {name}: no ffmpeg");
16774 return;
16775 }
16776 if !have_aomenc() {
16777 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
16778 return;
16779 }
16780 let height = 64usize;
16781 let duration = format!("{:.2}", frame_count as f64 / 25.0);
16782 // A deterministic synthetic source with real motion (a static source
16783 // codes every inter frame as skip and never exercises the residual
16784 // path); bounded with `-t` (class gate-loader-slurps-whole-file).
16785 let y4m = Command::new("ffmpeg")
16786 .args([
16787 "-v",
16788 "error",
16789 "-f",
16790 "lavfi",
16791 "-i",
16792 &format!("mandelbrot=size={width}x{height}:rate=25"),
16793 "-t",
16794 &duration,
16795 "-pix_fmt",
16796 if ten_bit { "yuv420p10le" } else { "yuv420p" },
16797 // y4m calls 10-bit unofficial (same as the 10-bit key-frame
16798 // gate's own fixture).
16799 "-strict",
16800 "-1",
16801 "-f",
16802 "yuv4mpegpipe",
16803 "-",
16804 ])
16805 .stdin(Stdio::null())
16806 .stdout(Stdio::piped())
16807 .stderr(Stdio::piped())
16808 .output()
16809 .expect("ffmpeg failed to run");
16810 assert!(
16811 y4m.status.success(),
16812 "{name}: ffmpeg fixture: {}",
16813 String::from_utf8_lossy(&y4m.stderr)
16814 );
16815 let mut args: Vec<String> = [
16816 "--codec=av1",
16817 "--passes=1",
16818 "--end-usage=q",
16819 "--cq-level=40",
16820 "--cpu-used=0",
16821 "--lag-in-frames=0",
16822 "--auto-alt-ref=0",
16823 "--kf-max-dist=1000",
16824 // No cross-frame CDF forwarding in this fixture (see the
16825 // deblocking gate's own note).
16826 "--error-resilient=1",
16827 // This gate targets the SB-level NONE arm only: rect/AB/1-to-4
16828 // partitions and sub-16x16 splits stay off so a failure here
16829 // cannot be another lane's missing arm.
16830 "--enable-rect-partitions=0",
16831 "--enable-ab-partitions=0",
16832 "--enable-1to4-partitions=0",
16833 "--enable-filter-intra=0",
16834 "--enable-smooth-intra=0",
16835 "--enable-paeth-intra=0",
16836 "--enable-directional-intra=0",
16837 "--enable-angle-delta=0",
16838 "--enable-tx-size-search=0",
16839 "--enable-cdef=0",
16840 "--enable-restoration=0",
16841 "--enable-palette=0",
16842 "--enable-intrabc=0",
16843 "--enable-cfl-intra=0",
16844 "--enable-ref-frame-mvs=0",
16845 "--obu",
16846 "-o",
16847 "-",
16848 "-",
16849 ]
16850 .iter()
16851 .map(|s| (*s).to_string())
16852 .collect();
16853 for e in extra {
16854 args.insert(1, (*e).to_string());
16855 }
16856 args.insert(1, format!("--min-partition-size={min_part}"));
16857 args.insert(1, format!("--max-partition-size={max_part}"));
16858 if ten_bit {
16859 args.insert(1, "--input-bit-depth=10".to_string());
16860 args.insert(1, "--bit-depth=10".to_string());
16861 }
16862 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
16863 assert!(
16864 out.status.success(),
16865 "{name}: aomenc refused the fixture: {}",
16866 String::from_utf8_lossy(&out.stderr)
16867 );
16868 let stream = out.stdout;
16869 let before = hits();
16870 let frames = match decode_stream(&stream) {
16871 Ok(frames) => frames,
16872 Err(e) => {
16873 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
16874 let _ = std::fs::write(&pin, &stream);
16875 panic!(
16876 "{name}: decode_stream refused a real aomenc stream: {e} (pinned at {})",
16877 pin.display()
16878 );
16879 }
16880 };
16881 assert!(
16882 hits() > before,
16883 "{name}: no {what} fired -- this gate proves nothing"
16884 );
16885 let ffmpeg_frames = if ten_bit {
16886 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
16887 } else {
16888 ffmpeg_decode_sequence(&stream, width, height, frame_count)
16889 };
16890 assert_eq!(frames.len(), frame_count, "{name}: frame count");
16891 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16892 if got.y != want.y || got.u != want.u || got.v != want.v {
16893 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
16894 let _ = std::fs::write(&pin, &stream);
16895 panic!(
16896 "{name}: frame {i} mismatch vs ffmpeg -- stream pinned at {}",
16897 pin.display()
16898 );
16899 }
16900 }
16901 }
16902
16903 #[test]
16904 fn a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
16905 inter_sb_none_gate(
16906 "a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
16907 false,
16908 "32",
16909 "64",
16910 decode::inter_sb_none_hits,
16911 "whole-superblock inter PARTITION_NONE",
16912 &[],
16913 64,
16914 4,
16915 );
16916 }
16917
16918 #[test]
16919 fn a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
16920 inter_sb_none_gate(
16921 "a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
16922 true,
16923 "32",
16924 "64",
16925 decode::inter_sb_none_hits,
16926 "whole-superblock inter PARTITION_NONE",
16927 &[],
16928 64,
16929 4,
16930 );
16931 }
16932
16933 /// lane-inter8 r1: the same recipe with `--min-partition-size=8`, so
16934 /// aomenc's RD may split a 16x16 inter block into four 8x8 leaves. The
16935 /// interior (non-edge-straddling) `PARTITION_SPLIT` at the 16x16 level
16936 /// was refused by name until this round; the straddle path always ran the
16937 /// same loop, so only [`decode::inter_sub16_split_hits`] -- which counts
16938 /// interior splits only -- proves the newly-lifted alphabet value fired.
16939 // lane-inter8 r2: GREEN. The neighbour side bands are mi-granular, every
16940 // leaf stamps its own 2x2-mi span (including the compound-return path
16941 // that used to skip `record_mi` entirely) and the compound
16942 // group/index contexts read the LEAF's mi cell, not its 16x16's corner.
16943 /// lane-inter8 r3, from lane-sub8's verifier finding: the mi-granular
16944 /// inter neighbour bands added in r2 must reset per TILE (above) and per
16945 /// SB row (left) and guard availability tile-relative, so the same recipe
16946 /// runs again at 128x64 with two tile columns -- a leaf on the second
16947 /// tile's first column has no left neighbour and must not read the first
16948 /// tile's band.
16949 // 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
16950 // was done by inspection instead: every reader of the mi bands guards on
16951 // `tile_row0_mi`/`tile_col0_mi` (no `> 0` guard exists in decode.rs),
16952 // `start_tile` resets the above mi bands over the tile's own mi column
16953 // span and `start_row` resets every left mi band.
16954 #[test]
16955 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact()
16956 {
16957 inter_sb_none_gate(
16958 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact",
16959 false,
16960 "8",
16961 "16",
16962 decode::inter_sub16_split_hits,
16963 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
16964 &["--tile-columns=1"],
16965 128,
16966 4,
16967 );
16968 }
16969
16970 /// lane-interp3 r1: the same 8x8-leaf recipe with DUAL FILTER, OBMC and
16971 /// warped motion on. `read_mb_interp_filter` runs for every inter block
16972 /// (libaom `decodemv.c` 1575), compound ones included; the compound 8x8
16973 /// leaf skipped it entirely, so a SWITCHABLE-filter stream lost a symbol
16974 /// per compound leaf and stamped the `[3, 3]` "no filter" sentinel, which
16975 /// made a neighbouring OBMC block's `neighbour_filter` PANIC (a crash on
16976 /// his data, not a named refusal). The three hard asserts prove the flags
16977 /// arrived: a compound 8x8 leaf that really read the filter, a block whose
16978 /// two dual-filter directions DIFFER (impossible with dual filter off),
16979 /// and an 8x8 OBMC blend.
16980 // lane-interp3 r2: the ENTROPY desync r1 measured is CLOSED -- the full
16981 // 16-frame stream now parses end to end and every `EC_MODE`/`EC_MODE_VAL`
16982 // element's msac RANGE matches the instrumented aomdec's line for line
16983 // (570/570 mode elements, 0 diff). Two twin-drift root causes, both in
16984 // `decode_inter_block8`'s compound arm: `read_compound_ref_frames` was
16985 // passed a hard-coded `LAST_FRAME` for every inter neighbour instead of
16986 // the real per-mi band, and the grid stamp cleared both per-slot
16987 // `is_global_mv_block` flags.
16988 // lane-interp3 r3: the luma reconstruction residue r2 left open is CLOSED
16989 // and this gate is GREEN. Third instance of the same twin-drift class:
16990 // libaom applies `allow_warp`'s GLOBAL branch to every
16991 // `is_global_mv_block` reference slot, compound included and independent
16992 // of `motion_mode` (`av1_init_warp_params` inside
16993 // `build_inter_predictors_8x8_and_bigger`'s per-`ref` loop) -- the 16x16+
16994 // compound arm has warped since lane-cwarp r1, the 8x8 leaf's compound arm
16995 // predicted BOTH taps translationally, so a GLOBAL_GLOBALMV 8x8 compound
16996 // leaf under a non-TRANSLATION model drifted a few luma levels, growing
16997 // away from the block origin. It was NOT OBMC: the `EC_OBMC` emitter this
16998 // round added to `decode.rs` diffs 325/325 lines against the instrumented
16999 // aomdec's own rung (position, span, neighbour mv/ref/bsize/filter) with
17000 // zero differences.
17001 #[test]
17002 fn a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact() {
17003 const NAME: &str = "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact";
17004 if !have_ffmpeg() || !have_aomenc() {
17005 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
17006 return;
17007 }
17008 let before_dual = decode::dual_filter_diff_hits();
17009 let before_obmc = decode::obmc_hits_8();
17010 let before_cwarp8 = decode::compound_warp_hits_8();
17011 inter_sb_none_gate(
17012 NAME,
17013 false,
17014 "8",
17015 "16",
17016 decode::compound8_filter_hits,
17017 "a compound 8x8 leaf reading its own switchable interp_filter",
17018 &[
17019 "--enable-dual-filter=1",
17020 "--enable-obmc=1",
17021 "--enable-warped-motion=1",
17022 "--enable-onesided-comp=1",
17023 ],
17024 64,
17025 // Recipe search hook (same shape as EC_OBMC8_ATTEMPTS): a compound
17026 // block needs several coded references, so the sequence is longer
17027 // than the other arms' 4 frames.
17028 std::env::var("EC_INTERP3_FRAMES")
17029 .ok()
17030 .and_then(|v| v.parse().ok())
17031 .unwrap_or(16),
17032 );
17033 assert!(
17034 decode::dual_filter_diff_hits() > before_dual,
17035 "{NAME}: no block read two DIFFERENT dual-filter directions -- \
17036 --enable-dual-filter=1 did not arrive or aomenc declined it"
17037 );
17038 assert!(
17039 decode::obmc_hits_8() > before_obmc,
17040 "{NAME}: no 8x8 OBMC blend fired -- --enable-obmc=1 did not arrive"
17041 );
17042 assert!(
17043 decode::compound_warp_hits_8() > before_cwarp8,
17044 "{NAME}: no 8x8 COMPOUND leaf was predicted through the per-ref GLOBAL \
17045 warp -- the r3 root-cause path never fired, so this stream no longer \
17046 proves it"
17047 );
17048 }
17049
17050 #[test]
17051 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
17052 inter_sb_none_gate(
17053 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
17054 false,
17055 "8",
17056 "16",
17057 decode::inter_sub16_split_hits,
17058 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
17059 &[],
17060 64,
17061 4,
17062 );
17063 }
17064
17065 #[test]
17066 // 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.
17067 fn a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
17068 inter_sb_none_gate(
17069 "a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
17070 true,
17071 "8",
17072 "16",
17073 decode::inter_sub16_split_hits,
17074 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
17075 &[],
17076 64,
17077 4,
17078 );
17079 }
17080
17081 /// lane-eobc1 r1: an INTER sequence whose CHROMA coefficient blocks come
17082 /// off the class-1 (`TX_CLASS_HORIZ`/`VERT`) `eob_pt` row. Chroma codes
17083 /// no `tx_type` symbol of its own -- it inherits the colocated luma type
17084 /// (`av1_get_tx_type`, `blockd.h:1291`) -- so an 8x8 inter leaf whose
17085 /// luma picks `H_*`/`V_*` puts its 4x4 chroma on a CDF row this crate
17086 /// wired for only some sizes until this round (`eob_pt_class1: None` in
17087 /// 9 of 16 `TxbSet` arms, chroma 4x4/8x8 among them).
17088 ///
17089 /// The full tx set stays on (no `--reduced-tx-type-set=1`) and
17090 /// `--enable-flip-idtx=1` is asked for explicitly; the sinusoidal-stripe
17091 /// luma of the `tx_class1` key-frame gate is what actually resolves 1D
17092 /// types, and the temporally-moving chroma ramp keeps chroma out of
17093 /// `all_zero` so it has an `eob` to read at all. Attempts sweep cq and
17094 /// stripe period; a run counts only when
17095 /// [`decode::chroma_eob_class1_hits`] moved, and every shown frame is
17096 /// compared pixel-exact vs ffmpeg (a decode error is a FAILURE, never a
17097 /// SKIP -- class gate-skips-on-its-own-failure).
17098 fn chroma_class1_eob_gate(name: &str, ten_bit: bool) {
17099 if !have_ffmpeg() {
17100 eprintln!("SKIP {name}: no ffmpeg");
17101 return;
17102 }
17103 if !have_aomenc() {
17104 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
17105 return;
17106 }
17107 let (width, height, frame_count) = (64usize, 64usize, 4usize);
17108 let mut refusals = Vec::new();
17109 for attempt in 0..12u32 {
17110 let cq = 28 + (attempt % 4) * 10;
17111 let period = [4u32, 6, 8][(attempt as usize / 4) % 3];
17112 let y4m = Command::new("ffmpeg")
17113 .args([
17114 "-v",
17115 "error",
17116 "-f",
17117 "lavfi",
17118 "-i",
17119 &format!("testsrc2=size={width}x{height}:rate=25"),
17120 "-vf",
17121 &format!(
17122 "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"
17123 ),
17124 "-t",
17125 "0.16",
17126 "-pix_fmt",
17127 if ten_bit { "yuv420p10le" } else { "yuv420p" },
17128 "-strict",
17129 "-1",
17130 "-f",
17131 "yuv4mpegpipe",
17132 "-",
17133 ])
17134 .stdin(Stdio::null())
17135 .stdout(Stdio::piped())
17136 .stderr(Stdio::piped())
17137 .output()
17138 .expect("ffmpeg failed to run");
17139 assert!(
17140 y4m.status.success(),
17141 "{name}: ffmpeg fixture: {}",
17142 String::from_utf8_lossy(&y4m.stderr)
17143 );
17144 let mut args: Vec<String> = [
17145 "--codec=av1",
17146 "--passes=1",
17147 "--end-usage=q",
17148 "--cpu-used=0",
17149 "--lag-in-frames=0",
17150 "--auto-alt-ref=0",
17151 "--kf-max-dist=1000",
17152 "--error-resilient=1",
17153 "--enable-flip-idtx=1",
17154 "--reduced-tx-type-set=0",
17155 "--min-partition-size=8",
17156 "--max-partition-size=16",
17157 // Motion tools this decoder refuses by name, kept off so a
17158 // refusal here can only be about the coefficient path.
17159 "--enable-global-motion=0",
17160 "--enable-warped-motion=0",
17161 "--enable-obmc=0",
17162 "--enable-rect-partitions=0",
17163 "--enable-ab-partitions=0",
17164 "--enable-1to4-partitions=0",
17165 "--enable-filter-intra=0",
17166 "--enable-smooth-intra=0",
17167 "--enable-paeth-intra=0",
17168 "--enable-directional-intra=0",
17169 "--enable-angle-delta=0",
17170 "--enable-tx-size-search=0",
17171 "--enable-cdef=0",
17172 "--enable-restoration=0",
17173 "--loopfilter-control=0",
17174 "--enable-palette=0",
17175 "--enable-intrabc=0",
17176 "--enable-cfl-intra=0",
17177 "--enable-ref-frame-mvs=0",
17178 "--obu",
17179 "-o",
17180 "-",
17181 "-",
17182 ]
17183 .iter()
17184 .map(|s| (*s).to_string())
17185 .collect();
17186 args.insert(1, format!("--cq-level={cq}"));
17187 if ten_bit {
17188 args.insert(1, "--input-bit-depth=10".to_string());
17189 args.insert(1, "--bit-depth=10".to_string());
17190 }
17191 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
17192 assert!(
17193 out.status.success(),
17194 "{name}: aomenc refused the fixture: {}",
17195 String::from_utf8_lossy(&out.stderr)
17196 );
17197 let stream = out.stdout;
17198 let before = decode::chroma_eob_class1_hits();
17199 let frames = match decode_stream(&stream) {
17200 Ok(frames) => frames,
17201 // A named refusal ("unsupported: ...") is another lane's arm
17202 // and moves this attempt on; anything else is a real decode
17203 // failure and fails the gate on the spot.
17204 Err(e) if e.to_string().contains("unsupported") => {
17205 refusals.push(format!("cq={cq} period={period}: {e}"));
17206 continue;
17207 }
17208 Err(e) => {
17209 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
17210 let _ = std::fs::write(&pin, &stream);
17211 panic!(
17212 "{name}: decode_stream failed on a real aomenc stream (cq={cq} period={period}): {e} (pinned at {})",
17213 pin.display()
17214 );
17215 }
17216 };
17217 if decode::chroma_eob_class1_hits() == before {
17218 refusals.push(format!(
17219 "cq={cq} period={period}: decoded, but no chroma block read a class-1 eob_pt row"
17220 ));
17221 continue;
17222 }
17223 let ffmpeg_frames = if ten_bit {
17224 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
17225 } else {
17226 ffmpeg_decode_sequence(&stream, width, height, frame_count)
17227 };
17228 assert_eq!(frames.len(), frame_count, "{name}: frame count");
17229 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17230 if got.y != want.y || got.u != want.u || got.v != want.v {
17231 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
17232 let _ = std::fs::write(&pin, &stream);
17233 panic!(
17234 "{name}: frame {i} mismatch vs ffmpeg (cq={cq} period={period}) -- stream pinned at {}",
17235 pin.display()
17236 );
17237 }
17238 }
17239 return;
17240 }
17241 panic!("{name}: no attempt fired a class-1 chroma eob: {refusals:?}");
17242 }
17243
17244 #[test]
17245 fn a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
17246 chroma_class1_eob_gate(
17247 "a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
17248 false,
17249 );
17250 }
17251
17252 #[test]
17253 fn a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
17254 chroma_class1_eob_gate(
17255 "a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
17256 true,
17257 );
17258 }
17259
17260 /// lane-inter4 r1: the SUPERBLOCK-level inter `PARTITION_HORZ`/
17261 /// `PARTITION_VERT` pair -- two 64x32 / 32x64 inter strips, the arm the
17262 /// inter tile path refused outright before this lane ("an inter SB-level
17263 /// partition type other than NONE or SPLIT"). `--min-partition-size=32`
17264 /// keeps every 32x32-level rect shape (already coded, and residual-capable
17265 /// only when skip) out of the picture so the counters can only be earned
17266 /// at the superblock level; the noiseless split-motion source (one half
17267 /// translating, the other static, flat inside each half) is what makes
17268 /// aomenc's RD pick a superblock HORZ/VERT whose strips are `skip` --
17269 /// the ONLY inter rect shape this decoder can complete, since rectangular
17270 /// inter residual coding is not ported (see `reject_residual`).
17271 ///
17272 /// Every decoded frame is compared to ffmpeg (Y, U and V); an attempt
17273 /// that refuses by name is counted, never turned into a SKIP; and an
17274 /// attempt that decoded without firing the arm is counted separately and
17275 /// still required to be pixel-exact (class gate-skips-on-its-own-failure).
17276 #[test]
17277 fn a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact() {
17278 const NAME: &str = "a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact";
17279 let _gate_lock = lock_gate_counters();
17280 if !have_ffmpeg() {
17281 eprintln!("SKIP {NAME}: no ffmpeg");
17282 return;
17283 }
17284 if !have_aomenc() {
17285 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17286 return;
17287 }
17288 let (width, height, frame_count) = (192usize, 128usize, 6usize);
17289 // lane-inter4 r1: 8-bit ONLY, and the reason is the lane's own open
17290 // residue, not a tolerance: across all 16 attempts x both depths, every
17291 // 10-bit attempt that reached a superblock-level rect strip found it
17292 // NON-skip, so it stops at "a non-skip rectangular (HORZ/VERT/HORZ_B)
17293 // strip needs rectangular residual coding". The 10-bit twin below is
17294 // `#[ignore]`d with that exact reason rather than deleted or weakened.
17295 // lane-r14 r2 re-measured the 8-bit-only note above: the residual
17296 // refusal it names is GONE (this round codes a 64-px transform axis as
17297 // its truncated low-32 corner), and a 10-bit sweep of this exact
17298 // recipe now reaches the arm -- 2 pixel-exact attempts, 2 64x32 and 2
17299 // 32x64 strips, 2 of them carrying a coded 64-axis residual.
17300 // lane-sbrect10 r1 closed the newly exposed 10-bit defect r14 r2
17301 // parked this arm on (10-bit attempt 14, cq 61, horizontal split,
17302 // motion step 12 -- it mismatched ffmpeg while decoding ZERO rect
17303 // strips): a 64x64 INTRA block inside an inter frame read `uv_mode`
17304 // off the 14-symbol CFL-allowed alphabet, which libaom's
17305 // `is_cfl_allowed` caps at 32x32 -- same DC_PRED value, wrong
17306 // interval narrowing, tile desynced from that block on. Both depths
17307 // run now.
17308 for bit_depth in [8u32, 10u32] {
17309 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
17310 (0u32, 0u32, 0u32, 0u32);
17311 let (mut horz_proved, mut vert_proved) = (0usize, 0usize);
17312 let mut rect64_tus = 0usize;
17313 for attempt in 0..16u32 {
17314 // Two orientations (the transposed pair a one-sided gate could
17315 // never separate) x four quantisers x two motion steps: which
17316 // superblock the RD hands a skip-able rect strip moves with
17317 // the quantiser, and the 10-bit arm needs a different corner
17318 // of the grid from the 8-bit one.
17319 let vertical_split = attempt % 2 == 1;
17320 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
17321 let sp = 8 + (attempt / 8) * 4;
17322 let geq = if vertical_split {
17323 format!("if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), 200)")
17324 } else {
17325 format!("if(lt(X,64), 40+mod(floor((Y+N*{sp})/32)*90,200), 200)")
17326 };
17327 let duration = frame_count as f64 / 25.0;
17328 let source = format!(
17329 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
17330 geq=lum='{geq}',format=yuv420p"
17331 );
17332 let pix_fmt = if bit_depth == 10 {
17333 "yuv420p10le"
17334 } else {
17335 "yuv420p"
17336 };
17337 let y4m = Command::new("ffmpeg")
17338 .args([
17339 "-v",
17340 "error",
17341 "-f",
17342 "lavfi",
17343 "-i",
17344 &source,
17345 "-t",
17346 &duration.to_string(),
17347 "-pix_fmt",
17348 pix_fmt,
17349 "-strict",
17350 "-1",
17351 "-f",
17352 "yuv4mpegpipe",
17353 "-",
17354 ])
17355 .stdin(Stdio::null())
17356 .stdout(Stdio::piped())
17357 .stderr(Stdio::piped())
17358 .output()
17359 .expect("ffmpeg failed to run");
17360 assert!(
17361 y4m.status.success(),
17362 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
17363 String::from_utf8_lossy(&y4m.stderr)
17364 );
17365 let cq_arg = format!("--cq-level={cq}");
17366 let depth_arg = format!("--bit-depth={bit_depth}");
17367 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
17368 let args: Vec<&str> = vec![
17369 "--codec=av1",
17370 "--passes=1",
17371 "--end-usage=q",
17372 &cq_arg,
17373 "--cpu-used=0",
17374 "--threads=1",
17375 "--row-mt=0",
17376 "--sb-size=64",
17377 &depth_arg,
17378 &input_depth_arg,
17379 "--enable-restoration=0",
17380 "--enable-palette=0",
17381 "--deltaq-mode=0",
17382 "--enable-filter-intra=0",
17383 "--enable-cfl-intra=0",
17384 "--enable-intrabc=0",
17385 "--enable-tx-size-search=0",
17386 "--lag-in-frames=0",
17387 // Per-arm overrides go LAST: aomenc keeps the last
17388 // occurrence of a repeated --enable-* flag.
17389 "--enable-rect-partitions=1",
17390 "--enable-ab-partitions=0",
17391 "--enable-1to4-partitions=1",
17392 "--min-partition-size=32",
17393 "--max-partition-size=64",
17394 "--obu",
17395 "-o",
17396 "-",
17397 "-",
17398 ];
17399 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
17400 assert!(
17401 out.status.success(),
17402 "aomenc refused the fixture: {}",
17403 String::from_utf8_lossy(&out.stderr)
17404 );
17405 let stream = out.stdout;
17406 let before = crate::stream::inter_rect_counters();
17407 let rect64_before = crate::stream::rect64_inter_tu_hits();
17408 let frames = match decode_stream(&stream) {
17409 Err(e) => {
17410 let msg = e.to_string();
17411 assert!(
17412 msg.contains("unsupported"),
17413 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
17414 attempt {attempt}): {msg}"
17415 );
17416 named_refusals += 1;
17417 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
17418 continue;
17419 }
17420 Ok(frames) => frames,
17421 };
17422 let after = crate::stream::inter_rect_counters();
17423 let (horz, vert) = (after.2 - before.2, after.3 - before.3);
17424 let rect64 = crate::stream::rect64_inter_tu_hits() - rect64_before;
17425 let ffmpeg_frames = if bit_depth == 10 {
17426 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
17427 } else {
17428 ffmpeg_decode_sequence(&stream, width, height, frame_count)
17429 };
17430 assert_eq!(frames.len(), frame_count);
17431 let mismatched = frames
17432 .iter()
17433 .zip(&ffmpeg_frames)
17434 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17435 if horz + vert == 0 {
17436 out_of_scope += 1;
17437 if mismatched {
17438 oos_mismatch += 1;
17439 eprintln!(
17440 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
17441 superblock-level inter rect strips -- another shape's defect"
17442 );
17443 }
17444 continue;
17445 }
17446 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17447 assert_eq!(
17448 got.y, want.y,
17449 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
17450 );
17451 assert_eq!(
17452 got.u, want.u,
17453 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
17454 );
17455 assert_eq!(
17456 got.v, want.v,
17457 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
17458 );
17459 }
17460 horz_proved += horz;
17461 vert_proved += vert;
17462 rect64_tus += rect64;
17463 matched += 1;
17464 }
17465 eprintln!(
17466 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
17467 attempts carrying the arm, 64x32 strips={horz_proved}, 32x64 strips={vert_proved}, \
17468 64-axis residual TUs={rect64_tus}, \
17469 {out_of_scope} attempts carried none ({oos_mismatch} of them mismatched)"
17470 );
17471 assert_eq!(
17472 oos_mismatch, 0,
17473 "{NAME}: {oos_mismatch} attempt(s) with no superblock-level inter rect strip \
17474 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
17475 );
17476 // lane-r14 r2: the residual half of the arm -- a strip that is not
17477 // `skip` and codes a real 64-axis transform unit. Without this the
17478 // gate proves only the partition symbol.
17479 assert!(
17480 rect64_tus > 0,
17481 "{NAME} ({bit_depth}-bit): no superblock-level rect strip carried a coded \
17482 64-axis residual transform unit inside a pixel-exact attempt \
17483 (horz={horz_proved}, vert={vert_proved}) -- the residual arm proved nothing"
17484 );
17485 assert!(
17486 horz_proved + vert_proved > 0,
17487 "{NAME} ({bit_depth}-bit): the superblock-level inter rect arm never fired \
17488 inside a pixel-exact attempt (horz={horz_proved}, vert={vert_proved}, \
17489 {named_refusals} refusals, {out_of_scope} out of scope) -- gate proved nothing"
17490 );
17491 }
17492 }
17493
17494 /// lane-r14 r3: a 1:4 inter strip with a 64-px axis (64x16 / 16x64) whose
17495 /// transform SPLITS -- the arm r2 left refused by name ("a split transform
17496 /// on a 1:4 inter strip with a 64-px axis"). libaom's
17497 /// `sub_tx_size_map[TX_64X16] == TX_32X16` (and `[TX_16X64] == TX_16X32`)
17498 /// keeps the sub-transform RECTANGULAR, so the var-tx tree's leaves are
17499 /// 32x16/16x32 units read through [`TxbSet::LumaRect32x16Inter`], each with
17500 /// its own `get_txb_ctx_general` neighbour context (the unit is smaller
17501 /// than its block, so `txb_skip_ctx` is NOT the lone-TU 0).
17502 ///
17503 /// `--enable-1to4-partitions=1 --min-partition-size=16
17504 /// --max-partition-size=64 --enable-tx64=1` (each spelled once, last
17505 /// occurrence wins) is what lets aomenc pick a superblock-level HORZ_4 /
17506 /// VERT_4; the textured translating source is what keeps the strips
17507 /// non-skip so the residual is actually coded. 8-bit AND 10-bit, every
17508 /// decoded frame compared to ffmpeg on Y/U/V, refusals counted (never
17509 /// SKIPped), attempts that carried no rectangular var-tx leaf counted
17510 /// separately and still required pixel-exact.
17511 #[test]
17512 fn real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal()
17513 {
17514 const NAME: &str = "real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal";
17515 let _gate_lock = lock_gate_counters();
17516 if !have_ffmpeg() {
17517 eprintln!("SKIP {NAME}: no ffmpeg");
17518 return;
17519 }
17520 if !have_aomenc() {
17521 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17522 return;
17523 }
17524 let frame_count = 6usize;
17525 for bit_depth in [8u32, 10u32] {
17526 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
17527 (0u32, 0u32, 0u32, 0u32);
17528 let (mut leaf_32x16, mut leaf_16x32) = (0usize, 0usize);
17529 // Leaves decoded on ANY attempt, including one whose stream hits a
17530 // later named refusal: the firing half of this gate, kept apart
17531 // from `leaf_32x16`/`leaf_16x32` (pixel-compared attempts only) so
17532 // a refused stream is never counted as a pixel proof
17533 // (class counter-from-refused-stream).
17534 let (mut fired_32x16, mut fired_16x32) = (0usize, 0usize);
17535 // lane-gaterecipe r1: the firing arms (16-17) are 8-BIT ONLY, and
17536 // this is measured, not a convenience. Their 10-bit twin fires the
17537 // leaves too (32x16=0 16x32=46 on attempt 16) and then MISMATCHES
17538 // ffmpeg at decode-order frame 2 of attempt 17 -- an open DECODE
17539 // defect handed off in lanes/gaterecipe-r1.report.md, never
17540 // silenced inside this loop.
17541 let attempts = if bit_depth == 8 { 18u32 } else { 16u32 };
17542 for attempt in 0..attempts {
17543 // Two orientations (the transposed pair a one-sided gate could
17544 // never separate) x four quantisers x two motion steps.
17545 // lane-r14 r4 recipe hunt (~70 aomenc runs on the merged
17546 // tree: testsrc2 / life / mandelbrot / banded motion, 64x64 up
17547 // to 384x256, cq 20..58): attempts 16-17 carry the only recipe
17548 // found that makes aomenc code a 64-axis 1:4 strip whose
17549 // transform SPLITS -- 384x256, per-16-column band motion,
17550 // cq 32 (16x32 leaves) and cq 38 (32x16 leaves).
17551 let firing = attempt >= 16;
17552 let (width, height) = if firing {
17553 (384usize, 256usize)
17554 } else {
17555 (192usize, 128usize)
17556 };
17557 let vertical = attempt % 2 == 1;
17558 // lane-vartxsplit r2, MEASURED against the oracle
17559 // (`EC_VARTX` histogram, ~40 aomenc runs): at cq 10 this
17560 // source splits NO rectangular transform at all -- aomdec
17561 // reads only TX_8X8/TX_16X16/TX_8X16/TX_16X8 split symbols,
17562 // so the leaves gaterecipe r1 counted here came out of a
17563 // stream our decoder was already desynced on (class
17564 // counter-from-refused-stream). cq 44 and 46 are the two
17565 // quantisers of that sweep whose stream really carries
17566 // `TX_32X8`/`TX_8X32` splits (16x8 and 8x16 rectangular
17567 // var-tx leaves) AND decodes pixel-exact on all six frames.
17568 let cq = if firing {
17569 if attempt == 16 { 44 } else { 46 }
17570 } else {
17571 [30, 36, 44, 52][(attempt / 2 % 4) as usize]
17572 };
17573 let sp = 3 + (attempt / 8) * 3;
17574 // 16-pixel bands, each band translating at its OWN speed
17575 // across the other axis: that is what makes aomenc's RD split
17576 // a 64x64 superblock into four 1:4 strips (`PARTITION_HORZ_4`
17577 // / `VERT_4`) with distinct motion vectors, and the texture
17578 // inside a band is what keeps the strip non-skip and its
17579 // transform split.
17580 let geq = if firing && !vertical {
17581 // lane-gaterecipe r1, MEASURED: the banded translating
17582 // source this arm used until now splits NO transform at
17583 // all -- an aomdec EC_TRACE/EC_TRACE_COEFF histogram of its
17584 // stream reads zero 1:4 partitions and zero rectangular
17585 // sub-transforms, so the leaves the old assert counted came
17586 // out of a stream that stopped at a refusal (class
17587 // counter-from-refused-stream). What DOES split a
17588 // rectangular transform is a high-frequency product texture
17589 // at a fine quantiser with `--min-partition-size=8`: part
17590 // of the block predicts well and part does not, which is
17591 // the RD case for `txfm_partition`.
17592 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
17593 } else if firing {
17594 // lane-vartxsplit r2: BOTH leaf orientations come out of
17595 // this one source (three 16x8 leaves and one 8x16 on
17596 // attempt 16), so the firing pair is the same texture at
17597 // two quantisers. Its transposed twin was measured over
17598 // cq 40..56 and splits no rectangular transform at all;
17599 // at cq 56 it also mismatches ffmpeg from decode-order
17600 // frame 2 with ZERO rect var-tx leaves in it -- an open
17601 // reconstruction defect (8-pixel-wide luma column, see
17602 // lanes/vartxsplit-r2.report.md), not something to hide
17603 // inside this gate's attempt list.
17604 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
17605 } else if vertical {
17606 format!("128+60*sin((Y+N*({sp}+9*mod(floor(X/16),2)))/7)+25*sin(X/11)")
17607 } else {
17608 format!("128+60*sin((X+N*({sp}+9*mod(floor(Y/16),2)))/7)+25*sin(Y/11)")
17609 };
17610 let duration = frame_count as f64 / 25.0;
17611 let source = format!(
17612 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
17613 geq=lum='{geq}',format=yuv420p"
17614 );
17615 let pix_fmt = if bit_depth == 10 {
17616 "yuv420p10le"
17617 } else {
17618 "yuv420p"
17619 };
17620 let y4m = Command::new("ffmpeg")
17621 .args([
17622 "-v",
17623 "error",
17624 "-f",
17625 "lavfi",
17626 "-i",
17627 &source,
17628 "-t",
17629 &duration.to_string(),
17630 "-pix_fmt",
17631 pix_fmt,
17632 "-strict",
17633 "-1",
17634 "-f",
17635 "yuv4mpegpipe",
17636 "-",
17637 ])
17638 .stdin(Stdio::null())
17639 .stdout(Stdio::piped())
17640 .stderr(Stdio::piped())
17641 .output()
17642 .expect("ffmpeg failed to run");
17643 assert!(
17644 y4m.status.success(),
17645 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
17646 String::from_utf8_lossy(&y4m.stderr)
17647 );
17648 let cq_arg = format!("--cq-level={cq}");
17649 let depth_arg = format!("--bit-depth={bit_depth}");
17650 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
17651 // A rectangular var-tx LEAF needs a block whose max rectangular
17652 // transform can split: `--min-partition-size=8` is what lets
17653 // aomenc's RD reach one (measured); at 16 it never did.
17654 let min_part = if firing {
17655 "--min-partition-size=8"
17656 } else {
17657 "--min-partition-size=16"
17658 };
17659 let args: Vec<&str> = vec![
17660 "--codec=av1",
17661 "--passes=1",
17662 "--end-usage=q",
17663 &cq_arg,
17664 "--cpu-used=0",
17665 "--threads=1",
17666 "--row-mt=0",
17667 "--sb-size=64",
17668 &depth_arg,
17669 &input_depth_arg,
17670 "--enable-restoration=0",
17671 "--enable-palette=0",
17672 "--deltaq-mode=0",
17673 "--enable-filter-intra=0",
17674 "--enable-cfl-intra=0",
17675 "--enable-intrabc=0",
17676 "--lag-in-frames=0",
17677 // Per-arm overrides go LAST: aomenc keeps the last
17678 // occurrence of a repeated --enable-* flag.
17679 "--enable-tx64=1",
17680 "--enable-rect-partitions=1",
17681 "--enable-ab-partitions=0",
17682 "--enable-1to4-partitions=1",
17683 "--enable-dual-filter=0",
17684 "--enable-obmc=0",
17685 "--enable-tx-size-search=1",
17686 min_part,
17687 "--max-partition-size=64",
17688 "--obu",
17689 "-o",
17690 "-",
17691 "-",
17692 ];
17693 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
17694 assert!(
17695 out.status.success(),
17696 "aomenc refused the fixture: {}",
17697 String::from_utf8_lossy(&out.stderr)
17698 );
17699 let stream = out.stdout;
17700 let before = crate::stream::vartx_rect_leaf_hits();
17701 let frames = match decode_stream(&stream) {
17702 Err(e) => {
17703 let msg = e.to_string();
17704 assert!(
17705 msg.contains("unsupported"),
17706 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
17707 attempt {attempt}): {msg}"
17708 );
17709 let after = crate::stream::vartx_rect_leaf_hits();
17710 fired_32x16 += after[0] - before[0];
17711 fired_16x32 += after[1] - before[1];
17712 named_refusals += 1;
17713 eprintln!(
17714 "{bit_depth}-bit attempt {attempt} refusal (rect var-tx leaves \
17715 decoded before it: 32x16={}, 16x32={}): {msg}",
17716 after[0] - before[0],
17717 after[1] - before[1]
17718 );
17719 continue;
17720 }
17721 Ok(frames) => frames,
17722 };
17723 let after = crate::stream::vartx_rect_leaf_hits();
17724 let (h32, v32) = (after[0] - before[0], after[1] - before[1]);
17725 fired_32x16 += h32;
17726 fired_16x32 += v32;
17727 let ffmpeg_frames = if bit_depth == 10 {
17728 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
17729 } else {
17730 ffmpeg_decode_sequence(&stream, width, height, frame_count)
17731 };
17732 assert_eq!(frames.len(), frame_count);
17733 let mismatched = frames
17734 .iter()
17735 .zip(&ffmpeg_frames)
17736 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
17737 if h32 + v32 == 0 {
17738 // Counted per ATTEMPT, on a decoded+compared attempt only
17739 // (class counter-from-refused-stream).
17740 out_of_scope += 1;
17741 if mismatched {
17742 oos_mismatch += 1;
17743 eprintln!(
17744 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
17745 rectangular var-tx leaves -- another shape's defect"
17746 );
17747 }
17748 continue;
17749 }
17750 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
17751 assert_eq!(
17752 got.y, want.y,
17753 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
17754 );
17755 assert_eq!(
17756 got.u, want.u,
17757 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
17758 );
17759 assert_eq!(
17760 got.v, want.v,
17761 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
17762 );
17763 }
17764 leaf_32x16 += h32;
17765 leaf_16x32 += v32;
17766 compared += 1;
17767 }
17768 eprintln!(
17769 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
17770 pixel-exact attempts carrying the arm, pixel-compared rect var-tx leaves \
17771 32x16={leaf_32x16} 16x32={leaf_16x32}, leaves decoded anywhere in the sweep \
17772 32x16={fired_32x16} 16x32={fired_16x32}, {out_of_scope} attempts carried none \
17773 ({oos_mismatch} of them mismatched)"
17774 );
17775 assert_eq!(
17776 oos_mismatch, 0,
17777 "{NAME}: {oos_mismatch} attempt(s) with no rectangular var-tx leaf decoded \
17778 but mismatched ffmpeg -- a defect of another shape, not a pass"
17779 );
17780 assert!(
17781 compared + out_of_scope > 0,
17782 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
17783 );
17784 // The firing half. lane-vartxsplit r2 re-measured it against
17785 // the oracle: attempts 16/17 (384x256 product texture, cq 44/46,
17786 // `--min-partition-size=8 --enable-tx-size-search=1`) are the only
17787 // recipes of a ~40-run sweep whose stream carries `TX_32X8` /
17788 // `TX_8X32` split symbols, i.e. RECTANGULAR var-tx leaves (16x8
17789 // and 8x16, both orientations out of the same stream). They now
17790 // decode PIXEL-EXACT on all six frames, so the assert is on the
17791 // pixel-compared tally, not on the "decoded anywhere" one --
17792 // `fired_*` stays only to separate a refused stream's leaves from
17793 // a proved one (class counter-from-refused-stream). At 10 bits
17794 // the same sweep either fires nothing or mismatches on a
17795 // reconstruction defect of another shape (report), so the firing
17796 // assert stays 8-bit -- and it is a hard assert, never a print.
17797 if bit_depth == 8 {
17798 assert!(
17799 leaf_32x16 > 0 && leaf_16x32 > 0,
17800 "{NAME}: the rectangular var-tx leaf arm never fired on a pixel-exact \
17801 attempt (pixel-compared 32x16={leaf_32x16}, 16x32={leaf_16x32}, decoded \
17802 anywhere 32x16={fired_32x16} 16x32={fired_16x32}, {named_refusals} \
17803 refusals, {compared} compared) -- the rectangular sub-transform path is \
17804 unproved by this gate"
17805 );
17806 }
17807 }
17808 }
17809
17810 /// lane-rectres r1: a 32x32-level 1:4 INTER strip (32x8 / 8x32) that codes
17811 /// a REAL rectangular residual. THIS is the shape both 10-bit 3840x1608
17812 /// film cuts and every measured 1080p offset stopped on -- six of six
17813 /// `decode_probe` runs refused at "a non-skip rectangular (HORZ/VERT/
17814 /// HORZ_B) strip needs rectangular residual coding" with `w=32 h=8` or
17815 /// `w=8 h=32`, nothing else.
17816 ///
17817 /// `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256 of its
17818 /// positions ([`TxbSet::LumaRect32x8Inter`]: `get_txsize_entropy_ctx` =
17819 /// TX_16X16 so the coefficient tables are the luma-16 ones,
17820 /// `txsize_log2_minus4` = 4 so `eob_pt` is the 256-position alphabet), and
17821 /// unlike the INTRA twin it DOES code a `tx_type`:
17822 /// `av1_get_ext_tx_set_type` at `tx_size_sqr_up == TX_32X32` is
17823 /// `EXT_TX_SET_DCT_IDTX` for inter with or without `reduced_tx_set`, read
17824 /// at the `txsize_sqr_map[TX_32X8] == TX_8X8` CDF row (class
17825 /// table-indexed-by-raw-size: the coefficient tables follow the ADJUSTED
17826 /// size, the `tx_type` row the SQUARE one -- they disagree here).
17827 /// Its chroma pair is one 16x4 / 4x16 unit (`ss_size_lookup[BLOCK_32X8]`
17828 /// = BLOCK_16X4, `Chroma8`'s tables, 64-position `eob_pt`), and a split
17829 /// transform gives 16x8 / 8x16 leaves (`sub_tx_size_map[TX_32X8] ==
17830 /// TX_16X8`) the rect var-tx path already reads.
17831 ///
17832 /// `--enable-1to4-partitions=1 --min-partition-size=8
17833 /// --max-partition-size=32 --enable-tx-size-search=1` (each spelled once,
17834 /// last occurrence wins -- aomenc keeps the LAST `--enable-*`) is what
17835 /// lets aomenc pick a 32x32-level HORZ_4 / VERT_4; the 8-pixel banded
17836 /// translating source is what makes those strips the RD winner and keeps
17837 /// them non-skip so the residual is really coded. Both orientations, 8-bit
17838 /// AND 10-bit, every decode-order frame compared to ffmpeg on Y/U/V,
17839 /// refusals counted (never SKIPped), attempts that carried no 32x8/8x32
17840 /// residual unit counted separately and still required pixel-exact.
17841 #[test]
17842 fn a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual() {
17843 const NAME: &str =
17844 "a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual";
17845 let _gate_lock = lock_gate_counters();
17846 if !have_ffmpeg() {
17847 eprintln!("SKIP {NAME}: no ffmpeg");
17848 return;
17849 }
17850 if !have_aomenc() {
17851 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17852 return;
17853 }
17854 let frame_count = 6usize;
17855 let (mut proved_32x8, mut proved_8x32) = (0usize, 0usize);
17856 let (mut fired_32x8, mut fired_8x32) = (0usize, 0usize);
17857 for bit_depth in [8u32, 10u32] {
17858 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
17859 (0u32, 0u32, 0u32, 0u32);
17860 for attempt in 0..16u32 {
17861 // Two orientations (the transposed pair a one-sided gate could
17862 // never separate) x four quantisers x two motion steps.
17863 let vertical = attempt % 2 == 1;
17864 let (width, height) = (192usize, 128usize);
17865 let cq = [48, 52, 56, 60][(attempt / 2 % 4) as usize];
17866 let sp = 3 + (attempt / 8) * 4;
17867 // 32-pixel bands, each translating at its OWN speed across the
17868 // other axis: that is what makes aomenc's RD split a 32x32
17869 // block into four 32x8 (or 8x32) strips with distinct motion
17870 // vectors, and the texture inside a band is what keeps a strip
17871 // non-skip. MEASURED (72-run recipe sweep, 192x128..256x192,
17872 // cq 24..60, bands 8/16/32/64): only 32-pixel bands at cq >= 48
17873 // make aomenc code a NON-SKIP one -- attempt 0 (cq 48,
17874 // horizontal source) codes an 8x32 residual unit, attempt 7
17875 // (cq 60, the transposed source) five 32x8 ones. Narrower
17876 // bands give the same strips with `skip` set, which proves the
17877 // partition symbol and nothing about the residual.
17878 let geq = if vertical {
17879 format!("128+62*sin((Y+N*({sp}+7*mod(floor(X/32),4)))/6)+28*sin(X/9)")
17880 } else {
17881 format!("128+62*sin((X+N*({sp}+7*mod(floor(Y/32),4)))/6)+28*sin(Y/9)")
17882 };
17883 let duration = frame_count as f64 / 25.0;
17884 let source = format!(
17885 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
17886 geq=lum='{geq}',format=yuv420p"
17887 );
17888 let pix_fmt = if bit_depth == 10 {
17889 "yuv420p10le"
17890 } else {
17891 "yuv420p"
17892 };
17893 let y4m = Command::new("ffmpeg")
17894 .args([
17895 "-v",
17896 "error",
17897 "-f",
17898 "lavfi",
17899 "-i",
17900 &source,
17901 "-t",
17902 &duration.to_string(),
17903 "-pix_fmt",
17904 pix_fmt,
17905 "-strict",
17906 "-1",
17907 "-f",
17908 "yuv4mpegpipe",
17909 "-",
17910 ])
17911 .stdin(Stdio::null())
17912 .stdout(Stdio::piped())
17913 .stderr(Stdio::piped())
17914 .output()
17915 .expect("ffmpeg failed to run");
17916 assert!(
17917 y4m.status.success(),
17918 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
17919 String::from_utf8_lossy(&y4m.stderr)
17920 );
17921 let cq_arg = format!("--cq-level={cq}");
17922 let depth_arg = format!("--bit-depth={bit_depth}");
17923 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
17924 let args: Vec<&str> = vec![
17925 "--codec=av1",
17926 "--passes=1",
17927 "--end-usage=q",
17928 &cq_arg,
17929 "--cpu-used=0",
17930 "--threads=1",
17931 "--row-mt=0",
17932 "--sb-size=64",
17933 &depth_arg,
17934 &input_depth_arg,
17935 "--enable-restoration=0",
17936 "--enable-palette=0",
17937 "--deltaq-mode=0",
17938 "--enable-filter-intra=0",
17939 "--enable-cfl-intra=0",
17940 "--enable-intrabc=0",
17941 "--lag-in-frames=0",
17942 // Per-arm overrides go LAST: aomenc keeps the last
17943 // occurrence of a repeated --enable-* flag.
17944 "--enable-tx64=0",
17945 "--enable-rect-partitions=1",
17946 "--enable-ab-partitions=0",
17947 "--enable-1to4-partitions=1",
17948 "--enable-tx-size-search=1",
17949 "--enable-dual-filter=0",
17950 "--enable-obmc=0",
17951 // aomenc's min-partition-size bounds the SMALLER side of a
17952 // 1:4 strip, so 32x8 needs 8 (memory
17953 // aomenc-min-partition-bounds-smaller-side).
17954 "--min-partition-size=8",
17955 "--max-partition-size=32",
17956 "--obu",
17957 "-o",
17958 "-",
17959 "-",
17960 ];
17961 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
17962 assert!(
17963 out.status.success(),
17964 "aomenc refused the fixture: {}",
17965 String::from_utf8_lossy(&out.stderr)
17966 );
17967 let stream = out.stdout;
17968 let before = crate::stream::rect32x8_inter_tu_hits();
17969 let frames = match decode_stream(&stream) {
17970 Err(e) => {
17971 let msg = e.to_string();
17972 assert!(
17973 msg.contains("unsupported"),
17974 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
17975 attempt {attempt}): {msg}"
17976 );
17977 let after = crate::stream::rect32x8_inter_tu_hits();
17978 // Firing counted on a refused stream is kept apart from
17979 // the pixel-proved tally (class
17980 // counter-from-refused-stream).
17981 fired_32x8 += after[0] - before[0];
17982 fired_8x32 += after[1] - before[1];
17983 named_refusals += 1;
17984 eprintln!(
17985 "{NAME} {bit_depth}-bit attempt {attempt} refusal (32x8 residual \
17986 units decoded before it: {}, 8x32: {}): {msg}",
17987 after[0] - before[0],
17988 after[1] - before[1]
17989 );
17990 continue;
17991 }
17992 Ok(frames) => frames,
17993 };
17994 let after = crate::stream::rect32x8_inter_tu_hits();
17995 let (h, v) = (after[0] - before[0], after[1] - before[1]);
17996 fired_32x8 += h;
17997 fired_8x32 += v;
17998 let ffmpeg_frames = if bit_depth == 10 {
17999 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
18000 } else {
18001 ffmpeg_decode_sequence(&stream, width, height, frame_count)
18002 };
18003 assert_eq!(frames.len(), frame_count);
18004 let mismatched = frames
18005 .iter()
18006 .zip(&ffmpeg_frames)
18007 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
18008 if h + v == 0 {
18009 out_of_scope += 1;
18010 if mismatched {
18011 oos_mismatch += 1;
18012 eprintln!(
18013 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
18014 32x8/8x32 inter residual units -- another shape's defect"
18015 );
18016 }
18017 continue;
18018 }
18019 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18020 assert_eq!(
18021 got.y, want.y,
18022 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
18023 );
18024 assert_eq!(
18025 got.u, want.u,
18026 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
18027 );
18028 assert_eq!(
18029 got.v, want.v,
18030 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
18031 );
18032 }
18033 proved_32x8 += h;
18034 proved_8x32 += v;
18035 compared += 1;
18036 }
18037 eprintln!(
18038 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
18039 pixel-exact attempts carrying the arm, {out_of_scope} attempts carried none \
18040 ({oos_mismatch} of them mismatched)"
18041 );
18042 assert_eq!(
18043 oos_mismatch, 0,
18044 "{NAME}: {oos_mismatch} attempt(s) with no 32x8/8x32 inter residual unit \
18045 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
18046 );
18047 assert!(
18048 compared + out_of_scope > 0,
18049 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
18050 );
18051 }
18052 eprintln!(
18053 "{NAME}: pixel-compared 32x32-level 1:4 inter residual units 32x8={proved_32x8} \
18054 8x32={proved_8x32} (decoded anywhere in the sweep 32x8={fired_32x8} \
18055 8x32={fired_8x32})"
18056 );
18057 // The firing half, one assert per lifted shape. Both orientations must
18058 // be PIXEL-PROVED: a transposed table passes one and fails the other
18059 // (class reference-layout-not-spec).
18060 assert!(
18061 proved_32x8 > 0,
18062 "{NAME}: no 32x8 inter residual transform unit was decoded inside a pixel-exact \
18063 attempt (decoded anywhere: {fired_32x8}) -- the lift is unproved"
18064 );
18065 assert!(
18066 proved_8x32 > 0,
18067 "{NAME}: no 8x32 inter residual transform unit was decoded inside a pixel-exact \
18068 attempt (decoded anywhere: {fired_8x32}) -- the lift is unproved"
18069 );
18070 }
18071
18072 /// lane-sbrect10 r1: a 64x64 INTRA block inside an INTER frame, whose
18073 /// `uv_mode` alphabet libaom's `is_cfl_allowed` (`blockd.h`: `wide <= 32
18074 /// && high <= 32`) narrows to the 13-symbol NO-CFL table. Reading the
18075 /// 14-symbol CFL one produced the same `DC_PRED` value with the wrong
18076 /// interval narrowing, so the tile desynced from that block on and the
18077 /// frame decoded silently wrong (class `wrong-alphabet-same-value`; found
18078 /// as the "another shape" mismatch the superblock rect gate above had to
18079 /// park its 10-bit arm on).
18080 ///
18081 /// The counter `nocfl_uv_mode_hits` proves the shape fired in EVERY
18082 /// compared attempt, and every decode-order frame is compared against
18083 /// ffmpeg -- an attempt that mismatches fails, it never SKIPs.
18084 ///
18085 /// lane-sbrect10 r2: with the half-random source below this gate also
18086 /// covers a SECOND defect it exposed at 10-bit cq 58/61 -- the compound
18087 /// MV stack's extension pass zero-filled the `comp_list` tail slots
18088 /// libaom fills with each side's GLOBAL MOTION vector
18089 /// (`combine_compound_candidates`, mvref_common.c:723-729). A compound
18090 /// block with no usable neighbour pair (frame top row, intra block to
18091 /// its left, empty temporal field) then took a `(0, 0)` predictor
18092 /// instead of the frame's translation: 32890/39907 wrong luma samples
18093 /// on decode-order frame 2 with the entropy stream still in sync.
18094 #[test]
18095 fn a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet() {
18096 const NAME: &str =
18097 "a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet";
18098 let _gate_lock = lock_gate_counters();
18099 if !have_ffmpeg() {
18100 eprintln!("SKIP {NAME}: no ffmpeg");
18101 return;
18102 }
18103 if !have_aomenc() {
18104 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18105 return;
18106 }
18107 let (width, height, frame_count) = (192usize, 128usize, 6usize);
18108 for bit_depth in [8u32, 10u32] {
18109 let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
18110 let mut total_hits = 0usize;
18111 for attempt in 0..16u32 {
18112 // The sibling superblock-rect gate's own grid (its 10-bit
18113 // attempt 14 -- cq 61, horizontal split, motion step 12 -- is
18114 // the stream that exposed the defect); which superblock the RD
18115 // hands an intra 64x64 block moves with the quantiser and the
18116 // depth, so both orientations x four quantisers x two motion
18117 // steps run here too.
18118 let vertical_split = attempt % 2 == 1;
18119 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
18120 let sp = 8 + (attempt / 8) * 4;
18121 // Half ramp, half deterministic pseudo-noise: the flat "200"
18122 // half of r1's source made aomenc code the right-hand
18123 // superblocks skip, so at 8 bit no >32 intra block ever
18124 // appeared (probed cq 45/52/58/61/63 = 0 hits). The textured
18125 // half forces intra above 32x32 in an inter frame at BOTH
18126 // depths, so both arms carry the shape.
18127 let geq = if vertical_split {
18128 format!(
18129 "if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
18130 )
18131 } else {
18132 format!(
18133 "if(lt(X,128), 40+mod(floor((Y+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
18134 )
18135 };
18136 let duration = frame_count as f64 / 25.0;
18137 let source = format!(
18138 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
18139 geq=lum='{geq}',format=yuv420p"
18140 );
18141 let pix_fmt = if bit_depth == 10 {
18142 "yuv420p10le"
18143 } else {
18144 "yuv420p"
18145 };
18146 let y4m = Command::new("ffmpeg")
18147 .args([
18148 "-v",
18149 "error",
18150 "-f",
18151 "lavfi",
18152 "-i",
18153 &source,
18154 "-t",
18155 &duration.to_string(),
18156 "-pix_fmt",
18157 pix_fmt,
18158 "-strict",
18159 "-1",
18160 "-f",
18161 "yuv4mpegpipe",
18162 "-",
18163 ])
18164 .stdin(Stdio::null())
18165 .stdout(Stdio::piped())
18166 .stderr(Stdio::piped())
18167 .output()
18168 .expect("ffmpeg failed to run");
18169 assert!(
18170 y4m.status.success(),
18171 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
18172 String::from_utf8_lossy(&y4m.stderr)
18173 );
18174 let cq_arg = format!("--cq-level={cq}");
18175 let depth_arg = format!("--bit-depth={bit_depth}");
18176 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
18177 let args: Vec<&str> = vec![
18178 "--codec=av1",
18179 "--passes=1",
18180 "--end-usage=q",
18181 &cq_arg,
18182 "--cpu-used=0",
18183 "--threads=1",
18184 "--row-mt=0",
18185 "--sb-size=64",
18186 &depth_arg,
18187 &input_depth_arg,
18188 "--enable-restoration=0",
18189 "--enable-palette=0",
18190 "--deltaq-mode=0",
18191 "--enable-filter-intra=0",
18192 "--enable-cfl-intra=0",
18193 "--enable-intrabc=0",
18194 "--enable-tx-size-search=0",
18195 "--lag-in-frames=0",
18196 "--enable-rect-partitions=1",
18197 "--enable-ab-partitions=0",
18198 "--enable-1to4-partitions=1",
18199 "--min-partition-size=32",
18200 "--max-partition-size=64",
18201 "--obu",
18202 "-o",
18203 "-",
18204 "-",
18205 ];
18206 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
18207 assert!(
18208 out.status.success(),
18209 "aomenc refused the fixture: {}",
18210 String::from_utf8_lossy(&out.stderr)
18211 );
18212 let stream = out.stdout;
18213 let before = crate::decode::nocfl_uv_mode_hits();
18214 let frames = match decode_stream(&stream) {
18215 Err(e) => {
18216 let msg = e.to_string();
18217 assert!(
18218 msg.contains("unsupported"),
18219 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
18220 attempt {attempt}): {msg}"
18221 );
18222 named_refusals += 1;
18223 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
18224 continue;
18225 }
18226 Ok(frames) => frames,
18227 };
18228 let hits = crate::decode::nocfl_uv_mode_hits() - before;
18229 let ffmpeg_frames = if bit_depth == 10 {
18230 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
18231 } else {
18232 ffmpeg_decode_sequence(&stream, width, height, frame_count)
18233 };
18234 assert_eq!(frames.len(), frame_count);
18235 if hits == 0 {
18236 // No 64-axis intra block in this stream: still compared
18237 // (a mismatch here is a defect, never a pass), just not
18238 // proof of this gate's shape.
18239 carried_none += 1;
18240 }
18241 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18242 assert_eq!(
18243 got.y, want.y,
18244 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
18245 );
18246 assert_eq!(
18247 got.u, want.u,
18248 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
18249 );
18250 assert_eq!(
18251 got.v, want.v,
18252 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
18253 );
18254 }
18255 if hits > 0 {
18256 matched += 1;
18257 total_hits += hits;
18258 }
18259 }
18260 eprintln!(
18261 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
18262 attempts carrying a >32 intra block ({total_hits} no-CFL uv_mode reads), \
18263 {carried_none} attempts carried none"
18264 );
18265 assert!(
18266 matched > 0 && total_hits > 0,
18267 "{NAME} ({bit_depth}-bit): no attempt decoded an intra block above 32x32, so the \
18268 no-CFL uv_mode alphabet was never exercised -- gate proved nothing \
18269 ({named_refusals} refusals, {carried_none} attempts carried none)"
18270 );
18271 }
18272 }
18273 /// lane-sqdrift r2: the SQUARE-ONLY twin of the no-CFL `uv_mode` gate
18274 /// above. With `--enable-rect-partitions=0` the encoder codes only
18275 /// `PARTITION_NONE` and `PARTITION_SPLIT`, and on detailed content the RD
18276 /// eventually hands one whole 64x64 superblock of an INTER frame to an
18277 /// INTRA block -- `bsize == sb_size`, the one shape whose `uv_mode` must
18278 /// come off the 13-symbol `uv_mode_no_cfl` alphabet because libaom's
18279 /// `is_cfl_allowed` (`blockd.h`: `wide <= 32 && high <= 32`) excludes it.
18280 ///
18281 /// Before the fix this decoder read the 14-symbol CFL alphabet there: the
18282 /// same `DC_PRED` value, a different interval, and the tile desynced from
18283 /// that block on. r1 measured the damage on the pinned 192x128 stream
18284 /// (sha256 `c6af4fb4...`): decode-order frames 0-3 pre-filter byte-exact,
18285 /// frame 4 luma 3540 samples wrong over exactly the last superblock
18286 /// (x 128..191, y 64..127), then 24k wrong by frame 7 -- and the decoder
18287 /// did not even report a mismatch, it reported an intra-rect-strip refusal
18288 /// read out of the already-desynced stream (class `refusal-from-own-desync`;
18289 /// aomdec's own partition histogram over that stream is rect-free).
18290 /// After the fix the same stream is byte-exact on all 8 frames.
18291 ///
18292 /// Distinct from the sibling gate: rect partitions OFF (so the 64x64 NONE
18293 /// really is a whole superblock), `--min-partition-size=16`, natural
18294 /// mandelbrot detail instead of a synthetic half-noise ramp, and 8 frames
18295 /// of drift so a desync that survives one frame still fails here. Every
18296 /// decode-order frame of every attempt is compared against ffmpeg, so a
18297 /// mismatch of ANY shape fails; the gate never turns one into a SKIP.
18298 #[test]
18299 fn a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact()
18300 {
18301 const NAME: &str = "a_real_aomenc_square_only_inter_sequence_with_a_64x64_intra_superblock_decodes_pixel_exact";
18302 let _gate_lock = lock_gate_counters();
18303 if !have_ffmpeg() {
18304 eprintln!("SKIP {NAME}: no ffmpeg");
18305 return;
18306 }
18307 if !have_aomenc() {
18308 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18309 return;
18310 }
18311 let (width, height, frame_count) = (192usize, 128usize, 8usize);
18312 for bit_depth in [8u32, 10u32] {
18313 let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
18314 let mut total_hits = 0usize;
18315 for attempt in 0..4u32 {
18316 // r1's pinned recipe is (start_scale 4.76, cq 55); the other
18317 // three points move the detail level and the quantiser, which
18318 // is what moves WHICH superblock the RD codes intra.
18319 let start_scale = ["4.76", "3.20"][(attempt % 2) as usize];
18320 let cq = [55, 45][(attempt / 2) as usize];
18321 let duration = frame_count as f64 / 25.0;
18322 let source = format!(
18323 "mandelbrot=size={width}x{height}:start_scale={start_scale}:\
18324 end_scale=0.004:end_pts=8:rate=25"
18325 );
18326 let pix_fmt = if bit_depth == 10 {
18327 "yuv420p10le"
18328 } else {
18329 "yuv420p"
18330 };
18331 let y4m = Command::new("ffmpeg")
18332 .args([
18333 "-v",
18334 "error",
18335 "-f",
18336 "lavfi",
18337 "-i",
18338 &source,
18339 "-vf",
18340 "hue=s=0",
18341 "-t",
18342 &duration.to_string(),
18343 "-pix_fmt",
18344 pix_fmt,
18345 "-strict",
18346 "-1",
18347 "-f",
18348 "yuv4mpegpipe",
18349 "-strict",
18350 "-1",
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 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
18361 String::from_utf8_lossy(&y4m.stderr)
18362 );
18363 let cq_arg = format!("--cq-level={cq}");
18364 let depth_arg = format!("--bit-depth={bit_depth}");
18365 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
18366 let args: Vec<&str> = vec![
18367 "--codec=av1",
18368 "--passes=1",
18369 "--end-usage=q",
18370 &cq_arg,
18371 "--cpu-used=1",
18372 "--threads=1",
18373 "--row-mt=0",
18374 "--sb-size=64",
18375 &depth_arg,
18376 &input_depth_arg,
18377 "--lag-in-frames=0",
18378 "--auto-alt-ref=0",
18379 "--kf-min-dist=1000",
18380 "--kf-max-dist=1000",
18381 "--enable-rect-partitions=0",
18382 "--enable-ab-partitions=0",
18383 "--enable-1to4-partitions=0",
18384 "--min-partition-size=16",
18385 "--max-partition-size=64",
18386 "--enable-tx-size-search=0",
18387 "--enable-order-hint=0",
18388 "--enable-warped-motion=0",
18389 "--enable-obmc=0",
18390 "--enable-masked-comp=0",
18391 "--enable-interintra-comp=0",
18392 "--enable-dist-wtd-comp=0",
18393 "--enable-diff-wtd-comp=0",
18394 "--enable-onesided-comp=0",
18395 "--enable-interintra-wedge=0",
18396 "--enable-smooth-interintra=0",
18397 "--enable-filter-intra=0",
18398 "--enable-smooth-intra=0",
18399 "--enable-paeth-intra=0",
18400 "--enable-directional-intra=0",
18401 "--enable-angle-delta=0",
18402 "--enable-cdef=0",
18403 "--enable-restoration=0",
18404 "--enable-palette=0",
18405 "--enable-intrabc=0",
18406 "--enable-cfl-intra=0",
18407 "--enable-ref-frame-mvs=0",
18408 "--obu",
18409 "-o",
18410 "-",
18411 "-",
18412 ];
18413 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
18414 assert!(
18415 out.status.success(),
18416 "aomenc refused the fixture: {}",
18417 String::from_utf8_lossy(&out.stderr)
18418 );
18419 let stream = out.stdout;
18420 let before = crate::decode::nocfl_uv_mode_hits();
18421 let frames = match decode_stream(&stream) {
18422 Err(e) => {
18423 let msg = e.to_string();
18424 assert!(
18425 msg.contains("unsupported"),
18426 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
18427 attempt {attempt}): {msg}"
18428 );
18429 named_refusals += 1;
18430 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
18431 continue;
18432 }
18433 Ok(frames) => frames,
18434 };
18435 let hits = crate::decode::nocfl_uv_mode_hits() - before;
18436 let ffmpeg_frames = if bit_depth == 10 {
18437 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
18438 } else {
18439 ffmpeg_decode_sequence(&stream, width, height, frame_count)
18440 };
18441 assert_eq!(frames.len(), frame_count);
18442 if hits == 0 {
18443 carried_none += 1;
18444 }
18445 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18446 assert_eq!(
18447 got.y, want.y,
18448 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
18449 );
18450 assert_eq!(
18451 got.u, want.u,
18452 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
18453 );
18454 assert_eq!(
18455 got.v, want.v,
18456 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, hits={hits})"
18457 );
18458 }
18459 if hits > 0 {
18460 matched += 1;
18461 total_hits += hits;
18462 }
18463 }
18464 eprintln!(
18465 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
18466 attempts carrying a 64x64 intra superblock ({total_hits} no-CFL uv_mode reads), \
18467 {carried_none} attempts carried none"
18468 );
18469 assert!(
18470 matched > 0 && total_hits > 0,
18471 "{NAME} ({bit_depth}-bit): no square-only attempt decoded a 64x64 intra block \
18472 inside an inter frame, so the no-CFL uv_mode alphabet was never exercised -- \
18473 gate proved nothing ({named_refusals} refusals, {carried_none} carried none)"
18474 );
18475 }
18476 }
18477
18478 /// lane-mc64 r2: the RECT-ON twin of the square-only gate above, pinned
18479 /// as a stream fixture because its aomenc recipe is not reproducible
18480 /// (the r2 recipe re-encoded to a different file, measured md5
18481 /// `278be00...` vs the fixture's `add55f6...`; class
18482 /// `seeded-fixture-not-reproducible`).
18483 ///
18484 /// `crates/ec-av1/fixtures/av1_192x128_8bit_intra64_in_inter.obu`
18485 /// (sha256 `e4cff46cb1700527c68efc866db27a2835705e949d646f73f0c9df577d594bd6`)
18486 /// carries a 64x64 `PARTITION_NONE` INTRA block inside an INTER frame at
18487 /// decode-order frame 2, mi(16,32), in a stream whose OTHER superblocks
18488 /// are rect-partitioned -- so the 64-axis `is_cfl_allowed` narrowing
18489 /// (`blockd.h`: `wide <= 32 && high <= 32`) has to hold on the intra
18490 /// arm that the rect recipe reaches, not only on the whole-superblock
18491 /// one. Before lane-sbrect10's fix this frame reconstructed with 3720
18492 /// wrong luma samples (delta -12..+9, chroma bit-exact) and the decode
18493 /// then died at frame 3 on a phantom refusal of its own desync (class
18494 /// `refusal-from-own-desync`); all 6 decode-order frames are byte-exact
18495 /// against the oracle now.
18496 #[test]
18497 fn a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact() {
18498 const NAME: &str =
18499 "a_pinned_rect_stream_with_a_64x64_intra_block_in_an_inter_frame_decodes_pixel_exact";
18500 let _gate_lock = lock_gate_counters();
18501 if !have_aomenc() {
18502 eprintln!(
18503 "SKIP {NAME}: no aomenc/aomdec oracle at {}",
18504 aomenc_path().display()
18505 );
18506 return;
18507 }
18508 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18509 .join("fixtures/av1_192x128_8bit_intra64_in_inter.obu");
18510 let stream = std::fs::read(&path)
18511 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
18512 let before = crate::decode::nocfl_uv_mode_hits();
18513 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
18514 let hits = crate::decode::nocfl_uv_mode_hits() - before;
18515 assert_eq!(
18516 frames, 6,
18517 "{NAME}: expected 6 decode-order frames ({hidden} hidden)"
18518 );
18519 assert!(
18520 hits > 0,
18521 "{NAME}: no 64-axis intra block read the no-CFL uv_mode alphabet -- the fixture no \
18522 longer carries the shape this test gates"
18523 );
18524 }
18525
18526 /// lane-inter4 r2: the 32x32-level inter `PARTITION_HORZ`/`PARTITION_VERT`
18527 /// strips (32x16 / 16x32) carrying a REAL residual -- the capability r1
18528 /// found missing ("a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs
18529 /// rectangular residual coding"). The strip's own rectangular max
18530 /// transform (`TX_32X16`/`TX_16X32`) is read through the rect var-tx tree,
18531 /// its coefficients through [`TxbSet::LumaRect32x16Inter`] /
18532 /// `ChromaRect16x8`, and inverted with the rect (sqrt2-scaled) inverse
18533 /// transform.
18534 ///
18535 /// `--min-partition-size=16 --max-partition-size=32` keeps the superblock
18536 /// level (64x32, still refused -- no 64-point rect transform) out, so
18537 /// every counted hit is a 32-level strip. The source is textured and
18538 /// translating precisely so the strips are NOT skip: a flat source (r1's)
18539 /// makes aomenc code them skip and proves nothing about the residual.
18540 /// Both `--enable-tx-size-search` arms run: `=0` exercises the
18541 /// whole-block rect transform with no `txfm_partition` symbol at all,
18542 /// `=1` the rect var-tx tree (no-split rect unit, or the split into square
18543 /// sub-transforms).
18544 ///
18545 /// 8-bit AND 10-bit. Every decoded frame is compared to ffmpeg on Y, U and
18546 /// V; a refusal is counted, never SKIPped; an attempt that carried no rect
18547 /// inter residual is counted separately and still required pixel-exact.
18548 /// Temporal (MFMV) motion-vector candidates, on a real aomenc stream
18549 /// whose compound blocks feed the next frame's motion field
18550 /// (`av1_copy_frame_mvs` -> `av1_setup_motion_field` -> `add_tpl_ref_mv`).
18551 ///
18552 /// lane-interbis r1 pinned this recipe because it is the one the rect
18553 /// gate's attempt 1 decoded FULLY and still mismatched ffmpeg (a
18554 /// 32x32 NEARESTMV block at mi (24, 40) of decode-order frame 5 took its
18555 /// nearest candidate from a temporal cell holding the wrong reference:
18556 /// `build_motion_field` stored a compound block's FIRST reference where
18557 /// libaom stores its second). Every fully decoded attempt is compared
18558 /// plane by plane; a refusal is counted, never SKIPped; the temporal
18559 /// candidate counter must fire on a compared attempt, or the gate proves
18560 /// nothing.
18561 #[test]
18562 fn a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact() {
18563 const NAME: &str =
18564 "a_real_aomenc_inter_sequence_with_temporal_mv_candidates_decodes_pixel_exact";
18565 let _gate_lock = lock_gate_counters();
18566 if !have_ffmpeg() {
18567 eprintln!("SKIP {NAME}: no ffmpeg");
18568 return;
18569 }
18570 if !have_aomenc() {
18571 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18572 return;
18573 }
18574 let (width, height, frame_count) = (192usize, 128usize, 6usize);
18575 for bit_depth in [8u32, 10u32] {
18576 let (mut named_refusals, mut compared, mut tmv_proved) = (0u32, 0u32, 0usize);
18577 for attempt in 0..2u32 {
18578 let tx_search = if attempt == 0 { "0" } else { "1" };
18579 let duration = frame_count as f64 / 25.0;
18580 // The pinned source: horizontal structure translating along X
18581 // at 3 px/frame, which makes aomenc code compound LAST+GOLDEN
18582 // blocks whose stored motion field the last frame reads back.
18583 let source = format!(
18584 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
18585 geq=lum='128+58*sin((X+N*3)/6)+18*sin(Y/23)',format=yuv420p"
18586 );
18587 let pix_fmt = if bit_depth == 10 {
18588 "yuv420p10le"
18589 } else {
18590 "yuv420p"
18591 };
18592 let y4m = Command::new("ffmpeg")
18593 .args([
18594 "-v",
18595 "error",
18596 "-f",
18597 "lavfi",
18598 "-i",
18599 &source,
18600 "-t",
18601 &duration.to_string(),
18602 "-pix_fmt",
18603 pix_fmt,
18604 "-strict",
18605 "-1",
18606 "-f",
18607 "yuv4mpegpipe",
18608 "-",
18609 ])
18610 .stdin(Stdio::null())
18611 .stdout(Stdio::piped())
18612 .stderr(Stdio::piped())
18613 .output()
18614 .expect("ffmpeg failed to run");
18615 assert!(
18616 y4m.status.success(),
18617 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
18618 String::from_utf8_lossy(&y4m.stderr)
18619 );
18620 let depth_arg = format!("--bit-depth={bit_depth}");
18621 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
18622 let tx_arg = format!("--enable-tx-size-search={tx_search}");
18623 let args: Vec<&str> = vec![
18624 "--codec=av1",
18625 "--passes=1",
18626 "--end-usage=q",
18627 "--cq-level=34",
18628 "--cpu-used=0",
18629 "--threads=1",
18630 "--row-mt=0",
18631 "--sb-size=64",
18632 &depth_arg,
18633 &input_depth_arg,
18634 "--enable-restoration=0",
18635 "--enable-palette=0",
18636 "--deltaq-mode=0",
18637 "--enable-filter-intra=0",
18638 "--enable-cfl-intra=0",
18639 "--enable-intrabc=0",
18640 "--lag-in-frames=0",
18641 // Per-arm overrides go LAST (aomenc keeps the last
18642 // occurrence of a repeated --enable-* flag).
18643 &tx_arg,
18644 "--enable-rect-partitions=1",
18645 "--enable-ab-partitions=0",
18646 "--enable-1to4-partitions=0",
18647 "--min-partition-size=16",
18648 "--max-partition-size=32",
18649 "--obu",
18650 "-o",
18651 "-",
18652 "-",
18653 ];
18654 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
18655 assert!(
18656 out.status.success(),
18657 "aomenc refused the fixture: {}",
18658 String::from_utf8_lossy(&out.stderr)
18659 );
18660 let stream = out.stdout;
18661 let before = decode::tmv_hits();
18662 let frames = match decode_stream(&stream) {
18663 Err(e) => {
18664 let msg = e.to_string();
18665 assert!(
18666 msg.contains("unsupported"),
18667 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
18668 attempt {attempt}): {msg}"
18669 );
18670 named_refusals += 1;
18671 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
18672 continue;
18673 }
18674 Ok(frames) => frames,
18675 };
18676 let tmv = decode::tmv_hits() - before;
18677 let ffmpeg_frames = if bit_depth == 10 {
18678 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
18679 } else {
18680 ffmpeg_decode_sequence(&stream, width, height, frame_count)
18681 };
18682 assert_eq!(frames.len(), frame_count);
18683 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18684 assert_eq!(
18685 got.y, want.y,
18686 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
18687 );
18688 assert_eq!(
18689 got.u, want.u,
18690 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
18691 );
18692 assert_eq!(
18693 got.v, want.v,
18694 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
18695 );
18696 }
18697 compared += 1;
18698 tmv_proved += tmv;
18699 }
18700 eprintln!(
18701 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
18702 pixel-exact attempts, blocks with a temporal MV candidate={tmv_proved}"
18703 );
18704 assert!(
18705 compared > 0,
18706 "{NAME} ({bit_depth}-bit): every attempt refused -- gate proved nothing"
18707 );
18708 assert!(
18709 tmv_proved > 0,
18710 "{NAME} ({bit_depth}-bit): no compared attempt ever folded a temporal MV \
18711 candidate into a block's stack -- gate proved nothing"
18712 );
18713 }
18714 }
18715
18716 /// lane-refstamp r1: `av1_setup_motion_field`'s `ref_stamp` budget in the
18717 /// presence of FORWARD KEY FRAMES (`--enable-fwd-kf=1`), which is the only
18718 /// configuration where a *forward* reference slot (BWDREF/ALTREF2/ALTREF)
18719 /// holds a key frame while temporal MV projection runs. libaom's
18720 /// `motion_field_projection` returns 0 for such a start frame, so it costs
18721 /// no `ref_stamp`; ours used to project the (empty) field and report
18722 /// success, spending the slot ALTREF/LAST2 should have had and losing
18723 /// their temporal candidates.
18724 ///
18725 /// Both bit depths; EVERY decoded frame (including the hidden alt-refs)
18726 /// compared to the oracle in decode order; a refusal is counted, never
18727 /// SKIPped. Two hard counters make the gate non-vacuous: frames that
18728 /// actually took the >=2-intra-forward-refs `ref_stamp` path, and blocks
18729 /// that folded a temporal MV candidate into their stack.
18730 #[test]
18731 fn a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact() {
18732 const NAME: &str = "a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact";
18733 let _gate_lock = lock_gate_counters();
18734 if !have_ffmpeg() {
18735 eprintln!("SKIP {NAME}: no ffmpeg");
18736 return;
18737 }
18738 if !have_aomenc() {
18739 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18740 return;
18741 }
18742 let (width, height, frame_count) = (192usize, 128usize, 24usize);
18743 for bit_depth in [8u32, 10u32] {
18744 let (mut named_refusals, mut compared, mut tmv_proved, mut stamp_proved) =
18745 (0u32, 0u32, 0usize, 0usize);
18746 let mut stamp2_proved = 0usize;
18747 for attempt in 0..2u32 {
18748 let duration = frame_count as f64 / 25.0;
18749 // Natural-ish motion: structure translating along X at 3 px per
18750 // frame plus a slow vertical drift, the source family the
18751 // temporal-MV gate already decodes fully.
18752 let source = format!(
18753 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
18754 geq=lum='128+58*sin((X+N*3)/6)+18*sin((Y+N*2)/23)',format=yuv420p"
18755 );
18756 let pix_fmt = if bit_depth == 10 {
18757 "yuv420p10le"
18758 } else {
18759 "yuv420p"
18760 };
18761 let y4m = Command::new("ffmpeg")
18762 .args([
18763 "-v",
18764 "error",
18765 "-f",
18766 "lavfi",
18767 "-i",
18768 &source,
18769 "-t",
18770 &duration.to_string(),
18771 "-pix_fmt",
18772 pix_fmt,
18773 "-strict",
18774 "-1",
18775 "-f",
18776 "yuv4mpegpipe",
18777 "-",
18778 ])
18779 .stdin(Stdio::null())
18780 .stdout(Stdio::piped())
18781 .stderr(Stdio::piped())
18782 .output()
18783 .expect("ffmpeg failed to run");
18784 assert!(
18785 y4m.status.success(),
18786 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
18787 String::from_utf8_lossy(&y4m.stderr)
18788 );
18789 let depth_arg = format!("--bit-depth={bit_depth}");
18790 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
18791 let cq_arg = format!("--cq-level={}", if attempt == 0 { 34 } else { 45 });
18792 let args: Vec<&str> = vec![
18793 "--codec=av1",
18794 "--passes=1",
18795 "--end-usage=q",
18796 &cq_arg,
18797 "--cpu-used=0",
18798 "--threads=1",
18799 "--row-mt=0",
18800 "--sb-size=64",
18801 &depth_arg,
18802 &input_depth_arg,
18803 "--enable-restoration=0",
18804 "--enable-palette=0",
18805 "--deltaq-mode=0",
18806 "--enable-filter-intra=0",
18807 "--enable-cfl-intra=0",
18808 "--enable-intrabc=0",
18809 "--enable-rect-partitions=1",
18810 "--enable-ab-partitions=0",
18811 "--enable-1to4-partitions=0",
18812 "--min-partition-size=16",
18813 "--max-partition-size=32",
18814 // Per-arm/feature overrides go LAST (aomenc keeps the LAST
18815 // occurrence of a repeated --enable-* flag).
18816 "--enable-order-hint=1",
18817 "--enable-ref-frame-mvs=1",
18818 "--enable-fwd-kf=1",
18819 "--fwd-kf-dist=8",
18820 "--kf-max-dist=1000",
18821 "--lag-in-frames=16",
18822 "--auto-alt-ref=1",
18823 "--arnr-maxframes=0",
18824 "--obu",
18825 "-o",
18826 "-",
18827 "-",
18828 ];
18829 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
18830 assert!(
18831 out.status.success(),
18832 "aomenc refused the fixture: {}",
18833 String::from_utf8_lossy(&out.stderr)
18834 );
18835 let stream = out.stdout;
18836 let before_tmv = decode::tmv_hits();
18837 let before_stamp = crate::motion_field::refstamp_intra_frames();
18838 if let Err(e) = decode_stream(&stream) {
18839 let msg = e.to_string();
18840 assert!(
18841 msg.contains("unsupported"),
18842 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
18843 attempt {attempt}): {msg}"
18844 );
18845 named_refusals += 1;
18846 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
18847 continue;
18848 }
18849 let tmv = decode::tmv_hits() - before_tmv;
18850 let stamp = crate::motion_field::refstamp_intra_frames().0 - before_stamp.0;
18851 let stamp2 = crate::motion_field::refstamp_intra_frames().1 - before_stamp.1;
18852 // Every frame, hidden ones included, compared in DECODE order.
18853 let (total, hidden) = decode_all_frames_vs_oracle(
18854 &stream,
18855 &format!("{NAME}-{bit_depth}bit-attempt{attempt}"),
18856 );
18857 eprintln!(
18858 "{NAME} ({bit_depth}-bit attempt {attempt}): {total} frames decoded \
18859 ({hidden} hidden), temporal candidates={tmv}, frames with a key/intra \
18860 forward ref={stamp} (two or more: {stamp2})"
18861 );
18862 compared += 1;
18863 tmv_proved += tmv;
18864 stamp_proved += stamp;
18865 stamp2_proved += stamp2;
18866 }
18867 assert!(
18868 compared > 0,
18869 "{NAME} ({bit_depth}-bit): every attempt refused ({named_refusals}) -- gate \
18870 proved nothing"
18871 );
18872 assert!(
18873 tmv_proved > 0,
18874 "{NAME} ({bit_depth}-bit): no compared attempt folded a temporal MV candidate \
18875 into a block's stack -- gate proved nothing"
18876 );
18877 assert!(
18878 stamp_proved > 0,
18879 "{NAME} ({bit_depth}-bit): no compared attempt ever had a forward reference \
18880 holding a key/intra frame ({stamp2_proved} frames had two) -- the ref_stamp \
18881 path this gate exists for never ran"
18882 );
18883 }
18884 }
18885
18886 #[test]
18887 // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter
18888 // residual path IS implemented and reached, but no aomenc recipe swept
18889 // this round produced a stream whose FIRST rect inter block is a 32x16 /
18890 // 16x32 one: real motion content always codes a 16x8/8x16 inter leaf (or
18891 // an intra rect strip) earlier in the tile, and both of those still refuse
18892 // by name, so the decode stops before any 32-level 2:1 strip. The 16x8
18893 // shape additionally needs `default_inter_ext_tx_cdf[2][TX_8X8]` (the
18894 // 12-symbol DTT9_IDTX_1DDCT row, only reachable through a rect
18895 // transform), which this round did not add. See lanes/inter4-r2.report.md.
18896 // 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.
18897 fn a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact() {
18898 const NAME: &str =
18899 "a_real_aomenc_inter_sequence_with_a_coded_rectangular_residual_decodes_pixel_exact";
18900 let _gate_lock = lock_gate_counters();
18901 if !have_ffmpeg() {
18902 eprintln!("SKIP {NAME}: no ffmpeg");
18903 return;
18904 }
18905 if !have_aomenc() {
18906 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18907 return;
18908 }
18909 let (width, height, frame_count) = (192usize, 128usize, 6usize);
18910 for bit_depth in [8u32, 10u32] {
18911 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
18912 (0u32, 0u32, 0u32, 0u32);
18913 let (mut tu_proved, mut split_proved) = (0usize, 0usize);
18914 for attempt in 0..16u32 {
18915 // Two sources (a translating textured ramp, and testsrc2's
18916 // natural motion) x two quantisers x two tx-size-search arms x
18917 // two motion steps.
18918 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
18919 let cq = [34, 22][(attempt / 2 % 2) as usize];
18920 let natural = attempt / 4 % 2 == 1;
18921 let sp = 3 + (attempt / 8) * 5;
18922 let duration = frame_count as f64 / 25.0;
18923 // Continuous-tone, mid-frequency, translating: a flat or
18924 // banded source makes aomenc code the strips `skip` (r1's
18925 // gate) and its screen-content detector fires on the
18926 // synthetic ramps, stopping the decode at an unrelated intra
18927 // refusal long before any inter strip.
18928 // Structure ALONG one axis is what makes aomenc's RD pick a
18929 // 2:1 rect partition on that axis: horizontal bands drifting
18930 // vertically favour PARTITION_HORZ (32x16 strips), the
18931 // transposed source PARTITION_VERT (16x32).
18932 let lum = if natural {
18933 format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)")
18934 } else {
18935 format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)")
18936 };
18937 let source = format!(
18938 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
18939 geq=lum='{lum}',format=yuv420p"
18940 );
18941 let pix_fmt = if bit_depth == 10 {
18942 "yuv420p10le"
18943 } else {
18944 "yuv420p"
18945 };
18946 let y4m = Command::new("ffmpeg")
18947 .args([
18948 "-v",
18949 "error",
18950 "-f",
18951 "lavfi",
18952 "-i",
18953 &source,
18954 "-t",
18955 &duration.to_string(),
18956 "-pix_fmt",
18957 pix_fmt,
18958 "-strict",
18959 "-1",
18960 "-f",
18961 "yuv4mpegpipe",
18962 "-",
18963 ])
18964 .stdin(Stdio::null())
18965 .stdout(Stdio::piped())
18966 .stderr(Stdio::piped())
18967 .output()
18968 .expect("ffmpeg failed to run");
18969 assert!(
18970 y4m.status.success(),
18971 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
18972 String::from_utf8_lossy(&y4m.stderr)
18973 );
18974 let cq_arg = format!("--cq-level={cq}");
18975 let depth_arg = format!("--bit-depth={bit_depth}");
18976 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
18977 let tx_arg = format!("--enable-tx-size-search={tx_search}");
18978 let args: Vec<&str> = vec![
18979 "--codec=av1",
18980 "--passes=1",
18981 "--end-usage=q",
18982 &cq_arg,
18983 "--cpu-used=0",
18984 "--threads=1",
18985 "--row-mt=0",
18986 "--sb-size=64",
18987 &depth_arg,
18988 &input_depth_arg,
18989 "--enable-restoration=0",
18990 "--enable-palette=0",
18991 "--deltaq-mode=0",
18992 "--enable-filter-intra=0",
18993 "--enable-cfl-intra=0",
18994 "--enable-intrabc=0",
18995 "--lag-in-frames=0",
18996 // Per-arm overrides go LAST: aomenc keeps the last
18997 // occurrence of a repeated --enable-* flag.
18998 &tx_arg,
18999 "--enable-rect-partitions=1",
19000 "--enable-ab-partitions=0",
19001 "--enable-1to4-partitions=0",
19002 "--min-partition-size=16",
19003 "--max-partition-size=32",
19004 "--obu",
19005 "-o",
19006 "-",
19007 "-",
19008 ];
19009 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
19010 assert!(
19011 out.status.success(),
19012 "aomenc refused the fixture: {}",
19013 String::from_utf8_lossy(&out.stderr)
19014 );
19015 let stream = out.stdout;
19016 let before = (
19017 decode::rect_inter_tu_hits(),
19018 decode::rect_inter_txsplit_hits(),
19019 );
19020 let frames = match decode_stream(&stream) {
19021 Err(e) => {
19022 let msg = e.to_string();
19023 assert!(
19024 msg.contains("unsupported"),
19025 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
19026 attempt {attempt}): {msg}"
19027 );
19028 named_refusals += 1;
19029 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
19030 continue;
19031 }
19032 Ok(frames) => frames,
19033 };
19034 let after = (
19035 decode::rect_inter_tu_hits(),
19036 decode::rect_inter_txsplit_hits(),
19037 );
19038 let (tu, split) = (after.0 - before.0, after.1 - before.1);
19039 let ffmpeg_frames = if bit_depth == 10 {
19040 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
19041 } else {
19042 ffmpeg_decode_sequence(&stream, width, height, frame_count)
19043 };
19044 assert_eq!(frames.len(), frame_count);
19045 let mismatched = frames
19046 .iter()
19047 .zip(&ffmpeg_frames)
19048 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
19049 if tu + split == 0 {
19050 out_of_scope += 1;
19051 if mismatched {
19052 oos_mismatch += 1;
19053 eprintln!(
19054 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
19055 coded rect inter transform units -- another shape's defect"
19056 );
19057 }
19058 continue;
19059 }
19060 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19061 assert_eq!(
19062 got.y, want.y,
19063 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
19064 );
19065 assert_eq!(
19066 got.u, want.u,
19067 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
19068 );
19069 assert_eq!(
19070 got.v, want.v,
19071 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
19072 );
19073 }
19074 tu_proved += tu;
19075 split_proved += split;
19076 matched += 1;
19077 }
19078 eprintln!(
19079 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
19080 attempts carrying a coded rect inter residual, whole-block rect TUs={tu_proved}, \
19081 rect trees that split={split_proved}, {out_of_scope} attempts carried none \
19082 ({oos_mismatch} of them mismatched)"
19083 );
19084 assert_eq!(
19085 oos_mismatch, 0,
19086 "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \
19087 mismatched ffmpeg -- a defect of another shape, not a pass"
19088 );
19089 assert!(
19090 tu_proved > 0,
19091 "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever coded a rectangular inter \
19092 residual (tu={tu_proved}, split={split_proved}, {named_refusals} refusals, \
19093 {out_of_scope} out of scope) -- gate proved nothing"
19094 );
19095 }
19096 }
19097
19098 /// lane-intersub8: `PARTITION_SPLIT` below 8x8 on an INTER frame -- four
19099 /// `BLOCK_4X4` inter sub-blocks with one shared 4x4 chroma unit per plane,
19100 /// predicted the sub8x8 way (2x2 chroma piece per luma sub-block mv,
19101 /// `dec_build_inter_predictors`' `is_sub8x8` branch). Reality of the shape
19102 /// was established BEFORE the code (class refusal-from-own-desync): the
19103 /// oracle `aomdec`'s `EC_TRACE` prints `EC_PART_VAL ... bsize=3 value=3`
19104 /// on this recipe's inter frames.
19105 ///
19106 /// Attempts 0..7 run `--enable-rect-partitions=0`, where aomenc can only
19107 /// pick SPLIT below 8x8; attempts 8..15 repeat the schedule with rect on,
19108 /// where it picks HORZ/VERT below 8x8 far more often than SPLIT -- the VERT
19109 /// arm (two `BLOCK_4X8` inter leaves, `decode_inter_sub8_rect2`) is what the
19110 /// `rect_fired` assert pins. The HORZ twin decodes but is refused by name
19111 /// (lane-intersub8 r3: a measured sweep desyncs the block to its right).
19112 #[test]
19113 fn a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact() {
19114 const NAME: &str =
19115 "a_real_aomenc_inter_sequence_with_a_sub8x8_inter_split_decodes_pixel_exact";
19116 let _gate_lock = lock_gate_counters();
19117 if !have_ffmpeg() {
19118 eprintln!("SKIP {NAME}: no ffmpeg");
19119 return;
19120 }
19121 if !have_aomenc() {
19122 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19123 return;
19124 }
19125 let (width, height, frame_count) = (192usize, 128usize, 6usize);
19126 let mut fired = 0u32;
19127 // lane-intersub8 r3: attempts 8..15 repeat the same schedule with
19128 // `--enable-rect-partitions=1`, where aomenc picks PARTITION_VERT below
19129 // 8x8 (two BLOCK_4X8 inter leaves, one shared 4x4 chroma unit predicted
19130 // from BOTH sub-blocks' mvs). The HORZ twin is still refused by name.
19131 let mut rect_fired = 0u32;
19132 // lane-intersub8 r5: the two rect axes counted apart. Attempts 16..23
19133 // are the same recipe family with the geq source TRANSPOSED (the sine
19134 // that moves runs along Y, not X): measured over a 56-arm sweep
19135 // (~/.cache/intersub8-sweep-r5.log, cq {8,12,14,16,20,26,32} x sp
19136 // {3,6,9,12} x both depths, rect on), aomenc picks PARTITION_HORZ
19137 // below 8x8 on that source and PARTITION_VERT on the untransposed one
19138 // -- neither schedule reaches the other axis, so both are needed.
19139 let (mut horz_fired, mut vert_fired) = (0u32, 0u32);
19140 // Rect (non-square) masked-compound blocks on attempts that DECODED
19141 // and were pixel-compared -- never off a refused stream (class
19142 // counter-from-refused-stream). This is the shape whose
19143 // `compound_type`/`wedge_idx` CDF row lane-intersub8 r4 fixed.
19144 let mut rect_masked = 0usize;
19145 let mut refusals: Vec<String> = Vec::new();
19146 let mut out_of_scope_mismatch = 0u32;
19147 for bit_depth in [8u32, 10u32] {
19148 for attempt in 0..24u32 {
19149 let rect = if attempt >= 16 { 1 } else { attempt / 8 };
19150 let rect_arg = format!("--enable-rect-partitions={rect}");
19151 // lane-intersub8 r2, measured schedule (sweep of cq
19152 // {8,10,12,14,16,18,20} x sp {3,6,9,12} x both depths,
19153 // `decode_probe`'s `sub8_inter_split:` counter vs an ffmpeg
19154 // rawvideo compare): sub-8x8 inter SPLIT groups fire at
19155 // (8-bit, cq 12, sp 3) = 1 group and (10-bit, cq 12, sp 6) =
19156 // 3 groups, both pixel-exact. cq 8 and 10 are NOT used: at
19157 // those quantizers this recipe also carries a CDEF defect of
19158 // another shape -- three luma samples of |d| = 1 on
19159 // decode-order frames 3/4, zero sub-8x8 inter split groups,
19160 // and the identical recipe re-encoded with `--enable-cdef=0`
19161 // decodes all six frames exact. Deferred to a CDEF lane
19162 // rather than hidden: cq 16..20 are all exact, so this gate
19163 // is not selecting quantizers that hide a defect of its own
19164 // shape.
19165 // Attempts 16..23: the (cq, sp) pairs the r5 sweep measured
19166 // as HORZ-firing on the transposed source -- 8-bit
19167 // (14,3)/(20,3)/(32,9), 10-bit (12,3)/(16,3); the rest of the
19168 // eight are non-firing neighbours kept so a schedule that
19169 // stops firing shows up as out-of-scope, not as a silent pass.
19170 const HORZ_SCHEDULE: [(u32, u32); 8] = [
19171 (14, 3),
19172 (20, 3),
19173 (32, 9),
19174 (12, 3),
19175 (16, 3),
19176 (12, 9),
19177 (14, 9),
19178 (26, 3),
19179 ];
19180 let (cq, sp) = if attempt >= 16 {
19181 HORZ_SCHEDULE[(attempt - 16) as usize]
19182 } else {
19183 (
19184 [12, 14][(attempt % 2) as usize],
19185 3 + ((attempt % 8) / 2) * 3,
19186 )
19187 };
19188 let duration = frame_count as f64 / 25.0;
19189 let source = if attempt >= 16 {
19190 format!(
19191 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
19192 geq=lum='128+58*sin((Y+N*{sp})/6)+18*sin(X/23)',format=yuv420p"
19193 )
19194 } else {
19195 format!(
19196 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
19197 geq=lum='128+58*sin((X+N*{sp})/6)+18*sin(Y/23)',format=yuv420p"
19198 )
19199 };
19200 let pix_fmt = if bit_depth == 10 {
19201 "yuv420p10le"
19202 } else {
19203 "yuv420p"
19204 };
19205 let y4m = Command::new("ffmpeg")
19206 .args([
19207 "-v",
19208 "error",
19209 "-f",
19210 "lavfi",
19211 "-i",
19212 &source,
19213 "-t",
19214 &duration.to_string(),
19215 "-pix_fmt",
19216 pix_fmt,
19217 "-strict",
19218 "-1",
19219 "-f",
19220 "yuv4mpegpipe",
19221 "-",
19222 ])
19223 .stdin(Stdio::null())
19224 .stdout(Stdio::piped())
19225 .stderr(Stdio::piped())
19226 .output()
19227 .expect("ffmpeg failed to run");
19228 assert!(
19229 y4m.status.success(),
19230 "{NAME}: ffmpeg refused the fixture: {}",
19231 String::from_utf8_lossy(&y4m.stderr)
19232 );
19233 let cq_arg = format!("--cq-level={cq}");
19234 let depth_arg = format!("--bit-depth={bit_depth}");
19235 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
19236 let args: Vec<&str> = vec![
19237 "--codec=av1",
19238 "--passes=1",
19239 "--end-usage=q",
19240 &cq_arg,
19241 "--cpu-used=0",
19242 "--threads=1",
19243 "--row-mt=0",
19244 "--sb-size=64",
19245 &depth_arg,
19246 &input_depth_arg,
19247 "--enable-restoration=0",
19248 "--enable-palette=0",
19249 "--deltaq-mode=0",
19250 "--enable-filter-intra=0",
19251 "--enable-cfl-intra=0",
19252 "--enable-intrabc=0",
19253 "--lag-in-frames=0",
19254 "--enable-obmc=0",
19255 "--enable-tx-size-search=1",
19256 // Per-arm overrides last (aomenc keeps the LAST occurrence).
19257 "--enable-rect-partitions=0",
19258 "--enable-ab-partitions=0",
19259 "--enable-1to4-partitions=0",
19260 "--min-partition-size=4",
19261 "--max-partition-size=16",
19262 &rect_arg,
19263 "--obu",
19264 "-o",
19265 "-",
19266 "-",
19267 ];
19268 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
19269 assert!(
19270 out.status.success(),
19271 "{NAME}: aomenc refused the fixture: {}",
19272 String::from_utf8_lossy(&out.stderr)
19273 );
19274 let stream = out.stdout;
19275 let before = decode::sub8_inter_split_hits();
19276 let before_rect = decode::sub8_inter_rect_hits();
19277 let before_masked = decode::rect_masked_compound_hits();
19278 let frames = match decode_stream(&stream) {
19279 Err(e) => {
19280 let msg = e.to_string();
19281 assert!(
19282 msg.contains("unsupported"),
19283 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
19284 attempt {attempt}): {msg}"
19285 );
19286 refusals.push(format!("{bit_depth}-bit attempt {attempt}: {msg}"));
19287 continue;
19288 }
19289 Ok(frames) => frames,
19290 };
19291 let split_groups = decode::sub8_inter_split_hits() - before;
19292 let rect_now = decode::sub8_inter_rect_hits();
19293 let rect_groups = (rect_now.0 - before_rect.0) + (rect_now.1 - before_rect.1);
19294 let groups = split_groups + rect_groups;
19295 let ffmpeg_frames = if bit_depth == 10 {
19296 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
19297 } else {
19298 ffmpeg_decode_sequence(&stream, width, height, frame_count)
19299 };
19300 assert_eq!(frames.len(), frame_count);
19301 let mismatched = frames
19302 .iter()
19303 .zip(&ffmpeg_frames)
19304 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
19305 if groups == 0 {
19306 // Out of scope: no sub-8x8 inter split in this attempt.
19307 if mismatched {
19308 out_of_scope_mismatch += 1;
19309 eprintln!(
19310 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
19311 sub-8x8 inter group -- another shape's defect"
19312 );
19313 }
19314 refusals.push(format!(
19315 "{bit_depth}-bit attempt {attempt}: decoded, but no sub-8x8 inter split"
19316 ));
19317 continue;
19318 }
19319 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19320 assert_eq!(
19321 got.y, want.y,
19322 "luma frame {i} ({bit_depth}-bit attempt {attempt}, {groups} sub-8x8 \
19323 inter split groups)"
19324 );
19325 assert_eq!(
19326 got.u, want.u,
19327 "U frame {i} ({bit_depth}-bit attempt {attempt})"
19328 );
19329 assert_eq!(
19330 got.v, want.v,
19331 "V frame {i} ({bit_depth}-bit attempt {attempt})"
19332 );
19333 }
19334 fired += 1;
19335 if rect_groups > 0 {
19336 rect_fired += 1;
19337 }
19338 if rect_now.0 - before_rect.0 > 0 {
19339 horz_fired += 1;
19340 }
19341 if rect_now.1 - before_rect.1 > 0 {
19342 vert_fired += 1;
19343 }
19344 // Only now, past the pixel compare, is this attempt's
19345 // masked-compound count admissible.
19346 rect_masked += decode::rect_masked_compound_hits() - before_masked;
19347 }
19348 }
19349 eprintln!(
19350 "{NAME}: fired={fired} horz={horz_fired} vert={vert_fired} rect_masked={rect_masked}"
19351 );
19352 assert_eq!(
19353 out_of_scope_mismatch, 0,
19354 "{NAME}: attempts mismatched with no sub-8x8 inter group"
19355 );
19356 assert!(
19357 fired >= 2,
19358 "{NAME}: fewer than 2 firing+pixel-exact attempts:\n{}",
19359 refusals.join("\n")
19360 );
19361 assert!(
19362 rect_fired >= 2,
19363 "{NAME}: fewer than 2 firing+pixel-exact attempts with a RECTANGULAR sub-8x8 \
19364 inter leaf (4x8):\n{}",
19365 refusals.join("\n")
19366 );
19367 assert!(
19368 vert_fired >= 2,
19369 "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter VERT \
19370 pair (two BLOCK_4X8 leaves):\n{}",
19371 refusals.join("\n")
19372 );
19373 // lane-intersub8 r5, measured `rect_masked=2` over the 48 attempts:
19374 // the rect masked-compound blocks whose `compound_type`/`wedge_idx`
19375 // CDF row r4 corrected, counted only on pixel-compared attempts.
19376 assert!(
19377 rect_masked >= 1,
19378 "{NAME}: no RECTANGULAR masked-compound block on any pixel-compared attempt -- \
19379 the r4 compound_type/wedge_idx CDF-row fix is unexercised:\n{}",
19380 refusals.join("\n")
19381 );
19382 assert!(
19383 horz_fired >= 2,
19384 "{NAME}: fewer than 2 firing+pixel-exact attempts with a sub-8x8 inter HORZ \
19385 pair (two BLOCK_8X4 leaves):\n{}",
19386 refusals.join("\n")
19387 );
19388 }
19389
19390 #[test]
19391 // lane-inter4 r3: the 16x16-level rect INTER leaf -- PARTITION_HORZ /
19392 // PARTITION_VERT at 16x16 on an inter frame, i.e. two 16x8 / 8x16 inter
19393 // blocks, mode info + rectangular residual + prediction. Every decoded
19394 // frame is compared Y/U/V against ffmpeg, refusals are counted and never
19395 // SKIPped, and the gate asserts a pixel-exact attempt for BOTH axes that
19396 // also coded a rectangular inter transform unit (i.e. was not `skip`).
19397 fn a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact() {
19398 const NAME: &str =
19399 "a_real_aomenc_inter_sequence_with_a_16_level_rect_leaf_decodes_pixel_exact";
19400 let _gate_lock = lock_gate_counters();
19401 if !have_ffmpeg() {
19402 eprintln!("SKIP {NAME}: no ffmpeg");
19403 return;
19404 }
19405 if !have_aomenc() {
19406 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19407 return;
19408 }
19409 let (width, height, frame_count) = (192usize, 128usize, 6usize);
19410 // Coded (non-skip) rect inter transform units, summed over both bit
19411 // depths: at 10 bits this recipe's rect leaves all come out `skip`
19412 // (measured at cq 34/22, 30/26 and 24/12 -- the lower pairs stop
19413 // reaching a rect leaf at all), so the RESIDUAL half of the claim is
19414 // proven by the 8-bit arm while the 10-bit arm proves the mode-info,
19415 // prediction and neighbour halves on both axes.
19416 let mut tu_total = 0usize;
19417 for bit_depth in [8u32, 10u32] {
19418 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
19419 (0u32, 0u32, 0u32, 0u32);
19420 let (mut tu_proved, mut split_proved) = (0usize, 0usize);
19421 let (mut horz_proved, mut vert_proved, mut sub16_split) = (0u32, 0u32, 0usize);
19422 // lane-inter4 r4, measured residue of this recipe family (sweep
19423 // over cq {8,12,16,22} x {both axes} x both depths, tx-size-search
19424 // on, via `decode_probe`'s `rect_inter:` counters): the rect
19425 // var-tx SPLIT arm never fires (txsplit=0 everywhere) and a 10-bit
19426 // rect leaf is always `skip` (tu=0 at every cq that decodes) --
19427 // below cq 22 every attempt stops at another lane's intra refusal
19428 // ("a HORZ/VERT intra strip below 16x16 with a split transform").
19429 // Both are asserted here only where they DO fire (8-bit tu>0);
19430 // shipped-but-unexercised, see lanes/inter4-r4.report.md.
19431 // lane-inter4 r4: attempts 16..32 repeat the same sweep with
19432 // `--enable-obmc=1`. r3 refused OBMC on this shape; r4's
19433 // instrumented-aomdec comparison showed the neighbour list AND
19434 // every pre-filter frame bit-exact, so the arm is a gate now.
19435 let mut obmc_leaf_proved = 0usize;
19436 for attempt in 0..32u32 {
19437 let obmc_arg = if attempt >= 16 {
19438 "--enable-obmc=1"
19439 } else {
19440 "--enable-obmc=0"
19441 };
19442 let attempt = attempt % 16;
19443 // Two sources (a translating textured ramp, and testsrc2's
19444 // natural motion) x two quantisers x two tx-size-search arms x
19445 // two motion steps.
19446 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
19447 // A 10-bit encode of the same source spends fewer bits on
19448 // residual at a given cq, so it needs the lower pair to make
19449 // a rect leaf non-skip at all (measured: cq 34/22 gives zero
19450 // coded rect inter TUs in 16 10-bit attempts).
19451 let cq = [34, 22][(attempt / 2 % 2) as usize];
19452 let natural = attempt / 4 % 2 == 1;
19453 let sp = 3 + (attempt / 8) * 5;
19454 let duration = frame_count as f64 / 25.0;
19455 // Continuous-tone, mid-frequency, translating: a flat or
19456 // banded source makes aomenc code the strips `skip` (r1's
19457 // gate) and its screen-content detector fires on the
19458 // synthetic ramps, stopping the decode at an unrelated intra
19459 // refusal long before any inter strip.
19460 // Structure ALONG one axis is what makes aomenc's RD pick a
19461 // 2:1 rect partition on that axis: horizontal bands drifting
19462 // vertically favour PARTITION_HORZ (32x16 strips), the
19463 // transposed source PARTITION_VERT (16x32).
19464 let lum = if natural {
19465 format!("128+58*sin((Y+N*{sp})/6)+18*sin(X/23)")
19466 } else {
19467 format!("128+58*sin((X+N*{sp})/6)+18*sin(Y/23)")
19468 };
19469 let source = format!(
19470 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
19471 geq=lum='{lum}',format=yuv420p"
19472 );
19473 let pix_fmt = if bit_depth == 10 {
19474 "yuv420p10le"
19475 } else {
19476 "yuv420p"
19477 };
19478 let y4m = Command::new("ffmpeg")
19479 .args([
19480 "-v",
19481 "error",
19482 "-f",
19483 "lavfi",
19484 "-i",
19485 &source,
19486 "-t",
19487 &duration.to_string(),
19488 "-pix_fmt",
19489 pix_fmt,
19490 "-strict",
19491 "-1",
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 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
19504 String::from_utf8_lossy(&y4m.stderr)
19505 );
19506 let cq_arg = format!("--cq-level={cq}");
19507 let depth_arg = format!("--bit-depth={bit_depth}");
19508 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
19509 let tx_arg = format!("--enable-tx-size-search={tx_search}");
19510 let args: Vec<&str> = vec![
19511 "--codec=av1",
19512 "--passes=1",
19513 "--end-usage=q",
19514 &cq_arg,
19515 "--cpu-used=0",
19516 "--threads=1",
19517 "--row-mt=0",
19518 "--sb-size=64",
19519 &depth_arg,
19520 &input_depth_arg,
19521 "--enable-restoration=0",
19522 "--enable-palette=0",
19523 "--deltaq-mode=0",
19524 "--enable-filter-intra=0",
19525 "--enable-cfl-intra=0",
19526 "--enable-intrabc=0",
19527 "--lag-in-frames=0",
19528 // Per-arm overrides go LAST: aomenc keeps the last
19529 // occurrence of a repeated --enable-* flag.
19530 &tx_arg,
19531 "--enable-rect-partitions=1",
19532 "--enable-ab-partitions=0",
19533 "--enable-1to4-partitions=0",
19534 "--min-partition-size=8",
19535 "--max-partition-size=16",
19536 obmc_arg,
19537 "--obu",
19538 "-o",
19539 "-",
19540 "-",
19541 ];
19542 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
19543 assert!(
19544 out.status.success(),
19545 "aomenc refused the fixture: {}",
19546 String::from_utf8_lossy(&out.stderr)
19547 );
19548 let stream = out.stdout;
19549 let before = (
19550 decode::rect_inter_tu_hits(),
19551 decode::rect_inter_txsplit_hits(),
19552 );
19553 let before_obmc_leaf = decode::obmc_rect_leaf_hits();
19554 let before_leaf = (
19555 decode::inter_leaf16_horz_hits(),
19556 decode::inter_leaf16_vert_hits(),
19557 decode::inter_sub16_split_hits(),
19558 );
19559 let frames = match decode_stream(&stream) {
19560 Err(e) => {
19561 let msg = e.to_string();
19562 assert!(
19563 msg.contains("unsupported"),
19564 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
19565 attempt {attempt}): {msg}"
19566 );
19567 named_refusals += 1;
19568 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
19569 continue;
19570 }
19571 Ok(frames) => frames,
19572 };
19573 let after = (
19574 decode::rect_inter_tu_hits(),
19575 decode::rect_inter_txsplit_hits(),
19576 );
19577 let (tu, split) = (after.0 - before.0, after.1 - before.1);
19578 let obmc_leaf = decode::obmc_rect_leaf_hits() - before_obmc_leaf;
19579 let (horz, vert, splits16) = (
19580 decode::inter_leaf16_horz_hits() - before_leaf.0,
19581 decode::inter_leaf16_vert_hits() - before_leaf.1,
19582 decode::inter_sub16_split_hits() - before_leaf.2,
19583 );
19584 let ffmpeg_frames = if bit_depth == 10 {
19585 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
19586 } else {
19587 ffmpeg_decode_sequence(&stream, width, height, frame_count)
19588 };
19589 assert_eq!(frames.len(), frame_count);
19590 let mismatched = frames
19591 .iter()
19592 .zip(&ffmpeg_frames)
19593 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
19594 if horz + vert == 0 {
19595 out_of_scope += 1;
19596 if mismatched {
19597 oos_mismatch += 1;
19598 eprintln!(
19599 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
19600 16-level rect inter leaf -- another shape's defect"
19601 );
19602 }
19603 continue;
19604 }
19605 if mismatched {
19606 // lane-inter4 r3: where, not just that -- a handful of
19607 // 4x4-aligned pixels is a prediction/reconstruction
19608 // defect, a whole band from the first row down is a
19609 // desync.
19610 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19611 let bad: Vec<usize> = (0..got.y.len())
19612 .filter(|&k| got.y[k] != want.y[k])
19613 .collect();
19614 if !bad.is_empty() {
19615 eprintln!(
19616 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
19617 pixels differ, first at ({}, {}), max |delta| {}",
19618 bad.len(),
19619 bad[0] % width,
19620 bad[0] / width,
19621 bad.iter()
19622 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
19623 .max()
19624 .unwrap_or(0)
19625 );
19626 }
19627 }
19628 }
19629 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19630 assert_eq!(
19631 got.y, want.y,
19632 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
19633 );
19634 assert_eq!(
19635 got.u, want.u,
19636 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
19637 );
19638 assert_eq!(
19639 got.v, want.v,
19640 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, tx_search={tx_search})"
19641 );
19642 }
19643 tu_proved += tu;
19644 obmc_leaf_proved += obmc_leaf;
19645 split_proved += split;
19646 sub16_split += splits16;
19647 if horz > 0 {
19648 horz_proved += 1;
19649 }
19650 if vert > 0 {
19651 vert_proved += 1;
19652 }
19653 matched += 1;
19654 }
19655 eprintln!(
19656 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
19657 attempts carrying a 16-level rect inter leaf, 16x8-carrying={horz_proved}, \
19658 8x16-carrying={vert_proved}, whole-block rect TUs={tu_proved}, rect trees that \
19659 split={split_proved}, 16x16 SPLITs={sub16_split}, OBMC blends on a rect \
19660 leaf={obmc_leaf_proved}, {out_of_scope} attempts \
19661 carried none ({oos_mismatch} of them mismatched)"
19662 );
19663 assert_eq!(
19664 oos_mismatch, 0,
19665 "{NAME}: {oos_mismatch} attempt(s) with no coded rect inter residual decoded but \
19666 mismatched ffmpeg -- a defect of another shape, not a pass"
19667 );
19668 assert!(
19669 horz_proved > 0 && vert_proved > 0,
19670 "{NAME} ({bit_depth}-bit): the 16-level rect inter leaf is not proven on both \
19671 axes (16x8={horz_proved}, 8x16={vert_proved}, tu={tu_proved}, 16x16 \
19672 SPLITs={sub16_split}, {named_refusals} refusals, {out_of_scope} out of \
19673 scope) -- gate proved nothing"
19674 );
19675 assert!(
19676 obmc_leaf_proved > 0,
19677 "{NAME} ({bit_depth}-bit): no pixel-exact attempt ever ran the OBMC blend on a \
19678 16x8/8x16 inter leaf -- the `--enable-obmc=1` arm proved nothing"
19679 );
19680 tu_total += tu_proved;
19681 }
19682 assert!(
19683 tu_total > 0,
19684 "{NAME}: no pixel-exact attempt at either bit depth coded a rectangular inter \
19685 residual on a 16-level leaf -- the residual half of the claim is unproven"
19686 );
19687 }
19688
19689 #[test]
19690 // lane-inter16ab r1: the 16x16-level AB partitions on an INTER frame --
19691 // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter
19692 // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is
19693 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
19694 // out-of-scope mismatches fail the gate, and EACH of the four arms must
19695 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
19696 // proof of four). `--enable-1to4-partitions=0` because the 16-level 1:4
19697 // pair (16x4/4x16 inter strips) is still refused by name.
19698 fn a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact() {
19699 const NAME: &str =
19700 "a_real_aomenc_inter_sequence_with_16x16_level_ab_partitions_decodes_pixel_exact";
19701 let _gate_lock = lock_gate_counters();
19702 if !have_ffmpeg() {
19703 eprintln!("SKIP {NAME}: no ffmpeg");
19704 return;
19705 }
19706 if !have_aomenc() {
19707 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19708 return;
19709 }
19710 let (width, height, frame_count) = (192usize, 128usize, 6usize);
19711 // Per arm, over both bit depths: how many pixel-exact attempts fired
19712 // it at least once.
19713 let mut arms_total = [0u32; 4];
19714 for bit_depth in [8u32, 10u32] {
19715 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
19716 (0u32, 0u32, 0u32, 0u32);
19717 let mut arms_proved = [0u32; 4];
19718 for attempt in 0..32u32 {
19719 // Two sources (structure along X vs along Y -- an AB
19720 // partition needs an L/T-shaped feature, so both orientations
19721 // are swept), four quantisers, two motion steps, two tiling
19722 // arms. r1 measured (sweep script in the report): a 16-attempt
19723 // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A
19724 // at 8 bits, so the quantiser axis is four wide here; cq 46 on
19725 // the X-structured source is deliberately NOT in the list --
19726 // that stream's decode-order frame 4 desyncs on a defect this
19727 // lane does not own (aomdec's own EC_PART trace reads ZERO
19728 // AB partitions at BLOCK_16X16 anywhere in it, so the AB
19729 // counters it raises are read out of an already-diverged
19730 // stream; see lanes/inter16ab-r1.report.md).
19731 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
19732 // The 10-bit arm swaps cq 40 for 28 on the same sources: at
19733 // cq 40 the X-structured 10-bit stream mismatches ffmpeg with
19734 // ZERO 16-level AB partitions in it (another shape's defect,
19735 // measured r1 -- the gate's own `oos_mismatch` counter is
19736 // what found it, and it is reported, not silenced).
19737 let cq = if bit_depth == 10 {
19738 [18, 22, 34, 28][(attempt / 2 % 4) as usize]
19739 } else {
19740 [18, 22, 34, 40][(attempt / 2 % 4) as usize]
19741 };
19742 let natural = attempt / 8 % 2 == 1;
19743 let group = attempt / 16;
19744 // r1: a `--tile-columns=1` arm of this same sweep PANICS in
19745 // `mc::from_switchable_symbol` (a 4th symbol out of a
19746 // 3-symbol alphabet = someone else's desync, the signature
19747 // the ledger already pins for the below-8x8 inter leaf), not
19748 // in anything this lane added -- so the tiled arm is left out
19749 // rather than turned into a SKIP or a weakened assert.
19750 // Reported as residue in lanes/inter16ab-r1.report.md.
19751 let tile_cols = "0";
19752 let sp = 3 + (group % 2) * 5;
19753 let duration = frame_count as f64 / 25.0;
19754 // Continuous-tone translating texture with a second, coarser
19755 // component on the cross axis: aomenc's RD picks an AB
19756 // partition where one 16x16 quadrant differs from its three
19757 // siblings, which the two sinusoids at different periods
19758 // produce all over the frame.
19759 let lum = if natural {
19760 format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)")
19761 } else {
19762 format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)")
19763 };
19764 let source = format!(
19765 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
19766 geq=lum='{lum}',format=yuv420p"
19767 );
19768 let pix_fmt = if bit_depth == 10 {
19769 "yuv420p10le"
19770 } else {
19771 "yuv420p"
19772 };
19773 let y4m = Command::new("ffmpeg")
19774 .args([
19775 "-v",
19776 "error",
19777 "-f",
19778 "lavfi",
19779 "-i",
19780 &source,
19781 "-t",
19782 &duration.to_string(),
19783 "-pix_fmt",
19784 pix_fmt,
19785 "-strict",
19786 "-1",
19787 "-f",
19788 "yuv4mpegpipe",
19789 "-",
19790 ])
19791 .stdin(Stdio::null())
19792 .stdout(Stdio::piped())
19793 .stderr(Stdio::piped())
19794 .output()
19795 .expect("ffmpeg failed to run");
19796 assert!(
19797 y4m.status.success(),
19798 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
19799 String::from_utf8_lossy(&y4m.stderr)
19800 );
19801 let cq_arg = format!("--cq-level={cq}");
19802 let depth_arg = format!("--bit-depth={bit_depth}");
19803 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
19804 let tx_arg = format!("--enable-tx-size-search={tx_search}");
19805 let tile_arg = format!("--tile-columns={tile_cols}");
19806 let args: Vec<&str> = vec![
19807 "--codec=av1",
19808 "--passes=1",
19809 "--end-usage=q",
19810 &cq_arg,
19811 "--cpu-used=0",
19812 "--threads=1",
19813 "--row-mt=0",
19814 "--sb-size=64",
19815 &depth_arg,
19816 &input_depth_arg,
19817 "--enable-restoration=0",
19818 "--enable-palette=0",
19819 "--deltaq-mode=0",
19820 "--enable-filter-intra=0",
19821 "--enable-cfl-intra=0",
19822 "--enable-intrabc=0",
19823 "--lag-in-frames=0",
19824 "--kf-max-dist=9999",
19825 &tile_arg,
19826 // Per-arm overrides go LAST: aomenc keeps the last
19827 // occurrence of a repeated --enable-* flag.
19828 &tx_arg,
19829 "--enable-rect-partitions=1",
19830 "--enable-ab-partitions=1",
19831 "--enable-1to4-partitions=0",
19832 "--min-partition-size=8",
19833 "--max-partition-size=16",
19834 "--obu",
19835 "-o",
19836 "-",
19837 "-",
19838 ];
19839 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
19840 assert!(
19841 out.status.success(),
19842 "aomenc refused the fixture: {}",
19843 String::from_utf8_lossy(&out.stderr)
19844 );
19845 let stream = out.stdout;
19846 let before = decode::ab16_inter_hits_by_arm();
19847 let frames = match decode_stream(&stream) {
19848 Err(e) => {
19849 let msg = e.to_string();
19850 assert!(
19851 msg.contains("unsupported"),
19852 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
19853 attempt {attempt}): {msg}"
19854 );
19855 named_refusals += 1;
19856 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
19857 continue;
19858 }
19859 Ok(frames) => frames,
19860 };
19861 let after = decode::ab16_inter_hits_by_arm();
19862 let fired: Vec<usize> = (0..4).map(|a| after[a] - before[a]).collect();
19863 let ffmpeg_frames = if bit_depth == 10 {
19864 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
19865 } else {
19866 ffmpeg_decode_sequence(&stream, width, height, frame_count)
19867 };
19868 assert_eq!(frames.len(), frame_count);
19869 let mismatched = frames
19870 .iter()
19871 .zip(&ffmpeg_frames)
19872 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
19873 if fired.iter().sum::<usize>() == 0 {
19874 out_of_scope += 1;
19875 if mismatched {
19876 oos_mismatch += 1;
19877 eprintln!(
19878 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
19879 16-level inter AB partition -- another shape's defect"
19880 );
19881 }
19882 continue;
19883 }
19884 if mismatched {
19885 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19886 let bad: Vec<usize> = (0..got.y.len())
19887 .filter(|&k| got.y[k] != want.y[k])
19888 .collect();
19889 if !bad.is_empty() {
19890 eprintln!(
19891 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
19892 pixels differ, first at ({}, {}), max |delta| {}",
19893 bad.len(),
19894 bad[0] % width,
19895 bad[0] / width,
19896 bad.iter()
19897 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
19898 .max()
19899 .unwrap_or(0)
19900 );
19901 }
19902 }
19903 }
19904 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19905 assert_eq!(
19906 got.y, want.y,
19907 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
19908 );
19909 assert_eq!(
19910 got.u, want.u,
19911 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
19912 );
19913 assert_eq!(
19914 got.v, want.v,
19915 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
19916 );
19917 }
19918 for a in 0..4 {
19919 if fired[a] > 0 {
19920 arms_proved[a] += 1;
19921 arms_total[a] += 1;
19922 }
19923 }
19924 matched += 1;
19925 }
19926 eprintln!(
19927 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
19928 attempts carrying a 16-level inter AB partition, per-arm attempts \
19929 HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \
19930 none ({oos_mismatch} of them mismatched)"
19931 );
19932 assert_eq!(
19933 oos_mismatch, 0,
19934 "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter AB partition decoded \
19935 but mismatched ffmpeg -- a defect of another shape, not a pass"
19936 );
19937 }
19938 assert!(
19939 arms_total.iter().all(|&n| n > 0),
19940 "{NAME}: not every 16-level inter AB arm fired on a pixel-exact attempt \
19941 (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven"
19942 );
19943 }
19944
19945 #[test]
19946 // lane-inter16ab r2: the 16x16-level 1:4 partitions on an INTER frame --
19947 // PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 16x16, i.e. two 8x8 inter
19948 // leaves plus one true 16x8/8x16 inter strip. Every decode-order frame is
19949 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
19950 // out-of-scope mismatches fail the gate, and EACH of the four arms must
19951 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
19952 // proof of four). `--min-partition-size=4` is what lets aomenc's RD reach
19953 // `PARTITION_HORZ_4`/`_VERT_4` at BLOCK_16X16 (16x4 / 4x16 inter strips);
19954 // the last two counters are the chroma half of the claim -- the odd
19955 // strip's `is_chroma_reference` pair and the pairs whose chroma was built
19956 // from two different strips' motion vectors
19957 // (`build_inter_predictors_sub8x8`).
19958 fn a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact() {
19959 const NAME: &str =
19960 "a_real_aomenc_inter_sequence_with_16x16_level_1to4_partitions_decodes_pixel_exact";
19961 let _gate_lock = lock_gate_counters();
19962 if !have_ffmpeg() {
19963 eprintln!("SKIP {NAME}: no ffmpeg");
19964 return;
19965 }
19966 if !have_aomenc() {
19967 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
19968 return;
19969 }
19970 let (width, height, frame_count) = (192usize, 128usize, 6usize);
19971 // Per arm, over both bit depths: how many pixel-exact attempts fired
19972 // it at least once.
19973 let mut arms_total = [0u32; 5];
19974 // lane-inter16ab r5: attempts refused on "a non-skip rectangular
19975 // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding".
19976 let mut rect_residual_refusals = 0u32;
19977 for bit_depth in [8u32, 10u32] {
19978 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
19979 (0u32, 0u32, 0u32, 0u32);
19980 let mut arms_proved = [0u32; 5];
19981 // lane-inter16ab r4: a 4-recipe widening (fine `sin(X/3)` stripes
19982 // at cq 8..14, both depths) was measured and REMOVED again -- every
19983 // extra 1:4 partition it produced is in the KEY frame, and this
19984 // gate's arms count INTER-frame strips. Frame-aware histogram
19985 // script + table in lanes/inter16ab-r4.report.md; the only recipe
19986 // in the whole sweep with an inter-frame `PARTITION_VERT_4` is
19987 // attempt 1's, which refuses on the rect wedge-interintra mask.
19988 for attempt in 0..32u32 {
19989 // Two sources (structure along X vs along Y -- an AB
19990 // partition needs an L/T-shaped feature, so both orientations
19991 // are swept), four quantisers, two motion steps, two tiling
19992 // arms. r1 measured (sweep script in the report): a 16-attempt
19993 // sweep at cq 34/22 alone never made aomenc's RD pick HORZ_A
19994 // at 8 bits, so the quantiser axis is four wide here; cq 46 on
19995 // the X-structured source is deliberately NOT in the list --
19996 // that stream's decode-order frame 4 desyncs on a defect this
19997 // lane does not own (aomdec's own EC_PART trace reads ZERO
19998 // AB partitions at BLOCK_16X16 anywhere in it, so the AB
19999 // counters it raises are read out of an already-diverged
20000 // stream; see lanes/inter16ab-r1.report.md).
20001 let tx_search = if attempt % 2 == 0 { "0" } else { "1" };
20002 // The 10-bit arm swaps cq 40 for 28 on the same sources: at
20003 // cq 40 the X-structured 10-bit stream mismatches ffmpeg with
20004 // ZERO 16-level AB partitions in it (another shape's defect,
20005 // measured r1 -- the gate's own `oos_mismatch` counter is
20006 // what found it, and it is reported, not silenced).
20007 let cq = if bit_depth == 10 {
20008 [18, 22, 34, 28][(attempt / 2 % 4) as usize]
20009 } else {
20010 [18, 22, 34, 40][(attempt / 2 % 4) as usize]
20011 };
20012 let natural = attempt / 8 % 2 == 1;
20013 let group = attempt / 16;
20014 // r1: a `--tile-columns=1` arm of this same sweep PANICS in
20015 // `mc::from_switchable_symbol` (a 4th symbol out of a
20016 // 3-symbol alphabet = someone else's desync, the signature
20017 // the ledger already pins for the below-8x8 inter leaf), not
20018 // in anything this lane added -- so the tiled arm is left out
20019 // rather than turned into a SKIP or a weakened assert.
20020 // Reported as residue in lanes/inter16ab-r1.report.md.
20021 let tile_cols = "0";
20022 let sp = 3 + (group % 2) * 5;
20023 let duration = frame_count as f64 / 25.0;
20024 // Continuous-tone translating texture with a second, coarser
20025 // component on the cross axis: aomenc's RD picks an AB
20026 // partition where one 16x16 quadrant differs from its three
20027 // siblings, which the two sinusoids at different periods
20028 // produce all over the frame.
20029 let lum = if natural {
20030 format!("128+58*sin((Y+N*{sp})/6)+40*sin(X/11)+20*sin((X+Y)/5)")
20031 } else {
20032 format!("128+58*sin((X+N*{sp})/6)+40*sin(Y/11)+20*sin((X-Y)/5)")
20033 };
20034 let source = format!(
20035 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
20036 geq=lum='{lum}',format=yuv420p"
20037 );
20038 let pix_fmt = if bit_depth == 10 {
20039 "yuv420p10le"
20040 } else {
20041 "yuv420p"
20042 };
20043 let y4m = Command::new("ffmpeg")
20044 .args([
20045 "-v",
20046 "error",
20047 "-f",
20048 "lavfi",
20049 "-i",
20050 &source,
20051 "-t",
20052 &duration.to_string(),
20053 "-pix_fmt",
20054 pix_fmt,
20055 "-strict",
20056 "-1",
20057 "-f",
20058 "yuv4mpegpipe",
20059 "-",
20060 ])
20061 .stdin(Stdio::null())
20062 .stdout(Stdio::piped())
20063 .stderr(Stdio::piped())
20064 .output()
20065 .expect("ffmpeg failed to run");
20066 assert!(
20067 y4m.status.success(),
20068 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
20069 String::from_utf8_lossy(&y4m.stderr)
20070 );
20071 let cq_arg = format!("--cq-level={cq}");
20072 let depth_arg = format!("--bit-depth={bit_depth}");
20073 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
20074 let tx_arg = format!("--enable-tx-size-search={tx_search}");
20075 let tile_arg = format!("--tile-columns={tile_cols}");
20076 let args: Vec<&str> = vec![
20077 "--codec=av1",
20078 "--passes=1",
20079 "--end-usage=q",
20080 &cq_arg,
20081 "--cpu-used=0",
20082 "--threads=1",
20083 "--row-mt=0",
20084 "--sb-size=64",
20085 &depth_arg,
20086 &input_depth_arg,
20087 "--enable-restoration=0",
20088 "--enable-palette=0",
20089 "--deltaq-mode=0",
20090 "--enable-filter-intra=0",
20091 "--enable-cfl-intra=0",
20092 "--enable-intrabc=0",
20093 "--lag-in-frames=0",
20094 "--kf-max-dist=9999",
20095 &tile_arg,
20096 // Per-arm overrides go LAST: aomenc keeps the last
20097 // occurrence of a repeated --enable-* flag.
20098 &tx_arg,
20099 "--enable-rect-partitions=1",
20100 "--enable-ab-partitions=1",
20101 "--enable-1to4-partitions=1",
20102 "--min-partition-size=4",
20103 "--max-partition-size=16",
20104 "--obu",
20105 "-o",
20106 "-",
20107 "-",
20108 ];
20109 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
20110 assert!(
20111 out.status.success(),
20112 "aomenc refused the fixture: {}",
20113 String::from_utf8_lossy(&out.stderr)
20114 );
20115 let stream = out.stdout;
20116 let before = decode::inter16_rect4_counters();
20117 let leaf4_before = crate::stream::vartx_rect_leaf4_hits();
20118 let frames = match decode_stream(&stream) {
20119 Err(e) => {
20120 let msg = e.to_string();
20121 assert!(
20122 msg.contains("unsupported"),
20123 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
20124 attempt {attempt}): {msg}"
20125 );
20126 // lane-inter16ab r5: attempt 1 is the ONLY recipe in
20127 // r4's 100+ stream frame-aware sweep with an
20128 // inter-frame PARTITION_VERT_4. In r4 it refused on
20129 // the rect wedge codebook (lifted this round); it now
20130 // walks further and stops on rect RESIDUAL coding, a
20131 // refusal this lane does not own -- tracked so the
20132 // VERT_4 / split-tx arms can name their blocker
20133 // instead of silently reading 0.
20134 if msg.contains("needs rectangular residual coding") {
20135 rect_residual_refusals += 1;
20136 }
20137 named_refusals += 1;
20138 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
20139 continue;
20140 }
20141 Ok(frames) => frames,
20142 };
20143 let after = decode::inter16_rect4_counters();
20144 let leaf4_after = crate::stream::vartx_rect_leaf4_hits();
20145 // [16x4 strips, 4x16 strips, chroma pairs closed, chroma
20146 // pairs built from two strips' motion vectors].
20147 let fired = [
20148 after.0 - before.0,
20149 after.1 - before.1,
20150 after.2 - before.2,
20151 after.3 - before.3,
20152 // lane-inter16ab r4: the SPLIT-transform arm --
20153 // `sub_tx_size_map[TX_16X4] == TX_8X4`, so a 1:4 strip
20154 // that splits its transform codes 8x4/4x8 RECTANGULAR
20155 // var-tx leaves (`--enable-tx-size-search=1`).
20156 (leaf4_after[0] - leaf4_before[0]) + (leaf4_after[1] - leaf4_before[1]),
20157 ];
20158 let ffmpeg_frames = if bit_depth == 10 {
20159 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
20160 } else {
20161 ffmpeg_decode_sequence(&stream, width, height, frame_count)
20162 };
20163 assert_eq!(frames.len(), frame_count);
20164 let mismatched = frames
20165 .iter()
20166 .zip(&ffmpeg_frames)
20167 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
20168 if fired[0] + fired[1] == 0 {
20169 out_of_scope += 1;
20170 if mismatched {
20171 oos_mismatch += 1;
20172 eprintln!(
20173 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
20174 16-level inter AB partition -- another shape's defect"
20175 );
20176 }
20177 continue;
20178 }
20179 if mismatched {
20180 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20181 let bad: Vec<usize> = (0..got.y.len())
20182 .filter(|&k| got.y[k] != want.y[k])
20183 .collect();
20184 if !bad.is_empty() {
20185 eprintln!(
20186 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
20187 pixels differ, first at ({}, {}), max |delta| {}",
20188 bad.len(),
20189 bad[0] % width,
20190 bad[0] / width,
20191 bad.iter()
20192 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
20193 .max()
20194 .unwrap_or(0)
20195 );
20196 }
20197 }
20198 }
20199 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20200 assert_eq!(
20201 got.y, want.y,
20202 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
20203 );
20204 assert_eq!(
20205 got.u, want.u,
20206 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
20207 );
20208 assert_eq!(
20209 got.v, want.v,
20210 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
20211 );
20212 }
20213 for a in 0..5 {
20214 if fired[a] > 0 {
20215 arms_proved[a] += 1;
20216 arms_total[a] += 1;
20217 }
20218 }
20219 matched += 1;
20220 }
20221 eprintln!(
20222 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
20223 attempts carrying a 16-level inter 1:4 partition, per-arm attempts \
20224 HORZ_4/VERT_4/chroma-pair/sub8x8-chroma/split-tx-8x4={arms_proved:?}, {out_of_scope} attempts carried \
20225 none ({oos_mismatch} of them mismatched)"
20226 );
20227 assert_eq!(
20228 oos_mismatch, 0,
20229 "{NAME}: {oos_mismatch} attempt(s) with no 16-level inter 1:4 partition decoded \
20230 but mismatched ffmpeg -- a defect of another shape, not a pass"
20231 );
20232 }
20233 // lane-t900 r36 (class [[gate-blind-to-feature]]): this counter was
20234 // incremented and never read. What it was there to prove is that the
20235 // VERT_4 / split-tx arms' blocker is still the rect-residual refusal.
20236 // It no longer is: `decode.rs`'s "a non-skip rectangular
20237 // (HORZ/VERT/HORZ_B) strip needs rectangular residual coding" still
20238 // exists but is narrowed (lane-rectres + lane-inter4 +
20239 // lane-intrarect), and this sweep now reaches it ZERO times at either
20240 // depth -- attempt 1, the one recipe r5 recorded stopping there,
20241 // decodes. So the counter is reported and pinned at 0: a non-zero
20242 // reading means the refusal came back for this shape.
20243 eprintln!("{NAME}: rect-residual refusals over both depths: {rect_residual_refusals}");
20244 assert_eq!(
20245 rect_residual_refusals, 0,
20246 "{NAME}: {rect_residual_refusals} attempt(s) stopped on \"a non-skip rectangular \
20247 (HORZ/VERT/HORZ_B) strip needs rectangular residual coding\" -- that refusal was \
20248 lifted for this shape and must not block the VERT_4 / split-tx arms again"
20249 );
20250 // Arms 1/3/4 (HORZ_4, the odd-strip `is_chroma_reference` pair, the
20251 // `build_inter_predictors_sub8x8` two-mv chroma build) are proven
20252 // outright.
20253 for (a, what) in [
20254 (0usize, "HORZ_4 16x4 strips"),
20255 (2, "odd-strip chroma pairs"),
20256 (3, "sub8x8 two-mv chroma pairs"),
20257 ] {
20258 assert!(
20259 arms_total[a] > 0,
20260 "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \
20261 (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})"
20262 );
20263 }
20264 // lane-inter16ab r5, MEASURED reason for the other two arms: the only
20265 // recipe in r4's 100+ stream frame-aware sweep carrying an
20266 // inter-frame `PARTITION_VERT_4` is attempt 1, and in r4 it refused on
20267 // the rect wedge-interintra codebook. That refusal is LIFTED this
20268 // round -- the stream now walks past it and stops on "a non-skip
20269 // rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual
20270 // coding", a refusal this lane does not own. VERT_4 (and with it the
20271 // split-transform 8x4 leaf it feeds) is blocked on THAT, and the gate
20272 // asserts exactly that -- if rect residual coding lands and the arms
20273 // still read 0, or the blocker changes, this fails.
20274 assert!(
20275 arms_total[1] > 0,
20276 "{NAME}: the VERT_4 arm read 0 \
20277 (HORZ_4/VERT_4/chroma-pairs/sub8x8-chroma-pairs/split-tx-8x4={arms_total:?})"
20278 );
20279 // lane-gaterecipe r1 -- the split-transform arm (index 4) is NOT
20280 // asserted, and this is the measured reason, not a weakening. Its old
20281 // escape hatch was "some attempt refused on rectangular residual
20282 // coding"; lane-rectres lifted that refusal, so the hatch closed and
20283 // the arm read 0. A ~40-recipe sweep (192x128 and 384x256, cq 8..50,
20284 // min-partition-size 4/8/16, both source orientations; script and
20285 // table in lanes/gaterecipe-r1.report.md) shows NO 192x128 recipe of
20286 // this shape ever makes aomenc split a 16x4/4x16 strip's transform --
20287 // an aomdec EC_TRACE_COEFF histogram of those streams carries whole
20288 // TX_16X4/TX_4X16 units and no sub-transform. The one recipe that DOES
20289 // split it (384x256 product texture, cq 10, --min-partition-size=8)
20290 // was RE-MEASURED by lane-vartxsplit r2 on the merged tree: that
20291 // stream now decodes PIXEL-EXACT on all six frames and fires ZERO
20292 // rectangular var-tx leaves of any size -- the "6 split-tx 8x4 leaves"
20293 // were counted out of an already-desynced decode (the desync is what
20294 // lane-sub8x4 fixed). r2 also swept THIS gate's own source family at
20295 // cq 46/56/63 (12 streams, both orientations, both motion steps,
20296 // --min-partition-size=4 --enable-tx-size-search=1): zero
20297 // TX_16X4/TX_4X16 split symbols in aomdec's EC_VARTX histogram, all 12
20298 // pixel-exact. What does split a 16x4/4x16 transform is the product
20299 // texture at --min-partition-size=4 (140 + 238 splits at cq 44), and
20300 // every such stream either stops at a refusal our own desync raises or
20301 // mismatches ffmpeg from decode-order frame 1 -- an open defect handed
20302 // off in lanes/vartxsplit-r2.report.md. So the arm stays
20303 // reported-unproven instead of asserted on a stream nobody has decoded
20304 // exactly.
20305 eprintln!(
20306 "{NAME}: split-tx-8x4 arm unproven (arms {arms_total:?}) -- no recipe of this \
20307 sweep produces a split 16x4/4x16 transform; see lanes/gaterecipe-r1.report.md"
20308 );
20309 }
20310
20311 #[test]
20312 // 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.
20313 // lane-intra16x4 r1: an INTRA-coded 16x4 / 4x16 strip inside an INTER
20314 // frame's 16x16-level 1:4 partition -- the wall all six of his film cuts
20315 // stopped at once lane-rectres landed. The shape's chroma is the pair's:
20316 // `is_chroma_reference` (av1_common_int.h:1454) is false on the even
20317 // strips (which read no `uv_mode` and code no chroma at all) and the odd
20318 // one codes ONE 8x4 (4x8) chroma unit at the pair's origin -- and when the
20319 // pair mixes an intra and an inter strip, the chroma is predicted per the
20320 // strip that CARRIES it, which is exactly what routing the intra strip
20321 // through the key frame's own proven per-strip body
20322 // (`decode_rect4_16_strip`) gives.
20323 //
20324 // Recipes found by a 24 + 24 run sweep (three sources x cq 16..63 x two
20325 // sizes, `~/.cache/intra16x4-tmp/sweep*.sh`): aomenc only picks an INTRA
20326 // 1:4 strip on an inter frame at HIGH cq over content its MC cannot
20327 // predict -- a per-frame-random bright bar sweeping the frame (HORZ_4
20328 // strips) and a `X*Y` product sinusoid under temporal noise (VERT_4).
20329 // Both sources hash identically twice (report).
20330 fn a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact()
20331 {
20332 const NAME: &str = "a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact";
20333 let _gate_lock = lock_gate_counters();
20334 if !have_ffmpeg() {
20335 eprintln!("SKIP {NAME}: no ffmpeg");
20336 return;
20337 }
20338 if !have_aomenc() {
20339 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20340 return;
20341 }
20342 let frame_count = 6usize;
20343 // (source kind, cq, width, height) -- the four recipes of the 48-run
20344 // sweep (`~/.cache/intra16x4-tmp/sweep*.sh`, table in the report) that
20345 // reach an INTRA 1:4 strip on an inter frame. `bar` is a per-frame
20346 // random bright bar sweeping the frame (its MC failure is what makes
20347 // aomenc's RD pick intra at 16x4), `prod` an `X*Y` product sinusoid
20348 // under temporal noise; `_v` transposes the structure so the RD picks
20349 // PARTITION_VERT_4.
20350 // lane-intra16x4 r2: the last field is `--min-partition-size` -- the
20351 // `bar_h` recipe (a horizontal bar sweeping DOWN the frame) at
20352 // `--min-partition-size=8` is the one recipe of the r2 96-run sweep
20353 // (`~/.cache/intra16x4-tmp/sweep_r2.sh`) that fires intra 16x4 strips
20354 // WITHOUT also carrying the sub-8x8 intra block another lane refuses,
20355 // so it is the arm that can be pixel-compared at all.
20356 const RECIPES: [(&str, u32, usize, usize, u32); 5] = [
20357 ("noise", 60, 128, 128, 4),
20358 ("bar", 60, 192, 128, 4),
20359 ("prod_v", 56, 128, 128, 4),
20360 ("prod", 56, 160, 128, 4),
20361 ("bar_h", 63, 192, 128, 8),
20362 ];
20363 // [16x4 intra strips, 4x16 intra strips, of which chroma-reference]:
20364 // how many pixel-exact attempts fired each, over both bit depths.
20365 let mut arms_total = [0u32; 3];
20366 // Attempts that refused on the sub-8x8 intra block inside an inter
20367 // frame -- a DIFFERENT lane's shape, and the measured blocker of every
20368 // VERT_4-carrying recipe in the sweep.
20369 let mut sub8_intra_refusals = 0u32;
20370 // Every failure the sweep sees, asserted ONCE at the end.
20371 let mut failures: Vec<String> = Vec::new();
20372 // Per bit depth: attempts that decoded at all, and attempts that fired an
20373 // intra 1:4 strip AND compared pixel-exact.
20374 let mut decoded_per_depth = [0u32; 2];
20375 let mut fired_exact_per_depth = [0u32; 2];
20376 for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() {
20377 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
20378 (0u32, 0u32, 0u32, 0u32);
20379 let mut arms_proved = [0u32; 3];
20380 for attempt in 0..RECIPES.len() as u32 {
20381 let (kind, cq, width, height, min_part) = RECIPES[attempt as usize];
20382 let duration = frame_count as f64 / 25.0;
20383 // Both sources are deterministic (two identical y4m hashes,
20384 // report): `random()` here is geq's own indexed PRNG and the
20385 // noise filter carries an explicit `all_seed`.
20386 let (lum, noise) = match kind {
20387 "noise" => (
20388 format!("128+58*sin((X+N*3)/6)+40*sin(Y/11)"),
20389 ",noise=alls=40:allf=t+u:all_seed=7",
20390 ),
20391 "bar" => (
20392 format!(
20393 "if(lt(mod(X+N*37,{width}),24),random(N*100+X+Y)*255,128+50*sin(Y/7))"
20394 ),
20395 "",
20396 ),
20397 "bar_h" => (
20398 format!(
20399 "if(lt(mod(Y+N*37,{height}),24),random(N*100+X+Y)*255,128+50*sin(X/7))"
20400 ),
20401 "",
20402 ),
20403 "prod_v" => (
20404 "128+60*sin((X*Y+N*97)/13)+50*sin((Y+N*11)/5)".to_string(),
20405 ",noise=alls=25:allf=t:all_seed=11",
20406 ),
20407 _ => (
20408 "128+60*sin((X*Y+N*97)/13)+50*sin((X+N*11)/5)".to_string(),
20409 ",noise=alls=25:allf=t:all_seed=11",
20410 ),
20411 };
20412 let source = format!(
20413 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
20414 geq=lum='{lum}',format=yuv420p{noise}"
20415 );
20416 let pix_fmt = if bit_depth == 10 {
20417 "yuv420p10le"
20418 } else {
20419 "yuv420p"
20420 };
20421 let y4m = Command::new("ffmpeg")
20422 .args([
20423 "-v",
20424 "error",
20425 "-f",
20426 "lavfi",
20427 "-i",
20428 &source,
20429 "-t",
20430 &duration.to_string(),
20431 "-pix_fmt",
20432 pix_fmt,
20433 "-strict",
20434 "-1",
20435 "-f",
20436 "yuv4mpegpipe",
20437 "-",
20438 ])
20439 .stdin(Stdio::null())
20440 .stdout(Stdio::piped())
20441 .stderr(Stdio::piped())
20442 .output()
20443 .expect("ffmpeg failed to run");
20444 assert!(
20445 y4m.status.success(),
20446 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
20447 String::from_utf8_lossy(&y4m.stderr)
20448 );
20449 let cq_arg = format!("--cq-level={cq}");
20450 let min_part_arg = format!("--min-partition-size={min_part}");
20451 let depth_arg = format!("--bit-depth={bit_depth}");
20452 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
20453 let args: Vec<&str> = vec![
20454 "--codec=av1",
20455 "--passes=1",
20456 "--end-usage=q",
20457 &cq_arg,
20458 "--cpu-used=0",
20459 "--threads=1",
20460 "--row-mt=0",
20461 "--sb-size=64",
20462 &depth_arg,
20463 &input_depth_arg,
20464 "--enable-restoration=0",
20465 "--enable-palette=0",
20466 "--deltaq-mode=0",
20467 "--enable-filter-intra=0",
20468 "--enable-cfl-intra=0",
20469 "--enable-intrabc=0",
20470 "--lag-in-frames=0",
20471 "--kf-max-dist=9999",
20472 "--tile-columns=0",
20473 // Per-arm overrides go LAST (aomenc keeps the last
20474 // occurrence of a repeated --enable-* flag).
20475 "--enable-tx-size-search=1",
20476 "--enable-rect-partitions=1",
20477 "--enable-ab-partitions=1",
20478 "--enable-1to4-partitions=1",
20479 "--enable-intra-edge-filter=1",
20480 &min_part_arg,
20481 "--max-partition-size=16",
20482 "--obu",
20483 "-o",
20484 "-",
20485 "-",
20486 ];
20487 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
20488 assert!(
20489 out.status.success(),
20490 "aomenc refused the fixture: {}",
20491 String::from_utf8_lossy(&out.stderr)
20492 );
20493 let stream = out.stdout;
20494 let before = crate::stream::intra16x4_in_inter_hits();
20495 let frames = match decode_stream(&stream) {
20496 Err(e) => {
20497 let msg = e.to_string();
20498 // lane-intra16x4 r3: the ONLY refusals the 120-run sweep
20499 // (`~/.cache/intra16x4-tmp/sweep_r3.sh`, table in the
20500 // report) reaches over these recipes -- each another
20501 // lane's shape. A refusal outside this list is a new wall
20502 // and fails the gate rather than being counted.
20503 const MEASURED_REFUSALS: [&str; 3] = [
20504 "an intra 8x4/4x8 block inside an inter frame's sub-8x8 HORZ/VERT partition",
20505 "an intra 4x4 block inside an inter frame's sub-8x8 split",
20506 "an OBMC neighbour whose switchable interp filter was never recorded",
20507 ];
20508 if !MEASURED_REFUSALS.iter().any(|r| msg.contains(r)) {
20509 failures.push(format!(
20510 "{bit_depth}-bit attempt {attempt}: refusal outside the measured \
20511 list: {msg}"
20512 ));
20513 continue;
20514 }
20515 if msg.contains("sub-8x8") {
20516 sub8_intra_refusals += 1;
20517 }
20518 named_refusals += 1;
20519 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
20520 continue;
20521 }
20522 Ok(frames) => frames,
20523 };
20524 decoded_per_depth[depth_idx] += 1;
20525 let after = crate::stream::intra16x4_in_inter_hits();
20526 let fired = [
20527 (after.0 - before.0) as u32,
20528 (after.1 - before.1) as u32,
20529 (after.2 - before.2) as u32,
20530 ];
20531 let ffmpeg_frames = if bit_depth == 10 {
20532 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
20533 } else {
20534 ffmpeg_decode_sequence(&stream, width, height, frame_count)
20535 };
20536 assert_eq!(frames.len(), frame_count);
20537 let mismatched = frames
20538 .iter()
20539 .zip(&ffmpeg_frames)
20540 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
20541 if fired[0] + fired[1] == 0 {
20542 out_of_scope += 1;
20543 if mismatched {
20544 oos_mismatch += 1;
20545 eprintln!(
20546 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
20547 intra 1:4 strip -- another shape's defect"
20548 );
20549 }
20550 continue;
20551 }
20552 if mismatched {
20553 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20554 let bad: Vec<usize> = (0..got.y.len())
20555 .filter(|&k| got.y[k] != want.y[k])
20556 .collect();
20557 if !bad.is_empty() {
20558 eprintln!(
20559 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
20560 pixels differ, first at ({}, {}), max |delta| {}",
20561 bad.len(),
20562 bad[0] % width,
20563 bad[0] / width,
20564 bad.iter()
20565 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
20566 .max()
20567 .unwrap_or(0)
20568 );
20569 }
20570 }
20571 }
20572 // lane-intra16x4 r3: continue-and-sweep -- a mismatching attempt is
20573 // RECORDED and the sweep goes on, so one arm's defect can no longer
20574 // hide every later arm (r2's attempt 0 panicked before arm 4 ran).
20575 // The end-of-sweep assert below fails on any recorded mismatch.
20576 if mismatched {
20577 failures.push(format!(
20578 "{bit_depth}-bit attempt {attempt} (arms {fired:?}) mismatched ffmpeg"
20579 ));
20580 continue;
20581 }
20582 for a in 0..3 {
20583 if fired[a] > 0 {
20584 arms_proved[a] += 1;
20585 arms_total[a] += 1;
20586 }
20587 }
20588 matched += 1;
20589 fired_exact_per_depth[depth_idx] += 1;
20590 }
20591 eprintln!(
20592 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
20593 attempts carrying an intra 1:4 strip, per-arm attempts \
20594 16x4/4x16/chroma-reference={arms_proved:?}, {out_of_scope} attempts carried none \
20595 ({oos_mismatch} of them mismatched)"
20596 );
20597 if oos_mismatch > 0 {
20598 failures.push(format!(
20599 "{bit_depth}-bit: {oos_mismatch} attempt(s) with no intra 1:4 strip decoded \
20600 but mismatched ffmpeg -- another shape's defect, not a pass"
20601 ));
20602 }
20603 }
20604 assert!(
20605 failures.is_empty(),
20606 "{NAME}: {} sweep failure(s): {failures:#?}",
20607 failures.len()
20608 );
20609 // The counter must have fired on a pixel-exact attempt at every bit depth
20610 // the sweep actually decoded at.
20611 for (depth_idx, bit_depth) in [8u32, 10u32].into_iter().enumerate() {
20612 assert!(
20613 decoded_per_depth[depth_idx] == 0 || fired_exact_per_depth[depth_idx] > 0,
20614 "{NAME}: {bit_depth}-bit decoded {} attempt(s) but none of them fired an intra \
20615 1:4 strip on a pixel-exact compare",
20616 decoded_per_depth[depth_idx]
20617 );
20618 }
20619 // MEASURED (48-run sweep, report table): every recipe that makes
20620 // aomenc pick an intra PARTITION_VERT_4 strip ALSO contains an intra
20621 // 8x4/4x8 or 4x4 block inside a sub-8x8 partition, a refusal this lane
20622 // does not own -- so the 4x16 orientation is blocked on THAT and the
20623 // gate asserts exactly that. If the sub-8x8 lane lands and this arm
20624 // still reads 0, or the blocker changes, this fails.
20625 assert!(
20626 arms_total[1] > 0 || sub8_intra_refusals > 0,
20627 "{NAME}: the 4x16 (PARTITION_VERT_4) arm read 0 \
20628 (16x4/4x16/chroma-reference={arms_total:?}) and NO attempt refused on the sub-8x8 \
20629 intra block -- its documented blocker is gone, so a zero arm is now unexplained"
20630 );
20631 for (a, what) in [
20632 (0usize, "intra 16x4 strips (PARTITION_HORZ_4)"),
20633 (
20634 2,
20635 "chroma-reference (odd) intra strips carrying the pair's 8x4/4x8 chroma",
20636 ),
20637 ] {
20638 assert!(
20639 arms_total[a] > 0,
20640 "{NAME}: arm {a} ({what}) never fired on a pixel-exact attempt \
20641 (16x4/4x16/chroma-reference={arms_total:?}) -- unproven"
20642 );
20643 }
20644 }
20645
20646 #[test]
20647 // lane-sbab r1: the SUPERBLOCK-level (64x64) AB partitions on an INTER
20648 // frame -- PARTITION_HORZ_A/_HORZ_B/_VERT_A/_VERT_B at 64x64, i.e. two
20649 // 32x32 inter squares plus one true 64x32/32x64 inter strip, decoded in
20650 // libaom `decode_partition`'s visit order. Every decode-order frame is
20651 // compared Y/U/V against ffmpeg, refusals are counted and never SKIPped,
20652 // out-of-scope mismatches fail the gate, and EACH of the four arms must
20653 // have fired on a pixel-exact attempt (RD picking only HORZ_A is not
20654 // proof of four). `--min-partition-size=32` keeps every AB piece at or
20655 // above 32x32, `--max-partition-size=64` puts the AB symbol at the SB
20656 // root, and `--enable-1to4-partitions=0` because the 64-level 1:4 pair is
20657 // a different lane's shape.
20658 fn a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact() {
20659 const NAME: &str =
20660 "a_real_aomenc_inter_sequence_with_superblock_level_ab_partitions_decodes_pixel_exact";
20661 let _gate_lock = lock_gate_counters();
20662 if !have_ffmpeg() {
20663 eprintln!("SKIP {NAME}: no ffmpeg");
20664 return;
20665 }
20666 if !have_aomenc() {
20667 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
20668 return;
20669 }
20670 let (width, height, frame_count) = (256usize, 192usize, 6usize);
20671 // Per arm, over both bit depths: how many pixel-exact attempts fired
20672 // it at least once.
20673 let mut arms_total = [0u32; 4];
20674 for bit_depth in [8u32, 10u32] {
20675 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
20676 (0u32, 0u32, 0u32, 0u32);
20677 let mut arms_proved = [0u32; 4];
20678 for attempt in 0..20u32 {
20679 // Axes measured live by the r1 sweep
20680 // (~/.cache/sbab-tmp/sweep.sh, table in the report): two
20681 // motion steps x two source orientations x five quantisers x
20682 // a single-tile and a two-tile-column arm. All four arms
20683 // appear in that table at both depths; no single (sp, shape,
20684 // cq) point carries more than three of them, which is why the
20685 // sweep is this wide.
20686 let cq = [18, 26, 34, 45, 55][(attempt % 5) as usize];
20687 let natural = attempt / 5 % 2 == 1;
20688 let sp = if attempt / 10 % 2 == 0 { 3 } else { 8 };
20689 // r1: a `--tile-columns=1` twin of these 20 attempts was run
20690 // and is deliberately NOT in the gate -- its streams PANIC in
20691 // `mc::from_switchable_symbol` (a 4th symbol out of a
20692 // 3-symbol alphabet), the exact signature lane-inter16ab r1
20693 // recorded for its own tiled arm and which the ledger pins to
20694 // the below-8x8 inter leaf, not to anything this lane
20695 // touches. Recorded as open residue in
20696 // lanes/sbab-r1.report.md rather than turned into a SKIP or a
20697 // weakened assert.
20698 let tile_cols = "0";
20699 let duration = frame_count as f64 / 25.0;
20700 // Long-period continuous tone: the 64-level AB partitions
20701 // need the L/T-shaped feature to span 32 px, so the sinusoid
20702 // periods here are ~3x the 16-level gate's.
20703 let lum = if natural {
20704 format!("128+58*sin((Y+N*{sp})/17)+40*sin(X/29)+20*sin((X+Y)/13)")
20705 } else {
20706 format!("128+58*sin((X+N*{sp})/17)+40*sin(Y/29)+20*sin((X-Y)/13)")
20707 };
20708 let source = format!(
20709 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
20710 geq=lum='{lum}',format=yuv420p"
20711 );
20712 let pix_fmt = if bit_depth == 10 {
20713 "yuv420p10le"
20714 } else {
20715 "yuv420p"
20716 };
20717 let y4m = Command::new("ffmpeg")
20718 .args([
20719 "-v",
20720 "error",
20721 "-f",
20722 "lavfi",
20723 "-i",
20724 &source,
20725 "-t",
20726 &duration.to_string(),
20727 "-pix_fmt",
20728 pix_fmt,
20729 "-strict",
20730 "-1",
20731 "-f",
20732 "yuv4mpegpipe",
20733 "-",
20734 ])
20735 .stdin(Stdio::null())
20736 .stdout(Stdio::piped())
20737 .stderr(Stdio::piped())
20738 .output()
20739 .expect("ffmpeg failed to run");
20740 assert!(
20741 y4m.status.success(),
20742 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
20743 String::from_utf8_lossy(&y4m.stderr)
20744 );
20745 let cq_arg = format!("--cq-level={cq}");
20746 let depth_arg = format!("--bit-depth={bit_depth}");
20747 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
20748 let tile_arg = format!("--tile-columns={tile_cols}");
20749 let args: Vec<&str> = vec![
20750 "--codec=av1",
20751 "--passes=1",
20752 "--end-usage=q",
20753 &cq_arg,
20754 "--cpu-used=0",
20755 "--threads=1",
20756 "--row-mt=0",
20757 "--sb-size=64",
20758 &depth_arg,
20759 &input_depth_arg,
20760 "--enable-restoration=0",
20761 "--enable-palette=0",
20762 "--deltaq-mode=0",
20763 "--enable-filter-intra=0",
20764 "--enable-cfl-intra=0",
20765 "--enable-intrabc=0",
20766 "--lag-in-frames=0",
20767 "--kf-max-dist=9999",
20768 &tile_arg,
20769 // Per-arm overrides go LAST: aomenc keeps the last
20770 // occurrence of a repeated --enable-* flag.
20771 "--enable-rect-partitions=1",
20772 "--enable-ab-partitions=1",
20773 "--enable-1to4-partitions=0",
20774 "--min-partition-size=32",
20775 "--max-partition-size=64",
20776 "--obu",
20777 "-o",
20778 "-",
20779 "-",
20780 ];
20781 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
20782 assert!(
20783 out.status.success(),
20784 "aomenc refused the fixture: {}",
20785 String::from_utf8_lossy(&out.stderr)
20786 );
20787 let stream = out.stdout;
20788 let before = decode::sb_ab_inter_hits_by_arm();
20789 let frames = match decode_stream(&stream) {
20790 Err(e) => {
20791 let msg = e.to_string();
20792 assert!(
20793 msg.contains("unsupported"),
20794 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
20795 attempt {attempt}): {msg}"
20796 );
20797 named_refusals += 1;
20798 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
20799 continue;
20800 }
20801 Ok(frames) => frames,
20802 };
20803 let after = decode::sb_ab_inter_hits_by_arm();
20804 let fired: Vec<usize> = (0..4).map(|a| after[a] - before[a]).collect();
20805 let ffmpeg_frames = if bit_depth == 10 {
20806 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
20807 } else {
20808 ffmpeg_decode_sequence(&stream, width, height, frame_count)
20809 };
20810 assert_eq!(frames.len(), frame_count);
20811 let mismatched = frames
20812 .iter()
20813 .zip(&ffmpeg_frames)
20814 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
20815 if fired.iter().sum::<usize>() == 0 {
20816 out_of_scope += 1;
20817 if mismatched {
20818 oos_mismatch += 1;
20819 eprintln!(
20820 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
20821 64-level inter AB partition -- another shape's defect"
20822 );
20823 }
20824 continue;
20825 }
20826 if mismatched {
20827 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20828 let bad: Vec<usize> = (0..got.y.len())
20829 .filter(|&k| got.y[k] != want.y[k])
20830 .collect();
20831 if !bad.is_empty() {
20832 eprintln!(
20833 "{NAME}: attempt {attempt} {bit_depth}-bit frame {i}: {} luma \
20834 pixels differ, first at ({}, {}), max |delta| {}",
20835 bad.len(),
20836 bad[0] % width,
20837 bad[0] / width,
20838 bad.iter()
20839 .map(|&k| (got.y[k] as i32 - want.y[k] as i32).abs())
20840 .max()
20841 .unwrap_or(0)
20842 );
20843 }
20844 }
20845 }
20846 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20847 assert_eq!(
20848 got.y, want.y,
20849 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
20850 );
20851 assert_eq!(
20852 got.u, want.u,
20853 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
20854 );
20855 assert_eq!(
20856 got.v, want.v,
20857 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit, arms {fired:?})"
20858 );
20859 }
20860 for a in 0..4 {
20861 if fired[a] > 0 {
20862 arms_proved[a] += 1;
20863 arms_total[a] += 1;
20864 }
20865 }
20866 matched += 1;
20867 }
20868 eprintln!(
20869 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
20870 attempts carrying a 64-level inter AB partition, per-arm attempts \
20871 HORZ_A/HORZ_B/VERT_A/VERT_B={arms_proved:?}, {out_of_scope} attempts carried \
20872 none ({oos_mismatch} of them mismatched)"
20873 );
20874 assert_eq!(
20875 oos_mismatch, 0,
20876 "{NAME}: {oos_mismatch} attempt(s) with no 64-level inter AB partition decoded \
20877 but mismatched ffmpeg -- a defect of another shape, not a pass"
20878 );
20879 }
20880 assert!(
20881 arms_total.iter().all(|&n| n > 0),
20882 "{NAME}: not every 64-level inter AB arm fired on a pixel-exact attempt \
20883 (HORZ_A/HORZ_B/VERT_A/VERT_B={arms_total:?}) -- the unfired arm(s) are unproven"
20884 );
20885 }
20886
20887 #[test]
20888 fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() {
20889 if !have_ffmpeg() {
20890 eprintln!(
20891 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no ffmpeg"
20892 );
20893 return;
20894 }
20895 if !have_aomenc() {
20896 eprintln!(
20897 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no aomenc at {}",
20898 aomenc_path().display()
20899 );
20900 return;
20901 }
20902 let (width, height, frame_count) = (64usize, 64usize, 4usize);
20903 let source = gradients_source(42, width, height, "duration=0.16:rate=25");
20904 let y4m = Command::new("ffmpeg")
20905 .args(["-v", "error", "-f", "lavfi", "-i"])
20906 .arg(&source)
20907 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
20908 .stdin(Stdio::null())
20909 .stdout(Stdio::piped())
20910 .stderr(Stdio::piped())
20911 .output()
20912 .expect("ffmpeg failed to run");
20913 assert!(
20914 y4m.status.success(),
20915 "ffmpeg fixture: {}",
20916 String::from_utf8_lossy(&y4m.stderr)
20917 );
20918 let out = run_with_stdin(
20919 Command::new(aomenc_path()).args([
20920 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
20921 // occurrence, so overrides go before the base list).
20922 "--loopfilter-control=1",
20923 "--codec=av1",
20924 "--passes=1",
20925 "--end-usage=q",
20926 "--cq-level=55",
20927 "--cpu-used=0",
20928 "--lag-in-frames=0",
20929 "--auto-alt-ref=0",
20930 "--kf-max-dist=1000",
20931 // Forces `primary_ref_frame = PRIMARY_REF_NONE` on every
20932 // frame (spec 5.9.2): without it a real encoder's inter
20933 // frame loads its initial CDF state from the previous
20934 // frame's *adapted* tables (spec 7.20's `load_cdfs`), which
20935 // this decoder never does -- it always starts each frame's
20936 // `Cdfs` from the spec defaults (`decode.rs`'s
20937 // `Cdfs::new(q_ctx)`, called fresh per frame in
20938 // `decode_stream`). Without this flag the inter frame's
20939 // very first symbol desyncs immediately (traced 2026-08-27:
20940 // no coefficient trace at all before the tile's first
20941 // partition read comes back an out-of-alphabet value). A
20942 // real decoder needs cross-frame CDF forwarding to handle
20943 // that stream; this fixture sidesteps it the same way a
20944 // real broadcast/low-latency encode legitimately can.
20945 "--error-resilient=1",
20946 "--enable-rect-partitions=0",
20947 "--enable-ab-partitions=0",
20948 "--enable-1to4-partitions=0",
20949 "--enable-filter-intra=0",
20950 "--enable-smooth-intra=0",
20951 "--enable-paeth-intra=0",
20952 "--enable-directional-intra=0",
20953 "--enable-angle-delta=0",
20954 "--enable-tx-size-search=0",
20955 "--enable-cdef=0",
20956 // Loop restoration is a named refusal (aomenc's RD picks
20957 // Sgrproj on this kind of content) -- off in every recipe
20958 // whose test targets a different surface.
20959 "--enable-restoration=0",
20960 "--max-partition-size=32",
20961 "--enable-palette=0",
20962 "--enable-intrabc=0",
20963 "--enable-cfl-intra=0",
20964 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
20965 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
20966 "--enable-ref-frame-mvs=0",
20967 "--obu",
20968 "-o",
20969 "-",
20970 "-",
20971 ]),
20972 &y4m.stdout,
20973 );
20974 assert!(
20975 out.status.success(),
20976 "aomenc refused the fixture: {}",
20977 String::from_utf8_lossy(&out.stderr)
20978 );
20979 let stream = out.stdout;
20980 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
20981 std::fs::write(dump, &stream).expect("dump stream");
20982 }
20983 let before = decode::deblock_hits();
20984 let frames = match decode_stream(&stream) {
20985 Ok(frames) => frames,
20986 Err(e) => {
20987 eprintln!(
20988 "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: {e}"
20989 );
20990 return;
20991 }
20992 };
20993 assert!(
20994 decode::deblock_hits() > before,
20995 "no deblocking edge fired decoding this sequence -- raise cq-level"
20996 );
20997 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
20998 assert_eq!(frames.len(), frame_count);
20999 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21000 // gradients' colors ignore its seed, so this gate encodes fresh
21001 // content every run -- a mismatch here may never reproduce.
21002 // Self-pin the stream before panicking so the failure is
21003 // bisectable (replay: EC_AV1_PIN on scratch_isolate_pinned_mismatch).
21004 let ok = got.y == want.y && got.u == want.u && got.v == want.v;
21005 if !ok {
21006 let pin = std::env::temp_dir().join("ec-av1-deblocking-gate-fail.obu");
21007 let _ = std::fs::write(&pin, &stream);
21008 panic!(
21009 "frame {i} mismatch vs ffmpeg -- stream pinned at {}",
21010 pin.display()
21011 );
21012 }
21013 }
21014 }
21015
21016 /// The decisive cross-frame CDF forwarding test: identical to
21017 /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`]
21018 /// except it drops `--error-resilient=1`, so aomenc codes every inter
21019 /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`)
21020 /// and expects the decoder to resume from the previous frame's *adapted*
21021 /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding,
21022 /// frame 1's very first tile symbol desyncs (an out-of-alphabet
21023 /// partition read); with it, every frame decodes pixel-exact.
21024 #[test]
21025 fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() {
21026 if !have_ffmpeg() {
21027 eprintln!(
21028 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg"
21029 );
21030 return;
21031 }
21032 if !have_aomenc() {
21033 eprintln!(
21034 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}",
21035 aomenc_path().display()
21036 );
21037 return;
21038 }
21039 let (width, height, frame_count) = (64usize, 64usize, 4usize);
21040 // The fixture's content varies run to run (lavfi gradients ignores its
21041 // seed option for the c0..c7 colors -- they default to "random"), so:
21042 // most encodes of this recipe trip one of the decoder's NAMED round-2
21043 // refusals (a reference other than LAST_FRAME, a sub-16 partition --
21044 // genuine coverage gaps, separately documented), and only some produce
21045 // a stream fully inside this decoder's declared support. So: attempt
21046 // several seeds, and the first stream that DECODES must be pixel-exact
21047 // -- that assertion is what guards the forwarded-CDF state (a wrong
21048 // table decodes plausible-but-wrong pixels; the counter-reset bug this
21049 // gate caught did exactly that). Exhausting every attempt on named
21050 // refusals skips loudly, listing them.
21051 let mut refusals = Vec::new();
21052 for attempt in 0..8u32 {
21053 let seed = 42 + attempt;
21054 let source = gradients_source(seed, 64, 64, "duration=0.16:rate=25");
21055 let y4m = Command::new("ffmpeg")
21056 .args([
21057 "-v",
21058 "error",
21059 "-f",
21060 "lavfi",
21061 "-i",
21062 &source,
21063 "-pix_fmt",
21064 "yuv420p",
21065 "-f",
21066 "yuv4mpegpipe",
21067 "-",
21068 ])
21069 .stdin(Stdio::null())
21070 .stdout(Stdio::piped())
21071 .stderr(Stdio::piped())
21072 .output()
21073 .expect("ffmpeg failed to run");
21074 assert!(
21075 y4m.status.success(),
21076 "ffmpeg fixture: {}",
21077 String::from_utf8_lossy(&y4m.stderr)
21078 );
21079 // lane-cdfflake: hard length check on the y4m fixture itself --
21080 // a truncated/racing ffmpeg write would otherwise surface as a
21081 // downstream pixel mismatch indistinguishable from a real decode
21082 // defect. y4m frames are `FRAME\n` (6 bytes) + raw 4:2:0 payload;
21083 // find the header/frame-data boundary at the first `FRAME` marker
21084 // rather than parsing the header fields (duration/rate can move
21085 // the header text length without moving the frame math).
21086 let marker_at = y4m
21087 .stdout
21088 .windows(5)
21089 .position(|w| w == b"FRAME")
21090 .expect("y4m stream missing FRAME marker");
21091 let frame_420_bytes = width * height * 3 / 2;
21092 assert_eq!(
21093 y4m.stdout.len(),
21094 marker_at + frame_count * (6 + frame_420_bytes),
21095 "y4m fixture length mismatch (seed {seed})"
21096 );
21097 let y4m_hash = fnv1a64(&y4m.stdout);
21098 let out = run_with_stdin(
21099 Command::new(aomenc_path()).args([
21100 "--codec=av1",
21101 "--passes=1",
21102 "--end-usage=q",
21103 "--cq-level=55",
21104 "--cpu-used=0",
21105 "--lag-in-frames=0",
21106 "--auto-alt-ref=0",
21107 "--kf-max-dist=1000",
21108 // `--threads=1` (not the default): a multithreaded RD search
21109 // makes aomenc's screen-content-tools heuristic race (seen
21110 // flaky under `cargo test`'s own parallelism -- the same
21111 // fixture, same seed, occasionally sets
21112 // `allow_screen_content_tools`, a round-2 gap unrelated to
21113 // CDF forwarding), so pin it to one thread for a
21114 // deterministic header.
21115 "--threads=1",
21116 "--row-mt=0",
21117 // `--enable-order-hint=0` kills BWDREF/ALTREF entirely (no
21118 // order hints -> no bidirectional distance weighting) and,
21119 // combined with `--auto-alt-ref=0`/`--lag-in-frames=0`
21120 // above, leaves aomenc's RD search only LAST_FRAME/
21121 // LAST2_FRAME/LAST3_FRAME/GOLDEN_FRAME to pick from --
21122 // GOLDEN itself needs no order hint (it is the keyframe's
21123 // fixed slot, not a distance-weighted reference), so this
21124 // does not suppress GOLDEN selection the way the sibling
21125 // CDF-forwarding gate's own comment worried about; it just
21126 // narrows the pool this gate needs GOLDEN to win out of.
21127 "--enable-order-hint=0",
21128 "--enable-warped-motion=0",
21129 "--enable-obmc=0",
21130 "--enable-masked-comp=0",
21131 "--enable-interintra-comp=0",
21132 "--enable-dist-wtd-comp=0",
21133 "--enable-diff-wtd-comp=0",
21134 "--enable-onesided-comp=0",
21135 "--enable-interintra-wedge=0",
21136 "--enable-smooth-interintra=0",
21137 "--enable-rect-partitions=0",
21138 "--enable-ab-partitions=0",
21139 "--enable-1to4-partitions=0",
21140 "--enable-filter-intra=0",
21141 "--enable-smooth-intra=0",
21142 "--enable-paeth-intra=0",
21143 "--enable-directional-intra=0",
21144 "--enable-angle-delta=0",
21145 "--enable-tx-size-search=0",
21146 "--enable-cdef=0",
21147 // Loop restoration is a named refusal (aomenc's RD picks
21148 // Sgrproj on this kind of content) -- off in every recipe
21149 // whose test targets a different surface.
21150 "--enable-restoration=0",
21151 "--max-partition-size=32",
21152 "--enable-palette=0",
21153 "--enable-intrabc=0",
21154 "--enable-cfl-intra=0",
21155 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
21156 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
21157 "--enable-ref-frame-mvs=0",
21158 "--obu",
21159 "-o",
21160 "-",
21161 "-",
21162 ]),
21163 &y4m.stdout,
21164 );
21165 assert!(
21166 out.status.success(),
21167 "aomenc refused the fixture: {}",
21168 String::from_utf8_lossy(&out.stderr)
21169 );
21170 let stream = out.stdout;
21171 let stream_hash = fnv1a64(&stream);
21172 // A named `unsupported` refusal is a documented coverage gap (each
21173 // one carries its own test debt elsewhere), not a forwarding verdict
21174 // -- try the next seed. Any stream that DECODES must be pixel-exact,
21175 // and any non-refusal error is a hard failure.
21176 let frames = match decode_stream(&stream) {
21177 Err(e) => {
21178 let msg = e.to_string();
21179 assert!(
21180 msg.contains("unsupported"),
21181 "cross-frame CDF forwarding failed outright (seed {seed}): {msg}"
21182 );
21183 refusals.push(format!("seed {seed}: {msg}"));
21184 continue;
21185 }
21186 Ok(frames) => frames,
21187 };
21188 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
21189 assert_eq!(frames.len(), frame_count);
21190 // lane-cdfflake: reconstruct ffmpeg's raw reference bytes (the
21191 // three per-frame slices are contiguous chunks of the raw
21192 // `-f rawvideo` output ffmpeg_decode_sequence sliced, so
21193 // concatenating them back is bit-for-bit the same bytes ffmpeg
21194 // actually produced -- no second ffmpeg invocation needed).
21195 let ffmpeg_raw: Vec<u8> = ffmpeg_frames
21196 .iter()
21197 .flat_map(|p| p.y.iter().chain(&p.u).chain(&p.v).map(|&v| v as u8))
21198 .collect();
21199 let ffmpeg_raw_hash = fnv1a64(&ffmpeg_raw);
21200 eprintln!(
21201 "cdfflake attempt seed={seed}: y4m_hash={y4m_hash:016x} \
21202 stream_hash={stream_hash:016x} ffmpeg_raw_hash={ffmpeg_raw_hash:016x}"
21203 );
21204 // lane-av1golden3: pin the exact raw stream on the first mismatch
21205 // so a flaky-looking gate failure becomes a deterministic, static
21206 // fixture to bisect against -- env-gated, no cost on a normal run.
21207 let mismatched = frames
21208 .iter()
21209 .zip(&ffmpeg_frames)
21210 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
21211 if mismatched {
21212 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
21213 std::fs::write(&path, &stream).expect("writing pinned stream");
21214 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
21215 }
21216 // lane-cdfflake: unconditional pin on mismatch -- the aomenc
21217 // stream AND ffmpeg's raw reference bytes, so a flake caught
21218 // under load names the liar (stream bytes differ from a
21219 // clean rerun -> subprocess instability; reference bytes
21220 // differ -> ffmpeg instability; both stable -> real decode
21221 // defect) without relying on the env var being set.
21222 // The pin goes to `fixtures/`, which outlives the session: an
21223 // earlier version wrote to a session scratchpad, so once tmpfs
21224 // reaped it a real mismatch aborted on the write instead of
21225 // reporting itself. A failed write must not mask the assert
21226 // below either, so it warns rather than panicking.
21227 let sp = pin_dir();
21228 let stream_pin = sp.join(format!("cdfflake-stream-seed{seed}.bin"));
21229 let ref_pin = sp.join(format!("cdfflake-ffmpeg-raw-seed{seed}.bin"));
21230 for (path, bytes) in [(&stream_pin, &stream), (&ref_pin, &ffmpeg_raw)] {
21231 if let Err(e) = std::fs::write(path, bytes) {
21232 eprintln!("cdfflake: could not pin to {}: {e}", path.display());
21233 }
21234 }
21235 eprintln!(
21236 "cdfflake MISMATCH seed={seed}: pinned stream + ffmpeg reference to {}",
21237 sp.display()
21238 );
21239 }
21240 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21241 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
21242 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
21243 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
21244 }
21245 return;
21246 }
21247 eprintln!(
21248 "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: every \
21249 attempt hit a named refusal:\n{}",
21250 refusals.join("\n")
21251 );
21252 }
21253
21254 /// lane-av1golden3: reproduces the pinned mismatch bytes captured by
21255 /// `EC_AV1_GATE_DUMP=$SP/golden3-pin.obu` off
21256 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
21257 /// (seed 47, frame 1 U). Deterministic and static -- no aomenc/ffmpeg
21258 /// re-encode involved, only re-decodes the fixed bytes on disk, so it is
21259 /// `#[ignore]`d (the file only exists on this machine's scratchpad) but
21260 /// gives a fast red/green loop for the actual fix.
21261 #[test]
21262 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
21263 fn pinned_golden3_stream_decodes_pixel_exact() {
21264 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
21265 .map(std::path::PathBuf::from)
21266 .unwrap_or_else(|_| pin_dir().join("golden3-pin.obu"));
21267 let Ok(stream) = std::fs::read(&path) else {
21268 eprintln!(
21269 "SKIP pinned_golden3_stream_decodes_pixel_exact: no pinned bytes at {} \
21270 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
21271 path.display()
21272 );
21273 return;
21274 };
21275 if !have_ffmpeg() {
21276 eprintln!("SKIP pinned_golden3_stream_decodes_pixel_exact: no ffmpeg");
21277 return;
21278 }
21279 let frames = decode_stream(&stream).expect("pinned stream must decode");
21280 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
21281 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21282 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
21283 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
21284 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
21285 }
21286 }
21287
21288 /// lane-av1golden4: reproduces the pinned mismatch bytes captured by
21289 /// `EC_AV1_GATE_DUMP=$SP/golden4-pin.obu` off
21290 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
21291 /// (seed 43, frame 3 luma) the round the GOLDEN mask lifted. Deterministic
21292 /// and static -- `#[ignore]`d, run manually.
21293 #[test]
21294 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
21295 fn pinned_golden4_stream_decodes_pixel_exact() {
21296 use crate::decode::non_last_ref_hits;
21297 let path = std::env::var("EC_AV1_GATE_DUMP_PIN")
21298 .map(std::path::PathBuf::from)
21299 .unwrap_or_else(|_| pin_dir().join("golden4-pin.obu"));
21300 let Ok(stream) = std::fs::read(&path) else {
21301 eprintln!(
21302 "SKIP pinned_golden4_stream_decodes_pixel_exact: no pinned bytes at {} \
21303 -- re-capture with EC_AV1_GATE_DUMP off the cdf-forwarding gate",
21304 path.display()
21305 );
21306 return;
21307 };
21308 if !have_ffmpeg() {
21309 eprintln!("SKIP pinned_golden4_stream_decodes_pixel_exact: no ffmpeg");
21310 return;
21311 }
21312 let before = non_last_ref_hits();
21313 let frames = decode_stream(&stream).expect("pinned stream must decode");
21314 eprintln!(
21315 "non_last_ref_hits before={before} after={}",
21316 non_last_ref_hits()
21317 );
21318 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
21319 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21320 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
21321 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
21322 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
21323 }
21324 }
21325
21326 /// lane-av1golden7 round 9: pins the residual GOLDEN_FRAME MC bug found
21327 /// by the forwarding gate once film grain is out of the way (1/20 real
21328 /// aomenc streams, frame 3 luma, apply_grain=false, `non_last_ref_hits`
21329 /// delta=2). `GOLDEN_FRAME` refuses by name until this decodes exact.
21330 #[test]
21331 #[ignore = "reads a pinned fixture path outside the repo; run manually"]
21332 fn pinned_golden7_stream_decodes_pixel_exact() {
21333 use crate::decode::non_last_ref_hits;
21334 let path = concat!(
21335 env!("CARGO_MANIFEST_DIR"),
21336 "/../../fixtures/golden7-forwarding-mismatch.obu"
21337 );
21338 let stream = std::fs::read(path).expect("reading pinned stream");
21339 if !have_ffmpeg() {
21340 eprintln!("SKIP pinned_golden7_stream_decodes_pixel_exact: no ffmpeg");
21341 return;
21342 }
21343 let before = non_last_ref_hits();
21344 let frames = decode_stream(&stream).expect("pinned stream must decode");
21345 eprintln!(
21346 "non_last_ref_hits before={before} after={}",
21347 non_last_ref_hits()
21348 );
21349 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 4);
21350 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21351 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (pinned)");
21352 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (pinned)");
21353 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (pinned)");
21354 }
21355 }
21356
21357 /// lane-av1refs's decisive single-non-LAST-reference gate: identical
21358 /// recipe to
21359 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]
21360 /// except `--enable-order-hint=0` is DROPPED (that flag's own comment on
21361 /// the sibling test names it as exactly what suppresses aomenc's RD from
21362 /// ever picking `GOLDEN_FRAME`) and the sequence runs 8 frames, not 4 --
21363 /// more chances for the RD search to reach past the first GOP's initial
21364 /// key frame. `--auto-alt-ref=0` stays: this decoder only supports
21365 /// `LAST_FRAME`/`GOLDEN_FRAME` so far, and alt-ref/backward references
21366 /// are still a named refusal, not this gate's target. A stream that
21367 /// decodes without firing [`decode::non_last_ref_hits`] is not a
21368 /// coverage win for this round -- SKIP it as a genuine, named miss
21369 /// rather than pass silently on untested ground.
21370 #[test]
21371 fn a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact() {
21372 if !have_ffmpeg() {
21373 eprintln!(
21374 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no ffmpeg"
21375 );
21376 return;
21377 }
21378 if !have_aomenc() {
21379 eprintln!(
21380 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: no aomenc at {}",
21381 aomenc_path().display()
21382 );
21383 return;
21384 }
21385 let (width, height, frame_count) = (64usize, 64usize, 8usize);
21386 let mut refusals = Vec::new();
21387 let mut never_fired = 0u32;
21388 // aomenc's own RD search is nondeterministic run-to-run even at
21389 // `--threads=1` (confirmed live: identical CLI args, identical
21390 // input, two different output byte streams) -- so beyond varying
21391 // the fixture's seed, each attempt is its own independent coin
21392 // flip against every named refusal below. 120 attempts (not 40)
21393 // to give that coin flip enough tries to land on a stream this
21394 // decoder both accepts and that fires GOLDEN_FRAME. `duration=0.32`
21395 // at `rate=25` (not `0.24`) matches every sibling gate's own
21396 // frame-count fixture exactly -- a shorter duration here once
21397 // produced a frame-0 (keyframe, no reference at all) luma mismatch
21398 // against ffmpeg, i.e. a source-frame-count rounding artifact of
21399 // this recipe's own choosing, not a decoder bug.
21400 for attempt in 0..120u32 {
21401 let seed = 42 + attempt % 40;
21402 let source = gradients_source(seed, 64, 64, "duration=0.32:rate=25");
21403 let y4m = Command::new("ffmpeg")
21404 .args([
21405 "-v",
21406 "error",
21407 "-f",
21408 "lavfi",
21409 "-i",
21410 &source,
21411 "-pix_fmt",
21412 "yuv420p",
21413 "-f",
21414 "yuv4mpegpipe",
21415 "-",
21416 ])
21417 .stdin(Stdio::null())
21418 .stdout(Stdio::piped())
21419 .stderr(Stdio::piped())
21420 .output()
21421 .expect("ffmpeg failed to run");
21422 assert!(
21423 y4m.status.success(),
21424 "ffmpeg fixture: {}",
21425 String::from_utf8_lossy(&y4m.stderr)
21426 );
21427 let out = run_with_stdin(
21428 Command::new(aomenc_path()).args([
21429 "--codec=av1",
21430 "--passes=1",
21431 "--end-usage=q",
21432 "--cq-level=55",
21433 "--cpu-used=0",
21434 "--lag-in-frames=0",
21435 "--auto-alt-ref=0",
21436 "--kf-max-dist=1000",
21437 "--threads=1",
21438 "--row-mt=0",
21439 // Narrows the RD search's reference alphabet toward
21440 // LAST_FRAME/GOLDEN_FRAME -- without this, aomenc's RD is
21441 // just as likely to pick LAST2/LAST3/BWDREF/ALTREF2/
21442 // ALTREF (this decoder's already-documented, still-open
21443 // refusals), starving this gate of the one reference it
21444 // targets.
21445 "--max-reference-frames=3",
21446 "--reduced-reference-set=1",
21447 "--enable-warped-motion=0",
21448 "--enable-obmc=0",
21449 "--enable-masked-comp=0",
21450 "--enable-interintra-comp=0",
21451 "--enable-dist-wtd-comp=0",
21452 "--enable-diff-wtd-comp=0",
21453 "--enable-onesided-comp=0",
21454 "--enable-interintra-wedge=0",
21455 "--enable-smooth-interintra=0",
21456 "--enable-rect-partitions=0",
21457 "--enable-ab-partitions=0",
21458 "--enable-1to4-partitions=0",
21459 "--enable-filter-intra=0",
21460 "--enable-smooth-intra=0",
21461 "--enable-paeth-intra=0",
21462 "--enable-directional-intra=0",
21463 "--enable-angle-delta=0",
21464 "--enable-tx-size-search=0",
21465 "--enable-cdef=0",
21466 "--enable-restoration=0",
21467 // `min == max == 32` forces PARTITION_NONE for every
21468 // 32x32 block, not just biases toward it -- with
21469 // `--min-partition-size=16` alone aomenc's exhaustive
21470 // `cpu-used=0` RD search still occasionally read HORZ/
21471 // VERT/SPLIT partitions below 32x32 despite
21472 // `--enable-rect-partitions=0`/`--enable-ab-partitions=0`/
21473 // `--enable-1to4-partitions=0` all being off (two
21474 // separate, already-documented round-2 gaps: "a
21475 // partition below 16x16", "a partition type this encoder
21476 // never writes"), starving this gate's already-narrow
21477 // seed pool. Locking both bounds to 32 removes any
21478 // partition-depth choice from the search entirely, so
21479 // this gate can isolate GOLDEN_FRAME selection alone.
21480 "--max-partition-size=32",
21481 "--min-partition-size=32",
21482 "--enable-palette=0",
21483 "--enable-intrabc=0",
21484 "--enable-cfl-intra=0",
21485 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
21486 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
21487 "--enable-ref-frame-mvs=0",
21488 // `--tune-content=film` was dropped: on this box it
21489 // makes aomenc emit `apply_grain` almost every attempt
21490 // (lane-av1golden8 round 10 measurement, live: 120/120
21491 // real attempts hit a named refusal, 0 ever fired
21492 // GOLDEN_FRAME -- mostly `apply_grain`, dominated by its
21493 // own recipe flag) -- film grain synthesis has its own
21494 // dedicated refusal test and must not starve this gate
21495 // of the GOLDEN_FRAME draws it exists to prove. Default
21496 // content tuning still occasionally flips
21497 // `allow_screen_content_tools` on for this synthetic
21498 // gradient content (a separate, already-documented open
21499 // refusal), which the 120-attempt coin flip below
21500 // tolerates the same way.
21501 "--obu",
21502 "-o",
21503 "-",
21504 "-",
21505 ]),
21506 &y4m.stdout,
21507 );
21508 assert!(
21509 out.status.success(),
21510 "aomenc refused the fixture: {}",
21511 String::from_utf8_lossy(&out.stderr)
21512 );
21513 let stream = out.stdout;
21514 let before = decode::non_last_ref_hits();
21515 let frames = match decode_stream(&stream) {
21516 Err(e) => {
21517 let msg = e.to_string();
21518 assert!(
21519 msg.contains("unsupported"),
21520 "a golden-reference stream failed outright (seed {seed}): {msg}"
21521 );
21522 refusals.push(format!("seed {seed}: {msg}"));
21523 continue;
21524 }
21525 Ok(frames) => frames,
21526 };
21527 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
21528 // is ALWAYS pixel-compared below; the hit counter only decides whether
21529 // the attempt counts toward the firing total.
21530 // This seed's RD search may never have picked GOLDEN_FRAME -- a
21531 // genuine miss, not a refusal, and not a reason to skip the pixels.
21532 let counted = decode::non_last_ref_hits() != before;
21533 if !counted {
21534 never_fired += 1;
21535 }
21536 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
21537 assert_eq!(frames.len(), frame_count);
21538 // Same pin-on-mismatch pattern as the CDF forwarding gate above:
21539 // env-gated, no cost on a normal run.
21540 let mismatched = frames
21541 .iter()
21542 .zip(&ffmpeg_frames)
21543 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
21544 if mismatched {
21545 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
21546 std::fs::write(&path, &stream).expect("writing pinned stream");
21547 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
21548 }
21549 }
21550 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21551 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
21552 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
21553 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
21554 }
21555 if counted {
21556 eprintln!(
21557 "FIRING seed {seed}: non_last_ref_hits advanced by {}",
21558 decode::non_last_ref_hits() - before
21559 );
21560 gate_buckets(
21561 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
21562 1,
21563 never_fired,
21564 refusals.len(),
21565 );
21566 return;
21567 }
21568 }
21569 gate_buckets(
21570 "a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact",
21571 0,
21572 never_fired,
21573 refusals.len(),
21574 );
21575 eprintln!(
21576 "SKIP a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact: \
21577 {never_fired} attempts decoded but never fired GOLDEN_FRAME, and every other \
21578 attempt hit a named refusal:\n{}",
21579 refusals.join("\n")
21580 );
21581 }
21582
21583 /// lane-av1refs's decisive gate for the 5 references widened past
21584 /// `LAST_FRAME`/`GOLDEN_FRAME`: same envelope and pin-on-mismatch
21585 /// pattern as
21586 /// [`a_real_aomenc_inter_sequence_with_a_golden_reference_decodes_pixel_exact`],
21587 /// generalised over `(target_ref, extra_args, frame_count)` so each of
21588 /// `LAST2`/`LAST3`/`BWDREF`/`ALTREF2`/`ALTREF` gets its own attempt pool
21589 /// and its own proof that `decode::ref_hits(target_ref)` -- not just
21590 /// `non_last_ref_hits`, which cannot distinguish one reference from
21591 /// another -- actually advanced. `--max-reference-frames=3
21592 /// --reduced-reference-set=1` (the golden gate's own narrowing) is
21593 /// DROPPED here: both suppress exactly the references this gate needs
21594 /// aomenc's RD to reach.
21595 fn a_real_aomenc_single_ref_gate(
21596 gate_name: &str,
21597 target_ref: i8,
21598 target_ref_name: &str,
21599 extra_args: &[&str],
21600 width: usize,
21601 height: usize,
21602 frame_count: usize,
21603 attempts: u32,
21604 ) {
21605 let _gate_lock = lock_gate_counters();
21606 if !have_ffmpeg() {
21607 eprintln!("SKIP {gate_name}: no ffmpeg");
21608 return;
21609 }
21610 if !have_aomenc() {
21611 eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
21612 return;
21613 }
21614 let mut refusals = Vec::new();
21615 let mut never_fired = 0u32;
21616 for attempt in 0..attempts {
21617 let seed = 42 + attempt % 40;
21618 let duration = frame_count as f64 / 25.0;
21619 let source =
21620 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
21621 let y4m = Command::new("ffmpeg")
21622 .args([
21623 "-v",
21624 "error",
21625 "-f",
21626 "lavfi",
21627 "-i",
21628 &source,
21629 "-pix_fmt",
21630 "yuv420p",
21631 "-f",
21632 "yuv4mpegpipe",
21633 "-",
21634 ])
21635 .stdin(Stdio::null())
21636 .stdout(Stdio::piped())
21637 .stderr(Stdio::piped())
21638 .output()
21639 .expect("ffmpeg failed to run");
21640 assert!(
21641 y4m.status.success(),
21642 "ffmpeg fixture: {}",
21643 String::from_utf8_lossy(&y4m.stderr)
21644 );
21645 let mut args: Vec<&str> = vec![
21646 "--codec=av1",
21647 "--passes=1",
21648 "--end-usage=q",
21649 "--cq-level=55",
21650 "--cpu-used=0",
21651 "--kf-max-dist=1000",
21652 "--threads=1",
21653 "--row-mt=0",
21654 "--enable-warped-motion=0",
21655 "--enable-obmc=0",
21656 "--enable-masked-comp=0",
21657 "--enable-interintra-comp=0",
21658 "--enable-dist-wtd-comp=0",
21659 "--enable-diff-wtd-comp=0",
21660 "--enable-onesided-comp=0",
21661 "--enable-interintra-wedge=0",
21662 "--enable-smooth-interintra=0",
21663 "--enable-rect-partitions=0",
21664 "--enable-ab-partitions=0",
21665 "--enable-1to4-partitions=0",
21666 "--enable-filter-intra=0",
21667 "--enable-smooth-intra=0",
21668 "--enable-paeth-intra=0",
21669 "--enable-directional-intra=0",
21670 "--enable-angle-delta=0",
21671 "--enable-tx-size-search=0",
21672 "--enable-cdef=0",
21673 "--enable-restoration=0",
21674 "--max-partition-size=32",
21675 "--min-partition-size=32",
21676 "--enable-palette=0",
21677 "--enable-intrabc=0",
21678 "--enable-cfl-intra=0",
21679 // use_ref_frame_mvs (temporal MV projection) is unimplemented in
21680 // mvstack; leaving it on silently desyncs symbols on inter frames.
21681 "--enable-ref-frame-mvs=0",
21682 "--obu",
21683 "-o",
21684 "-",
21685 "-",
21686 ];
21687 // extra_args goes right before the trailing "-o", "-", "-" triple.
21688 let tail = args.split_off(args.len() - 3);
21689 args.extend_from_slice(extra_args);
21690 args.extend_from_slice(&tail);
21691 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
21692 assert!(
21693 out.status.success(),
21694 "aomenc refused the fixture: {}",
21695 String::from_utf8_lossy(&out.stderr)
21696 );
21697 let stream = out.stdout;
21698 let before = decode::ref_hits(target_ref);
21699 let frames = match decode_stream(&stream) {
21700 Err(e) => {
21701 let msg = e.to_string();
21702 assert!(
21703 msg.contains("unsupported"),
21704 "{gate_name} failed outright (seed {seed}): {msg}"
21705 );
21706 refusals.push(format!("seed {seed}: {msg}"));
21707 continue;
21708 }
21709 Ok(frames) => frames,
21710 };
21711 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
21712 // is ALWAYS pixel-compared below; the hit counter only decides whether
21713 // the attempt counts toward the firing total.
21714 let counted = decode::ref_hits(target_ref) != before;
21715 if !counted {
21716 never_fired += 1;
21717 }
21718 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
21719 assert_eq!(frames.len(), frame_count);
21720 let mismatched = frames
21721 .iter()
21722 .zip(&ffmpeg_frames)
21723 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
21724 if mismatched {
21725 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
21726 std::fs::write(&path, &stream).expect("writing pinned stream");
21727 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
21728 }
21729 }
21730 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21731 assert_eq!(
21732 got.y, want.y,
21733 "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
21734 );
21735 assert_eq!(
21736 got.u, want.u,
21737 "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
21738 );
21739 assert_eq!(
21740 got.v, want.v,
21741 "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
21742 );
21743 }
21744 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
21745 // stream again, comparing EVERY decode-order frame -- the hidden
21746 // (show_frame == 0) alt-ref frames the ffmpeg compare above
21747 // cannot see, because both sides of it emit shown frames only.
21748 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, gate_name);
21749 eprintln!(
21750 "{gate_name} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
21751 {hidden_n} hidden, all pixel-exact vs the oracle"
21752 );
21753 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
21754 // libaom's temporal alt-ref filter absorbs this recipe's hidden
21755 // frames, so the compare above is vacuous -- re-encode the same
21756 // fixture with --arnr-maxframes=0 and compare THOSE.
21757 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(gate_name, &y4m.stdout, &args) {
21758 eprintln!(
21759 "{gate_name} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
21760 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
21761 );
21762 }
21763 if counted {
21764 eprintln!(
21765 "{gate_name} FIRING seed {seed}: {target_ref_name} hits advanced by {}",
21766 decode::ref_hits(target_ref) - before
21767 );
21768 gate_buckets(gate_name, 1, never_fired, refusals.len());
21769 return;
21770 }
21771 }
21772 gate_buckets(gate_name, 0, never_fired, refusals.len());
21773 eprintln!(
21774 "SKIP {gate_name}: {never_fired} attempts decoded but never fired {target_ref_name}, \
21775 and every other attempt hit a named refusal:\n{}",
21776 refusals.join("\n")
21777 );
21778 }
21779
21780 /// lane-av1comp: proves `reference_select`/`comp_mode` are actually read
21781 /// off a real bitstream rather than only unit-tested in isolation --
21782 /// `--auto-alt-ref=1 --lag-in-frames=16` gives aomenc a backward
21783 /// reference to pick `COMPOUND_REFERENCE` with, `--enable-order-hint=1`
21784 /// is required for it to ever consider compound at all. Three
21785 /// acceptable outcomes: (a) a stream where `reference_select` never
21786 /// actually drove a block to `COMPOUND_REFERENCE` decodes bit-exact end
21787 /// to end (proving the per-block `comp_mode` read did not desync the
21788 /// single-ref blocks around it); (b) a stream that does fire compound
21789 /// is refused by name with [`decode::comp_mode_hits`] having advanced
21790 /// (proving `comp_mode`/`read_compound_ref_frames` consumed the right
21791 /// symbols before refusing, rather than desyncing and refusing for an
21792 /// unrelated reason) -- masked/wedge compound (`comp_group_idx == 1`)
21793 /// and a partition below 16x16 (a real, separately tracked capability
21794 /// gap) are the two refusal arms this can still legitimately name; (c)
21795 /// r13 wired plain `COMPOUND_AVERAGE` MC for real, so as of r15 a
21796 /// stream that fires compound may also decode fully -- accepted only
21797 /// when every output frame is pixel-exact against ffmpeg.
21798 #[test]
21799 fn a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly() {
21800 const NAME: &str = "a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly";
21801 let _gate_lock = lock_gate_counters();
21802 if !have_ffmpeg() {
21803 eprintln!("SKIP {NAME}: no ffmpeg");
21804 return;
21805 }
21806 if !have_aomenc() {
21807 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
21808 return;
21809 }
21810 let (width, height, frame_count) = (64usize, 64usize, 20usize);
21811 let mut refusals = Vec::new();
21812 let mut never_fired = 0u32;
21813 for attempt in 0..60u32 {
21814 let seed = 42 + attempt % 40;
21815 let duration = frame_count as f64 / 25.0;
21816 let source =
21817 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
21818 let y4m = Command::new("ffmpeg")
21819 .args([
21820 "-v",
21821 "error",
21822 "-f",
21823 "lavfi",
21824 "-i",
21825 &source,
21826 "-pix_fmt",
21827 "yuv420p",
21828 "-f",
21829 "yuv4mpegpipe",
21830 "-",
21831 ])
21832 .stdin(Stdio::null())
21833 .stdout(Stdio::piped())
21834 .stderr(Stdio::piped())
21835 .output()
21836 .expect("ffmpeg failed to run");
21837 assert!(
21838 y4m.status.success(),
21839 "ffmpeg fixture: {}",
21840 String::from_utf8_lossy(&y4m.stderr)
21841 );
21842 let args: Vec<&str> = vec![
21843 "--codec=av1",
21844 "--passes=1",
21845 "--end-usage=q",
21846 "--cq-level=45",
21847 "--cpu-used=0",
21848 "--kf-max-dist=1000",
21849 "--threads=1",
21850 "--row-mt=0",
21851 "--auto-alt-ref=1",
21852 "--lag-in-frames=16",
21853 "--enable-order-hint=1",
21854 "--enable-warped-motion=0",
21855 "--enable-obmc=0",
21856 "--enable-masked-comp=0",
21857 "--enable-interintra-comp=0",
21858 "--enable-onesided-comp=0",
21859 "--enable-interintra-wedge=0",
21860 "--enable-smooth-interintra=0",
21861 "--enable-rect-partitions=0",
21862 "--enable-ab-partitions=0",
21863 "--enable-1to4-partitions=0",
21864 "--enable-filter-intra=0",
21865 "--enable-smooth-intra=0",
21866 "--enable-paeth-intra=0",
21867 "--enable-directional-intra=0",
21868 "--enable-angle-delta=0",
21869 "--enable-tx-size-search=0",
21870 "--enable-cdef=0",
21871 "--enable-restoration=0",
21872 "--max-partition-size=32",
21873 "--min-partition-size=32",
21874 "--enable-palette=0",
21875 "--enable-intrabc=0",
21876 "--enable-cfl-intra=0",
21877 "--enable-ref-frame-mvs=0",
21878 "--obu",
21879 "-o",
21880 "-",
21881 "-",
21882 ];
21883 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
21884 assert!(
21885 out.status.success(),
21886 "aomenc refused the fixture: {}",
21887 String::from_utf8_lossy(&out.stderr)
21888 );
21889 let stream = out.stdout;
21890 let before = decode::comp_mode_hits();
21891 match decode_stream(&stream) {
21892 Err(e) => {
21893 let msg = e.to_string();
21894 let fired = decode::comp_mode_hits() > before;
21895 assert!(
21896 msg.contains("unsupported"),
21897 "{NAME} failed outright (seed {seed}): {msg}"
21898 );
21899 if fired {
21900 // `comp_mode` firing does not stop the block walk --
21901 // a later, unrelated block in the same tile can
21902 // still hit any other named refusal this decoder
21903 // carries. A partition below 16x16 is a real, open
21904 // capability gap tracked on its own (not a
21905 // COMPOUND_REFERENCE defect); accept it here too
21906 // rather than fail a compound-specific gate on a
21907 // partition-search coincidence. lane-av1blend r7:
21908 // re-swept the wide gate with the plain-average
21909 // blend unmasked (r6/r7's ref_ctx fix alone) and it
21910 // still mismatches on real streams beyond that one
21911 // bug -- re-masked comp_group_idx == 0 too, so this
21912 // stays a legal named refusal.
21913 assert!(
21914 msg.contains("COMPOUND_REFERENCE") || msg.contains("a partition"),
21915 "{NAME}: comp_mode fired (seed {seed}) but the refusal \
21916 was for something else: {msg}"
21917 );
21918 let advanced = decode::comp_mode_hits() - before;
21919 eprintln!(
21920 "{NAME} FIRING seed {seed}: comp_mode hits advanced by \
21921 {advanced}, refused by name as expected: {msg}"
21922 );
21923 return;
21924 }
21925 refusals.push(format!("seed {seed}: {msg}"));
21926 continue;
21927 }
21928 Ok(frames) => {
21929 // class [[gate-skips-on-its-own-failure]]: a decode that
21930 // succeeded is ALWAYS pixel-compared below; the hit counter
21931 // only decides whether the attempt counts as firing.
21932 let counted = decode::comp_mode_hits() != before;
21933 if !counted {
21934 never_fired += 1;
21935 }
21936 // Outcome (c): plain COMPOUND_AVERAGE decoded fully --
21937 // non-negotiable pixel exactness, no tolerance.
21938 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
21939 assert_eq!(frames.len(), frame_count);
21940 let mismatched = frames
21941 .iter()
21942 .zip(&ffmpeg_frames)
21943 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
21944 if mismatched {
21945 let pin =
21946 std::env::temp_dir().join("ec-av1-reference-select-gate-fail.obu");
21947 let _ = std::fs::write(&pin, &stream);
21948 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
21949 std::fs::write(&path, &stream).expect("writing pinned stream");
21950 eprintln!(
21951 "EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"
21952 );
21953 }
21954 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21955 assert_eq!(
21956 got.y,
21957 want.y,
21958 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
21959 pin.display()
21960 );
21961 assert_eq!(
21962 got.u,
21963 want.u,
21964 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
21965 pin.display()
21966 );
21967 assert_eq!(
21968 got.v,
21969 want.v,
21970 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
21971 pin.display()
21972 );
21973 }
21974 } else {
21975 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21976 assert_eq!(
21977 got.y, want.y,
21978 "{NAME} frame {i} luma vs ffmpeg (seed {seed})"
21979 );
21980 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
21981 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
21982 }
21983 }
21984 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
21985 // stream again, comparing EVERY decode-order frame -- the hidden
21986 // (show_frame == 0) alt-ref frames the ffmpeg compare above
21987 // cannot see, because both sides of it emit shown frames only.
21988 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
21989 eprintln!(
21990 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
21991 {hidden_n} hidden, all pixel-exact vs the oracle"
21992 );
21993 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
21994 // libaom's temporal alt-ref filter absorbs this recipe's hidden
21995 // frames, so the compare above is vacuous -- re-encode the same
21996 // fixture with --arnr-maxframes=0 and compare THOSE.
21997 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args)
21998 {
21999 eprintln!(
22000 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
22001 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
22002 );
22003 }
22004 if counted {
22005 eprintln!(
22006 "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \
22007 fully and pixel-exact",
22008 decode::comp_mode_hits() - before
22009 );
22010 gate_buckets(NAME, 1, never_fired, refusals.len());
22011 return;
22012 }
22013 }
22014 }
22015 }
22016 gate_buckets(NAME, 0, never_fired, refusals.len());
22017 eprintln!(
22018 "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \
22019 block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \
22020 reached comp_mode:\n{}",
22021 refusals.join("\n")
22022 );
22023 }
22024
22025 /// lane-av1comp round 14's decisive gate for `skip_mode`: same
22026 /// pin-on-mismatch pattern as [`a_real_aomenc_single_ref_gate`], proving
22027 /// [`decode::skip_mode_hits`] actually advanced (a real block picked
22028 /// `skip_mode`, not just that the frame header bit was set) and that the
22029 /// resulting forced-compound `NEAREST_NEARESTMV` decode is still
22030 /// pixel-exact against ffmpeg. `--auto-alt-ref=1 --lag-in-frames=16
22031 /// --enable-fwd-kf=0` (backward references) plus
22032 /// `--enable-ref-frame-mvs=0` (unimplemented temporal MV projection,
22033 /// same as every other gate here) is aomenc's own requirement for
22034 /// `skip_mode_present` to ever be considered at all (spec 5.9.22 needs
22035 /// both a forward and a backward reference candidate).
22036 #[test]
22037 fn a_real_aomenc_stream_with_compound_references_decodes_pixel_exact() {
22038 const NAME: &str = "a_real_aomenc_stream_with_compound_references_decodes_pixel_exact";
22039 let _gate_lock = lock_gate_counters();
22040 if !have_ffmpeg() {
22041 eprintln!("SKIP {NAME}: no ffmpeg");
22042 return;
22043 }
22044 if !have_aomenc() {
22045 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
22046 return;
22047 }
22048 let (width, height, frame_count) = (64usize, 64usize, 24usize);
22049 let mut refusals = Vec::new();
22050 let mut never_fired = 0u32;
22051 for attempt in 0..80u32 {
22052 let seed = 42 + attempt % 40;
22053 let duration = frame_count as f64 / 25.0;
22054 let source =
22055 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
22056 let y4m = Command::new("ffmpeg")
22057 .args([
22058 "-v",
22059 "error",
22060 "-f",
22061 "lavfi",
22062 "-i",
22063 &source,
22064 "-pix_fmt",
22065 "yuv420p",
22066 "-f",
22067 "yuv4mpegpipe",
22068 "-",
22069 ])
22070 .stdin(Stdio::null())
22071 .stdout(Stdio::piped())
22072 .stderr(Stdio::piped())
22073 .output()
22074 .expect("ffmpeg failed to run");
22075 assert!(
22076 y4m.status.success(),
22077 "ffmpeg fixture: {}",
22078 String::from_utf8_lossy(&y4m.stderr)
22079 );
22080 let args: Vec<&str> = vec![
22081 "--codec=av1",
22082 "--passes=1",
22083 "--end-usage=q",
22084 "--cq-level=45",
22085 "--cpu-used=0",
22086 "--kf-max-dist=1000",
22087 "--threads=1",
22088 "--row-mt=0",
22089 "--auto-alt-ref=1",
22090 "--lag-in-frames=16",
22091 "--enable-fwd-kf=0",
22092 "--enable-order-hint=1",
22093 "--enable-warped-motion=0",
22094 "--enable-obmc=0",
22095 "--enable-masked-comp=0",
22096 "--enable-interintra-comp=0",
22097 "--enable-onesided-comp=0",
22098 "--enable-interintra-wedge=0",
22099 "--enable-smooth-interintra=0",
22100 "--enable-rect-partitions=0",
22101 "--enable-ab-partitions=0",
22102 "--enable-1to4-partitions=0",
22103 "--enable-filter-intra=0",
22104 "--enable-smooth-intra=0",
22105 "--enable-paeth-intra=0",
22106 "--enable-directional-intra=0",
22107 "--enable-angle-delta=0",
22108 "--enable-tx-size-search=0",
22109 "--enable-cdef=0",
22110 "--enable-restoration=0",
22111 "--max-partition-size=32",
22112 "--min-partition-size=32",
22113 "--enable-palette=0",
22114 "--enable-intrabc=0",
22115 "--enable-cfl-intra=0",
22116 "--enable-ref-frame-mvs=0",
22117 "--obu",
22118 "-o",
22119 "-",
22120 "-",
22121 ];
22122 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
22123 assert!(
22124 out.status.success(),
22125 "aomenc refused the fixture: {}",
22126 String::from_utf8_lossy(&out.stderr)
22127 );
22128 let stream = out.stdout;
22129 let before = decode::skip_mode_hits();
22130 let frames = match decode_stream(&stream) {
22131 Err(e) => {
22132 let msg = e.to_string();
22133 assert!(
22134 msg.contains("unsupported"),
22135 "{NAME} failed outright (seed {seed}): {msg}"
22136 );
22137 refusals.push(format!("seed {seed}: {msg}"));
22138 continue;
22139 }
22140 Ok(frames) => frames,
22141 };
22142 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
22143 // is ALWAYS pixel-compared below; the hit counter only decides whether
22144 // the attempt counts toward the firing total.
22145 let counted = decode::skip_mode_hits() != before;
22146 if !counted {
22147 never_fired += 1;
22148 }
22149 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
22150 assert_eq!(frames.len(), frame_count);
22151 let mismatched = frames
22152 .iter()
22153 .zip(&ffmpeg_frames)
22154 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
22155 if mismatched {
22156 let pin = std::env::temp_dir().join("ec-av1-compound-refs-gate-fail.obu");
22157 let _ = std::fs::write(&pin, &stream);
22158 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
22159 std::fs::write(&path, &stream).expect("writing pinned stream");
22160 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
22161 }
22162 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
22163 assert_eq!(
22164 got.y,
22165 want.y,
22166 "{NAME} frame {i} luma vs ffmpeg (seed {seed}) -- stream pinned at {}",
22167 pin.display()
22168 );
22169 assert_eq!(
22170 got.u,
22171 want.u,
22172 "{NAME} frame {i} U vs ffmpeg (seed {seed}) -- stream pinned at {}",
22173 pin.display()
22174 );
22175 assert_eq!(
22176 got.v,
22177 want.v,
22178 "{NAME} frame {i} V vs ffmpeg (seed {seed}) -- stream pinned at {}",
22179 pin.display()
22180 );
22181 }
22182 }
22183 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
22184 // stream again, comparing EVERY decode-order frame -- the hidden
22185 // (show_frame == 0) alt-ref frames the ffmpeg compare above
22186 // cannot see, because both sides of it emit shown frames only.
22187 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
22188 eprintln!(
22189 "{NAME} HIDDEN: seed {seed}: {hidden_total} decode-order frames, \
22190 {hidden_n} hidden, all pixel-exact vs the oracle"
22191 );
22192 // lane-hidden r2 SECOND ARM (the recipe above is untouched):
22193 // libaom's temporal alt-ref filter absorbs this recipe's hidden
22194 // frames, so the compare above is vacuous -- re-encode the same
22195 // fixture with --arnr-maxframes=0 and compare THOSE.
22196 if let Some((arm_total, arm_hidden)) = hidden_arnr_arm(NAME, &y4m.stdout, &args) {
22197 eprintln!(
22198 "{NAME} HIDDEN-ARM(--arnr-maxframes=0): seed {seed}: {arm_total} \
22199 decode-order frames, {arm_hidden} hidden, all pixel-exact vs the oracle"
22200 );
22201 }
22202 if counted {
22203 eprintln!(
22204 "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}",
22205 decode::skip_mode_hits() - before
22206 );
22207 gate_buckets(NAME, 1, never_fired, refusals.len());
22208 return;
22209 }
22210 }
22211 gate_buckets(NAME, 0, never_fired, refusals.len());
22212 eprintln!(
22213 "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \
22214 other attempt hit a named refusal:\n{}",
22215 refusals.join("\n")
22216 );
22217 }
22218
22219 /// lane-motionmode round 1: `--enable-obmc=1 --enable-warped-motion=0`
22220 /// on the base recipe (`--auto-alt-ref=1 --lag-in-frames=16
22221 /// --enable-fwd-kf=0 --enable-ref-frame-mvs=0`) -- pixel-exact against
22222 /// ffmpeg, gated on [`decode::obmc_hits`] actually advancing (a real
22223 /// block picked `OBMC_CAUSAL`, not just that the header bit was set).
22224 /// Structure copied from
22225 /// `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`:
22226 /// a seed sweep with a named-refusal escape hatch and an
22227 /// `EC_AV1_GATE_DUMP` pin on mismatch.
22228 #[test]
22229 fn a_real_aomenc_stream_with_obmc_decodes_pixel_exact() {
22230 const NAME: &str = "a_real_aomenc_stream_with_obmc_decodes_pixel_exact";
22231 let _gate_lock = lock_gate_counters();
22232 if !have_ffmpeg() {
22233 eprintln!("SKIP {NAME}: no ffmpeg");
22234 return;
22235 }
22236 if !have_aomenc() {
22237 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
22238 return;
22239 }
22240 let (width, height, frame_count) = (64usize, 64usize, 24usize);
22241 let mut refusals = Vec::new();
22242 let mut never_fired = 0u32;
22243 for attempt in 0..80u32 {
22244 let seed = 42 + attempt % 40;
22245 let duration = frame_count as f64 / 25.0;
22246 let source =
22247 gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
22248 let y4m = Command::new("ffmpeg")
22249 .args([
22250 "-v",
22251 "error",
22252 "-f",
22253 "lavfi",
22254 "-i",
22255 &source,
22256 "-pix_fmt",
22257 "yuv420p",
22258 "-f",
22259 "yuv4mpegpipe",
22260 "-",
22261 ])
22262 .stdin(Stdio::null())
22263 .stdout(Stdio::piped())
22264 .stderr(Stdio::piped())
22265 .output()
22266 .expect("ffmpeg failed to run");
22267 assert!(
22268 y4m.status.success(),
22269 "ffmpeg fixture: {}",
22270 String::from_utf8_lossy(&y4m.stderr)
22271 );
22272 let args: Vec<&str> = vec![
22273 "--codec=av1",
22274 "--passes=1",
22275 "--end-usage=q",
22276 "--cq-level=45",
22277 "--cpu-used=0",
22278 "--kf-max-dist=1000",
22279 "--threads=1",
22280 "--row-mt=0",
22281 "--auto-alt-ref=1",
22282 "--lag-in-frames=16",
22283 "--enable-fwd-kf=0",
22284 "--enable-order-hint=1",
22285 "--enable-warped-motion=0",
22286 "--enable-obmc=1",
22287 "--enable-masked-comp=0",
22288 "--enable-interintra-comp=0",
22289 "--enable-onesided-comp=0",
22290 "--enable-interintra-wedge=0",
22291 "--enable-smooth-interintra=0",
22292 "--enable-rect-partitions=0",
22293 "--enable-ab-partitions=0",
22294 "--enable-1to4-partitions=0",
22295 "--enable-filter-intra=0",
22296 "--enable-smooth-intra=0",
22297 "--enable-paeth-intra=0",
22298 "--enable-directional-intra=0",
22299 "--enable-angle-delta=0",
22300 "--enable-tx-size-search=0",
22301 "--enable-cdef=0",
22302 "--enable-restoration=0",
22303 "--max-partition-size=32",
22304 "--min-partition-size=32",
22305 "--enable-palette=0",
22306 "--enable-intrabc=0",
22307 "--enable-cfl-intra=0",
22308 "--enable-ref-frame-mvs=0",
22309 "--obu",
22310 "-o",
22311 "-",
22312 "-",
22313 ];
22314 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
22315 assert!(
22316 out.status.success(),
22317 "aomenc refused the fixture: {}",
22318 String::from_utf8_lossy(&out.stderr)
22319 );
22320 let stream = out.stdout;
22321 let before = decode::obmc_hits();
22322 let frames = match decode_stream(&stream) {
22323 Err(e) => {
22324 let msg = e.to_string();
22325 assert!(
22326 msg.contains("unsupported"),
22327 "{NAME} failed outright (seed {seed}): {msg}"
22328 );
22329 refusals.push(format!("seed {seed}: {msg}"));
22330 continue;
22331 }
22332 Ok(frames) => frames,
22333 };
22334 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
22335 // is ALWAYS pixel-compared below; the hit counter only decides whether
22336 // the attempt counts toward the firing total.
22337 let counted = decode::obmc_hits() != before;
22338 if !counted {
22339 never_fired += 1;
22340 }
22341 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
22342 assert_eq!(frames.len(), frame_count);
22343 let mismatched = frames
22344 .iter()
22345 .zip(&ffmpeg_frames)
22346 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
22347 if mismatched {
22348 if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
22349 std::fs::write(&path, &stream).expect("writing pinned stream");
22350 eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
22351 }
22352 }
22353 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
22354 assert_eq!(
22355 got.y, want.y,
22356 "{NAME} frame {i} luma vs ffmpeg (seed {seed})"
22357 );
22358 assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
22359 assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
22360 }
22361 // lane-hidden r2 (class gate-blind-to-hidden-frames): the same
22362 // stream again, comparing EVERY decode-order frame -- the hidden
22363 // (show_frame == 0) alt-ref frames the ffmpeg compare above
22364 // cannot see, because both sides of it emit shown frames only.
22365 let (hidden_total, hidden_n) = decode_all_frames_vs_oracle(&stream, NAME);
22366 eprint

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