forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.8 MiB052d1d3Tahinli2 months ago3627 commits

stream.rs22280 lines, 2.3 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/// lane-av1chromarect: 128-root intra-BC HORZ/VERT strips whose chroma plane
144/// block was sized `bw >> ss_x` by `bh >> ss_y` rather than the hardcoded
145/// 4:2:0 halving -- i.e. the 4:4:4 (and 4:4:0) cells, where
146/// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h:1372) applies no
147/// halving of its own. At 4:2:0 the two forms are the same arithmetic, so a
148/// `>= 1` witness can only come from a stream that is not 4:2:0. EXCLUSIVE to
149/// `decode_intrabc_owned_rect`: no other caller sizes a 128-root intra-BC
150/// strip's chroma plane block.
151pub fn ibc_owned_rect_chroma_footprint_444_hits() -> usize {
152 crate::decode::ibc_owned_rect_chroma_footprint_444_hits()
153}
154
155/// Gate-side reset for the lane-av1chromarect counter above.
156pub fn reset_ibc_owned_rect_chroma_footprint_444_hits() {
157 crate::decode::reset_ibc_owned_rect_chroma_footprint_444_hits()
158}
159
160/// lane-av1chromadc: chroma units of a skipped block whose intra-BC / UV
161/// palette override had to be windowed to the unit's own extent -- `cn_cols *
162/// cn_rows > 1`, which at 4:2:0 never happens and at 4:4:4 is every block of
163/// 64 and above. Counts UNITS. EXCLUSIVE to `decode_block`'s skipped square
164/// block chroma walk.
165pub fn skip_chroma_override_window_hits() -> usize {
166 crate::decode::skip_chroma_override_window_hits()
167}
168
169/// Gate-side reset for the lane-av1chromadc counter above.
170pub fn reset_skip_chroma_override_window_hits() {
171 crate::decode::reset_skip_chroma_override_window_hits()
172}
173
174/// lane-av1rectreach: the `chroma_tiled` walk's per-unit reach and grid-shape
175/// counters, as `(unit_reach_differs_from_block, 2x1 units, 1x2 units, other
176/// multi-unit units)`. See [`crate::decode::rect_tiled_chroma_grid_hits`].
177pub fn rect_tiled_chroma_grid_hits() -> (usize, usize, usize, usize) {
178 crate::decode::rect_tiled_chroma_grid_hits()
179}
180
181/// Gate-side reset for the lane-av1rectreach counters above.
182pub fn reset_rect_tiled_chroma_grid_hits() {
183 crate::decode::reset_rect_tiled_chroma_grid_hits()
184}
185
186/// `(y, uv)` palette blocks RECONSTRUCTED inside an inter frame (lane-t900
187/// r22) -- the counter a screen-content witness gate reads to prove it
188/// exercises the inter-frame palette path, not the key frame's.
189pub fn intra_in_inter_palette_hits() -> (usize, usize) {
190 crate::decode::intra_in_inter_palette_hits()
191}
192
193/// `(y, uv)` palette blocks reconstructed on an 8x8 LEAF inside an inter
194/// frame (lane-t900 r23) -- the site-specific half of
195/// [`intra_in_inter_palette_hits`], which a >=16 block also moves.
196pub fn inter8_palette_hits() -> (usize, usize) {
197 crate::decode::inter8_palette_hits()
198}
199
200/// lane-rect64port r1: coded 64-level HORZ/VERT intra strips whose luma
201/// transform unit is the un-split TX_64X32 (orient 0) / TX_32X64 (orient 1).
202pub fn rect64_corner_tu_hits(orient: usize) -> usize {
203 crate::decode::rect64_corner_tu_hits(orient)
204}
205
206/// lane-inter16ab r4: RECTANGULAR var-tx leaves with a 4-px axis, `[8x4, 4x8]`
207/// -- what `sub_tx_size_map[TX_16X4] == TX_8X4` produces when a 16x16-level
208/// 1:4 inter strip splits its transform.
209pub fn vartx_rect_leaf4_hits() -> [usize; 2] {
210 crate::decode::vartx_rect_leaf4_hits()
211}
212
213/// lane-inter16ab r5: COMPOUND_WEDGE / wedge-INTERINTRA blocks that used a
214/// RECTANGULAR wedge codebook row, per shape (`RECT_WEDGE_SHAPES` order:
215/// 8x16, 16x8, 16x32, 32x16, 8x32, 32x8).
216pub fn rect_wedge_hits() -> [usize; 6] {
217 crate::decode::rect_wedge_hits()
218}
219
220/// lane-inter16ab r5: the wedge-interintra half of [`rect_wedge_hits`].
221pub fn rect_wii_hits() -> [usize; 6] {
222 crate::decode::rect_wii_hits()
223}
224
225/// lane-sb128c r7: the 128 root's rect arms -- (gathered edge HORZ, gathered
226/// edge VERT, inter 128x64 blocks, inter 64x128 blocks).
227pub fn sb128_rect_counters() -> (usize, usize, usize, usize) {
228 (
229 crate::decode::part128_edge_horz_hits(),
230 crate::decode::part128_edge_vert_hits(),
231 crate::decode::inter_sb128_horz_hits(),
232 crate::decode::inter_sb128_vert_hits(),
233 )
234}
235
236/// lane-av1-ibcrect: the 128 root's interior partition arms plus the key-frame
237/// intra 128-axis blocks -- (split, none, horz, vert, ab[4], intra_horz,
238/// intra_vert). Non-zero horz/vert mean a stream carried real PARTITION_HORZ/
239/// VERT at the 128 root, so an intrabc-rect hunt can tell "the partition was
240/// never chosen" from "chosen and decoded intra (or refused)".
241pub fn part128_census() -> (usize, usize, usize, usize, [usize; 4], usize, usize) {
242 (
243 crate::decode::part128_split_hits(),
244 crate::decode::part128_none_hits(),
245 crate::decode::part128_horz_hits(),
246 crate::decode::part128_vert_hits(),
247 crate::decode::part128_ab_hits(),
248 crate::decode::intra_sb128_hits().0,
249 crate::decode::intra_sb128_hits().1,
250 )
251}
252
253/// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip whose
254/// reconstruction ([`crate::decode::decode_intrabc_128rect`]) ran -- the
255/// engagement counter the sb128 intrabc-rect gate asserts on.
256pub fn intrabc_128rect_hits() -> usize {
257 crate::decode::intrabc_128rect_hits()
258}
259
260/// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc strip's
261/// mu-chunk walk read, one per `read_inter_plane` chroma call. At 4:2:2 a
262/// 64x64 mu chunk's chroma plane block is 32x64 and holds TWO STACKED
263/// TX_32X32 units per plane; the square-cut walk this gate witnesses read
264/// one. Measured on the pinned witness: 8 before, 48 after.
265pub fn intrabc_128rect_chroma_chunk_hits() -> usize {
266 crate::decode::intrabc_128rect_chroma_chunk_hits()
267}
268
269/// lane-av1-ibc128chunk: the 128-root intrabc strip's per-axis chroma chunk
270/// extents as `(64 >> ss_x) << 8 | (64 >> ss_y)` on the last chunk walked --
271/// 32|32 at 4:2:0, 32|64 at 4:2:2, 64|64 at 4:4:4.
272pub fn intrabc_128rect_chunk_shape() -> usize {
273 crate::decode::intrabc_128rect_chunk_shape()
274}
275
276/// Blocks reconstructed with intra block copy at an 8x8 LEAF specifically
277/// (lane-kf900 r7's shape); [`crate::decode::intrabc_hits`] counts every shape.
278pub fn leaf8_intrabc_hits() -> usize {
279 crate::decode::leaf8_intrabc_hits()
280}
281
282/// Blocks whose `use_intrabc` symbol came out 1 and took the DV path, at ANY
283/// shape -- the engagement counter the intrabc gates assert on. It counts
284/// "read a `use_intrabc` DV", not "reconstructed": a block the rect-strip
285/// reader REFUSES for an unported shape bumps it too (the symbol and the DV
286/// are parsed before the refusal). [`leaf8_intrabc_hits`] is its 8x8-leaf
287/// subset.
288pub fn intrabc_hits() -> usize {
289 crate::decode::intrabc_hits()
290}
291
292/// lane-av1txbands: sub-8x8 group chroma-reference leaves that USED intrabc and
293/// were SKIPPED -- the route that armed [`crate::decode::intrabc_hits`]'s chroma
294/// transform slot and then read no chroma coefficient. A non-zero value is what
295/// makes the disarm at that route load-bearing on a real stream.
296pub fn skipped_intrabc_chroma_arm_hits() -> usize {
297 crate::decode::skipped_intrabc_chroma_arm_hits()
298}
299
300/// lane-sb128c r8: the 128 root's INTRA (key-frame) rect arm -- (128x64
301/// blocks, 64x128 blocks, blocks per resolved intra `tx_depth` 0/1/2).
302pub fn intra_sb128_counters() -> (usize, usize, [usize; 3]) {
303 crate::decode::intra_sb128_hits()
304}
305
306/// lane-inter128intra r1: the 128 root's HORZ/VERT half coded INTRA inside an
307/// INTER frame -- (128x64 blocks, 64x128 blocks).
308pub fn intra128_in_inter_counters() -> [usize; 2] {
309 crate::decode::intra128_in_inter_hits()
310}
311
312/// lane-lossless128: intra 128-axis blocks decoded on a LOSSLESS frame, where
313/// every plane is a TX_4X4 unit. The engagement counter for
314/// `a_lossless_sb128_rect_intra_block_decodes_sample_exact`.
315pub fn intra128_lossless_counters() -> usize {
316 crate::decode::intra128_lossless_hits()
317}
318
319/// lane-av1-128rectspan: chroma transform units re-stamped by
320/// `decode_block_128rect`'s end-of-block replay, and how many of those
321/// replays stamped a height that was not the unit's own (the 4:2:2 signature
322/// -- zero on every stream this decoder admits, since 4:2:2 is refused by
323/// name at the sequence header).
324pub fn sb128rect_chroma_replay_counters() -> (usize, usize) {
325 crate::decode::sb128rect_chroma_replay_hits()
326}
327
328/// lane-sb128c r9: the four AB shapes at the 128 root, in `PARTITION_HORZ_A`,
329/// `_HORZ_B`, `_VERT_A`, `_VERT_B` order (key and inter tile paths share the
330/// counter -- it is bumped where the root symbol resolves).
331pub fn sb128_ab_counters() -> [usize; 4] {
332 crate::decode::part128_ab_hits()
333}
334
335/// lane-obmcrec r1: OBMC neighbours taken from the second half of a 1:4-strip
336/// chroma pair -- the shape whose filter record the r1 fix re-sourced.
337pub fn obmc_pair_filter_hits() -> usize {
338 crate::decode::obmc_pair_filter_hits()
339}
340
341/// Gate counters for the 4x32/32x4 rectangular strips: `(horz, vert, coeff)` hits.
342pub fn rect4_32_counters() -> (usize, usize, usize) {
343 (
344 crate::decode::rect4_32_horz_hits(),
345 crate::decode::rect4_32_vert_hits(),
346 crate::decode::rect4_coeff_hits(),
347 )
348}
349
350/// lane-inter4 r4: rectangular inter transform units coded whole, rect
351/// var-tx trees that split, and OBMC blends run on a 16x8/8x16 leaf -- the
352/// three counters a recipe sweep needs to see from outside the crate.
353pub fn rect_inter_tu_counters() -> (usize, usize, usize) {
354 (
355 crate::decode::rect_inter_tu_hits(),
356 crate::decode::rect_inter_txsplit_hits(),
357 crate::decode::obmc_rect_leaf_hits(),
358 )
359}
360
361/// Decode every frame in a raw AV1 OBU stream, in coding order.
362///
363/// A key frame becomes the reference for the inter frames that follow it,
364/// until the next key frame resets the DPB — the same single-slot chain
365/// [`crate::encode::encode_sequence`] threads on the write side. Only a
366/// `Frame` OBU (an uncompressed header and its tile group in one OBU, which
367/// is all this crate's encoder ever writes) carries a tile payload; sequence
368/// headers and temporal delimiters are consumed for the state they carry (or
369/// skipped) and produce no picture.
370///
371/// # Errors
372/// Returns an error when the stream is truncated or malformed (as
373/// [`Av1Parser`] reports it), when a frame header names anything this
374/// crate's tile decoders do not reconstruct (see their own docs), or when an
375/// inter frame appears before any key frame has supplied a reference.
376pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
377 let mut pictures = Vec::new();
378 decode_stream_with(data, |picture, _decode_idx, shown| {
379 if shown {
380 pictures.push(picture.clone());
381 }
382 Ok(())
383 })?;
384 Ok(pictures)
385}
386
387/// Streaming form of [`decode_stream`]: hand every completed picture to
388/// `sink` the moment it exists and drop it right after, so peak memory is one
389/// output picture plus the 8-slot DPB instead of the whole decoded stream --
390/// a 4K long-GOP segment costs the same as a short one. `decode_stream`
391/// itself is this function collecting into a `Vec`.
392///
393/// `sink` is called with the picture, the decode-order index of the coded
394/// frame it came from, and whether it is output: a hidden reference frame
395/// (`show_frame == 0`) is reported with `shown == false` and is NOT part of
396/// `decode_stream`'s output, a `show_existing_frame` output with `true`.
397/// The grain-synthesised picture is what a shown frame's sink sees; the
398/// reference bank keeps the clean one (spec 7.18.3.1). An `Err` the sink
399/// returns aborts the decode and is returned unchanged.
400///
401/// # Errors
402/// As [`decode_stream`], plus whatever `sink` returns.
403pub fn decode_stream_with(
404 data: &[u8],
405 sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
406) -> Result<()> {
407 decode_stream_with_threads(data, decode_threads(), sink)
408}
409
410/// lane-thread2: how many threads [`decode_stream_with`] decodes with --
411/// `EC_AV1_THREADS`, default 1. One is not "threading with a pool of one":
412/// it is the single-threaded decoder unchanged, which is what keeps every
413/// gate that reads this crate's per-thread counters meaningful.
414fn decode_threads() -> usize {
415 static N: std::sync::LazyLock<usize> = std::sync::LazyLock::new(|| {
416 crate::envflags::var("EC_AV1_THREADS")
417 .ok()
418 .and_then(|v| v.parse::<usize>().ok())
419 .filter(|&n| n > 0)
420 .unwrap_or(1)
421 });
422 *N
423}
424
425/// lane-thread2: output-order queue. A leaf frame decoded on a worker
426/// finishes whenever it finishes; `sink` must still see every picture in the
427/// order the stream codes them, so each sink call gets an `emit_seq` when the
428/// main thread reaches its frame header and is held here until every earlier
429/// one has been emitted. (The decode index the sink is TOLD is unchanged, and
430/// is deliberately not unique: a `show_existing_frame` re-output reports the
431/// count of frames decoded before it, per this function's contract.)
432#[derive(Default)]
433struct Reorder {
434 next: usize,
435 // lane-pool1: the picture is shared, not owned -- a decoded frame that
436 // refreshes a reference slot is already behind an `Arc` for the slot, and
437 // handing the output an owned `Picture` meant copying every plane of it
438 // (24 MB per 4K 10-bit frame) purely to put it in this queue.
439 pending: std::collections::BTreeMap<usize, (std::sync::Arc<Picture>, usize, bool)>,
440}
441
442impl Reorder {
443 fn push(
444 &mut self,
445 seq: usize,
446 picture: std::sync::Arc<Picture>,
447 decode_idx: usize,
448 shown: bool,
449 ) {
450 self.pending.insert(seq, (picture, decode_idx, shown));
451 }
452
453 /// Emits every queued picture whose turn has come. An `Err` from `sink`
454 /// aborts the decode, unchanged, exactly as the serial path did.
455 fn drain(&mut self, sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>) -> Result<()> {
456 while let Some((picture, decode_idx, shown)) = self.pending.remove(&self.next) {
457 self.next += 1;
458 sink(&picture, decode_idx, shown)?;
459 crate::timeline::output(decode_idx);
460 }
461 Ok(())
462 }
463}
464
465/// lane-thread2/3: how many coded frames this PROCESS has dispatched to a
466/// worker thread (see [`decode_stream_with_threads`]). Process-global and
467/// atomic on purpose: it is the only counter here a caller can read after a
468/// threaded decode, and it is what keeps a "decodes identically with 4
469/// threads" gate from silently proving nothing because every frame ran
470/// inline. (lane-thread2 counted only LEAF frames, the only ones it could
471/// dispatch; lane-thread3 dispatches every non-key, non-`show_existing_frame`
472/// frame, hence the rename.)
473static FRAMES_DISPATCHED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
474
475/// Reads [`FRAMES_DISPATCHED`].
476pub fn frames_dispatched() -> usize {
477 FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed)
478}
479
480/// lane-thread3: what one decoded frame stores into every reference slot its
481/// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated
482/// object -- so a slot costs an `Arc` clone instead of a picture copy.
483struct SlotValue {
484 /// lane-twostage: this frame's FILTERED pixels, still being produced
485 /// when the rest of this value is published.
486 pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>>,
487 /// The size those pixels will have, known from the tile decode.
488 width: usize,
489 height: usize,
490 cdfs: Cdfs,
491 motion_field: crate::motion_field::MotionField,
492 seg_map: Vec<u8>,
493 order_hint: u32,
494}
495
496/// lane-thread3: a reference slot's contents as a FUTURE. At `threads > 1`
497/// the 8-slot bank holds these instead of values: a slot refreshed by a frame
498/// that is still decoding on a worker holds the promise from the moment the
499/// parsing thread DISPATCHES that frame, so the next frame can be dispatched
500/// straight away and waits, on its own worker, for exactly the slots it
501/// reads. This is what makes a pyramid stream (aomenc's default, where nearly
502/// every coded frame refreshes a slot, so lane-thread2's leaf rule dispatched
503/// almost nothing) decode in parallel.
504///
505/// DEADLOCK ARGUMENT. A promise is installed into a slot on the parsing
506/// thread, in decode order, when its producer is dispatched; a consumer
507/// captures the promises of the slots it reads at ITS dispatch, which is
508/// strictly later in decode order. Every wait therefore points from a later
509/// coded frame to an earlier one -- the wait graph is the reference DAG, and
510/// is acyclic. The parsing thread waits only for a `show_existing_frame`
511/// output (again an earlier frame) and at the in-flight bound, where it waits
512/// for ANY worker to answer: the earliest in-flight frame has no earlier
513/// in-flight producer, so it is always runnable and the bound always clears.
514/// Each dispatched frame gets its own thread, so a blocked waiter never holds
515/// a resource its producer needs. A producer that errors or panics marks its
516/// promise `Failed`, so no consumer can wait for a value that never comes.
517struct SlotPromise<T = std::sync::Arc<SlotValue>> {
518 state: std::sync::Mutex<PromiseState<T>>,
519 ready: std::sync::Condvar,
520}
521
522enum PromiseState<T> {
523 Pending,
524 Ready(T),
525 Failed,
526}
527
528impl<T: Clone> SlotPromise<T> {
529 fn pending() -> std::sync::Arc<Self> {
530 std::sync::Arc::new(Self {
531 state: std::sync::Mutex::new(PromiseState::Pending),
532 ready: std::sync::Condvar::new(),
533 })
534 }
535
536 /// A slot filled by a frame the parsing thread decoded itself.
537 fn ready(value: T) -> std::sync::Arc<Self> {
538 std::sync::Arc::new(Self {
539 state: std::sync::Mutex::new(PromiseState::Ready(value)),
540 ready: std::sync::Condvar::new(),
541 })
542 }
543
544 fn fulfil(&self, value: T) {
545 *self.state.lock().expect("slot promise") = PromiseState::Ready(value);
546 self.ready.notify_all();
547 }
548
549 /// lane-twostage: fulfils only a promise the stage-1 sink did not
550 /// already fill (a superres frame, or a key frame, whose meta is
551 /// published here as it always was).
552 fn fulfil_if_pending(&self, value: impl FnOnce() -> T) {
553 let mut state = self.state.lock().expect("slot promise");
554 if matches!(*state, PromiseState::Pending) {
555 *state = PromiseState::Ready(value());
556 }
557 self.ready.notify_all();
558 }
559
560 fn fail(&self) {
561 let mut state = self.state.lock().expect("slot promise");
562 if matches!(*state, PromiseState::Pending) {
563 *state = PromiseState::Failed;
564 }
565 self.ready.notify_all();
566 }
567
568 /// Blocks until the producing frame has published this slot.
569 fn wait(&self) -> Result<T> {
570 let mut state = self.state.lock().expect("slot promise");
571 loop {
572 match &*state {
573 PromiseState::Ready(value) => return Ok(value.clone()),
574 PromiseState::Failed => {
575 return Err(Error::corrupt(
576 "AV1 decode_stream: a reference frame this frame depends on failed to decode",
577 ));
578 }
579 PromiseState::Pending => {
580 state = self.ready.wait(state).expect("slot promise");
581 }
582 }
583 }
584 }
585}
586
587/// One finished frame from a worker: its output position, whether the job was
588/// a frame DECODE (as opposed to a `show_existing_frame` output, which only
589/// waits for a slot and synthesises grain -- lane-thread3 counts the two
590/// against separate in-flight bounds, since a waiting output job costs no
591/// CPU), and either the (grain-synthesised) picture with the decode index to
592/// report or the error that aborts the stream.
593type LeafResult = (usize, bool, Result<(std::sync::Arc<Picture>, usize, bool)>);
594
595/// Waits for one in-flight job and emits whatever that unblocks.
596fn collect_one(
597 rx: &std::sync::mpsc::Receiver<LeafResult>,
598 decodes: &mut usize,
599 shows: &mut usize,
600 reorder: &mut Reorder,
601 sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>,
602) -> Result<()> {
603 // Every dispatched worker answers exactly once, panic included (it is
604 // caught and turned into an error below), so the sender count cannot
605 // reach zero while `in_flight > 0`.
606 let (seq, decode_job, result) = rx
607 .recv()
608 .map_err(|_| Error::corrupt("AV1 decode_stream: a worker thread vanished"))?;
609 if decode_job {
610 *decodes -= 1;
611 } else {
612 *shows -= 1;
613 }
614 let (picture, decode_idx, shown) = result?;
615 reorder.push(seq, picture, decode_idx, shown);
616 reorder.drain(sink)
617}
618
619/// [`decode_stream_with`] with an explicit worker count (lane-thread2).
620///
621/// `threads == 1` is the serial decoder. Above that, frames that no later
622/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags`
623/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads
624/// while the main thread keeps parsing headers and decoding the frames that
625/// DO feed the reference banks; `sink` still sees every picture in coded
626/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot
627/// of the banks taken before dispatch, so no decode state is shared.
628///
629/// The per-decode counters this crate's gates read are thread-local, so at
630/// `threads > 1` a leaf frame's counts land on the worker and are invisible
631/// to the caller; that is why the default is 1.
632///
633/// # Errors
634/// As [`decode_stream_with`]; a worker's error aborts the stream.
635pub fn decode_stream_with_threads(
636 data: &[u8],
637 threads: usize,
638 mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
639) -> Result<()> {
640 // lane-pool1: this replaced a `std::thread::scope` -- frame workers now
641 // come from a persistent pool (one per submitting thread, workers reused
642 // across frames, so their `thread_local!` decode scratch survives the
643 // frame). `jobs` is declared here and dropped at the end of the function,
644 // including on `?`, so no job outlives the data it borrows.
645 let jobs = crate::par::Batch::new("ec-av1-frame");
646 // lane-thread1: this stream's per-frame decode state (was 38 thread_local
647 // statics in decode.rs) -- one object, threaded down the decode call graph.
648 let fctx = &crate::decode::FrameCtx::new();
649 let final_dump = final_dump_prefix();
650 let mut parser = Av1Parser::new();
651 let mut pictures_shown: usize = 0;
652 let mut pictures_decoded: usize = 0;
653 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
654 // previous frame's `refresh_frame_flags` stored into it, exactly like the
655 // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,
656 // not simply "the previous frame decoded"; a frame whose own predecessor
657 // didn't refresh that slot (an altref/hidden frame, or any GOP with more
658 // than one live reference) must keep predicting from whatever picture is
659 // still sitting there. Round 7's cdffwd hunt: a global `reference`
660 // overwritten every frame silently always used "the most recent decode"
661 // instead, producing a bit-exact motion vector into the WRONG picture --
662 // luma-only (chroma coincidentally shares this fixture's flat regions)
663 // and small-magnitude (the two pictures mostly agree), which is exactly
664 // what made it look like a rounding bug rather than a wrong reference.
665 // lane-pool1: shared, not owned -- a frame refreshing k slots used to copy
666 // its whole picture k times, and its output a (k+1)-th time.
667 let mut ref_slots: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] =
668 std::array::from_fn(|_| None);
669 // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion
670 // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom
671 // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was
672 // decoded with -- `Picture` itself carries neither, so both ride
673 // alongside `ref_slots` on the exact same `refresh_frame_flags` update.
674 let mut motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES] =
675 std::array::from_fn(|_| None);
676 let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES];
677 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
678 // previous frame's `refresh_frame_flags` stored into it -- the frame's
679 // own end-of-tile adapted table, or (when the frame set
680 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
681 let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
682 // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also
683 // remembers the segment map the frame stored there decoded, which is what
684 // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds`
685 // (spec `load_previous_segment_ids`) for temporal segment-id prediction
686 // and for a `segmentation_update_map == 0` frame's inherited map.
687 let mut seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
688
689 // lane-thread2: output plumbing (inert at `threads == 1`, where nothing
690 // is ever dispatched and `reorder` emits each picture the moment it is
691 // pushed).
692 let mut emit_seq = 0usize;
693 let mut reorder = Reorder::default();
694 // lane-thread3: frame decodes and `show_existing_frame` outputs are
695 // bounded separately -- an output job is a promise wait plus a memcpy, so
696 // letting it eat a decode's budget just idles a core (measured: sharing
697 // one bound cost 4K 18.7 s at 244% CPU against 17.7 s at 287%).
698 let mut in_flight_decodes = 0usize;
699 let mut in_flight_shows = 0usize;
700 let in_flight_cap = threads + 2;
701 let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();
702 // lane-thread3: at `threads > 1` THIS is the reference bank -- one
703 // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled
704 // itself and pending for one an in-flight frame will fill. The owned
705 // arrays above are then untouched (and the single-threaded path never
706 // creates a promise: it stays exactly the decoder it was, which is what
707 // keeps every counter-reading gate meaningful).
708 let mut slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
709 std::array::from_fn(|_| None);
710 // lane-timeline: which decoded frame installed each slot's promise, so
711 // the timeline records a dependency EDGE (frame -> producing frame) and
712 // not just a slot number. `usize::MAX` = nobody yet.
713 let mut slot_owner = [usize::MAX; NUM_REF_FRAMES];
714
715 let mut pos = 0usize;
716 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec
717 // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone
718 // `OBU_FRAME_HEADER` first, with `show_existing_frame == false` and no
719 // tile payload of its own -- `OBU_FRAME` (the `ObuKind::Frame` arm below)
720 // only ever folds ONE tile group into the header's own OBU. Stash the
721 // header here and accumulate tiles from each `OBU_TILE_GROUP` that
722 // follows until every tile of the frame has arrived.
723 let mut pending_header: Option<Box<FrameHeader>> = None;
724 let mut pending_tiles: Vec<Tile> = Vec::new();
725 while pos < data.len() {
726 let obu = parser.parse_obu(&data[pos..])?;
727 let obu_offset = pos;
728 pos += obu.total_size;
729
730 if let ObuKind::FrameHeader(header) = &obu.kind {
731 if !header.show_existing_frame {
732 // Before this fix, this branch fired unconditionally for
733 // EVERY `FrameHeader` OBU (including this one), so a
734 // standalone header always fell into the `show_existing_frame`
735 // slot lookup below and misreported "a show_existing_frame
736 // header naming an empty reference slot" for a frame that was
737 // never a show_existing_frame header at all.
738 pending_header = Some(header.clone());
739 pending_tiles = Vec::new();
740 continue;
741 }
742 // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this
743 // OBU only names a DPB slot to output again -- the coded-frame
744 // count and the shown-picture count are different things (a
745 // hidden altref's own `Frame` OBU below is never pushed to
746 // `pictures` on its own; it is only pushed here, later, when a
747 // `show_existing_frame` header names its slot). Before r15 this
748 // arm didn't exist at all: every `ObuKind::Frame` was pushed
749 // unconditionally regardless of `show_frame`, so a hidden altref
750 // was emitted (wrongly, in decode order) and its real
751 // `show_existing_frame` output was silently dropped.
752 let slot = header.frame_to_show_map_idx as usize;
753 // lane-hdrlossless: libaom errors on the same stream
754 // (`decodeframe.c:4651`: `if (frame_to_show == NULL)
755 // aom_internal_error(... AOM_CODEC_UNSUP_BITSTREAM, "Buffer does
756 // not contain a decoded frame")`) -- a spec-conformant guard.
757 let empty_slot = || {
758 Error::unsupported(
759 "AV1 decode_stream",
760 "a show_existing_frame header naming an empty reference slot",
761 )
762 };
763 if threads > 1 {
764 // lane-thread3: the named slot may still be decoding on a
765 // worker, and the copy into the slots this header refreshes
766 // is then just the promise -- no value needed. The OUTPUT
767 // does need the picture, so it is produced on a worker too:
768 // waiting for it here would stall the parsing thread, and a
769 // stalled parser dispatches nothing (measured before this
770 // arm existed: 7.9 s of an 8.8 s 1080p decode, 18.9 s of
771 // 23.3 s at 4K, spent in this one wait). The wait still
772 // points at an earlier coded frame, so the argument in
773 // [`SlotPromise`] is unchanged.
774 let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?;
775 for i in 0..NUM_REF_FRAMES {
776 if header.refresh_frame_flags & (1 << i) != 0 {
777 slot_promises[i] = Some(promise.clone());
778 slot_owner[i] = slot_owner[slot];
779 }
780 }
781 let cap_t0 = crate::timeline::now();
782 let capped = in_flight_shows >= in_flight_cap;
783 while in_flight_shows >= in_flight_cap {
784 collect_one(
785 &rx,
786 &mut in_flight_decodes,
787 &mut in_flight_shows,
788 &mut reorder,
789 &mut sink,
790 )?;
791 }
792 if capped {
793 crate::timeline::cap_wait("show", cap_t0, crate::timeline::now());
794 }
795 let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
796 emit_seq += 1;
797 pictures_shown += 1;
798 let grain = header.film_grain;
799 let seq = SeqFlags::read(&parser);
800 let tx = tx.clone();
801 jobs.submit(move || {
802 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
803 let value = promise.wait()?;
804 let shown_picture = value.pixels.wait()?;
805 let output = if grain.apply_grain && !no_grain() {
806 std::sync::Arc::new(crate::film_grain::apply_grain(
807 &shown_picture,
808 &grain,
809 seq.mc_identity,
810 u32::from(seq.bit_depth),
811 &crate::decode::FrameCtx::new(),
812 ))
813 } else {
814 std::sync::Arc::clone(&shown_picture)
815 };
816 Ok((output, decode_idx, true))
817 }))
818 .unwrap_or_else(|_| {
819 Err(Error::corrupt(
820 "AV1 decode_stream: a worker thread panicked on a show_existing_frame output",
821 ))
822 });
823 let _ = tx.send((job_seq, false, reply));
824 });
825 in_flight_shows += 1;
826 while let Ok((seq, decode_job, result)) = rx.try_recv() {
827 if decode_job {
828 in_flight_decodes -= 1;
829 } else {
830 in_flight_shows -= 1;
831 }
832 let (picture, decode_idx, shown) = result?;
833 reorder.push(seq, picture, decode_idx, shown);
834 reorder.drain(&mut sink)?;
835 }
836 continue;
837 }
838 let picture = {
839 let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?;
840 for i in 0..NUM_REF_FRAMES {
841 if header.refresh_frame_flags & (1 << i) != 0 {
842 cdf_slots[i] = cdf_slots[slot].clone();
843 ref_slots[i] = Some(picture.clone());
844 motion_field_slots[i] = motion_field_slots[slot].clone();
845 seg_map_slots[i] = seg_map_slots[slot].clone();
846 order_hint_slots[i] = order_hint_slots[slot];
847 }
848 }
849 picture
850 };
851 let output = if header.film_grain.apply_grain && !no_grain() {
852 // lane-hbd10 r1: grain synthesis is bit-depth generic
853 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
854 let bit_depth = parser
855 .sequence_header()
856 .map_or(8, |seq| seq.color_config.bit_depth);
857 let mc_identity = parser
858 .sequence_header()
859 .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
860 std::sync::Arc::new(crate::film_grain::apply_grain(
861 &picture,
862 &header.film_grain,
863 mc_identity,
864 bit_depth as u32,
865 fctx,
866 ))
867 } else {
868 picture
869 };
870 reorder.push(emit_seq, output, pictures_decoded, true);
871 emit_seq += 1;
872 reorder.drain(&mut sink)?;
873 pictures_shown += 1;
874 continue;
875 }
876 // `tiles_base_offset` is added to every `Tile::offset` below to reach
877 // an absolute position in `data`. `OBU_FRAME`'s tiles are relative to
878 // this OBU's own `obu_offset`; an accumulated run of `OBU_TILE_GROUP`s
879 // may span several different OBUs (each at a different offset in
880 // `data`), so those tiles are normalised to an absolute offset the
881 // moment they are appended to `pending_tiles`, and `tiles_base_offset`
882 // is 0 for that case.
883 let (header, tiles, tiles_base_offset): (Box<FrameHeader>, Vec<Tile>, usize) =
884 match obu.kind {
885 ObuKind::Frame(header, tiles) => (header, tiles, obu_offset),
886 ObuKind::TileGroup(new_tiles) => {
887 let header = pending_header.clone().ok_or_else(|| {
888 Error::corrupt(
889 "AV1 decode_stream: a tile group OBU with no preceding frame header",
890 )
891 })?;
892 let expected = header.tile_info.cols * header.tile_info.rows;
893 pending_tiles.extend(new_tiles.into_iter().map(|mut t| {
894 t.offset += obu_offset;
895 t
896 }));
897 if (pending_tiles.len() as u32) < expected {
898 continue;
899 }
900 pending_header = None;
901 (header, std::mem::take(&mut pending_tiles), 0)
902 }
903 _ => continue,
904 };
905 // Every tile is decoded below through `tile_bufs`; this only rejects a
906 // frame OBU that carries no tile group at all.
907 if tiles.is_empty() {
908 return Err(Error::unsupported(
909 "AV1 decode_stream",
910 "a frame OBU with no tile group",
911 ));
912 }
913 // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
914 // block of each 64x64) only reads a literal `cdef_idx` when
915 // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a
916 // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is
917 // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into
918 // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so
919 // a `cdef_bits > 0` stream no longer needs this refusal.
920 // Both frame types now read their transform size under
921 // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads
922 // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's
923 // `decode_inter_block`/`decode_inter_block8` read the recursive
924 // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the
925 // blanket inter-frame refusal that used to stand here is gone. What
926 // remains refused is named at its own site in `read_block_tx_size`.
927 // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`,
928 // libaom decodemv.c): three more per-block/per-SB symbols this crate
929 // never reads at all, each gated by a header field this decoder
930 // otherwise accepts uncomplaining -- the same silent-desync shape
931 // `use_filter_intra` was. `allow_screen_content_tools` gates both
932 // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/
933 // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel`
934 // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse
935 // before desyncing rather than silently miscode, the same pattern as
936 // the CDEF/TxMode::Select refusals above.
937 // lane-screen r2: key frames consume (not reconstruct) palette/
938 // intrabc syntax via read_intra_mode, and decode_inter_block/
939 // decode_inter_block8's own intra-sub-block branches now consume
940 // palette the same way (libaom's read_intra_block_mode_info has no
941 // intrabc call at all -- that symbol is intra-frame-only). A
942 // genuine palette/intrabc use still refuses by name deeper in the
943 // block readers, so no whole-frame refusal is needed here anymore.
944 // lane-realworld r5: both delta_q (maybe_read_delta_q, CURRENT_Q_IDX)
945 // and delta_lf (maybe_read_delta_lf, CURRENT_DELTA_LF ->
946 // Neighbours::delta_lf_grid -> lf_level) are now read and applied;
947 // no whole-frame refusal needed here anymore.
948 //
949 // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an
950 // earlier round), `BIT_DEPTH` is wired from this frame's own sequence
951 // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10`
952 // stream decodes pixel-exact against ffmpeg's own decode of the same
953 // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The
954 // blanket refusal that used to be here is gone; `film_grain.rs` and
955 // `superres.rs` still refuse narrowly by name (their own hardcoded
956 // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes
957 // will show up as a real pixel mismatch, not a silent truncation --
958 // the whole reason the widen (and this wiring) happened.
959 // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9,
960 // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the
961 // per-segment quantizer (spec 7.12.2) and loop-filter level
962 // (spec 7.14.4). The three features that instead REWRITE a block's
963 // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the
964 // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress
965 // symbols `decode_inter_block` unconditionally reads) -- have no
966 // reader on the inter path, so they still refuse by name rather than
967 // desyncing. aomenc's `--aq-mode` segmentation only ever sets
968 // `SEG_LVL_ALT_Q` (census gate
969 // `a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`:
970 // 1-pass, alt-ref-lag and two-pass arms, every frame header parsed).
971 let tile_bufs: Vec<&[u8]> = tiles
972 .iter()
973 .map(|t| {
974 data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size)
975 .ok_or(Error::NeedMore)
976 })
977 .collect::<Result<_>>()?;
978 let seq = SeqFlags::read(&parser);
979 // lane-thread3: at `threads > 1` every coded frame that is not a key
980 // frame is decoded on a worker -- frames that refresh reference slots
981 // included, which on a pyramid stream is nearly all of them. Its
982 // inputs are taken as promises and its output is published as one,
983 // installed into the slots it refreshes HERE, on the parsing thread,
984 // in decode order, so the next frame's dependencies are known without
985 // waiting for this one to finish (see [`SlotPromise`] for the
986 // deadlock argument). A key frame stays inline: it resets the whole
987 // bank and reads nothing, so there is nothing to gain.
988 if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame {
989 let cap_t0 = crate::timeline::now();
990 let capped = in_flight_decodes >= in_flight_cap;
991 while in_flight_decodes >= in_flight_cap {
992 collect_one(
993 &rx,
994 &mut in_flight_decodes,
995 &mut in_flight_shows,
996 &mut reorder,
997 &mut sink,
998 )?;
999 }
1000 if capped {
1001 crate::timeline::cap_wait("decode", cap_t0, crate::timeline::now());
1002 }
1003 // Exactly the slots this frame reads: `ref_frame_idx` names its
1004 // references, and its `primary_ref_frame` CDFs/segment map, its
1005 // reference order hints and every field `setup_motion_field`
1006 // projects all come from those same slots. Nothing else is
1007 // waited on.
1008 let mut deps: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
1009 std::array::from_fn(|_| None);
1010 for i in 0..7 {
1011 let slot = header.ref_frame_idx[i] as usize;
1012 deps[slot] = slot_promises[slot].clone();
1013 }
1014 let dep_owner = slot_owner;
1015 let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending);
1016 if let Some(promise) = &produces {
1017 for i in 0..NUM_REF_FRAMES {
1018 if header.refresh_frame_flags & (1 << i) != 0 {
1019 slot_promises[i] = Some(promise.clone());
1020 slot_owner[i] = pictures_decoded;
1021 }
1022 }
1023 }
1024 let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);
1025 emit_seq += 1;
1026 pictures_decoded += 1;
1027 let shown = header.show_frame;
1028 if shown {
1029 pictures_shown += 1;
1030 }
1031 let tx = tx.clone();
1032 let dump = final_dump.clone();
1033 crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown);
1034 jobs.submit(move || {
1035 let promise = produces;
1036 // lane-twostage: stage 2 -- this frame's filtered pixels. Its
1037 // consumers hold this promise from the moment stage 1 (CDFs,
1038 // segment map, motion field, size) is published at the tile
1039 // boundary, and wait on it at their first prediction.
1040 let pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>> =
1041 SlotPromise::pending();
1042 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1043 crate::timeline::start(decode_idx);
1044 // The wait happens HERE, off the parsing thread, and only
1045 // for this frame's own references.
1046 let mut resolved: [Option<std::sync::Arc<SlotValue>>; NUM_REF_FRAMES] =
1047 std::array::from_fn(|_| None);
1048 for (slot, dep) in deps.iter().enumerate() {
1049 if let Some(dep) = dep {
1050 let t0 = crate::timeline::now();
1051 resolved[slot] = Some(dep.wait()?);
1052 crate::timeline::ref_wait(
1053 decode_idx,
1054 slot,
1055 dep_owner[slot],
1056 crate::timeline::now().saturating_sub(t0),
1057 );
1058 }
1059 }
1060 crate::timeline::refs_ready();
1061 // Fresh per-thread state: every field this path reads is
1062 // written from this frame's own header before it is read.
1063 let fctx = crate::decode::FrameCtx::new();
1064 // lane-twostage: the pictures behind this frame's own
1065 // references, waited for at the first `ref_planes` call
1066 // inside the tile decode rather than here.
1067 let ref_metas: [Option<std::sync::Arc<SlotValue>>; 8] =
1068 std::array::from_fn(|i| {
1069 if i == 0 {
1070 None
1071 } else {
1072 resolved
1073 .get(header.ref_frame_idx[i - 1] as usize)
1074 .cloned()
1075 .flatten()
1076 }
1077 });
1078 let pix_cell: std::sync::OnceLock<
1079 [Option<std::sync::Arc<Picture>>; 8],
1080 > = std::sync::OnceLock::new();
1081 let wait_pixels = || -> Result<[Option<&Picture>; 8]> {
1082 if pix_cell.get().is_none() {
1083 let mut pics: [Option<std::sync::Arc<Picture>>; 8] =
1084 Default::default();
1085 for (i, meta) in ref_metas.iter().enumerate() {
1086 if let Some(meta) = meta {
1087 let slot = header.ref_frame_idx[i - 1] as usize;
1088 let t0 = crate::timeline::now();
1089 pics[i] = Some(meta.pixels.wait()?);
1090 crate::timeline::ref_wait(
1091 decode_idx,
1092 slot,
1093 dep_owner[slot],
1094 crate::timeline::now().saturating_sub(t0),
1095 );
1096 }
1097 }
1098 let _ = pix_cell.set(pics);
1099 }
1100 let pics = pix_cell.get().expect("the pictures were just set");
1101 Ok(std::array::from_fn(|i| pics[i].as_deref()))
1102 };
1103 let refpix = decode::RefPix::lazy(
1104 std::array::from_fn(|i| {
1105 ref_metas[i].as_ref().map(|m| (m.width, m.height))
1106 }),
1107 &wait_pixels,
1108 );
1109 // Stage 1: published at this frame's tile boundary, before
1110 // its filters run (`take_segment_ids` copies the map, so
1111 // the filters that read it are unaffected).
1112 let stage1 = |cdfs: Cdfs,
1113 motion_field: crate::motion_field::MotionField,
1114 width: usize,
1115 height: usize| {
1116 if let Some(promise) = &promise {
1117 promise.fulfil(std::sync::Arc::new(SlotValue {
1118 pixels: pixels.clone(),
1119 width,
1120 height,
1121 cdfs,
1122 motion_field,
1123 seg_map: decode::take_segment_ids(&fctx),
1124 order_hint: header.order_hint,
1125 }));
1126 crate::timeline::slot_fulfil();
1127 }
1128 };
1129 // spec 7.9's `av1_setup_motion_field` runs inside
1130 // `RefSnapshot::take`, i.e. here, after those waits --
1131 // it reads the referenced slots' saved motion fields.
1132 let motion_fields =
1133 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.motion_field));
1134 let snap = RefSnapshot::take(
1135 &header,
1136 seq,
1137 &refpix,
1138 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)),
1139 std::array::from_fn(|i| {
1140 resolved[i].as_ref().map(|v| v.seg_map.as_slice())
1141 }),
1142 &motion_fields,
1143 std::array::from_fn(|i| resolved[i].as_ref().map_or(0, |v| v.order_hint)),
1144 );
1145 let out = decode_frame(
1146 &fctx,
1147 &header,
1148 &tile_bufs,
1149 seq,
1150 snap,
1151 decode_idx,
1152 shown_idx,
1153 dump.as_deref(),
1154 // lane-twostage publishes a frame's meta at its tile
1155 // boundary instead of after its filters, so a consumer
1156 // parses over its producer's filter tail. It is ON by
1157 // default since lane-sub8group: with every reference
1158 // pixel read deferred to the recon workers, the
1159 // consumer parses its WHOLE tile before it needs a
1160 // pixel, and the 4K critical chain shortens by 11-14%
1161 // in three interleaved pairs (14450/10594/14407 ms off
1162 // vs 12790/9207/12463 ms on) where it moved 3-7%
1163 // before. `EC_AV1_TWO_STAGE=0` turns it back off.
1164 (crate::envflags::var("EC_AV1_TWO_STAGE").as_deref() != Ok("0"))
1165 .then_some(&stage1 as &dyn Fn(_, _, _, _)),
1166 )?;
1167 // Publish before grain synthesis: every frame waiting on
1168 // this slot can start the moment the clean picture exists
1169 // (spec 7.18.3.1 -- the bank never stores grain).
1170 let picture = std::sync::Arc::new(out.picture);
1171 pixels.fulfil(picture.clone());
1172 if let Some(promise) = &promise {
1173 // Only a frame whose stage-1 sink never fired (a
1174 // superres frame) still has meta to publish here.
1175 promise.fulfil_if_pending(|| {
1176 std::sync::Arc::new(SlotValue {
1177 pixels: pixels.clone(),
1178 width: picture.width,
1179 height: picture.height,
1180 cdfs: out.stored_cdfs,
1181 motion_field: out.motion_field.expect(
1182 "a frame that published no stage 1 carries its motion field back",
1183 ),
1184 seg_map: out.seg_map,
1185 order_hint: header.order_hint,
1186 })
1187 });
1188 crate::timeline::slot_fulfil();
1189 }
1190 // Grain is synthesised for OUTPUT only: a hidden frame is
1191 // reported to the sink clean, exactly as the inline path
1192 // below reports it (spec 7.18.3.1).
1193 let output = if shown && header.film_grain.apply_grain && !no_grain() {
1194 std::sync::Arc::new(crate::film_grain::apply_grain(
1195 &picture,
1196 &header.film_grain,
1197 seq.mc_identity,
1198 u32::from(seq.bit_depth),
1199 &fctx,
1200 ))
1201 } else {
1202 picture
1203 };
1204 crate::timeline::grain_done();
1205 Ok((output, decode_idx, shown))
1206 }))
1207 .unwrap_or_else(|_| {
1208 Err(Error::corrupt(
1209 "AV1 decode_stream: a worker thread panicked decoding a frame",
1210 ))
1211 });
1212 // A frame nobody can decode must not leave its consumers
1213 // waiting for a slot that will never be filled.
1214 if reply.is_err() {
1215 // Neither stage may leave a consumer waiting for a value
1216 // that will never come.
1217 if let Some(promise) = &promise {
1218 promise.fail();
1219 }
1220 pixels.fail();
1221 }
1222 let _ = tx.send((job_seq, true, reply));
1223 });
1224 in_flight_decodes += 1;
1225 FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1226 // Anything that finished while this frame was being set up.
1227 while let Ok((seq, decode_job, result)) = rx.try_recv() {
1228 if decode_job {
1229 in_flight_decodes -= 1;
1230 } else {
1231 in_flight_shows -= 1;
1232 }
1233 let (picture, decode_idx, shown) = result?;
1234 reorder.push(seq, picture, decode_idx, shown);
1235 reorder.drain(&mut sink)?;
1236 }
1237 continue;
1238 }
1239 // lane-twostage: the inline path's references are decoded already,
1240 // so its handle never waits.
1241 let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| {
1242 if i == 0 {
1243 None
1244 } else {
1245 ref_slots
1246 .get(header.ref_frame_idx[i - 1] as usize)
1247 .and_then(|p| p.as_deref())
1248 }
1249 }));
1250 let snap = RefSnapshot::take(
1251 &header,
1252 seq,
1253 &inline_refpix,
1254 std::array::from_fn(|i| cdf_slots[i].as_ref()),
1255 std::array::from_fn(|i| seg_map_slots[i].as_deref()),
1256 &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
1257 order_hint_slots,
1258 );
1259 let bit_depth = seq.bit_depth;
1260 let FrameOutput {
1261 picture,
1262 stored_cdfs,
1263 motion_field,
1264 seg_map: decoded_seg_map,
1265 } = decode_frame(
1266 fctx,
1267 &header,
1268 &tile_bufs,
1269 seq,
1270 snap,
1271 pictures_decoded,
1272 pictures_shown,
1273 final_dump.as_deref(),
1274 None,
1275 )?;
1276 let motion_field = motion_field.expect("the inline path passes no stage-1 sink");
1277 pictures_decoded += 1;
1278 // lane-pool1: one allocation, then every slot store and the output
1279 // itself are refcount bumps instead of plane copies.
1280 let picture = std::sync::Arc::new(picture);
1281 if threads > 1 {
1282 // lane-thread3: only a key frame reaches this inline path at
1283 // `threads > 1`, and the bank it fills is the promise array --
1284 // already resolved, since the picture exists right here.
1285 if header.refresh_frame_flags != 0 {
1286 let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {
1287 pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)),
1288 width: picture.width,
1289 height: picture.height,
1290 cdfs: stored_cdfs,
1291 motion_field,
1292 seg_map: decoded_seg_map,
1293 order_hint: header.order_hint,
1294 }));
1295 for i in 0..NUM_REF_FRAMES {
1296 if header.refresh_frame_flags & (1 << i) != 0 {
1297 slot_promises[i] = Some(promise.clone());
1298 slot_owner[i] = pictures_decoded - 1;
1299 }
1300 }
1301 }
1302 } else {
1303 for i in 0..NUM_REF_FRAMES {
1304 if header.refresh_frame_flags & (1 << i) != 0 {
1305 cdf_slots[i] = Some(stored_cdfs.clone());
1306 // Spec 7.18.3.1: synthesized grain is never stored for
1307 // later prediction -- the reference bank always keeps the
1308 // clean, pre-grain decode, even though the frame pushed
1309 // onto the caller's output below carries the grained
1310 // picture.
1311 ref_slots[i] = Some(std::sync::Arc::clone(&picture));
1312 motion_field_slots[i] = Some(motion_field.clone());
1313 seg_map_slots[i] = Some(decoded_seg_map.clone());
1314 order_hint_slots[i] = header.order_hint;
1315 }
1316 }
1317 }
1318 // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a
1319 // KEY frame coded with `show_frame == 0`, output later by a
1320 // `show_existing_frame` header -- counted only once its tiles have
1321 // decoded, so the gate's assert covers decoded-and-compared frames.
1322 if header.frame_type == FrameType::Key && !header.show_frame {
1323 decode::note_fwd_kf();
1324 }
1325 if header.show_frame {
1326 let output = if header.film_grain.apply_grain && !no_grain() {
1327 let mc_identity = seq.mc_identity;
1328 std::sync::Arc::new(crate::film_grain::apply_grain(
1329 &picture,
1330 &header.film_grain,
1331 mc_identity,
1332 bit_depth as u32,
1333 fctx,
1334 ))
1335 } else {
1336 picture
1337 };
1338 reorder.push(emit_seq, output, pictures_decoded - 1, true);
1339 emit_seq += 1;
1340 reorder.drain(&mut sink)?;
1341 pictures_shown += 1;
1342 } else {
1343 // Hidden (alt-ref/forward-key) frames never reach
1344 // `decode_stream`'s output, but a decode-order consumer -- the
1345 // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs
1346 // them, so they are reported too, with `shown == false`.
1347 reorder.push(emit_seq, picture, pictures_decoded - 1, false);
1348 emit_seq += 1;
1349 reorder.drain(&mut sink)?;
1350 }
1351 }
1352 while in_flight_decodes + in_flight_shows > 0 {
1353 collect_one(
1354 &rx,
1355 &mut in_flight_decodes,
1356 &mut in_flight_shows,
1357 &mut reorder,
1358 &mut sink,
1359 )?;
1360 }
1361 debug_assert!(reorder.pending.is_empty(), "a frame was never emitted");
1362 crate::timeline::dump();
1363 Ok(())
1364}
1365
1366/// lane-thread2: the sequence-header bits a single frame's decode needs,
1367/// read once on the parsing thread so that [`decode_frame`] never touches the
1368/// [`Av1Parser`] (a worker thread has no access to it).
1369#[derive(Clone, Copy)]
1370pub(crate) struct SeqFlags {
1371 pub(crate) enable_filter_intra: bool,
1372 pub(crate) enable_dual_filter: bool,
1373 pub(crate) enable_edge_filter: bool,
1374 pub(crate) enable_masked_compound: bool,
1375 pub(crate) enable_jnt_comp: bool,
1376 pub(crate) enable_interintra_compound: bool,
1377 pub(crate) use_sb128: bool,
1378 pub(crate) bit_depth: u8,
1379 /// lane-av1mono: `color_config.mono_chrome` (spec 5.5.2):
1380 /// `NumPlanes == 1`, no chroma is coded or reconstructed.
1381 pub(crate) mono_chrome: bool,
1382 pub(crate) order_hint_bits: u32,
1383 pub(crate) mc_identity: bool,
1384 /// lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2). The decoder
1385 /// itself hardcodes 4:2:0 everywhere, so these exist only for the
1386 /// sequence-level refusal in [`decode_stream_with`] -- nothing downstream
1387 /// reads them. A monochrome header parses as 1,1, so `!(1,1)` singles out
1388 /// 4:4:4 (profile 1 / sRGB) and 4:2:2 (profile 2 below 12-bit).
1389 pub(crate) subsampling_x: u8,
1390 pub(crate) subsampling_y: u8,
1391}
1392
1393impl SeqFlags {
1394 fn read(parser: &Av1Parser) -> Self {
1395 let seq = parser.sequence_header();
1396 Self {
1397 enable_filter_intra: seq.is_some_and(|s| s.enable_filter_intra),
1398 enable_dual_filter: seq.is_some_and(|s| s.enable_dual_filter),
1399 enable_edge_filter: seq.is_some_and(|s| s.enable_intra_edge_filter),
1400 enable_masked_compound: seq.is_some_and(|s| s.enable_masked_compound),
1401 enable_jnt_comp: seq.is_some_and(|s| s.enable_jnt_comp),
1402 enable_interintra_compound: seq.is_some_and(|s| s.enable_interintra_compound),
1403 use_sb128: seq.is_some_and(|s| s.use_128x128_superblock),
1404 bit_depth: seq.map_or(8, |s| s.color_config.bit_depth),
1405 mono_chrome: seq.is_some_and(|s| s.color_config.mono_chrome),
1406 order_hint_bits: seq.map_or(0, |s| s.order_hint_bits),
1407 mc_identity: seq.is_some_and(|s| s.color_config.matrix_coefficients == 0),
1408 subsampling_x: seq.map_or(1, |s| s.color_config.subsampling_x),
1409 subsampling_y: seq.map_or(1, |s| s.color_config.subsampling_y),
1410 }
1411 }
1412}
1413
1414/// lane-thread2: everything one frame's decode reads out of the cross-frame
1415/// banks `decode_stream_with` owns -- taken on the parsing thread, before any
1416/// later frame can overwrite a slot, so a frame can be decoded anywhere.
1417pub(crate) struct RefSnapshot<'a> {
1418 /// lane-twostage: this frame's references, indexed by `ref_frame`
1419 /// (`LAST_FRAME` = 1) -- sizes now, pixels at the first prediction.
1420 pub(crate) refpix: &'a decode::RefPix<'a>,
1421 /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame
1422 /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the
1423 /// second case is the refusal [`decode_frame`] raises where it always
1424 /// did, so the error order over a malformed stream is unchanged).
1425 pub(crate) primary_cdfs: Option<Cdfs>,
1426 /// Spec `load_previous_segment_ids`, from the same slot.
1427 pub(crate) prev_seg_map: Option<Vec<u8>>,
1428 /// Spec 7.9's projection, already run against `motion_field_slots`.
1429 pub(crate) tpl_field: Option<crate::motion_field::TplField>,
1430 /// `order_hint_slots[ref_frame_idx[i]]` for `LAST_FRAME + i`.
1431 pub(crate) ref_order_hints: [u32; 7],
1432}
1433
1434impl<'a> RefSnapshot<'a> {
1435 /// Reads the banks for `header`. Every slot is passed in by reference so
1436 /// that the single-threaded path can borrow the DPB in place while a
1437 /// worker borrows the resolved [`SlotPromise`] values it waited on --
1438 /// spec 7.9's `setup_motion_field` therefore runs on the DECODING thread
1439 /// (lane-thread3), after those waits.
1440 fn take(
1441 header: &FrameHeader,
1442 seq: SeqFlags,
1443 refpix: &'a decode::RefPix<'a>,
1444 cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],
1445 seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],
1446 motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],
1447 order_hint_slots: [u32; NUM_REF_FRAMES],
1448 ) -> Self {
1449 let primary = (header.primary_ref_frame != PRIMARY_REF_NONE)
1450 .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize);
1451 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
1452 // this frame's header asks for it, and never for a key frame (which
1453 // codes no inter block at all).
1454 let tpl_field =
1455 (header.frame_type != FrameType::Key && header.use_ref_frame_mvs).then(|| {
1456 crate::motion_field::setup_motion_field(
1457 motion_field_slots,
1458 header.ref_frame_idx,
1459 header.order_hint,
1460 seq.order_hint_bits,
1461 header.mi_rows as usize,
1462 header.mi_cols as usize,
1463 )
1464 });
1465 if std::env::var_os("EC_TPL").is_some() {
1466 eprintln!(
1467 "EC_TPL order_hint={} use_ref_frame_mvs={} cells={}",
1468 header.order_hint,
1469 header.use_ref_frame_mvs,
1470 tpl_field
1471 .as_ref()
1472 .map_or(0, crate::motion_field::TplField::filled_cells)
1473 );
1474 }
1475 Self {
1476 refpix,
1477 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),
1478 prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)),
1479 tpl_field,
1480 ref_order_hints: std::array::from_fn(|i| {
1481 order_hint_slots[header.ref_frame_idx[i] as usize]
1482 }),
1483 }
1484 }
1485}
1486
1487/// lane-thread2: what one decoded frame contributes back to the stream --
1488/// its picture (clean, pre-grain: spec 7.18.3.1) plus the three pieces a
1489/// `refresh_frame_flags` bit stores into a reference slot.
1490pub(crate) struct FrameOutput {
1491 pub(crate) picture: Picture,
1492 pub(crate) stored_cdfs: Cdfs,
1493 /// lane-twostage: `None` when this frame handed its motion field to the
1494 /// stage-1 sink at its tile boundary instead of carrying it back here.
1495 pub(crate) motion_field: Option<crate::motion_field::MotionField>,
1496 pub(crate) seg_map: Vec<u8>,
1497}
1498
1499/// Spec 7.20's own `save_cdfs`: what a frame's `refresh_frame_flags` slots
1500/// keep -- the frame's INITIAL table when `disable_frame_end_update_cdf`,
1501/// otherwise the adapted end-of-tile table with every symbol counter zeroed
1502/// (libaom `av1_reset_cdf_symbol_counters`). lane-twostage: shared with the
1503/// stage-1 publish, which hands a consumer the same table it always got.
1504fn stored_cdfs_for(header: &FrameHeader, end_cdfs: Cdfs, started_from: Option<Cdfs>) -> Cdfs {
1505 if header.disable_frame_end_update_cdf {
1506 started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
1507 } else {
1508 let mut end_cdfs = end_cdfs;
1509 end_cdfs.reset_counts();
1510 end_cdfs
1511 }
1512}
1513
1514/// lane-thread2: one coded frame, decoded from its header, its tile payload
1515/// and a snapshot of the reference banks -- and from nothing else. Lifted
1516/// verbatim out of [`decode_stream_with`]'s loop so that the same code can
1517/// run on the parsing thread (a frame that refreshes a reference slot) or on
1518/// a worker (a leaf frame, see `decode_stream_with_threads`).
1519///
1520/// `fctx` is the DECODING thread's context: a worker uses a fresh one, which
1521/// is sound because every field this path reads is written by this function
1522/// (or by the tile decoders it calls) before it is read -- see the
1523/// `a_worker_context_starts_where_the_stream_context_would` gate.
1524///
1525/// # Errors
1526/// As [`decode_stream_with`], for this one frame.
1527#[allow(clippy::too_many_arguments)]
1528fn decode_frame(
1529 fctx: &crate::decode::FrameCtx,
1530 header: &FrameHeader,
1531 tile_bufs: &[&[u8]],
1532 seq: SeqFlags,
1533 snap: RefSnapshot<'_>,
1534 decode_idx: usize,
1535 shown_idx: usize,
1536 final_dump: Option<&str>,
1537 // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`.
1538 stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,
1539) -> Result<FrameOutput> {
1540 crate::census::frame_start(header, tile_bufs.iter().map(|t| t.len()).sum(), decode_idx);
1541 if header.segmentation.enabled {
1542 // lane-hdrlossless: libaom IMPLEMENTS these three -- they rewrite a
1543 // block's reference / skip / mode BEFORE the symbols are read
1544 // (`decodemv.c:431` SEG_LVL_SKIP, `:437` SEG_LVL_REF_FRAME /
1545 // SEG_LVL_GLOBALMV, `:1071` in `read_ref_frames`, `:1350` in
1546 // `read_is_inter_block`), so a conformant stream CAN carry them and
1547 // this is a capability gap, not a spec-conformant guard. Reachability
1548 // from `aomenc` is nil, for three independent reasons (lane-av1seglvl
1549 // census): the AQ modules clear the table then set `SEG_LVL_ALT_Q`
1550 // only (`aq_variance.c:61` clear + `:89` enable, `aq_complexity.c:74`
1551 // + `:118`, `aq_cyclicrefresh.c:616` + `:630`); the one other setter,
1552 // `configure_static_seg_features` (`encoder_utils.c:315`, which would
1553 // set ALT_LF/REF_FRAME/SKIP around alt-ref groups), is gated on
1554 // `hl_sf.static_segmentation` -- a speed feature libaom's own
1555 // `speed_features.h` documents as "Always set to 0" -- AND on the
1556 // second pass of a two-pass encode (`encoder_utils.c:738`); and
1557 // ROI/active-map maps are control-API only (`av1_apply_roi_map`,
1558 // `av1_apply_active_map`: the CLI exposes no flag for either). Kept as
1559 // a named gap: the lift is an INTER-block-path change (ref/skip/mode
1560 // selection) outside this lane's region. See `lanes/av1hdr.report.md`
1561 // §4.1 and `lanes/av1seglvl.report.md`.
1562 for segment in 0..MAX_SEGMENTS {
1563 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
1564 if header.segmentation.feature_enabled[segment][feature] {
1565 return Err(Error::unsupported(
1566 "AV1 decode_stream",
1567 "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)",
1568 ));
1569 }
1570 }
1571 }
1572 }
1573 // spec `load_previous_segment_ids`: `PrevSegmentIds` comes from the
1574 // primary reference frame's slot, and is all-zero without one.
1575 decode::set_segmentation(
1576 header.segmentation,
1577 header.mi_rows as usize,
1578 header.mi_cols as usize,
1579 snap.prev_seg_map.as_deref(),
1580 fctx,
1581 );
1582 // lane-superres stage 2/3: `use_superres` adds/removes no per-block
1583 // symbol (spec 7.16's upscaling is a pixel-domain post-process
1584 // libaom's `decodeframe.c` runs between CDEF and loop restoration,
1585 // `av1_upscale_normative_*` in `resize.c`), so a key frame's tile
1586 // reads stay bit-exact in sync and `crate::superres::upscale_picture`
1587 // (below, after decode) makes its `Picture` the spec-correct
1588 // `upscaled_width` instead of silently staying at `frame_width`.
1589 // lane-superres r10: an INTER frame under `use_superres` no longer
1590 // refuses at the frame level. `mc::predict_scaled` (spec 7.11.3.3)
1591 // is wired into `decode_inter_block`'s single-ref, non-warp/OBMC/
1592 // interintra branch, and `decode_inter_frame_tile_with_cdfs` decodes
1593 // at the downscaled `frame_width` and upscales its own output the
1594 // same way the key-frame branch above does (see the inter branch
1595 // below). The combinations `predict_scaled` does not cover
1596 // (compound MC, warp/OBMC/interintra, `decode_inter_block8`'s 8x8
1597 // leaf) still refuse by name, deep in `decode.rs`, rather than
1598 // silently mispredicting -- see `refusal_inventory.rs`.
1599 // Loop restoration carries per-restoration-unit symbols in the tile
1600 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
1601 // superblock walk) -- lane-lr r2 ported the reader
1602 // (`crate::restoration`), r3 moved this refusal check to AFTER the
1603 // tile decode call below (was here, before it, in r2 -- meaning
1604 // `read_lr` was NEVER actually reached through `decode_stream`, the
1605 // gap the r3 gate caught live: 40/40 attempts hit this refusal with
1606 // zero `read_lr_unit` hits). Checking post-decode instead proves the
1607 // superblock walk actually survived `read_lr` (no desync) before
1608 // refusing on the true remaining gap: decoded Wiener/SGR filters are
1609 // stored per unit but never applied to pixels.
1610 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
1611 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
1612 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
1613 // zero vector only under `GmType == IDENTITY` -- any other warp
1614 // model needs the full affine/translation MV derivation this
1615 // decoder does not carry. `global_motion` is indexed `ref_frame - 1`
1616 // (`read_global_motion_params`'s `i` loops from `LAST_FRAME`);
1617 // lane-av1refs widens this from `[0, 3]` (LAST_FRAME/GOLDEN_FRAME)
1618 // to every one of the 7 single-reference slots `decode_inter_block`
1619 // can now select.
1620 //
1621 // lane-gm r2 STEP-8 ATTEMPT (reverted): removing this refusal
1622 // exposed a real pixel mismatch --
1623 // a_real_aomenc_stream_with_interintra_wedge_decodes_pixel_exact
1624 // seed 43, frame 1 luma, with EC_WEDGE_GATE_ATTEMPTS=20
1625 // EC_AV1_REQUIRE_AOMENC=1 -- so the single-ref/compound MV wiring
1626 // is not yet provably correct end to end; keeping the refusal
1627 // until that seed is captured (EC_AV1_GATE_DUMP), self-pinned, and
1628 // root-caused rather than shipping a wrong decode.
1629 //
1630 // lane-gm r3 ROOT CAUSE (pinned, range-ladder-confirmed, still not
1631 // fixed): the mismatch is NOT an mv/mvstack/entropy bug -- msac
1632 // RANGE at the first divergent block (mi=(8,0), frame 1) matches
1633 // aomdec's own `EC_PART` trace bit-for-bit (rng=38664 both sides),
1634 // and this decoder's own `gm_get_motion_vector` for that block
1635 // (ROTZOOM, seed 43's own header) computes the spec-correct
1636 // mv=(-8,8) (hand-verified against mv.h's `block_center_x`/`_y`,
1637 // which found and fixed a real `- 1` omission in `warp.rs` --
1638 // harmless for THIS block's rounding but a genuine spec bug fixed
1639 // regardless). The actual gap: `reconinter.c`'s `allow_warp` has a
1640 // `global_warp_allowed` branch (`warp_types.global_warp_allowed =
1641 // is_global_mv_block(...)`, `reconinter_enc.c:281`) that predicts
1642 // an `is_global_mv_block` block (ROTZOOM/AFFINE GLOBALMV, >=8x8)
1643 // with the FULL per-pixel affine global-motion warp, independent
1644 // of `motion_mode` -- this decoder only ever builds a warp
1645 // prediction for local `WARPED_CAUSAL` motion mode and falls back
1646 // to plain translational MC with the block-centre mv for every
1647 // other GLOBALMV block, which is only a centre-point approximation
1648 // of the true per-pixel warp. That is the entire remaining gap.
1649 // lane-gm r4: `decode.rs` now feeds `global_motion[ref]` into
1650 // `crate::warp::global_warp_params` for every single-ref
1651 // `is_global_mv_block` (ROTZOOM/AFFINE), matching `allow_warp`'s
1652 // `global_warp_allowed` branch -- ROTZOOM is pin-verified
1653 // (`gm-seed43.obu`, frame 1 luma MATCH) and TRANSLATION already
1654 // worked (`gm_get_motion_vector`'s translation-only mv, no warp
1655 // needed). AFFINE is untested this round (no aomenc fixture in the
1656 // wedge gate reached a 6-parameter model) -- keep refusing it by
1657 // name rather than shipping an unverified decode.
1658 // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom
1659 // can never write a 6-parameter model -- its encoder-side search is
1660 // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`,
1661 // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) --
1662 // which is why four rounds of `--enable-global-motion=1` recipes
1663 // never reached the case. `scripts/build-aom-affine-oracle.sh` widens
1664 // exactly that search range in a side build, and
1665 // `a_real_affine_global_motion_stream_decodes_pixel_exact` below
1666 // decodes its output pixel-exact against ffmpeg with
1667 // `affine_gm_hits() > 0`, i.e. real blocks predicted through the
1668 // 6-parameter warp. Nothing in the decoder needed changing: the
1669 // header reader already reads params 4/5 with their own subexp refs
1670 // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s
1671 // shear-validity check + `warp_affine` are model-agnostic.
1672 // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two
1673 // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and
1674 // refused the shape by name rather than guess-fix it. r5 localized
1675 // the mismatch to an ordinary NEWMV/GOLDEN block, not the new
1676 // global-warp branch at all -- proving "two active slots" was a
1677 // correlated symptom, not the cause. r6 range-laddered that block
1678 // against aomdec's `EC_TRACE_MODE` (identical `rng` before/after
1679 // mode info -- symbol consumption bit-exact) and found the real
1680 // defect in `mvstack.rs`'s single-reference predictor fallback:
1681 // libaom's `setup_ref_mv_list` fills any `mv_ref_list` slot the real
1682 // neighbour scan left short with this block's OWN global motion
1683 // vector for its ref (`gm_get_motion_vector`), not zero -- invisible
1684 // whenever the live ref's global motion is itself
1685 // identity/translation, wrong the moment it's a real ROTZOOM/AFFINE
1686 // and the querying block's own stack comes up short (frame 14's
1687 // mi=(0,0), the very first block decoded, has no neighbours at
1688 // all). Fixed at the predictor fallback; the refusal above (single
1689 // untested shape: AFFINE on a single-ref frame) stays, but the
1690 // *multi-slot* refusal this comment used to guard is lifted -- the
1691 // r5/r6 pin (seed-43 wedge-gate mismatch) now decodes all 24 frames
1692 // byte-exact with it gone.
1693 // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
1694 // `comp_mode` per block whenever this frame's own `reference_select`
1695 // header bit is set (spec 5.11.25), and refuse by name the blocks
1696 // that pick `COMPOUND_REFERENCE` -- two-reference motion
1697 // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
1698 // is wired at the block level too (forced NEAREST_NEARESTMV compound
1699 // of `skip_mode_frame`, plain average blend), so the old blanket
1700 // `skip_mode_present` refusal is gone.
1701 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
1702 // which tile's end-of-tile adapted CDFs become the frame's own.
1703 // lane-tiles r8: this comment used to claim a `!= 0` refusal existed
1704 // "further down" -- it did not (`decode.rs` reads
1705 // `tile_info.context_update_tile_id` generically at both the
1706 // key-frame and inter-frame tile loops' `result_cdfs = cdfs` sites,
1707 // never hardcoded to tile 0); stale documentation, not a real gap.
1708 // `a_real_aomenc_stream_with_four_tile_rows_decodes_pixel_exact`
1709 // hard-asserts a live aomenc stream naming tile 1/2/3 decodes
1710 // pixel-exact, so the capability is now proven as well as described
1711 // correctly.
1712 //
1713 // lane-tiles r4/r6/r7/r8: the multi-tile refusal itself is scoped,
1714 // not blanket. `decode_key_frame_tile_with_cdfs` and (r6)
1715 // `decode_inter_frame_tile_with_cdfs` both genuinely loop every
1716 // tile, `mvstack.rs`'s `MiGrid` is bounded per tile
1717 // (`MiGrid::set_tile_bounds`), and `PlaneBuf`'s `tile_x0/y0/x1/y1`
1718 // origin receives real values at every call site (r6's
1719 // `set_tile_origin` sweep). r7 proved the two remaining
1720 // tile-*column* gaps closed (inter frames, >2 columns with loop
1721 // filtering on). r8 proved tile *rows* the same way: the per-tile
1722 // loop's row math (`tile_num / tile_info.cols`,
1723 // `mi_row_starts`/`set_tile_origin`'s `y0`/`y1`) is exactly
1724 // symmetric with the column path already proven, and
1725 // `a_real_aomenc_stream_with_two_tile_rows_decodes_pixel_exact`
1726 // (bypass gate, loop filter ON) confirmed it: 20/20 pixel-exact.
1727 // `a_real_aomenc_stream_with_two_tile_rows_decodes_through_decode_
1728 // stream` below re-proves it through this entry point. Tile columns
1729 // and tile rows (any count, loop filter on) are no longer capped.
1730 // `Tile::offset` is relative to the buffer `parse_obu` was handed
1731 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
1732 // to `obu_offset`, not to `data` as a whole.
1733 let enable_filter_intra = seq.enable_filter_intra;
1734 let enable_dual_filter = seq.enable_dual_filter;
1735 let enable_edge_filter = seq.enable_edge_filter;
1736 // Inter frames' intra blocks read this through a thread-local that only
1737 // the key-frame tile path used to set; without this call a stream whose
1738 // inter frames are decoded on a thread that previously decoded a
1739 // different sequence would inherit that sequence's bit.
1740 crate::decode::set_enable_edge_filter(enable_edge_filter, fctx);
1741 // lane-sb128 r1/r2: `use_128x128_superblock` (spec 5.5.1). Both the
1742 // key-frame and the inter tile path read the 128 partition root and
1743 // recurse SPLIT into the four 64x64 quadrants (r2 ported the root and
1744 // libaom's quadrant visit order into the inter loop too). A frame at
1745 // most 64x64 decodes identically either way (its 128 root reads no
1746 // symbol -- neither half is in frame, so SPLIT is inferred), so the
1747 // flag is only armed for frames bigger than one 64x64 superblock.
1748 let use_sb128 = seq.use_sb128;
1749 let sb128_active = use_sb128 && (header.mi_cols > 16 || header.mi_rows > 16);
1750 crate::decode::set_sb128(sb128_active, fctx);
1751 // lane-hbd r5: `BIT_DEPTH` (decode.rs) drives `crate::decode::sample_max`,
1752 // which every dequant/inverse-transform clamp reads -- set per frame,
1753 // not once per process, for the same cross-sequence-on-one-thread
1754 // reason as `set_enable_edge_filter` above. Defaults to 8 when no
1755 // sequence header has been seen yet, matching every existing fixture.
1756 let bit_depth = seq.bit_depth;
1757 // lane-av112bit: the blanket 12-bit refusal is LIFTED for the paths the
1758 // lane's witnesses prove byte-exact against ffmpeg on real `aomenc
1759 // --bit-depth=12` streams (key frame and inter sequence, CDEF and loop
1760 // restoration ON, grain off -- gates
1761 // `a_real_aomenc_12bit_stream_decodes_pixel_exact` and
1762 // `a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact`). The
1763 // rounding sites that move at 12 bits are parameterised from libaom's
1764 // own rule (`mc.rs`'s `round_pair` -- convolve.h:81..86's `intbufrange`
1765 // delta: round_0 += bd-10, non-compound round_1 -= bd-10; the Wiener
1766 // pair via `get_conv_params_wiener`; the compound post-rounds absorb
1767 // the CONV_BUF gain), and CDEF/deblock/quant tables/SGR/palette reads/
1768 // superres upscale were already bit-depth generic (10-bit-proven).
1769 // Everything no 12-bit witness reached stays refused BY NAME at its own
1770 // site: warp (decode.rs, warp's reduce bits inherit the 12-bit round_0)
1771 // and any per-feature gap the witnesses' counters prove unreached -- see
1772 // the 12-bit refusals in decode.rs and `refusal_inventory.rs`.
1773 // lane-av112bitg: film grain joined the witnessed set (`grain_refusal`
1774 // deleted; the two-arm witness is
1775 // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
1776 // lane-av1txr: `color_config.subsampling_x/y` (spec 5.5.2) are parsed by
1777 // `ec-av1-syntax` -- profile 1 forces 4:4:4, profile 2 below 12-bit forces
1778 // 4:2:2, and the sRGB identity description forces full-range 4:4:4 -- but
1779 // the decoder reads them NOWHERE: every chroma extent is hardcoded 4:2:0
1780 // (`let (chroma_w, chroma_h) = (bw / 2, bh / 2)` at every rect site,
1781 // `chroma_side = side / 2` in `decode_block`) and the probe emits 4:2:0
1782 // planes only. Measured consequence: EVERY 4:4:4 stream desyncs at the
1783 // first chroma transform (a444-cu6 block (0,0): aomdec reads
1784 // `EC_COEFF plane=1 tx=TX_8X16` at rng 39857 where ours reads a 4-wide,
1785 // 8-high 4:2:0 chroma block at the same rng) and then decodes pixels that
1786 // are silently wrong. Refuse by name rather than return garbage. A
1787 // `num_planes == 1` (monochrome) header keeps its parsed 1,1 and is
1788 // unaffected. Gates: `a_non_420_subsampled_sequence_header_is_refused_by_
1789 // name` below (hand-built profile 1/2 headers plus a real aomenc 4:4:4
1790 // stream).
1791 // lane-av1-444: 4:4:4 (ss 0,0) is decoded. 4:2:2 (ss_x != ss_y) is not.
1792 // lane-av1odd440: the CONDITION is left as `ss_x != ss_y` because that is
1793 // what a parsed header can violate, but the STRING now names the only
1794 // shape that can: `subsampling_y` is coded ONLY when `subsampling_x` is
1795 // 1 (spec 5.5.2's `color_config`; libaom `av1_read_color_config`,
1796 // `av1/decoder/decodeframe.c:4171-4175`, and its writer's own
1797 // `assert(seq_params->subsampling_y == 0 && "4:4:0 subsampling not
1798 // allowed in AV1")`, `av1/encoder/bitstream.c:2467-2468`), so a header can
1799 // carry (1,1), (1,0) or (0,0) and never (0,1) -- 4:4:0 is not a cell a
1800 // decoder can be handed at all. The gate
1801 // `the_440_cell_is_not_a_codable_chroma_shape` proves the whole reachable
1802 // set, so this string is not a claim about a shape that cannot arrive.
1803 if seq.subsampling_x != seq.subsampling_y {
1804 return Err(Error::unsupported(
1805 "AV1 decode_stream",
1806 "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, and 4:4:0 (0,1) is not a codable cell",
1807 ));
1808 }
1809 // lane-av1-qmatrix: `quantization_params.using_qmatrix` + `qm_y`/`qm_u`/
1810 // `qm_v` (spec 5.9.12) select per-plane INVERSE QUANTISATION MATRICES --
1811 // spec 7.12.3's per-position `dqv` scale, libaom `get_dqv` over
1812 // `iwt_matrix_ref`. The parsed 4-bit values ARE the table levels
1813 // (libaom `quant_params->qmatrix_level_y/u/v`); 15 is libaom's flat
1814 // NULL-table sentinel, and a `using_qmatrix == 0` frame keeps all three
1815 // parked there, selecting no matrix. Frame-constant: recorded here (the
1816 // spot where this decoder refused such frames until this lane), read by
1817 // every dequantisation call site through [`crate::decode::block_iqmatrix`].
1818 // A real `aomenc --enable-qm=1` stream (`using_qmatrix = 1`, levels 5)
1819 // decodes byte-exact vs ffmpeg; the witness is
1820 // `a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact` below.
1821 let q = &header.quantization;
1822 // When the bit is UNSET the parsed 4-bit fields read 0 but mean nothing
1823 // (spec: they are not even coded): libaom parks the level at
1824 // `NUM_QM_LEVELS - 1`, its flat NULL-table sentinel
1825 // (`setup_segmentation_dequant`: `use_qmatrix ? qmatrix_level_y : 15`),
1826 // so a matrix-free frame selects no matrix.
1827 let flat = crate::qm::NUM_QM_LEVELS as u8 - 1;
1828 let levels = if q.using_qmatrix {
1829 [q.qm_y, q.qm_u, q.qm_v]
1830 } else {
1831 [flat; 3]
1832 };
1833 crate::decode::set_qm_levels(levels, fctx);
1834 // lane-av112bit: the frame-level half of the 12-bit gate -- screen
1835 // content tools. Neither palette nor intrabc has a 12-bit witness (the
1836 // 12-bit gates are natural content), and both hang off this header bit:
1837 // `allow_screen_content_tools` is what lets a block code a palette or
1838 // read a `use_intrabc` symbol. Refusing the FRAME by name keeps every
1839 // palette/intrabc code path 12-bit-unreachable rather than unwitnessed
1840 // and trusted. Gate:
1841 // `a_12bit_screen_content_stream_is_refused_by_name`.
1842 if bit_depth == 12 && header.allow_screen_content_tools {
1843 return Err(Error::unsupported(
1844 "AV1 decode_stream",
1845 "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)",
1846 ));
1847 }
1848 // lane-dpm1: a LOSSLESS frame (`qindex == 0` with zero deltas, spec 5.9.12)
1849 // is a different tile syntax, and this decoder has none of it: libaom
1850 // forces TX_4X4 with the WALSH-HADAMARD transform over every block (so no
1851 // `tx_depth` symbol is coded at all), and `is_cfl_allowed` narrows to
1852 // `plane_bsize == BLOCK_4X4` instead of the 32x32 rule, which changes the
1853 // `uv_mode` ALPHABET. Measured on his own screen-capture row at libaom
1854 // `-crf 5` (base_q_idx 0): the very first block, mi(0,0) BLOCK_32X32,
1855 // reads `uv_mode` off the CfL alphabet where libaom reads the plain one
1856 // (ours 12 = UV_CFL_PRED, aomdec 1 = V_PRED) and the tile desyncs at
1857 // symbol four of the frame. Refuse by name rather than return a picture
1858 // that is silently wrong from luma sample 0 (class `refusal-hides-a-defect`
1859 // read the other way: a silent wrong decode is worse than a named gap).
1860 // lane-lossless: `CodedLossless` (spec 5.9.12) -- every segment at
1861 // `qindex == 0` with zero plane deltas. The tile reader then forces TX_4X4
1862 // with the Walsh-Hadamard transform on every plane, codes no `tx_type`
1863 // symbol and narrows `is_cfl_allowed` to `plane_bsize == BLOCK_4X4`
1864 // (libaom `read_tx_size`/`read_tx_type`/`is_cfl_allowed`).
1865 //
1866 // lane-av1mixloss: PER-SEGMENT lossless (libaom `decodeframe.c:5205`) --
1867 // the header parser computes `lossless[segment_id]` for all 8 segments
1868 // (`qindex == 0` with zero plane deltas, `segment_qindex` applying that
1869 // segment's own `SEG_LVL_ALT_Q`) and `coded_lossless` = every segment
1870 // lossless. Everything FRAME-level already keys on the header's fields,
1871 // exactly as libaom gates them on `features->coded_lossless`/
1872 // `all_lossless`: `tx_mode` is `Only4x4` only when EVERY segment is
1873 // lossless, CDEF and the loop-filter levels are forced to 0 only then,
1874 // and loop restoration only on `all_lossless`. What this decoder lacked
1875 // was the BLOCK level: every block-decoder rule -- `read_tx_size`'s TX_4X4
1876 // early return, the suppressed `tx_type`, the Walsh-Hadamard,
1877 // `is_cfl_allowed`'s narrowing, the 4x4 chroma rasters -- indexes
1878 // `xd->lossless[segment_id]`, so a frame whose segments DISAGREE codes
1879 // lossless blocks inside a lossy frame. aomenc WRITES one:
1880 // `--end-usage=q --cq-level=0 --aq-mode=1` (variance AQ over a lossless
1881 // base) gives a high-variance segment a positive `SEG_LVL_ALT_Q` while a
1882 // flat one stays at `qindex == 0`. The table goes in whole and
1883 // [`decode::lossless`] resolves it per block through the block's own
1884 // `segment_id` (set by the spec-order `segment_id` read that precedes
1885 // every mode/transform symbol). Witness:
1886 // `a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact`.
1887 crate::decode::set_lossless_per_seg(header.lossless, fctx);
1888 crate::decode::set_bit_depth(bit_depth, fctx);
1889 // lane-av1mono: the sequence header's `mono_chrome`, set per frame like
1890 // the bit depth so a mono frame decoded on a thread that last saw a
1891 // 4:2:0 one never inherits the wrong plane count.
1892 crate::decode::set_mono(seq.mono_chrome, fctx);
1893 crate::decode::set_subsampling(seq.subsampling_x, seq.subsampling_y, fctx);
1894 // lane-av1readcensus: the 4:4:4 coefficient-unit census is armed here,
1895 // off the same sequence-header subsampling -- at 4:2:0/4:2:2 every census
1896 // counter reads zero, so a 4:2:0 control can assert exactly that.
1897 crate::decode::set_census_444(seq.subsampling_x, seq.subsampling_y);
1898 // lane-av1txr: spec 5.9.2 `disable_cdf_update` -- a frame that sets it
1899 // codes every tile symbol against the CDFs it started with, so the tile
1900 // readers must not adapt (libaom `decodeframe.c:2909`:
1901 // `allow_update_cdf = allow_update_cdf && !cm->features.disable_cdf_update`).
1902 crate::decode::set_disable_cdf_update(header.disable_cdf_update, fctx);
1903 // spec 7.16: this frame's superres state, for the filter chain --
1904 // `decode.rs` upscales between CDEF and loop restoration and sizes
1905 // the LR unit grid in upscaled coordinates. Cleared (0, 8) on an
1906 // unscaled frame so a later frame never inherits it.
1907 crate::decode::set_superres(
1908 if header.use_superres {
1909 header.upscaled_width
1910 } else {
1911 0
1912 },
1913 u32::from(header.superres_denom),
1914 fctx,
1915 );
1916 // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
1917 let enable_masked_compound = seq.enable_masked_compound;
1918 let enable_jnt_comp = seq.enable_jnt_comp;
1919 // lane-sb128 r4: `interintra`'s own gating bit -- see decode.rs's
1920 // read site doc.
1921 let enable_interintra_compound = seq.enable_interintra_compound;
1922 let interp_fixed = match header.interpolation_filter {
1923 ec_av1_syntax::InterpolationFilter::Switchable => None,
1924 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
1925 };
1926 // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
1927 // from that reference slot's saved CDF state instead of the spec 8.4
1928 // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
1929 // builds.
1930 // lane-hdrlossless: libaom errors on the same stream (`decodeframe.c:5075`:
1931 // `if (features->primary_ref_frame != PRIMARY_REF_NONE &&
1932 // get_primary_ref_frame_buf(cm) == NULL) aom_internal_error(...,
1933 // AOM_CODEC_CORRUPT_FRAME, "Reference frame containing this frame's
1934 // initial frame context is unavailable.")`) -- a spec-conformant guard.
1935 let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
1936 None
1937 } else {
1938 Some(snap.primary_cdfs.clone().ok_or_else(|| {
1939 Error::unsupported(
1940 "AV1 decode_stream",
1941 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
1942 )
1943 })?)
1944 };
1945 let started_from = initial_cdfs.clone();
1946 // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame.
1947 decode::set_coeff_trace_frame(decode_idx);
1948 // lane-t900 r9: one line per DECODE-order frame naming the header
1949 // fields a desync cliff is usually keyed on (frame type, base q,
1950 // primary_ref, the 7 ref slots, refresh mask, order hints).
1951 if std::env::var_os("EC_PROBE_HDR").is_some() {
1952 eprintln!(
1953 "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={:?}",
1954 header.frame_type,
1955 header.show_frame,
1956 header.show_existing_frame,
1957 header.quantization.base_q_idx,
1958 header.primary_ref_frame,
1959 header.ref_frame_idx,
1960 header.refresh_frame_flags,
1961 header.order_hint,
1962 header.tile_info.cols,
1963 header.tile_info.rows,
1964 header.tx_mode,
1965 header.interpolation_filter,
1966 header.reduced_tx_set,
1967 header.allow_warped_motion,
1968 header.is_motion_mode_switchable,
1969 header.use_ref_frame_mvs,
1970 header.skip_mode_present,
1971 header.cdef.bits,
1972 header.loop_restoration.frame_restoration_type,
1973 );
1974 }
1975
1976 let order_hint_bits = seq.order_hint_bits;
1977 // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
1978 // of the picture sitting in each of its 7 single references' DPB
1979 // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
1980 // (a later frame projects from it) whether or not this frame itself
1981 // reads temporal candidates.
1982 let ref_order_hints = snap.ref_order_hints;
1983
1984 crate::timeline::bind(
1985 decode_idx,
1986 if header.frame_type == FrameType::Key {
1987 'K'
1988 } else if header.show_frame {
1989 'P'
1990 } else {
1991 'A'
1992 },
1993 header.show_frame,
1994 );
1995 crate::timeline::hdr_done();
1996 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
1997 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
1998 &tile_bufs,
1999 &header.tile_info,
2000 header.mi_cols,
2001 header.mi_rows,
2002 header.quantization.base_q_idx,
2003 crate::quant::QuantDeltas {
2004 y_dc: i32::from(header.quantization.delta_q_y_dc),
2005 u_dc: i32::from(header.quantization.delta_q_u_dc),
2006 u_ac: i32::from(header.quantization.delta_q_u_ac),
2007 v_dc: i32::from(header.quantization.delta_q_v_dc),
2008 v_ac: i32::from(header.quantization.delta_q_v_ac),
2009 },
2010 header.frame_width,
2011 header.frame_height,
2012 enable_filter_intra,
2013 enable_edge_filter,
2014 &header.cdef,
2015 &header.loop_filter,
2016 &header.loop_restoration,
2017 initial_cdfs,
2018 header.tx_mode == TxMode::Select,
2019 header.reduced_tx_set,
2020 header.allow_screen_content_tools,
2021 header.allow_intrabc,
2022 header.delta,
2023 fctx,
2024 )?;
2025 // A key frame codes no inter blocks -- its own saved motion
2026 // field has no cells set, matching libaom's own "intra frame
2027 // contributes nothing to a later projection" behaviour, but
2028 // still carries `order_hint`/`ref_order_hints` for the distance
2029 // arithmetic a later frame's projection needs.
2030 let motion_field = crate::motion_field::MotionField::new(
2031 header.mi_cols as usize,
2032 header.mi_rows as usize,
2033 header.order_hint,
2034 ref_order_hints,
2035 // `frame_type` for the DPB slot: a key (or intra-only) frame is
2036 // never a projection source, and never spends a `ref_stamp`.
2037 true,
2038 );
2039 (picture, end_cdfs, Some(motion_field))
2040 } else {
2041 let last_slot = header.ref_frame_idx[0] as usize;
2042 let _ = last_slot;
2043 // lane-hdrlossless: libaom errors on the same stream -- a stream may
2044 // OPEN on an intra-only frame, but a reference resolving to a slot
2045 // that is still NULL is `AOM_CODEC_CORRUPT_FRAME "Inter frame
2046 // requests nonexistent reference"` (`decodeframe.c:5008-5031`) -- a
2047 // spec-conformant guard.
2048 if snap.refpix.dims(1).is_none() {
2049 return Err(Error::unsupported(
2050 "AV1 decode_stream",
2051 "an inter frame with no key frame before it",
2052 ));
2053 }
2054 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
2055 // (spec 7.8/7.20). Any of them having no picture yet is not a
2056 // stream error on its own: `decode_inter_block` only needs a
2057 // given slot when a block actually selects that reference, and
2058 // refuses by name there if the slot is still empty -- widened
2059 // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
2060 // one of the 7 single-reference slots.
2061 // lane-fimv r1: record the header state the fimv gate asserts on
2062 // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause).
2063 if header.force_integer_mv {
2064 decode::note_force_integer_mv_frame();
2065 }
2066 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
2067 // this frame's header actually asks for temporal candidates --
2068 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
2069 // behaviour bit for bit when this is `None` (see its own doc).
2070 // lane-twostage: the stage-1 sink is handed the table a consumer
2071 // would have read out of the slot, not the raw end-of-tile one.
2072 let started_from_stage1 = started_from.clone();
2073 let stage1_adapter = stage1.map(|sink| {
2074 move |end_cdfs: Cdfs,
2075 motion_field: crate::motion_field::MotionField,
2076 width: usize,
2077 height: usize| {
2078 sink(
2079 stored_cdfs_for(header, end_cdfs, started_from_stage1.clone()),
2080 motion_field,
2081 width,
2082 height,
2083 )
2084 }
2085 });
2086 let tpl_field = &snap.tpl_field;
2087 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
2088 &tile_bufs,
2089 &header.tile_info,
2090 header.mi_cols,
2091 header.mi_rows,
2092 header.quantization.base_q_idx,
2093 crate::quant::QuantDeltas {
2094 y_dc: i32::from(header.quantization.delta_q_y_dc),
2095 u_dc: i32::from(header.quantization.delta_q_u_dc),
2096 u_ac: i32::from(header.quantization.delta_q_u_ac),
2097 v_dc: i32::from(header.quantization.delta_q_v_dc),
2098 v_ac: i32::from(header.quantization.delta_q_v_ac),
2099 },
2100 header.frame_width,
2101 header.frame_height,
2102 snap.refpix,
2103 &header.cdef,
2104 &header.loop_filter,
2105 &header.loop_restoration,
2106 initial_cdfs,
2107 header.allow_high_precision_mv,
2108 header.force_integer_mv,
2109 header.ref_frame_sign_bias,
2110 header.global_motion,
2111 interp_fixed,
2112 enable_dual_filter,
2113 order_hint_bits,
2114 header.order_hint,
2115 ref_order_hints,
2116 tpl_field.as_ref(),
2117 header.reference_select,
2118 enable_masked_compound,
2119 enable_jnt_comp,
2120 enable_interintra_compound,
2121 header.skip_mode_present,
2122 header.skip_mode_frame,
2123 header.reduced_tx_set,
2124 header.tx_mode == TxMode::Select,
2125 header.is_motion_mode_switchable,
2126 header.allow_warped_motion,
2127 header.allow_screen_content_tools,
2128 header.delta,
2129 enable_filter_intra,
2130 stage1_adapter
2131 .as_ref()
2132 .map(|f| f as &dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)),
2133 fctx,
2134 )?;
2135 (picture, end_cdfs, motion_field)
2136 };
2137 // lane-lr r4: the Wiener/self-guided pixel filters are wired
2138 // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
2139 // `uses_lr` frames now decode all the way to pixels.
2140 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
2141 // *initial* table into the slots it refreshes, not the adapted
2142 // end-of-tile one.
2143 let stored_cdfs = stored_cdfs_for(header, end_cdfs, started_from);
2144 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
2145 use std::io::Write;
2146 if let Ok(mut f) = std::fs::OpenOptions::new()
2147 .create(true)
2148 .append(true)
2149 .open(&path)
2150 {
2151 let _ = writeln!(f, "=== frame idx={} ===", shown_idx);
2152 let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
2153 let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
2154 let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
2155 let _ = writeln!(f, "skip {:?}", stored_cdfs.skip);
2156 let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv);
2157 let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv);
2158 let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv);
2159 let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint);
2160 }
2161 }
2162 // lane-comppin r3: decode-order (not display-order) dump of every
2163 // frame's own post-deblock buffer -- the pre-existing pixel diff
2164 // (`scratch_isolate_pinned_mismatch`) only ever compares *shown*
2165 // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a
2166 // later shown frame is otherwise invisible; diff this byte-for-byte
2167 // against `EC_AV1_POSTFILT_DUMP.fN` from the instrumented aomdec
2168 // build to isolate whether the defect is in a hidden frame's own
2169 // reconstruction or downstream of it.
2170 if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") {
2171 use std::io::Write;
2172 let idx = decode_idx;
2173 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
2174 // lane-hbd r4: debug dump narrows to u8 -- this diagnostic
2175 // predates 10-bit support and is an 8-bit-oracle comparison
2176 // only (aomdec's own dump is 8-bit here too).
2177 let narrow = |v: &[u16]| -> Vec<u8> { v.iter().map(|&s| s as u8).collect() };
2178 let _ = f.write_all(&narrow(&picture.y));
2179 let _ = f.write_all(&narrow(&picture.u));
2180 let _ = f.write_all(&narrow(&picture.v));
2181 }
2182 }
2183 // lane-hidden r1: the frame exactly as it is about to be stored into
2184 // the reference slots -- after deblock/CDEF/LR/superres, in DECODE
2185 // order, hidden (`show_frame == 0`) alt-ref frames included, and
2186 // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the
2187 // u8-narrowing diagnostic dumps above. Matches the instrumented
2188 // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte
2189 // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a
2190 // hidden frame's pixels comparable at all.
2191 if let Some(prefix) = final_dump {
2192 use std::io::Write;
2193 if let Ok(mut f) = std::fs::File::create(format!("{prefix}.f{decode_idx}")) {
2194 let mut buf = Vec::new();
2195 for plane in [&picture.y, &picture.u, &picture.v] {
2196 if bit_depth == 8 {
2197 buf.extend(plane.iter().map(|&s| s as u8));
2198 } else {
2199 for &s in plane {
2200 buf.extend_from_slice(&s.to_le_bytes());
2201 }
2202 }
2203 }
2204 let _ = f.write_all(&buf);
2205 }
2206 }
2207 Ok(FrameOutput {
2208 picture,
2209 stored_cdfs,
2210 motion_field,
2211 seg_map: decode::take_segment_ids(fctx),
2212 })
2213}
2214
2215/// lane-intra14 r1: INTRA-coded 1:4 strips decoded on the INTER block path
2216/// (64x16, 16x64, 32x8, 8x32) -- the counters a recipe sweep needs from
2217/// outside the crate.
2218pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) {
2219 (
2220 crate::decode::intra_rect4_strip_in_inter_hits(0),
2221 crate::decode::intra_rect4_strip_in_inter_hits(1),
2222 crate::decode::intra_rect4_strip_in_inter_hits(2),
2223 crate::decode::intra_rect4_strip_in_inter_hits(3),
2224 )
2225}
2226
2227/// lane-av1recipehunt: the recipe sweep's view of the `delta_q` story from
2228/// OUTSIDE the crate -- `(delta_q symbol groups read, rect64 dequant calls that
2229/// saw `CURRENT_Q_IDX != base_q_idx`)`. A recipe that reads delta_q but never
2230/// lands one inside a rect64 root is a different failure from one that reads
2231/// neither, and the gate can only tell them apart with both numbers.
2232pub fn rect64_qidx_drift_counters() -> (usize, usize) {
2233 (
2234 crate::decode::delta_q_hits(),
2235 crate::decode::rect64_qidx_drift_hits(),
2236 )
2237}
2238
2239#[cfg(test)]
2240pub(crate) mod tests {
2241 use super::*;
2242 use crate::encode::{Picture as Pic, encode_key_frame_with_ctx, encode_sequence_with_ctx};
2243
2244 fn test_card(width: usize, height: usize) -> Pic {
2245 let mut picture = Pic::grey(width, height);
2246 for row in 0..height {
2247 for col in 0..width {
2248 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
2249 }
2250 }
2251 for row in 0..height / 2 {
2252 for col in 0..width / 2 {
2253 let i = row * width / 2 + col;
2254 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
2255 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
2256 }
2257 }
2258 picture
2259 }
2260
2261 fn panned_test_card(width: usize, height: usize, shift: i64) -> Pic {
2262 let mut picture = Pic::grey(width, height);
2263 for y in 0..height {
2264 for x in 0..width {
2265 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
2266 let gradient = sx * 200.0 / width as f64;
2267 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
2268 }
2269 }
2270 for y in 0..height / 2 {
2271 for x in 0..width / 2 {
2272 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
2273 let i = y * width / 2 + x;
2274 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
2275 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
2276 }
2277 }
2278 picture
2279 }
2280
2281 /// lane-av1txr: a sequence header describing any chroma shape but 4:2:0 is
2282 /// refused by name, because the decoder reconstructs every chroma extent
2283 /// at hardcoded 4:2:0 (`bw / 2, bh / 2` at every rect site) and the probe
2284 /// emits 4:2:0 planes only -- a 4:4:4 stream "decodes" into silently wrong
2285 /// pixels (measured: a444-cu6's first chroma transform reads a 4x2-wide/
2286 /// 8-high 4:2:0 chroma at aomdec's `TX_8X16` entry rng 39857, then
2287 /// desyncs; every 4:4:4 fixture measured byte-differs from ffmpeg).
2288 ///
2289 /// Reachability, not a pixel claim: the header is written at the two
2290 /// profiles that force a non-4:2:0 shape (spec 5.5.2 -- profile 1 forces
2291 /// 4:4:4 with no coded bit; profile 2 below 12-bit forces 4:2:2) and the
2292 /// tile is never reached. The 4:2:0 CONTROL below proves the refusal is
2293 /// about the shape, not about this construction.
2294 #[test]
2295 fn a_non_420_subsampled_sequence_header_is_refused_by_name() {
2296 const NAME: &str = "a_non_420_subsampled_sequence_header_is_refused_by_name";
2297 const REFUSAL: &str = "a chroma format of 4:2:2";
2298 let fctx = &crate::decode::FrameCtx::new();
2299 let picture = test_card(64, 64);
2300 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2301 for (profile, label, sx, sy) in [(2u8, "4:2:2", 1u8, 0u8)] {
2302 let color = ec_av1_syntax::ColorConfig {
2303 num_planes: 3,
2304 subsampling_x: sx,
2305 subsampling_y: sy,
2306 ..Default::default()
2307 };
2308 let (mut seq, header) =
2309 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
2310 seq.seq_profile = profile;
2311 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2312 stream
2313 .extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap());
2314 let err = decode_stream(&stream).unwrap_err().to_string();
2315 assert!(
2316 err.contains(REFUSAL),
2317 "{NAME}: expected the non-4:2:0 refusal for the {label} header, got: {err}"
2318 );
2319 }
2320 // CONTROL: the same construction at profile 0 (4:2:0) still decodes.
2321 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
2322 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
2323 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap());
2324 let frames = decode_stream(&stream).expect("the 4:2:0 control must decode");
2325 assert_eq!(
2326 frames.len(),
2327 1,
2328 "{NAME}: the 4:2:0 control decoded no frame"
2329 );
2330 }
2331
2332 /// lane-av1odd440, CELL 1 of 2: `4:2:0 with an ODD luma dimension`, the
2333 /// cell `lanes/av1formatsweep.report.md` left as declared debt because
2334 /// "aomenc rounds a 4:2:0 frame's coded size DOWN to even, so no stream
2335 /// this recipe can produce codes an odd luma dimension".
2336 ///
2337 /// The pin, `420_odd65x65_key.obu` (2305 bytes,
2338 /// sha256 `66986019a561f81130f407f426c4379b25e6e80c2cd9ce47d517b3216e9a03cf`),
2339 /// is that missing stream, built offline by
2340 /// `examples/gen_coverage_cells.rs`: a 96x96 card padded to the block
2341 /// grid, coded by `encode::encode_key_frame_at_size` with a 65x65 frame
2342 /// header. Provenance: that example, `cargo run -p ec-av1 --example
2343 /// gen_coverage_cells -- crates/ec-av1/fixtures`; no encoder, no ffmpeg,
2344 /// no lavfi.
2345 ///
2346 /// WHY THE CELL IS NOT A RUBBER STAMP -- the chroma extent is where a
2347 /// floor shows. A 65-wide 4:2:0 frame has
2348 /// `ROUND_POWER_OF_TWO(65, 1) = 33` chroma columns (libaom
2349 /// `av1_common_plane_width`, `av1/common/av1_common_int.h`), not 32, so
2350 /// the decoded frame's own plane sizes, the rawvideo sample count and
2351 /// the oracle compare all move if `decode::round_ss` is floored. The
2352 /// mutation was run: flooring `round_ss` (`decode.rs:697`) turns the
2353 /// `round_ss` assert below red at 32 chroma columns and the oracle arm
2354 /// red at a 6273-byte raw against the oracle's 6403. The gate is
2355 /// therefore not green on a floored decoder, which is the whole content
2356 /// of this cell.
2357 ///
2358 /// The stream decodes PIXEL-EXACT against the instrumented `aomdec`
2359 /// (6403 raw bytes = 65*65 + 2*33*33, byte-identical), so the cell is a
2360 /// `y` and not a `–`.
2361 #[test]
2362 fn an_odd_luma_420_key_frame_decodes_pixel_exact() {
2363 const NAME: &str = "an_odd_luma_420_key_frame_decodes_pixel_exact";
2364 let _gate_lock = lock_gate_counters();
2365 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2366 .join("fixtures")
2367 .join("420_odd65x65_key.obu");
2368 let stream = read_pin(&path, 2305, 0xf55645c4b139e8f7, NAME);
2369
2370 // The stream's OWN header, read from its own bytes: an odd luma size
2371 // at 4:2:0, which is the cell. (Taken from the pin, not from the
2372 // gate's name -- class `helper-packs-u16-for-an-8-bit-stream`.)
2373 let mut probe = Av1Parser::new();
2374 let mut pos = 0usize;
2375 while pos < stream.len() && probe.sequence_header().is_none() {
2376 let obu = probe
2377 .parse_obu(&stream[pos..])
2378 .unwrap_or_else(|e| panic!("{NAME}: OBU at byte {pos} does not parse: {e:?}"));
2379 pos += obu.total_size;
2380 }
2381 let seq = probe
2382 .sequence_header()
2383 .unwrap_or_else(|| panic!("{NAME}: the pin carries no sequence header"));
2384 assert_eq!(
2385 (seq.max_frame_width, seq.max_frame_height),
2386 (65, 65),
2387 "{NAME}: the pin must declare an ODD luma size, it declares {}x{}",
2388 seq.max_frame_width,
2389 seq.max_frame_height
2390 );
2391 assert_eq!(
2392 (
2393 seq.color_config.subsampling_x,
2394 seq.color_config.subsampling_y
2395 ),
2396 (1, 1),
2397 "{NAME}: this cell is an odd luma SIZE at 4:2:0, not another chroma shape"
2398 );
2399
2400 // The decoded frame's own extents. This arm needs no oracle, and it
2401 // is the one a floored `round_ss` turns red.
2402 let frames = decode_stream(&stream).expect("the odd-luma 4:2:0 pin must decode");
2403 assert_eq!(frames.len(), 1, "{NAME}: frame count");
2404 let frame = &frames[0];
2405 assert_eq!(
2406 (frame.width, frame.height),
2407 (65, 65),
2408 "{NAME}: decoded luma extent"
2409 );
2410 assert_eq!(frame.y.len(), 65 * 65, "{NAME}: decoded luma sample count");
2411 assert_eq!(
2412 (frame.u.len(), frame.v.len()),
2413 (33 * 33, 33 * 33),
2414 "{NAME}: a 65x65 4:2:0 frame has ROUND_POWER_OF_TWO(65,1) = 33 chroma \
2415 columns and rows -- 32 means the extent was floored"
2416 );
2417
2418 if !aomdec_available(NAME) {
2419 return;
2420 }
2421 assert_rawvideo_matches(&path, &stream, NAME, 1, 8);
2422 }
2423
2424 /// lane-av1odd440, CELL 2 of 2: the `4:4:0 (ss 0,1)` row, which the same
2425 /// report called "unmeasured and unproducible by recipe". It is neither
2426 /// unmeasured nor unproducible: it is NOT A CELL AT ALL.
2427 ///
2428 /// `subsampling_y` is coded only when `subsampling_x` is 1 (spec 5.5.2
2429 /// `color_config`), so a sequence header can carry exactly three chroma
2430 /// shapes -- 4:2:0 `(1,1)`, 4:2:2 `(1,0)`, 4:4:4 `(0,0)` -- and never
2431 /// `(0,1)`. libaom says so in both directions: the reader leaves
2432 /// `subsampling_y = 0` when `subsampling_x` is 0
2433 /// (`av1_read_color_config`, `av1/decoder/decodeframe.c:4171-4175`) and
2434 /// the writer ASSERTS it -- `assert(seq_params->subsampling_y == 0 &&
2435 /// "4:4:0 subsampling not allowed in AV1")`, `av1/encoder/bitstream.c:
2436 /// 2463-2465`. So there is no stream to decode, no fixture to pin that
2437 /// a decoder could be handed, and no oracle to compare against: a
2438 /// 4:4:0 row in a coverage matrix is a matrix bug, not a decoder gap.
2439 ///
2440 /// What is pinned, then, is the claim itself, in three arms that a
2441 /// mutation turns red:
2442 ///
2443 /// 1. WRITER: every `(profile, bit_depth, mono, colour description,
2444 /// requested subsampling)` combination a `color_config` can carry is
2445 /// written by this crate's own writer and read back by this crate's
2446 /// own reader. The reachable set is asserted to be EXACTLY
2447 /// `{(1,1), (1,0), (0,0)}` -- each legal shape present, `(0,1)`
2448 /// absent -- and, on the BYTES rather than on the round trip, the two
2449 /// requests that differ only in `subsampling_y` must write identical
2450 /// headers whenever `subsampling_x` is 0. A sweep that silently wrote
2451 /// nothing would pass, so the count of combinations actually written
2452 /// and read is asserted too.
2453 /// 2. READER: the one byte that carries `subsampling_x` is found by
2454 /// diffing an `(0,0)` header against an `(1,0)` one, and then all 256
2455 /// values of that byte are fed back through the reader. Not one of the
2456 /// headers that parse reads back `(0,1)`, because the reader never
2457 /// reads a `subsampling_y` bit in that position. A reader that always
2458 /// read a second bit would produce `(0,1)` at the one value that sets
2459 /// both bits.
2460 /// 3. THE PIN: `440_request_is_422.obu` (2014 bytes, sha256
2461 /// `4afaa5470c4e010d9d970086ef514680adfe801a579e4deeec582f52d13c5e7c`,
2462 /// fnv1a64 `0x98a1378df976253d`) is what this crate's writer produces
2463 /// when it is handed `subsampling (0,1)` at profile 2 -- profile 2
2464 /// below 12 bits is 4:2:2 and codes no subsampling bit at all, so the
2465 /// request lands on `(1,0)`. The pin is asserted to read back `(1,0)`,
2466 /// NOT `(0,1)`, and the decoder is asserted to refuse it by name,
2467 /// which is the honest outcome for the shape a 4:4:0 request actually
2468 /// yields. Its frame OBU is a 4:2:0 key frame's, so the pin is a HEADER
2469 /// witness, not a decodable 4:2:2 stream -- nothing here claims
2470 /// pixels for it. Provenance: `examples/gen_coverage_cells.rs`, `cargo
2471 /// run -p ec-av1 --example gen_coverage_cells -- crates/ec-av1/fixtures`.
2472 #[test]
2473 fn the_440_cell_is_not_a_codable_chroma_shape() {
2474 const NAME: &str = "the_440_cell_is_not_a_codable_chroma_shape";
2475 let _gate_lock = lock_gate_counters();
2476 let header_obu = |profile: u8, color: ec_av1_syntax::ColorConfig| -> Vec<u8> {
2477 let (mut seq, _header) = crate::encode::key_frame_headers_colour(64, 64, 100, color)
2478 .expect("the header builders accept a colour config");
2479 seq.seq_profile = profile;
2480 crate::sequence::sequence_header_obu(&seq).expect("writing the sequence header")
2481 };
2482 let shape_of = |obu: &[u8]| -> Option<(u8, u8)> {
2483 let mut parser = Av1Parser::new();
2484 let parsed = parser.parse_obu(obu).ok()?;
2485 if !matches!(parsed.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)) {
2486 return None;
2487 }
2488 let seq = parser.sequence_header()?;
2489 Some((
2490 seq.color_config.subsampling_x,
2491 seq.color_config.subsampling_y,
2492 ))
2493 };
2494
2495 // ---- arm 1: the writer's whole reachable space --------------------
2496 let mut reachable: std::collections::BTreeSet<(u8, u8)> = Default::default();
2497 let mut asked = 0usize;
2498 for profile in [0u8, 1, 2] {
2499 for bit_depth in [8u8, 10, 12] {
2500 for mono_chrome in [false, true] {
2501 // Profile 1 is 4:4:4 and codes no mono bit; asking for
2502 // monochrome there is refused by the writer, which is
2503 // not a chroma shape and not this gate's subject.
2504 if mono_chrome && profile == 1 {
2505 continue;
2506 }
2507 for (label, (cp, tc, mc)) in [
2508 ("unspecified", (2u8, 2u8, 2u8)),
2509 ("bt709", (1u8, 1u8, 1u8)),
2510 ("srgb", (1u8, 13u8, 0u8)),
2511 ] {
2512 for sx in [0u8, 1] {
2513 for sy in [0u8, 1] {
2514 let color = ec_av1_syntax::ColorConfig {
2515 bit_depth,
2516 mono_chrome,
2517 num_planes: if mono_chrome { 1 } else { 3 },
2518 color_primaries: cp,
2519 transfer_characteristics: tc,
2520 matrix_coefficients: mc,
2521 color_range: false,
2522 subsampling_x: sx,
2523 subsampling_y: sy,
2524 chroma_sample_position:
2525 ec_av1_syntax::ChromaSamplePosition::Unknown,
2526 separate_uv_delta_q: false,
2527 };
2528 asked += 1;
2529 let obu = header_obu(profile, color);
2530 // The WRITER half of the claim, measured on the
2531 // bytes rather than on a round trip: with
2532 // `subsampling_x == 0` the spec codes no
2533 // `subsampling_y` bit at all, so the two
2534 // requests that differ ONLY in `subsampling_y`
2535 // must produce byte-identical headers. A
2536 // writer that emitted the bit anyway (the
2537 // mutation libaom's own `assert` exists to
2538 // catch, av1/encoder/bitstream.c:2467-2468) fails
2539 // here -- and note it does NOT fail the
2540 // round trip, because the reader then absorbs
2541 // the extra bit as `separate_uv_delta_q`.
2542 if sx == 0 {
2543 let mut other = color;
2544 other.subsampling_y = 1;
2545 assert_eq!(
2546 obu,
2547 header_obu(profile, other),
2548 "{NAME}: a (0,0) and a (0,1) request wrote DIFFERENT \
2549 bytes at profile {profile}, {bit_depth}-bit, mono \
2550 {mono_chrome}, {label} -- `subsampling_y` must not be \
2551 coded at all when `subsampling_x` is 0"
2552 );
2553 }
2554 if let Some(got) = shape_of(&obu) {
2555 assert_ne!(
2556 got,
2557 (0, 1),
2558 "{NAME}: a 4:4:0 shape came back out of the writer at \
2559 profile {profile}, {bit_depth}-bit, mono {mono_chrome}, \
2560 {label}, asked for ({sx},{sy}) -- libaom forbids this \
2561 shape outright (av1/encoder/bitstream.c:2467-2468)"
2562 );
2563 reachable.insert(got);
2564 }
2565 }
2566 }
2567 }
2568 }
2569 }
2570 }
2571 assert!(
2572 asked >= 100 && reachable.len() == 3,
2573 "{NAME}: the sweep asked {asked} combinations and reached {} shapes -- it must reach \
2574 all three legal ones, or it is not measuring the space",
2575 reachable.len()
2576 );
2577 assert_eq!(
2578 reachable,
2579 std::collections::BTreeSet::from([(0u8, 0u8), (1u8, 0u8), (1u8, 1u8)]),
2580 "{NAME}: the chroma shapes a `color_config` can code are exactly 4:4:4 (0,0), 4:2:2 \
2581 (1,0) and 4:2:0 (1,1)"
2582 );
2583
2584 // ---- arm 2: the reader's bit at that position ----------------------
2585 // Profile 2 at 12 bits is the only place BOTH subsampling bits are
2586 // coded, so it is where a hand-built header could try to smuggle a
2587 // `subsampling_y`. Find the byte that carries `subsampling_x` by
2588 // diffing the two shapes, then read back all eight of its values.
2589 let at_444 = |sx: u8| {
2590 let color = ec_av1_syntax::ColorConfig {
2591 bit_depth: 12,
2592 subsampling_x: sx,
2593 subsampling_y: 0,
2594 chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown,
2595 ..ec_av1_syntax::ColorConfig::default()
2596 };
2597 let (mut seq, _h) =
2598 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
2599 seq.seq_profile = 2;
2600 let obu = crate::sequence::sequence_header_obu(&seq).unwrap();
2601 let mut parser = Av1Parser::new();
2602 parser.parse_obu(&obu).expect("the profile-2 header parses");
2603 let seq = parser.sequence_header().expect("sequence header");
2604 (
2605 seq.color_config.subsampling_x,
2606 seq.color_config.subsampling_y,
2607 )
2608 };
2609 assert_eq!(at_444(0), (0, 0), "{NAME}: the sx=0 header is 4:4:4");
2610 assert_eq!(at_444(1), (1, 0), "{NAME}: the sx=1 header is 4:2:2");
2611 let base = {
2612 let color = ec_av1_syntax::ColorConfig {
2613 bit_depth: 12,
2614 subsampling_x: 0,
2615 subsampling_y: 0,
2616 chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown,
2617 ..ec_av1_syntax::ColorConfig::default()
2618 };
2619 let (mut seq, _h) =
2620 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
2621 seq.seq_profile = 2;
2622 crate::sequence::sequence_header_obu(&seq).unwrap()
2623 };
2624 let other = {
2625 let color = ec_av1_syntax::ColorConfig {
2626 bit_depth: 12,
2627 subsampling_x: 1,
2628 subsampling_y: 0,
2629 chroma_sample_position: ec_av1_syntax::ChromaSamplePosition::Unknown,
2630 ..ec_av1_syntax::ColorConfig::default()
2631 };
2632 let (mut seq, _h) =
2633 crate::encode::key_frame_headers_colour(64, 64, 100, color).unwrap();
2634 seq.seq_profile = 2;
2635 crate::sequence::sequence_header_obu(&seq).unwrap()
2636 };
2637 assert_eq!(
2638 base.len(),
2639 other.len(),
2640 "{NAME}: the two headers must differ in place"
2641 );
2642 let byte_at = base
2643 .iter()
2644 .zip(&other)
2645 .position(|(a, b)| a != b)
2646 .expect("the two shapes must differ somewhere");
2647 // Every value of that byte is fed back through the reader -- it is the
2648 // LAST payload byte, so the bits a smuggled `subsampling_y` would come
2649 // from are in it too (spec 5.5.2 always codes `separate_uv_delta_q`
2650 // after the subsampling pair, and the payload is padded out to the
2651 // byte with `trailing_bits`). A header that stops parsing is not a
2652 // 4:4:0 shape and cannot be counted as one; the sweep asserts how
2653 // many DID parse, so a sweep that quietly parsed nothing is not
2654 // evidence of anything.
2655 let mut parsed_headers = 0usize;
2656 for value in 0..256u16 {
2657 let mut poked = base.clone();
2658 poked[byte_at] = value as u8;
2659 let mut parser = Av1Parser::new();
2660 let Ok(parsed) = parser.parse_obu(&poked) else {
2661 continue;
2662 };
2663 if !matches!(parsed.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)) {
2664 continue;
2665 }
2666 let seq = parser.sequence_header().expect("sequence header");
2667 parsed_headers += 1;
2668 assert_ne!(
2669 (
2670 seq.color_config.subsampling_x,
2671 seq.color_config.subsampling_y
2672 ),
2673 (0, 1),
2674 "{NAME}: payload byte {byte_at} = {value:#04x} read back as 4:4:0 -- the reader \
2675 took a `subsampling_y` bit that spec 5.5.2 does not code when `subsampling_x` \
2676 is 0"
2677 );
2678 }
2679 assert!(
2680 parsed_headers > 100,
2681 "{NAME}: only {parsed_headers} of the 256 poked headers parsed -- the sweep is not \
2682 measuring the reader"
2683 );
2684
2685 // ---- arm 3: the pinned bytes a 4:4:0 request produces --------------
2686 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2687 .join("fixtures")
2688 .join("440_request_is_422.obu");
2689 let pinned = read_pin(&path, 2014, 0x98a1378df976253d, NAME);
2690 let mut parser = Av1Parser::new();
2691 let obu = parser
2692 .parse_obu(&pinned)
2693 .unwrap_or_else(|e| panic!("{NAME}: the pin's first OBU does not parse: {e:?}"));
2694 assert!(
2695 matches!(obu.kind, ec_av1_syntax::ObuKind::SequenceHeader(_)),
2696 "{NAME}: the pin must start with its sequence header"
2697 );
2698 let seq = parser.sequence_header().expect("the pin's sequence header");
2699 assert_eq!(
2700 (
2701 seq.color_config.subsampling_x,
2702 seq.color_config.subsampling_y
2703 ),
2704 (1, 0),
2705 "{NAME}: the pin is what a 4:4:0 request at profile 2 produces -- 4:2:2 (1,0). If this \
2706 ever reads (0,1), a 4:4:0 cell became codable and this whole gate is wrong about the \
2707 format."
2708 );
2709 let err = decode_stream(&pinned).unwrap_err().to_string();
2710 assert!(
2711 err.contains("a chroma format of 4:2:2"),
2712 "{NAME}: the shape the 4:4:0 request lands on must still refuse by name, got: {err}"
2713 );
2714 }
2715 /// lane-av1-422bigblock: the two witnessed 4:2:2 big-block defects, pinned
2716 /// as fixtures (`git add -f`; `fixtures/` is gitignored).
2717 ///
2718 /// `422_allskip_2f.obu` (62 bytes) is a 128x128 profile-2 key frame plus
2719 /// its all-skip first inter frame: the pre-port decoder read phantom
2720 /// coefficient units in the inter frame and then panicked in
2721 /// `reconstruct_mc_rect` on a full-height 4:2:2 chroma rect. At this
2722 /// lane's HEAD the block-half port's per-axis plane-block model already
2723 /// has it entropy-locked (all 20 key-frame coefficient units pair
2724 /// rng-for-rng with the instrumented oracle, the inter frame reads
2725 /// zero, matching the oracle) and pixel-exact vs aomdec.
2726 ///
2727 /// `422_sb128_3f.obu` (12543 bytes) carries the f2 128x128
2728 /// `PARTITION_NONE` non-skip inter block: the mu-chunk chroma walk cut
2729 /// each chunk's 32x64 chroma into a `chroma_side`-square 64x64 (twice
2730 /// the units the oracle codes), indexed the prediction buffer at the
2731 /// square `chroma_side` instead of `chroma_stride` (the empty-slice
2732 /// panic at `push_mc_rect_tx`'s densify), and the reference plane
2733 /// resolution guessed every non-4:4:4 picture quarter-height, so the
2734 /// bottom mu-chunk row predicted from a clamped row-63 edge. All fixed;
2735 /// both witnesses decode pixel-exact vs aomdec on the lane's local
2736 /// `EC_AV1_ALLOW_422_PROBE` patch-run-restore build (recipe and measured
2737 /// numbers in `lanes/av1422bigblock.report.md`).
2738 ///
2739 /// `decode_stream` itself still refuses 4:2:2 at the sequence header --
2740 /// unconditionally, per the standing family rule -- so the committed
2741 /// assertion is the byte pin (fnv1a64, the same load-bearing-identity
2742 /// fingerprint as the cdf-forwarding gate) plus the refusal-by-name
2743 /// contract over the pinned bytes.
2744 #[test]
2745 fn the_pinned_422_bigblock_witnesses_are_present_and_refuse_by_name() {
2746 const NAME: &str = "the_pinned_422_bigblock_witnesses_are_present_and_refuse_by_name";
2747 const REFUSAL: &str = "a chroma format of 4:2:2";
2748 for (file, bytes, fp) in [
2749 ("422_allskip_2f.obu", 62usize, 0x7e4d69d3c728c55f_u64),
2750 ("422_sb128_3f.obu", 12543, 0x5171e0aab8000da7),
2751 ] {
2752 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2753 .join("fixtures")
2754 .join(file);
2755 let data = std::fs::read(&path).unwrap_or_else(|e| {
2756 panic!(
2757 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
2758 path.display()
2759 )
2760 });
2761 assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
2762 assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
2763 let err = decode_stream(&data).unwrap_err().to_string();
2764 assert!(
2765 err.contains(REFUSAL),
2766 "{NAME}: {file} must refuse by name, got: {err}"
2767 );
2768 }
2769 }
2770
2771 /// lane-av1-ibc128chunk: the WITNESS for the 128-root intrabc strip's
2772 /// de-square-cut mu-chunk chroma walk, and the byte pin for it.
2773 ///
2774 /// `decode_intrabc_128rect` cut each mu chunk's chroma plane block with
2775 /// `chunk_chroma = cside * 64 / side` -- a `chroma_side`-SQUARE chunk,
2776 /// i.e. the 4:2:0 count on BOTH axes (the same defect lane-av1-422bigblock
2777 /// fixed, and witnessed, in `decode_inter_block` and
2778 /// `decode_block_128rect`; this copy was deferred there as unwitnessed).
2779 /// At 4:2:2 a 64x64 mu chunk's chroma plane block is 32x64, so it holds
2780 /// TWO STACKED TX_32X32 units per plane: the square-cut walk read one per
2781 /// plane per chunk, left the chunk's lower 32 chroma rows with no
2782 /// residual at all, and stamped each unit's entropy context over a
2783 /// 16x16-mi luma span instead of 16x8.
2784 ///
2785 /// Measured red-before on the pinned witness (parent `a7d22aec`, via the
2786 /// local `EC_AV1_ALLOW_422_PROBE` patch-run-restore build): 8 chroma
2787 /// units stamped over the stream's two reached blocks and frames 0 and 3
2788 /// diverge from `aomdec` (45135 / 44540 of 245760 samples each), the
2789 /// first difference at Y sample 98368 -- frame 0, row 256, col 64, the
2790 /// top-left corner of the first 128x64 intrabc block at mi(64,0). The
2791 /// red build then lost 4 of the stream's 6 intrabc blocks to the desync.
2792 /// Green-after, same fixture: 48 chroma units stamped, all 6 blocks
2793 /// decoded, and ALL FIVE frames byte-identical to `aomdec --rawvideo`.
2794 ///
2795 /// Committed code refuses 4:2:2 at the sequence header, so the decode
2796 /// assertions above are probe-measured and reproducible from the lane
2797 /// report's recipe; what this gate can assert in committed code is the
2798 /// byte pin, the refusal-by-name contract, and -- in the arm below --
2799 /// that the per-axis walk is still spelled per-axis in the source.
2800 #[test]
2801 fn the_pinned_422_intrabc_sb128_strip_witnesses_refuse_by_name() {
2802 const NAME: &str = "the_pinned_422_intrabc_sb128_strip_witnesses_refuse_by_name";
2803 const REFUSAL: &str = "a chroma format of 4:2:2";
2804 for (file, bytes, fp) in [
2805 (
2806 "422_intrabc_sb128_strip.obu",
2807 1672usize,
2808 0x50f5cfc576e4cd00_u64,
2809 ),
2810 (
2811 "422_intrabc_sb128_strip_notxsearch.obu",
2812 1675,
2813 0xd4936f252ff8cff0,
2814 ),
2815 ] {
2816 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2817 .join("fixtures")
2818 .join(file);
2819 let data = std::fs::read(&path).unwrap_or_else(|e| {
2820 panic!(
2821 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
2822 path.display()
2823 )
2824 });
2825 assert_eq!(data.len(), bytes, "{NAME}: {file} size drifted");
2826 assert_eq!(fnv1a64(&data), fp, "{NAME}: {file} bytes drifted");
2827 let err = decode_stream(&data).unwrap_err().to_string();
2828 assert!(
2829 err.contains(REFUSAL),
2830 "{NAME}: {file} must refuse by name, got: {err}"
2831 );
2832 }
2833 }
2834
2835 /// lane-av1-ibc128chunk: the SOURCE-SCAN arm of the witness gate above.
2836 ///
2837 /// The decode-level half of the red/green evidence cannot run in
2838 /// committed code (the 4:2:2 refusal stands), so this arm pins the thing
2839 /// that would silently bring the defect back: the square-cut
2840 /// `chunk_chroma = cside * 64 / side` expression, and the per-axis
2841 /// replacements that replaced it at BOTH sites in
2842 /// [`decode_intrabc_128rect`] -- the mu-chunk read walk and the
2843 /// `mu_chroma` per-unit context replay. It also pins the per-axis
2844 /// counters' accessors so the arms stay reachable, and the walk's own
2845 /// per-axis extent, derived here from the same `64 >> ss` form the
2846 /// witnesses measured (4:2:0 = one TX_32X32 per plane per chunk,
2847 /// 4:2:2 = two stacked, 4:4:4 = four).
2848 #[test]
2849 fn the_intrabc_128rect_chroma_chunk_walk_stays_per_axis() {
2850 const NAME: &str = "the_intrabc_128rect_chroma_chunk_walk_stays_per_axis";
2851 let src = include_str!("decode.rs");
2852 let body = src
2853 .split_once("fn decode_intrabc_128rect(")
2854 .expect("decode_intrabc_128rect must exist")
2855 .1
2856 .split_once("\nfn ")
2857 .expect("decode_intrabc_128rect must be a top-level fn")
2858 .0;
2859 // Scan CODE only: the fix's own comments quote the old expression to
2860 // say what it was, and a prose mention must not read as a
2861 // reintroduction (nor mask one).
2862 let stripped: Vec<&str> = body
2863 .lines()
2864 .map(|l| l.split_once("//").map_or(l, |(c, _)| c))
2865 .collect();
2866 let code = stripped.join("\n");
2867 let body = code.as_str();
2868 assert_eq!(
2869 body.matches("cside * 64 / side").count(),
2870 0,
2871 "{NAME}: the square-cut `cside * 64 / side` chunk extent is BACK in \
2872 decode_intrabc_128rect -- that expression is the 4:2:2 defect this \
2873 gate exists for (a 64x64 mu chunk's chroma plane block is \
2874 (64 >> ss_x) x (64 >> ss_y), not `chroma_side` square)"
2875 );
2876 // The per-axis chunk extent, declared once at the mu-chunk read walk
2877 // and once at the `mu_chroma` replay -- the two de-square-cut sites.
2878 //
2879 // The replay must ALSO enumerate every unit inside a chunk, not just
2880 // its first: counting mu CHUNKS in `rows`/`cols` and then stepping the
2881 // mi origin and reading the grid per UNIT only agrees when a chunk
2882 // holds exactly one unit (4:2:0). At 4:2:2 and 4:4:4 a chunk holds two
2883 // or four, so the per-unit body alone left the rest of the chunk with
2884 // the composed-grid smearing the replay exists to undo.
2885 for name in [
2886 "let chunk_chroma_w = (64usize) >> ss_x(fctx);",
2887 "let chunk_chroma_h = (64usize) >> ss_y(fctx);",
2888 ] {
2889 assert_eq!(
2890 body.matches(name).count(),
2891 2,
2892 "{NAME}: `{name}` must appear at BOTH de-square-cut sites in \
2893 decode_intrabc_128rect (the mu-chunk read walk and the mu_chroma \
2894 context replay), found {}",
2895 body.matches(name).count()
2896 );
2897 }
2898 for name in [
2899 "let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);",
2900 "for kr in 0..ur {",
2901 "for kc in 0..uc {",
2902 ] {
2903 assert_eq!(
2904 body.matches(name).count(),
2905 1,
2906 "{NAME}: `{name}` must appear exactly once in \
2907 decode_intrabc_128rect -- the mu_chroma replay must walk chunk \
2908 THEN unit (decode_inter_block's `mu_chroma_units` shape), found {}",
2909 body.matches(name).count()
2910 );
2911 }
2912 for name in [
2913 "let unit_luma_w = cu_tx << ss_x(fctx);",
2914 "let unit_luma_h = cu_tx << ss_y(fctx);",
2915 "let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));",
2916 "let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));",
2917 "neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h)",
2918 ] {
2919 assert_eq!(
2920 body.matches(name).count(),
2921 1,
2922 "{NAME}: `{name}` must appear exactly once in \
2923 decode_intrabc_128rect, found {}",
2924 body.matches(name).count()
2925 );
2926 }
2927 // The replay's own unit luma span is the lossless/lossy `cu << ss` form
2928 // (site 2 spells it separately from the read walk's `cu_tx << ss`).
2929 for name in [
2930 "let unit_luma_w = cu << ss_x(fctx);",
2931 "let unit_luma_h = cu << ss_y(fctx);",
2932 ] {
2933 assert_eq!(
2934 body.matches(name).count(),
2935 1,
2936 "{NAME}: `{name}` must appear exactly once in \
2937 decode_intrabc_128rect, found {}",
2938 body.matches(name).count()
2939 );
2940 }
2941 // The per-axis chunk extent the geometry demands, spelled out here so
2942 // the scan and the witnesses cannot disagree about it.
2943 let per_axis_units = |ss_x: u32, ss_y: u32| (64 >> ss_x) / 32 * (64 >> ss_y) / 32;
2944 assert_eq!(per_axis_units(1, 1), 1, "{NAME}: 4:2:0 must stay one unit");
2945 assert_eq!(per_axis_units(1, 0), 2, "{NAME}: 4:2:2 must be two units");
2946 assert_eq!(per_axis_units(0, 0), 4, "{NAME}: 4:4:4 must be four units");
2947 // The counters the probe arms read must stay exported.
2948 for name in [
2949 "pub fn intrabc_128rect_chroma_chunk_hits()",
2950 "pub fn intrabc_128rect_chunk_shape()",
2951 ] {
2952 assert!(
2953 src.contains(name),
2954 "{NAME}: the accessor `{name}` must stay in decode.rs"
2955 );
2956 }
2957 }
2958 /// lane-av1422warp: the SECOND 4:2:2 coverage witness -- the one
2959 /// `422_sb128_3f.obu` could not be, because that stream's inter content
2960 /// is skip-heavy (see `lanes/av1422stripwrite.report.md`, which named a
2961 /// second fixture with real residuals, compound and warped motion above
2962 /// the vertical midpoint as the thing that would justify lifting the
2963 /// refusal). This is that fixture.
2964 ///
2965 /// `422_residual_compound_warp_16f.obu` (38845 bytes), sha256
2966 /// `d78e2afb43ce311d3d82335a945c6f80f62db4537966d881c1349a68b3aecb95`:
2967 ///
2968 /// ```text
2969 /// 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" \
2970 /// -frames:v 24 -pix_fmt yuv422p -f yuv4mpegpipe src422.y4m
2971 /// aomenc --codec=av1 --profile=2 --input-bit-depth=8 --limit=16
2972 /// --width=256 --height=288 --lag-in-frames=25 --auto-alt-ref=1
2973 /// --enable-global-motion=1 --pass=1
2974 /// --cq-level=24 --cpu-used=0
2975 /// --threads=4 --kf-min-dist=0 --kf-max-dist=999999 \
2976 /// src422.y4m -o a1.webm
2977 /// ffmpeg -i a1.webm -c copy -f obu -y a1.obu
2978 /// ```
2979 ///
2980 /// CORRECTED by lane-av1422lrless (reviewer P2). This doc previously
2981 /// carried a different ffmpeg filter (`rotate=a=0.10`, no `*t`, no
2982 /// `:c=none:ow/oh`) and a `-n ffp --pass=2 --fpf=...` two-pass line.
2983 /// **Neither produced these bytes.** Re-encoding from the recorded
2984 /// source `src422.y4m` (sha256
2985 /// `4d35eaf65d1a5541b3177e1183644c163b3868d8f141bed0ce9fdf833280ba9f`)
2986 /// was measured three ways: the two-pass form gives 38774 bytes
2987 /// (`e93c4ed7...`), and only adding `--pass=1` reproduces these 38845
2988 /// bytes byte for byte (`d78e2afb...`). `aomenc` DEFAULTS to two-pass,
2989 /// so the flag has to be stated to get back the pinned stream. The
2990 /// recipe above is the one that was actually run.
2991 ///
2992 /// Measured on a patch-run-restore build (the `EC_AV1_ALLOW_422_PROBE`
2993 /// bypass applied for the run, reverted after -- it is deliberately NOT
2994 /// committed, and the refusal below is what the committed tree asserts):
2995 ///
2996 /// - all 16 frames pixel-exact against `aomdec --rawvideo`, 2359296
2997 /// bytes each, sha256 `4bfc2395e5ca6ea178f606e6b1ced773e26fc2d85b
2998 /// c3a6cdb63a402939aeb203` on both sides;
2999 /// - the entropy stream pairs bit-for-bit against the instrumented
3000 /// oracle -- 246735 symbol reads each, no divergence anywhere in the
3001 /// stream, not merely at the window this lane spent nine rounds
3002 /// narrowing;
3003 /// - the arms this fixture exists to cover really fire ABOVE the
3004 /// vertical midpoint: 3 upper-half blocks on a non-`TRANSLATION`
3005 /// global-motion model (`top_half_warp_hits`, gated on libaom's
3006 /// `is_global_mv_block` per slot) and 3 upper-half
3007 /// `GLOBAL_GLOBALMV` compound blocks (`top_half_compound_hits`),
3008 /// alongside 25 compound-warp, 18 compound-warp-8x8-leaf, 84
3009 /// rotzoom global-warp, 22 Wiener and 10 SGRPROJ loop-restoration
3010 /// units frame-globally.
3011 ///
3012 /// The loop-restoration numbers are load-bearing twice over: decoding
3013 /// this stream is what exposed the per-axis `read_lr` corner bug
3014 /// (`restoration.rs`, `av1_loop_restoration_corners_in_sb`), whose fix
3015 /// is what made the whole sequence pair. 4:2:0 and 4:4:4 are unchanged
3016 /// by it -- byte-identical to their pre-lane decodes, with the LR gate
3017 /// family green.
3018 ///
3019 /// Like its two siblings, the committed assertion is the byte pin plus
3020 /// the refusal-by-name contract: with the header refusal standing,
3021 /// NO committed test can decode a 4:2:2 stream, because the bypass that
3022 /// would allow it must never be committed.
3023 #[test]
3024 fn the_pinned_422_residual_compound_warp_witness_is_present_and_refuses_by_name() {
3025 const NAME: &str =
3026 "the_pinned_422_residual_compound_warp_witness_is_present_and_refuses_by_name";
3027 const REFUSAL: &str = "a chroma format of 4:2:2";
3028 const FILE: &str = "422_residual_compound_warp_16f.obu";
3029 const BYTES: usize = 38845;
3030 const FP: u64 = 0x0e73a51e2cc0c424;
3031 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3032 .join("fixtures")
3033 .join(FILE);
3034 let data = std::fs::read(&path).unwrap_or_else(|e| {
3035 panic!(
3036 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
3037 path.display()
3038 )
3039 });
3040 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
3041 assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted");
3042 let err = decode_stream(&data).unwrap_err().to_string();
3043 assert!(
3044 err.contains(REFUSAL),
3045 "{NAME}: {FILE} must refuse by name, got: {err}"
3046 );
3047 }
3048 /// lane-av1422lrless: the LR-OFF half of the 4:2:2 coverage pair.
3049 ///
3050 /// This is `422_residual_compound_warp_16f.obu`'s recipe with EXACTLY
3051 /// ONE flag changed, `--enable-restoration=0`, and that is a measured
3052 /// claim rather than an assertion: both arms were re-encoded from the
3053 /// same source `src422.y4m` (sha256
3054 /// `4d35eaf65d1a5541b3177e1183644c163b3868d8f141bed0ce9fdf833280ba9f`)
3055 /// with the same aomenc invocation, and the LR-on arm reproduces the
3056 /// committed 38845 bytes byte for byte. So the pair is controlled, and
3057 /// the corners code is the only thing that can differ between their
3058 /// decodes: with restoration off, every plane's `frame_restoration_type`
3059 /// is `RESTORE_NONE`, so `read_lr` skips each plane and never computes a
3060 /// range. The LR-on stream exercises the range; this one proves the skip
3061 /// is the skip.
3062 ///
3063 /// ```text
3064 /// aomenc --codec=av1 --profile=2 --input-bit-depth=8 --limit=16
3065 /// --width=256 --height=288 --lag-in-frames=25 --auto-alt-ref=1
3066 /// --enable-global-motion=1 --pass=1 --enable-restoration=0
3067 /// --cq-level=24 --cpu-used=0
3068 /// --threads=4 --kf-min-dist=0 --kf-max-dist=999999 \
3069 /// src422.y4m -o a3.webm
3070 /// ffmpeg -i a3.webm -c copy -f obu -y a3.obu
3071 /// ```
3072 ///
3073 /// 38538 bytes, sha256
3074 /// `8bed368f7ec4bca772137c6a9c2af89e1b2767ed5f937b91bd9e72ec60aeb42f`.
3075 ///
3076 /// Measured on a patch-run-restore build (the `EC_AV1_ALLOW_422_PROBE`
3077 /// bypass applied for the run, reverted after -- deliberately not
3078 /// committed, and the refusal asserted below is what this tree ships):
3079 ///
3080 /// - all 16 frames pixel-exact against `aomdec --rawvideo`, 2359296
3081 /// bytes each, sha256 `1cf47bc9e06a6e286452dfe4ffe457a85b6badd25
3082 /// 657dfd36af48262e8eb2464` on both sides;
3083 /// - the entropy stream pairs **244756-for-244756** against the
3084 /// instrumented oracle with no divergence anywhere -- a different
3085 /// read count from the LR-on sibling's 246735, which is the corners
3086 /// skip showing up in the symbol stream, so the two arms really are
3087 /// on different paths;
3088 /// - **loop restoration is proved off, not inferred from the flag**:
3089 /// all five LR counters read zero where the LR-on sibling reads
3090 /// `lr_wiener` 22, `lr_sgrproj` 10, `lr_stripe0` 26, `lr_last_stripe`
3091 /// 28;
3092 /// - and it carries MORE of the coverage than its sibling, which is
3093 /// what rescues the thin leg of the lift argument: **top-half
3094 /// compound 11** against the sibling's 3, and top-half warp 5 against
3095 /// 3. Frame-globally compound_warp 25, compound_warp_8 15, rotzoom
3096 /// global-warp 77, cdef_idx 39, part128_split 95. The stronger arm is
3097 /// the one where `read_lr` does nothing at all, so the engagement is
3098 /// not an artefact of the code under test.
3099 ///
3100 /// Same scope as its siblings, for the same reason: with the header
3101 /// refusal standing no committed test can decode a 4:2:2 stream,
3102 /// because the bypass that would allow it must never be committed.
3103 #[test]
3104 fn the_pinned_422_lr_off_witness_is_present_and_refuses_by_name() {
3105 const NAME: &str = "the_pinned_422_lr_off_witness_is_present_and_refuses_by_name";
3106 const REFUSAL: &str = "a chroma format of 4:2:2";
3107 const FILE: &str = "422_residual_compound_warp_nolr_16f.obu";
3108 const BYTES: usize = 38538;
3109 const FP: u64 = 0x4b8ff761701e2bef;
3110 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3111 .join("fixtures")
3112 .join(FILE);
3113 let data = std::fs::read(&path).unwrap_or_else(|e| {
3114 panic!(
3115 "{NAME}: pinned witness {} is missing ({e}) -- the gate cannot run",
3116 path.display()
3117 )
3118 });
3119 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
3120 assert_eq!(fnv1a64(&data), FP, "{NAME}: {FILE} bytes drifted");
3121 let err = decode_stream(&data).unwrap_err().to_string();
3122 assert!(
3123 err.contains(REFUSAL),
3124 "{NAME}: {FILE} must refuse by name, got: {err}"
3125 );
3126 }
3127
3128 /// lane-av1-qmatrix: WITNESS for the lifted `using_qmatrix` refusal (the
3129 /// old gate `a_frame_using_quantisation_matrices_is_refused_by_name` is
3130 /// its mirror image -- its own panic said "flip this gate to a witness"
3131 /// the moment the dequant landed).
3132 ///
3133 /// A REAL `aomenc --enable-qm=1` stream (same source and recipe as the
3134 /// refusal's gate, plus its `--enable-qm=0` control) now DECODES, and
3135 /// every frame of both arms is pixel-exact against ffmpeg's own decode
3136 /// of the same OBU. The census proves the feature non-vacuously both
3137 /// ways (class `gate-blind-to-feature`): the parsed frame headers really
3138 /// carry `using_qmatrix = 1`, the dequantiser really SCALED transform
3139 /// units through a matrix on the qm-on arm (`qm_scaled_units() > 0`),
3140 /// and the qm-off control really scaled none (`== 0`).
3141 #[test]
3142 fn a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact() {
3143 const NAME: &str = "a_real_aomenc_quantisation_matrix_stream_decodes_pixel_exact";
3144 if !have_ffmpeg() || !have_aomenc() {
3145 eprintln!(
3146 "SKIP {NAME}: needs ffmpeg + an aomenc oracle at {}",
3147 aomenc_path().display()
3148 );
3149 return;
3150 }
3151 const W: usize = 128;
3152 const H: usize = 96;
3153 const FRAMES: usize = 3;
3154 // Every frame header's (using_qmatrix, qm_y, qm_u, qm_v), parsed
3155 // straight off the encoded bytes.
3156 let qm_headers = |stream: &[u8]| -> Vec<(bool, u8, u8, u8)> {
3157 let mut parser = Av1Parser::new();
3158 let mut pos = 0usize;
3159 let mut out = Vec::new();
3160 while pos < stream.len() {
3161 let obu = parser.parse_obu(&stream[pos..]).unwrap();
3162 pos += obu.total_size;
3163 if let ObuKind::Frame(header, _) = obu.kind {
3164 let q = &header.quantization;
3165 out.push((q.using_qmatrix, q.qm_y, q.qm_u, q.qm_v));
3166 }
3167 }
3168 out
3169 };
3170 // `census_attempt` hands back only the stream LENGTH; this witness
3171 // needs the BYTES to hand ffmpeg, so the same recipe (its base args
3172 // verbatim, `testsrc2` 128x96 @ 25fps, 3 frames) runs inline.
3173 let encode = |extra: &[&str]| -> Vec<u8> {
3174 let y4m = Command::new("ffmpeg")
3175 .args([
3176 "-v",
3177 "error",
3178 "-f",
3179 "lavfi",
3180 "-i",
3181 &format!("testsrc2=size={W}x{H}:rate=25"),
3182 "-t",
3183 "0.12",
3184 "-pix_fmt",
3185 "yuv420p",
3186 "-strict",
3187 "-1",
3188 "-f",
3189 "yuv4mpegpipe",
3190 "-",
3191 ])
3192 .stdin(Stdio::null())
3193 .stdout(Stdio::piped())
3194 .stderr(Stdio::piped())
3195 .output()
3196 .expect("ffmpeg failed to run");
3197 assert!(y4m.status.success(), "ffmpeg refused the {W}x{H} fixture");
3198 let mut args: Vec<String> = [
3199 "--codec=av1",
3200 "--passes=1",
3201 "--end-usage=q",
3202 "--threads=1",
3203 "--row-mt=0",
3204 "--kf-max-dist=9999",
3205 "--lag-in-frames=0",
3206 ]
3207 .iter()
3208 .map(|s| (*s).to_owned())
3209 .collect();
3210 args.push(format!("--limit={FRAMES}"));
3211 args.extend(extra.iter().map(|s| (*s).to_owned()));
3212 args.extend([
3213 "--obu".to_owned(),
3214 "-o".to_owned(),
3215 "-".to_owned(),
3216 "-".to_owned(),
3217 ]);
3218 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3219 assert!(
3220 out.status.success(),
3221 "aomenc refused {args:?}: {}",
3222 String::from_utf8_lossy(&out.stderr)
3223 );
3224 out.stdout
3225 };
3226 // Pixel-exact every decoded frame of `stream` against ffmpeg, plane
3227 // by plane, first differing sample named.
3228 let compare = |stream: &[u8], frames: usize, label: &str| {
3229 let want = ffmpeg_decode_sequence(stream, W, H, frames);
3230 let got =
3231 decode_stream(stream).unwrap_or_else(|e| panic!("{NAME}: {label} decode: {e}"));
3232 assert_eq!(got.len(), want.len(), "{NAME}: {label} frame count");
3233 for (i, (g, w)) in got.iter().zip(want.iter()).enumerate() {
3234 for (plane, (gp, wp)) in [(&g.y, &w.y), (&g.u, &w.u), (&g.v, &w.v)]
3235 .into_iter()
3236 .enumerate()
3237 {
3238 assert_eq!(
3239 gp,
3240 wp,
3241 "{NAME}: {label} frame {i} plane {plane} differs from ffmpeg (first mismatching sample: got {}, want {})",
3242 gp.iter()
3243 .zip(wp.iter())
3244 .find(|(a, b)| a != b)
3245 .map_or(0, |(a, _)| *a),
3246 gp.iter()
3247 .zip(wp.iter())
3248 .find(|(a, b)| a != b)
3249 .map_or(0, |(_, b)| *b)
3250 );
3251 }
3252 }
3253 };
3254
3255 // CONTROL: the same source and recipe with quantisation matrices OFF
3256 // -- unchanged by this lane, and it must not scale a single unit
3257 // through a matrix.
3258 crate::quant::reset_qm_scaled_units();
3259 let control_stream = encode(&["--enable-qm=0"]);
3260 let control_frames = decode_stream(&control_stream)
3261 .unwrap_or_else(|e| panic!("{NAME}: the --enable-qm=0 control must decode, got: {e}"))
3262 .len();
3263 assert!(
3264 control_frames >= 1,
3265 "{NAME}: the qm-off control decoded no frame"
3266 );
3267 for (using, y, u, v) in qm_headers(&control_stream) {
3268 assert!(
3269 !using,
3270 "{NAME}: the control's frame header set using_qmatrix"
3271 );
3272 assert_eq!(
3273 (y, u, v),
3274 (0, 0, 0),
3275 "{NAME}: the control's frame header carried qm levels {y}/{u}/{v}"
3276 );
3277 }
3278 compare(&control_stream, control_frames, "qm-off control");
3279 assert_eq!(
3280 crate::quant::qm_scaled_units(),
3281 0,
3282 "{NAME}: the qm-off control scaled units through a matrix"
3283 );
3284
3285 // The qm-on stream: decodes now, pixel-exact, levels 5 per plane as
3286 // aomenc writes them.
3287 crate::quant::reset_qm_scaled_units();
3288 let qm_stream = encode(&["--enable-qm=1"]);
3289 let qm_frames = decode_stream(&qm_stream)
3290 .unwrap_or_else(|e| panic!("{NAME}: the --enable-qm=1 stream must decode, got: {e}"))
3291 .len();
3292 assert!(qm_frames >= 1, "{NAME}: the qm-on stream decoded no frame");
3293 let headers = qm_headers(&qm_stream);
3294 assert!(
3295 !headers.is_empty() && headers.iter().all(|h| h.0),
3296 "{NAME}: not every qm-on frame header set using_qmatrix: {headers:?}"
3297 );
3298 assert!(
3299 headers.iter().all(|h| (h.1, h.2, h.3) == (5, 5, 5)),
3300 "{NAME}: expected aomenc's qm levels 5/5/5, got {headers:?}"
3301 );
3302 compare(&qm_stream, qm_frames, "qm-on");
3303 let scaled = crate::quant::qm_scaled_units();
3304 assert!(
3305 scaled > 0,
3306 "{NAME}: the --enable-qm=1 stream dequantized every unit flat -- \
3307 the matrices were never applied (class gate-blind-to-feature)"
3308 );
3309 eprintln!(
3310 "{NAME}: qm-off control {control_frames} frames exact (0 matrix-scaled units), \
3311 qm-on {qm_frames} frames exact ({scaled} matrix-scaled units, levels 5/5/5)"
3312 );
3313 }
3314
3315 /// lane-av1mono: the INVERSE of the pilot's
3316 /// `a_real_libaom_monochrome_key_frame_is_refused_by_name`, which the
3317 /// pilot's merge `d71084ae` landed on `main` (after this lane's base
3318 /// `7f4e8301`): the very same recipe now decodes, and its luma is
3319 /// byte-exact against ffmpeg's own decode of the same OBU. A merge of this
3320 /// lane into `main` must therefore resolve that pinning gate by adopting
3321 /// this witness in its place.
3322 ///
3323 /// `ffmpeg -pix_fmt gray -c:v libaom-av1` sets `color_config.mono_chrome`,
3324 /// so libaom codes NO chroma symbol anywhere in the sequence -- not the
3325 /// mode syntax, not a coefficient. That reaches all three classes this lane
3326 /// had to close: chroma SYMBOL reads (`uv_mode`/cfl/angle/palette), chroma
3327 /// COEFFICIENT reads on the rect-strip paths that call `read_coeffs_rect`
3328 /// DIRECTLY instead of through `read_plane`'s own plane gate, and the
3329 /// palette-mode neighbour band a mono sub-8x8 leaf must still clear before
3330 /// it returns (an uncleared band made the next block read `palette_y_mode`
3331 /// off the wrong CDF row and silently desynced the rest of the tile --
3332 /// measured at decode-order frame 33 of this very recipe).
3333 ///
3334 /// The 4:2:0 twin of the same source and settings is the control: it proves
3335 /// the recipe is decodable, so a failure here is about the plane count and
3336 /// not about the source or the encoder settings.
3337 #[test]
3338 fn a_real_libaom_monochrome_key_frame_decodes_pixel_exact() {
3339 const NAME: &str = "a_real_libaom_monochrome_key_frame_decodes_pixel_exact";
3340 if !have_ffmpeg() {
3341 eprintln!("SKIP {NAME}: no ffmpeg");
3342 return;
3343 }
3344 let emit = |pix: &str| -> Vec<u8> {
3345 let out = Command::new("ffmpeg")
3346 .args([
3347 "-v",
3348 "error",
3349 "-f",
3350 "lavfi",
3351 "-i",
3352 "testsrc2=size=320x240:rate=30:duration=2",
3353 "-pix_fmt",
3354 pix,
3355 "-c:v",
3356 "libaom-av1",
3357 "-cpu-used",
3358 "8",
3359 "-b:v",
3360 "300k",
3361 "-f",
3362 "obu",
3363 "-",
3364 ])
3365 .stdin(Stdio::null())
3366 .stdout(Stdio::piped())
3367 .stderr(Stdio::piped())
3368 .output()
3369 .expect("ffmpeg failed to run");
3370 assert!(
3371 out.status.success(),
3372 "{NAME}: ffmpeg ({pix}) failed: {}",
3373 String::from_utf8_lossy(&out.stderr)
3374 );
3375 out.stdout
3376 };
3377 // CONTROL: the identical recipe at 4:2:0 still decodes.
3378 let twin = decode_stream(&emit("yuv420p")).expect("the 4:2:0 twin must decode");
3379 assert!(!twin.is_empty(), "{NAME}: the 4:2:0 twin decoded no frames");
3380 // THE WITNESS: the monochrome stream decodes and every luma sample
3381 // equals ffmpeg's own decode of the same OBU.
3382 let gray = emit("gray");
3383 let ours = decode_stream(&gray)
3384 .unwrap_or_else(|e| panic!("{NAME}: the monochrome stream is REFUSED again: {e}"));
3385 let (width, height) = (320usize, 240usize);
3386 const FRAMES: usize = 60;
3387 assert_eq!(ours.len(), FRAMES, "{NAME}: expected {FRAMES} mono frames");
3388 let reference = ffmpeg_decode_gray_sequence(&gray, width, height, FRAMES);
3389 for (i, plane) in reference.chunks_exact(width * height).enumerate() {
3390 assert_eq!(ours[i].width, width, "{NAME}: frame {i} width");
3391 assert_eq!(ours[i].height, height, "{NAME}: frame {i} height");
3392 assert_eq!(
3393 ours[i].y.len(),
3394 width * height,
3395 "{NAME}: frame {i} luma length"
3396 );
3397 for (j, (got, want)) in plane.iter().zip(ours[i].y.iter()).enumerate() {
3398 assert_eq!(
3399 *want,
3400 u16::from(*got),
3401 "{NAME}: frame {i} luma sample {j} (row {}, col {}) is {want}, ffmpeg says {got}",
3402 j / width,
3403 j % width
3404 );
3405 }
3406 }
3407 eprintln!(
3408 "{NAME}: 4:2:0 twin {} frames, monochrome {} frames byte-exact vs ffmpeg",
3409 twin.len(),
3410 ours.len()
3411 );
3412 }
3413
3414 /// lane-t900 r25: the refusal "a frame OBU with no tile group" names a
3415 /// shape the parser cannot hand [`decode_stream`].
3416 ///
3417 /// `tiles` reaches that check from exactly two places -- `ObuKind::Frame`'s
3418 /// own vector and the `ObuKind::TileGroup` accumulation -- and both are
3419 /// filled by `ec_av1_syntax`'s `parse_tile_group`, whose only success path
3420 /// pushes one `Tile` per `tile_num` of the INCLUSIVE range
3421 /// `tg_start..=tg_end`. That range is never empty: the single-tile-group
3422 /// case takes `(0, num_tiles - 1)` saturating at 0, and the multi-group
3423 /// case rejects `end < start` as corrupt. So an `OBU_FRAME` either fails to
3424 /// parse or carries at least one tile, however short its payload is --
3425 /// including the empty payload the charter for this round asked to build,
3426 /// which parses into ONE zero-byte tile rather than none.
3427 ///
3428 /// Sweeping a real frame OBU's tile payload from empty upwards asserts both
3429 /// halves: every `Frame` OBU that parses has a tile, and `decode_stream`
3430 /// never reports this refusal for any of them.
3431 #[test]
3432 fn a_frame_obu_that_parses_always_carries_at_least_one_tile() {
3433 let fctx = &crate::decode::FrameCtx::new();
3434 const REFUSAL: &str = "a frame OBU with no tile group";
3435 let picture = test_card(64, 64);
3436 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3437 let (seq, header) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
3438 let mut frame_obus_parsed = 0;
3439 for len in 0..=encoded.tile.len().min(24) {
3440 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
3441 stream.extend_from_slice(
3442 &crate::frame::frame_obu(&seq, &header, &encoded.tile[..len]).unwrap(),
3443 );
3444 let mut parser = Av1Parser::new();
3445 let mut pos = 0usize;
3446 while pos < stream.len() {
3447 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
3448 break;
3449 };
3450 pos += obu.total_size;
3451 if let ObuKind::Frame(_, tiles) = &obu.kind {
3452 frame_obus_parsed += 1;
3453 assert!(
3454 !tiles.is_empty(),
3455 "a {len}-byte tile payload parsed into a frame OBU with no tile group -- \
3456 the refusal {REFUSAL:?} is reachable after all"
3457 );
3458 }
3459 }
3460 if let Err(e) = decode_stream(&stream) {
3461 let e = e.to_string();
3462 assert!(
3463 !e.contains(REFUSAL),
3464 "a {len}-byte tile payload reached {REFUSAL:?}: {e}"
3465 );
3466 }
3467 }
3468 assert!(
3469 frame_obus_parsed >= 2,
3470 "the sweep parsed {frame_obus_parsed} frame OBUs -- it proves nothing about the \
3471 refusal's reachability"
3472 );
3473 }
3474
3475 /// lane-t900 r27, negative gate: a frame whose segmentation enables one of
3476 /// the three MODE-OVERRIDING features -- `SEG_LVL_REF_FRAME` (forces a
3477 /// block's reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both
3478 /// suppress symbols `decode_inter_block` reads unconditionally) -- is
3479 /// refused BY NAME and outputs no picture, rather than desyncing on the
3480 /// first block that would have obeyed the override.
3481 ///
3482 /// Written, not hand-built: `write_segmentation_params` (spec 5.9.14)
3483 /// codes `feature_enabled`/`feature_data` for every segment, so a real
3484 /// key frame carrying the flag is a two-line change to the header the
3485 /// encoder already produced. Swept over all three features and over the
3486 /// first, a middle and the last segment id.
3487 #[test]
3488 fn a_frame_whose_segmentation_overrides_a_block_mode_is_refused_by_name() {
3489 let fctx = &crate::decode::FrameCtx::new();
3490 const REFUSAL: &str = "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
3491 let picture = test_card(64, 64);
3492 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3493 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
3494 for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] {
3495 for segment in [0usize, 3, 7] {
3496 let mut header = key.clone();
3497 header.segmentation.enabled = true;
3498 header.segmentation.update_map = true;
3499 header.segmentation.update_data = true;
3500 header.segmentation.feature_enabled[segment][feature] = true;
3501 header.segmentation.feature_data[segment][feature] = 1;
3502 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
3503 stream.extend_from_slice(
3504 &crate::frame::frame_obu(&seq, &header, &encoded.tile).unwrap(),
3505 );
3506 let mut shown = 0;
3507 let err = decode_stream_with(&stream, |_, _, _| {
3508 shown += 1;
3509 Ok(())
3510 })
3511 .unwrap_err()
3512 .to_string();
3513 assert!(
3514 err.contains(REFUSAL),
3515 "feature {feature} segment {segment}: expected {REFUSAL:?}, got: {err}"
3516 );
3517 assert_eq!(
3518 shown, 0,
3519 "feature {feature} segment {segment}: a refused frame produced a picture"
3520 );
3521 }
3522 }
3523 }
3524
3525 /// One census attempt: encode `frames` frames of `source` with real
3526 /// aomenc plus `extra` args, decode with THIS decoder, and return the
3527 /// stream's byte length with either the picture count or the refusal (any
3528 /// decode error) it produced. A census is about what the encoder emits,
3529 /// so a refusal is data here, not a failure.
3530 fn census_attempt(
3531 source: &str,
3532 width: usize,
3533 height: usize,
3534 frames: usize,
3535 extra: &[&str],
3536 ) -> (usize, std::result::Result<usize, String>) {
3537 let duration = format!("{}", frames as f64 / 25.0);
3538 let src = format!("{source}=size={width}x{height}:rate=25");
3539 let y4m = Command::new("ffmpeg")
3540 .args([
3541 "-v",
3542 "error",
3543 "-f",
3544 "lavfi",
3545 "-i",
3546 &src,
3547 "-t",
3548 &duration,
3549 "-pix_fmt",
3550 "yuv420p",
3551 "-strict",
3552 "-1",
3553 "-f",
3554 "yuv4mpegpipe",
3555 "-",
3556 ])
3557 .stdin(Stdio::null())
3558 .stdout(Stdio::piped())
3559 .stderr(Stdio::piped())
3560 .output()
3561 .expect("ffmpeg failed to run");
3562 assert!(
3563 y4m.status.success(),
3564 "ffmpeg refused the {width}x{height} fixture"
3565 );
3566 let limit = format!("--limit={frames}");
3567 let mut args: Vec<String> = [
3568 "--codec=av1",
3569 "--passes=1",
3570 "--end-usage=q",
3571 "--threads=1",
3572 "--row-mt=0",
3573 "--kf-max-dist=9999",
3574 "--lag-in-frames=0",
3575 ]
3576 .iter()
3577 .map(|s| (*s).to_owned())
3578 .collect();
3579 args.push(limit);
3580 args.extend(extra.iter().map(|s| (*s).to_owned()));
3581 args.extend([
3582 "--obu".to_owned(),
3583 "-o".to_owned(),
3584 "-".to_owned(),
3585 "-".to_owned(),
3586 ]);
3587 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3588 assert!(
3589 out.status.success(),
3590 "aomenc refused {args:?}: {}",
3591 String::from_utf8_lossy(&out.stderr)
3592 );
3593 let stream = out.stdout;
3594 let result = match decode_stream(&stream) {
3595 Ok(pictures) => Ok(pictures.len()),
3596 Err(e) => Err(e.to_string()),
3597 };
3598 (stream.len(), result)
3599 }
3600
3601 /// lane-av1seglvl: encode `frames` frames of `source` with real aomenc
3602 /// plus `extra` args and return the raw `.obu` bytes -- the census's
3603 /// half-sibling of [`census_attempt`] that keeps the STREAM instead of
3604 /// only its decode verdict, so the caller can parse the frame headers'
3605 /// segmentation tables themselves.
3606 fn encode_aomenc_stream(
3607 source: &str,
3608 width: usize,
3609 height: usize,
3610 frames: usize,
3611 extra: &[&str],
3612 ) -> Vec<u8> {
3613 let duration = format!("{}", frames as f64 / 25.0);
3614 let src = format!("{source}=size={width}x{height}:rate=25");
3615 let y4m = Command::new("ffmpeg")
3616 .args([
3617 "-v",
3618 "error",
3619 "-f",
3620 "lavfi",
3621 "-i",
3622 &src,
3623 "-t",
3624 &duration,
3625 "-pix_fmt",
3626 "yuv420p",
3627 "-strict",
3628 "-1",
3629 "-f",
3630 "yuv4mpegpipe",
3631 "-",
3632 ])
3633 .stdin(Stdio::null())
3634 .stdout(Stdio::piped())
3635 .stderr(Stdio::piped())
3636 .output()
3637 .expect("ffmpeg failed to run");
3638 assert!(
3639 y4m.status.success(),
3640 "ffmpeg refused the {width}x{height} fixture"
3641 );
3642 let limit = format!("--limit={frames}");
3643 let mut args: Vec<String> = [
3644 "--codec=av1",
3645 "--passes=1",
3646 "--end-usage=q",
3647 "--threads=1",
3648 "--row-mt=0",
3649 "--kf-max-dist=9999",
3650 "--lag-in-frames=0",
3651 ]
3652 .iter()
3653 .map(|s| (*s).to_owned())
3654 .collect();
3655 args.push(limit);
3656 args.extend(extra.iter().map(|s| (*s).to_owned()));
3657 args.extend([
3658 "--obu".to_owned(),
3659 "-o".to_owned(),
3660 "-".to_owned(),
3661 "-".to_owned(),
3662 ]);
3663 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3664 assert!(
3665 out.status.success(),
3666 "aomenc refused {args:?}: {}",
3667 String::from_utf8_lossy(&out.stderr)
3668 );
3669 out.stdout
3670 }
3671
3672 /// lane-av1seglvl: encode `frames` frames with a real TWO-PASS aomenc
3673 /// (pass 1 writes the stats file into the session temp dir, pass 2
3674 /// consumes it) and return the `.obu` bytes. This is the only shape that
3675 /// reaches libaom's `is_stat_consumption_stage_twopass` segmentation
3676 /// setup (`configure_static_seg_features`), so the census is not proven
3677 /// over the encoder's whole reachable surface without it.
3678 fn encode_aomenc_stream_twopass(
3679 source: &str,
3680 width: usize,
3681 height: usize,
3682 frames: usize,
3683 extra: &[&str],
3684 ) -> Vec<u8> {
3685 let duration = format!("{}", frames as f64 / 25.0);
3686 let src = format!("{source}=size={width}x{height}:rate=25");
3687 let y4m = Command::new("ffmpeg")
3688 .args([
3689 "-v",
3690 "error",
3691 "-f",
3692 "lavfi",
3693 "-i",
3694 &src,
3695 "-t",
3696 &duration,
3697 "-pix_fmt",
3698 "yuv420p",
3699 "-strict",
3700 "-1",
3701 "-f",
3702 "yuv4mpegpipe",
3703 "-",
3704 ])
3705 .stdin(Stdio::null())
3706 .stdout(Stdio::piped())
3707 .stderr(Stdio::piped())
3708 .output()
3709 .expect("ffmpeg failed to run");
3710 assert!(
3711 y4m.status.success(),
3712 "ffmpeg refused the {width}x{height} fixture"
3713 );
3714 let limit = format!("--limit={frames}");
3715 let fpf =
3716 std::env::temp_dir().join(format!("ec-av1-segldapass-{}.fpf", std::process::id()));
3717 let mut base: Vec<String> = [
3718 "--codec=av1",
3719 "--passes=2",
3720 "--end-usage=q",
3721 "--threads=1",
3722 "--row-mt=0",
3723 "--kf-max-dist=9999",
3724 "--lag-in-frames=0",
3725 ]
3726 .iter()
3727 .map(|s| (*s).to_owned())
3728 .collect();
3729 base.push(limit);
3730 base.extend(extra.iter().map(|s| (*s).to_owned()));
3731 let mut pass1 = base.clone();
3732 pass1.extend(["--pass=1".to_owned(), format!("--fpf={}", fpf.display())]);
3733 pass1.extend([
3734 "--obu".to_owned(),
3735 "-o".to_owned(),
3736 "/dev/null".to_owned(),
3737 "-".to_owned(),
3738 ]);
3739 let out1 = run_with_stdin(Command::new(aomenc_path()).args(&pass1), &y4m.stdout);
3740 assert!(
3741 out1.status.success(),
3742 "aomenc pass 1 refused {pass1:?}: {}",
3743 String::from_utf8_lossy(&out1.stderr)
3744 );
3745 let mut pass2 = base;
3746 pass2.extend(["--pass=2".to_owned(), format!("--fpf={}", fpf.display())]);
3747 pass2.extend([
3748 "--obu".to_owned(),
3749 "-o".to_owned(),
3750 "-".to_owned(),
3751 "-".to_owned(),
3752 ]);
3753 let out2 = run_with_stdin(Command::new(aomenc_path()).args(&pass2), &y4m.stdout);
3754 let _ = std::fs::remove_file(&fpf);
3755 assert!(
3756 out2.status.success(),
3757 "aomenc pass 2 refused {pass2:?}: {}",
3758 String::from_utf8_lossy(&out2.stderr)
3759 );
3760 out2.stdout
3761 }
3762
3763 /// lane-av1seglvl: walk every frame OBU of `stream` and tally which
3764 /// `SEG_LVL` features the frame headers actually ENABLE, plus the shape
3765 /// counters a census premise is asserted against: frames with
3766 /// segmentation on, of which `update_map == 1` (the map is coded) and
3767 /// `update_map == 0` (every block's id is INHERITED), and frames whose
3768 /// table carries a real `SEG_LVL_ALT_Q` delta.
3769 /// The last vector counts per SEGMENT-FEATURE INSTANCE (a frame with
3770 /// ALT_Q on all 8 segments contributes 8), which is all the verdict
3771 /// needs: only index `SEG_LVL_ALT_Q` may be non-zero.
3772 /// Returns `(enabled_frames, update_map_frames, inherited_frames,
3773 /// alt_q_frames, feature_instances: [usize; SEG_LVL_MAX])`.
3774 #[allow(clippy::type_complexity)]
3775 fn segmentation_feature_census(
3776 stream: &[u8],
3777 ) -> (usize, usize, usize, usize, [usize; SEG_LVL_MAX]) {
3778 let mut parser = Av1Parser::new();
3779 let obus = parser
3780 .parse_temporal_unit(stream)
3781 .unwrap_or_else(|e| panic!("the census stream does not even parse: {e}"));
3782 let mut enabled = 0usize;
3783 let mut update_map = 0usize;
3784 let mut inherited = 0usize;
3785 let mut alt_q = 0usize;
3786 let mut feature_frames = [0usize; SEG_LVL_MAX];
3787 for obu in &obus {
3788 if let ObuKind::Frame(header, _) = &obu.kind {
3789 let seg = &header.segmentation;
3790 if !seg.enabled {
3791 continue;
3792 }
3793 enabled += 1;
3794 if seg.update_map {
3795 update_map += 1;
3796 } else {
3797 inherited += 1;
3798 }
3799 let mut any_q = false;
3800 for segment in 0..MAX_SEGMENTS {
3801 for feature in 0..SEG_LVL_MAX {
3802 if seg.feature_enabled[segment][feature] {
3803 feature_frames[feature] += 1;
3804 if feature == SEG_LVL_ALT_Q {
3805 any_q = true;
3806 }
3807 }
3808 }
3809 }
3810 if any_q {
3811 alt_q += 1;
3812 }
3813 }
3814 }
3815 (enabled, update_map, inherited, alt_q, feature_frames)
3816 }
3817
3818 /// lane-hdrlossless WITNESS → lane-av1mixloss LIFT. `--end-usage=q
3819 /// --cq-level=0 --aq-mode=1` (variance AQ over a lossless base) gives a
3820 /// high-variance segment a positive `SEG_LVL_ALT_Q` while a flat segment
3821 /// stays at `qindex == 0` (`aq_variance.c` sets `SEG_LVL_ALT_Q` per
3822 /// segment and only clamps when `base_qindex != 0`, so a lossless base is
3823 /// exactly where the mixed case comes from): a frame MIXING lossless and
3824 /// lossy segments, which this decoder refused by name until the
3825 /// per-segment lossless table (libaom `decodeframe.c:5205`,
3826 /// `xd->lossless[segment_id]`; `read_tx_size` returns TX_4X4 before it
3827 /// reads a symbol, `decodeframe.c:1170`) landed. Non-vacuity, three ways:
3828 /// (1) the header census proves the arms REALLY carry a mixed frame
3829 /// (class `gate-blind-to-feature` -- variance AQ over a lossless base is
3830 /// the whole point, not the flag spelling), (2) the WHT-unit counter
3831 /// proves the per-segment lossless reconstruction really ran, and (3)
3832 /// every decoded plane is compared SAMPLE-EXACT against ffmpeg's libaom,
3833 /// which accepts the same stream -- so the old refusal named a capability
3834 /// gap, and this gate now proves the gap closed on a real encoder output.
3835 #[test]
3836 fn a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact() {
3837 const NAME: &str = "a_real_aomenc_mixed_lossless_segment_frame_decodes_sample_exact";
3838 if !have_ffmpeg() {
3839 eprintln!("SKIP {NAME}: no ffmpeg");
3840 return;
3841 }
3842 if !have_aomenc() {
3843 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3844 return;
3845 }
3846 const FRAMES: usize = 4;
3847 const WIDTH: usize = 256;
3848 const HEIGHT: usize = 192;
3849 // (source, per-arm overrides). `--end-usage=q --cq-level=0` is the
3850 // lossless base; `--aq-mode=1` is variance AQ, the only aomenc path
3851 // that sets `SEG_LVL_ALT_Q` with no clamp at base 0 (`aq_variance.c`).
3852 // Several arms because the segment split depends on the encoder's own
3853 // variance decisions (class knob-never-reached-the-tool: require at
3854 // least one arm to actually mix, and fail if none does).
3855 let arms: [(&str, &[&str]); 3] = [
3856 (
3857 "testsrc2=size=256x192:rate=25",
3858 &[
3859 "--end-usage=q",
3860 "--cq-level=0",
3861 "--aq-mode=1",
3862 "--good",
3863 "--cpu-used=3",
3864 "--sb-size=64",
3865 ],
3866 ),
3867 (
3868 "testsrc2=size=256x192:rate=25",
3869 &[
3870 "--end-usage=q",
3871 "--cq-level=0",
3872 "--aq-mode=1",
3873 "--good",
3874 "--cpu-used=5",
3875 "--sb-size=64",
3876 ],
3877 ),
3878 (
3879 "gradients=size=256x192:rate=25",
3880 &[
3881 "--end-usage=q",
3882 "--cq-level=0",
3883 "--aq-mode=1",
3884 "--good",
3885 "--cpu-used=6",
3886 "--sb-size=64",
3887 ],
3888 ),
3889 ];
3890 let mut mixed_arms = 0usize;
3891 // The WHT-unit delta below is a process-wide counter: serialize the
3892 // arms against the other counter-reading gates.
3893 let _gate_lock = lock_gate_counters();
3894 for (src, extra) in &arms {
3895 let y4m = Command::new("ffmpeg")
3896 .args([
3897 "-v",
3898 "error",
3899 "-f",
3900 "lavfi",
3901 "-i",
3902 *src,
3903 "-t",
3904 "0.16",
3905 "-pix_fmt",
3906 "yuv420p",
3907 "-strict",
3908 "-1",
3909 "-f",
3910 "yuv4mpegpipe",
3911 "-",
3912 ])
3913 .stdin(Stdio::null())
3914 .stdout(Stdio::piped())
3915 .stderr(Stdio::piped())
3916 .output()
3917 .expect("ffmpeg failed to run");
3918 assert!(y4m.status.success(), "{NAME}: ffmpeg failed for {src}");
3919 let limit = format!("--limit={FRAMES}");
3920 let mut args: Vec<String> = [
3921 "--codec=av1",
3922 "--passes=1",
3923 "--threads=1",
3924 "--obu",
3925 "-o",
3926 "-",
3927 "-",
3928 ]
3929 .iter()
3930 .map(|s| (*s).to_owned())
3931 .collect();
3932 args.insert(1, limit);
3933 args.extend(extra.iter().map(|s| (*s).to_owned()));
3934 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
3935 assert!(
3936 out.status.success(),
3937 "{NAME}: aomenc refused {args:?}: {}",
3938 String::from_utf8_lossy(&out.stderr)
3939 );
3940 let stream = out.stdout;
3941 // (2) the stream really carries a frame the old refusal named.
3942 let mut parser = Av1Parser::new();
3943 let (mut pos, mut mixed) = (0usize, 0usize);
3944 while pos < stream.len() {
3945 let obu = parser.parse_obu(&stream[pos..]).expect("aomenc OBU parses");
3946 pos += obu.total_size.max(1);
3947 let header = match &obu.kind {
3948 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
3949 _ => continue,
3950 };
3951 if header.lossless.iter().any(|&l| l) && !header.lossless.iter().all(|&l| l) {
3952 mixed += 1;
3953 }
3954 }
3955 if mixed == 0 {
3956 eprintln!("{NAME}: arm {extra:?} coded no mixed frame -- trying the next");
3957 continue;
3958 }
3959 // (3) ours DECODES it, sample-exact against ffmpeg's libaom (the
3960 // reference decode doubles as the libaom-accepts proof). The
3961 // WHT-unit delta proves the per-segment lossless reconstruction
3962 // really ran inside a frame that is NOT `CodedLossless`.
3963 let before = crate::decode::lossless_wht_units();
3964 let ours = decode_stream(&stream).unwrap_or_else(|e| {
3965 panic!("{NAME}: a mixed-lossless frame decodes after the per-segment lift: {e}")
3966 });
3967 let wht_units = crate::decode::lossless_wht_units() - before;
3968 let refs = ffmpeg_decode_sequence(&stream, WIDTH, HEIGHT, FRAMES);
3969 assert_eq!(ours.len(), FRAMES, "{NAME}: frame count");
3970 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
3971 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
3972 .iter()
3973 .enumerate()
3974 {
3975 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
3976 assert_eq!(
3977 bad, 0,
3978 "{NAME}: arm {extra:?} frame {i} plane {plane}: {bad} samples differ"
3979 );
3980 assert_eq!(
3981 g.len(),
3982 r.len(),
3983 "{NAME}: arm {extra:?} frame {i} plane {plane}: ours has {} samples, \
3984 ffmpeg's has {} -- a short plane would zip-truncate the compare above \
3985 and hide a chroma-span defect",
3986 g.len(),
3987 r.len()
3988 );
3989 }
3990 }
3991 assert!(
3992 wht_units > 0,
3993 "{NAME}: arm {extra:?} reconstructed no Walsh-Hadamard unit -- the mixed census is lying or the lossless path never ran"
3994 );
3995 mixed_arms += 1;
3996 eprintln!(
3997 "{NAME}: arm {extra:?}: {mixed} mixed frame(s), {FRAMES} frames sample-exact vs ffmpeg, {wht_units} WHT units"
3998 );
3999 }
4000 assert!(
4001 mixed_arms > 0,
4002 "{NAME}: no arm produced a mixed lossless/lossy frame -- the witness is vacuous \
4003 (re-measure the aomenc recipe)"
4004 );
4005 }
4006
4007 /// lane-t900 r27 CENSUS behind the negative gate above: does a real
4008 /// aomenc ever ENABLE one of the three mode-overriding segmentation
4009 /// features? Measured over the recipes that turn segmentation on --
4010 /// `--aq-mode=1/2/3` (variance, complexity and cyclic-refresh AQ) and
4011 /// `--deltaq-mode=1` -- with the refusal as the instrument: if one of
4012 /// those features appeared, the decode would stop by name.
4013 ///
4014 /// lane-av1seglvl re-scope: r27's arms were all `--passes=1
4015 /// --lag-in-frames=0`, so they never coded an alt-ref frame or ran an
4016 /// encoder second pass -- the only shapes where libaom's OTHER seg
4017 /// feature setup (`configure_static_seg_features`) could ever run. The
4018 /// re-scoped half below adds alt-ref-group arms and a real two-pass arm,
4019 /// and upgrades the instrument from the refusal (blind to a pure-ALT_LF
4020 /// stream) to a direct parse of every frame header's `feature_enabled`
4021 /// table: over all of it, aomenc enables `SEG_LVL_ALT_Q` and nothing
4022 /// else.
4023 #[test]
4024 fn a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature() {
4025 if !have_aomenc() {
4026 eprintln!("SKIP a_segmentation_census_over_real_aq_streams: no aomenc");
4027 return;
4028 }
4029 const REFUSAL: &str = "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV";
4030 let recipes: [(&str, Vec<&str>); 6] = [
4031 ("baseline", vec!["--cpu-used=4", "--cq-level=40"]),
4032 (
4033 "aq-mode=1",
4034 vec!["--cpu-used=4", "--aq-mode=1", "--cq-level=40"],
4035 ),
4036 (
4037 "aq-mode=2",
4038 vec!["--cpu-used=4", "--aq-mode=2", "--cq-level=40"],
4039 ),
4040 (
4041 "aq-mode=3",
4042 vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=40"],
4043 ),
4044 (
4045 "aq-mode=3 cq10",
4046 vec!["--cpu-used=4", "--aq-mode=3", "--cq-level=10"],
4047 ),
4048 (
4049 "deltaq-mode=1",
4050 vec!["--cpu-used=4", "--deltaq-mode=1", "--cq-level=40"],
4051 ),
4052 ];
4053 // Arrival, not intent (class knob-never-reached-the-tool): a recipe
4054 // whose stream is byte-for-byte the baseline's changed nothing, and a
4055 // census over such arms would be vacuous. Measured r27: only
4056 // `--aq-mode=3` (cyclic refresh) does -- aq-mode 1/2 and deltaq-mode=1
4057 // all reproduce the baseline's 7147 B at this recipe.
4058 let mut baseline_bytes = 0usize;
4059 let mut segment_symbols = 0usize;
4060 let mut refused = 0usize;
4061 let mut decoded = 0usize;
4062 for (name, extra) in &recipes {
4063 let before = crate::decode::segment_id_hits();
4064 let (bytes, result) = census_attempt("mandelbrot", 192, 128, 8, extra);
4065 match result {
4066 Ok(pictures) => {
4067 decoded += 1;
4068 let symbols = crate::decode::segment_id_hits() - before;
4069 segment_symbols += symbols;
4070 if *name == "baseline" {
4071 baseline_bytes = bytes;
4072 }
4073 eprintln!(
4074 "SEGCENSUS {name}: {bytes} B{}, {pictures} pictures, segment_id symbols {symbols}",
4075 if bytes == baseline_bytes && *name != "baseline" {
4076 " (== baseline: the flag changed nothing)"
4077 } else {
4078 ""
4079 }
4080 );
4081 }
4082 Err(e) => {
4083 eprintln!("SEGCENSUS {name}: {bytes} B, refused: {e}");
4084 assert!(
4085 !e.contains(REFUSAL),
4086 "{name}: a real aomenc stream DOES enable a mode-overriding \
4087 segmentation feature -- the refusal is a capability gap, not a \
4088 claim about the encoder: {e}"
4089 );
4090 refused += 1;
4091 }
4092 }
4093 }
4094 eprintln!(
4095 "SEGCENSUS: {} recipes, {decoded} decoded, {refused} refused for other reasons",
4096 recipes.len()
4097 );
4098 assert_eq!(
4099 decoded,
4100 recipes.len(),
4101 "every recipe must decode; {refused} refused"
4102 );
4103 assert!(
4104 segment_symbols > 0,
4105 "no recipe coded a single segment_id symbol -- segmentation never arrived, so \
4106 this census measures nothing about the three mode-overriding features"
4107 );
4108
4109 // lane-av1seglvl re-scope: the r27 arms above are all `--passes=1
4110 // --lag-in-frames=0`, which never codes an alt-ref frame -- the one
4111 // frame type whose segmentation libaom sets up differently
4112 // (`configure_static_seg_features`, encoder_utils.c:738, is further
4113 // gated on the second pass AND on `hl_sf.static_segmentation`, which
4114 // speed_features.h itself documents as "Always set to 0"). The arms
4115 // below cover that whole remaining surface: alt-ref groups under
4116 // `--aq-mode`, a high-cq arm (the branch's own `high_q` gate is
4117 // `avg_q > 48`), and a genuine two-pass encode. The instrument is no
4118 // longer the refusal -- the refusal only fires on
4119 // REF_FRAME/SKIP/GLOBALMV, so an ALT_LF-only stream would decode
4120 // silently past it -- but a direct parse of every frame header's
4121 // `feature_enabled` table.
4122 let lag_recipes: [(&str, &str, usize, usize, Vec<&str>); 3] = [
4123 (
4124 "aq-mode=1 lag16 mandelbrot",
4125 "mandelbrot",
4126 192,
4127 128,
4128 vec![
4129 "--cpu-used=4",
4130 "--aq-mode=1",
4131 "--cq-level=45",
4132 "--lag-in-frames=16",
4133 "--auto-alt-ref=1",
4134 ],
4135 ),
4136 (
4137 "aq-mode=1 lag16 screen",
4138 "testsrc2",
4139 256,
4140 192,
4141 vec![
4142 "--cpu-used=4",
4143 "--aq-mode=1",
4144 "--cq-level=45",
4145 "--lag-in-frames=16",
4146 "--auto-alt-ref=1",
4147 ],
4148 ),
4149 (
4150 "aq-mode=1 lag16 cq63 high_q",
4151 "mandelbrot",
4152 192,
4153 128,
4154 vec![
4155 "--cpu-used=4",
4156 "--aq-mode=1",
4157 "--cq-level=63",
4158 "--lag-in-frames=16",
4159 "--auto-alt-ref=1",
4160 ],
4161 ),
4162 // `--aq-mode=2 lag16` (complexity AQ over an alt-ref group) was
4163 // measured 2026-09-24: it encodes and decodes cleanly but codes
4164 // ZERO segmentation-enabled frames -- complexity AQ never reaches
4165 // the seg table at this recipe -- so as a census arm it measures
4166 // nothing (class gate-blind-to-feature) and was dropped; the
4167 // 1-pass `aq-mode=2` r27 arm above stays.
4168 ];
4169 let mut total_enabled = 0usize;
4170 let mut total_inherited = 0usize;
4171 let mut total_alt_q = 0usize;
4172 let mut feature_frames = [0usize; SEG_LVL_MAX];
4173 for (name, source, w, h, extra) in &lag_recipes {
4174 let stream = encode_aomenc_stream(source, *w, *h, 40, extra);
4175 let (enabled, umap, inherited, alt_q, frames_per_feature) =
4176 segmentation_feature_census(&stream);
4177 eprintln!(
4178 "SEGCENSUS {name}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}"
4179 );
4180 total_enabled += enabled;
4181 total_inherited += inherited;
4182 total_alt_q += alt_q;
4183 for (f, n) in frames_per_feature.iter().enumerate() {
4184 feature_frames[f] += n;
4185 }
4186 }
4187 // The two-pass arm: `configure_static_seg_features` runs ONLY at
4188 // `is_stat_consumption_stage_twopass`, so this is the arm that would
4189 // catch its ALT_LF/REF_FRAME/SKIP tables if the dead speed feature
4190 // were ever revived.
4191 {
4192 let stream = encode_aomenc_stream_twopass(
4193 "mandelbrot",
4194 192,
4195 128,
4196 40,
4197 &[
4198 "--cpu-used=4",
4199 "--aq-mode=1",
4200 "--cq-level=45",
4201 "--lag-in-frames=16",
4202 "--auto-alt-ref=1",
4203 ],
4204 );
4205 let (enabled, umap, inherited, alt_q, frames_per_feature) =
4206 segmentation_feature_census(&stream);
4207 eprintln!(
4208 "SEGCENSUS twopass aq-mode=1 lag16: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q {alt_q}, per-feature {frames_per_feature:?}"
4209 );
4210 total_enabled += enabled;
4211 total_inherited += inherited;
4212 total_alt_q += alt_q;
4213 for (f, n) in frames_per_feature.iter().enumerate() {
4214 feature_frames[f] += n;
4215 }
4216 }
4217 // Premise (class gate-blind-to-feature): the arms must actually reach
4218 // the shapes the census speaks about -- segmentation-carrying frames,
4219 // frames whose map is INHERITED (update_map == 0), and frames with a
4220 // real ALT_Q table -- or the "only ALT_Q" verdict below measures
4221 // nothing.
4222 assert!(
4223 total_enabled > 0 && total_alt_q > 0,
4224 "no lag/two-pass arm carried a segmentation-enabled frame -- the census premise \
4225 never arrived"
4226 );
4227 assert!(
4228 total_inherited > 0,
4229 "no arm carried an update_map == 0 frame -- the map-inheritance path the decoder \
4230 reads segment ids through is unmeasured"
4231 );
4232 // The census verdict, over every frame of every arm: segmentation on
4233 // aomenc's CLI carries SEG_LVL_ALT_Q and NOTHING else. The three
4234 // mode-overriding features and the four ALT_LF deltas have no encoder
4235 // path: `configure_static_seg_features` (the only setter of ALT_LF/
4236 // REF_FRAME/SKIP in the tree) is gated on `hl_sf.static_segmentation`,
4237 // documented "Always set to 0" (speed_features.h), and ROI/active-map
4238 // are control-API only (aomenc.c has no flag for either).
4239 for (feature, frames) in feature_frames.iter().enumerate() {
4240 if feature == SEG_LVL_ALT_Q {
4241 continue;
4242 }
4243 assert_eq!(
4244 *frames, 0,
4245 "feature index {feature} appeared on {frames} frames of real aomenc output -- \
4246 the refusal's encoder-never-writes claim is FALSE and the mode path needs \
4247 porting before this census can stay green"
4248 );
4249 }
4250 eprintln!(
4251 "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"
4252 );
4253 }
4254
4255 /// lane-av1seglvl WITNESS: the reaching stream. `--aq-mode=1` turns
4256 /// segmentation on for every frame; `--lag-in-frames=16 --auto-alt-ref=1`
4257 /// adds real alt-ref groups, so the stream mixes map-CODING frames
4258 /// (`update_map == 1`: the key frame and each group's arf) with dozens of
4259 /// map-INHERITING frames (`update_map == 0`), and an inheriting block's
4260 /// id is the MIN of the previous map over its own footprint while the
4261 /// saved map itself inherits that footprint VERBATIM
4262 /// (`copy_segment_id`, decodemv.c:342) -- heterogeneous footprints are
4263 /// exactly what a 1:4-split arf leaves behind. Stamping the minified id
4264 /// (the pre-lane defect) flattened those footprints and mis-dequantized
4265 /// scattered blocks frames later: 2 luma bytes of mandelbrot frame 35
4266 /// differed from the oracle, everything else exact.
4267 ///
4268 /// Both arms decode EVERY frame in decode order -- hidden arfs included
4269 /// -- byte-exact against the instrumented oracle, and every SHOWN frame
4270 /// pixel-exact against ffmpeg; the census counters prove the premise
4271 /// (segmentation symbols read, a wider-than-zero quantizer span from
4272 /// `SEG_LVL_ALT_Q`, and an inheritance-heavy shape).
4273 #[test]
4274 fn a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact() {
4275 const NAME: &str =
4276 "a_real_aomenc_segmentation_stream_with_map_inheritance_decodes_pixel_exact";
4277 // lane-av1cmpaudit2: this gate reaches the oracle without the gate
4278 // mutex, so a sibling flipping `EC_AV1_AOMDEC` (the one-byte-wrong
4279 // oracle control) could hand it a tampered oracle mid-compare.
4280 let _gate_lock = lock_gate_counters();
4281 if !have_aomenc() {
4282 eprintln!("SKIP {NAME}: no aomenc");
4283 return;
4284 }
4285 if !have_ffmpeg() {
4286 eprintln!("SKIP {NAME}: no ffmpeg");
4287 return;
4288 }
4289 let extra = [
4290 "--cpu-used=4",
4291 "--aq-mode=1",
4292 "--cq-level=45",
4293 "--lag-in-frames=16",
4294 "--auto-alt-ref=1",
4295 ];
4296 let arms: [(&str, &str, usize, usize); 2] = [
4297 ("screen testsrc2", "testsrc2", 256, 192),
4298 ("film mandelbrot", "mandelbrot", 192, 128),
4299 ];
4300 for (arm, source, width, height) in &arms {
4301 // r7: the ENCODE's frame count, bound so the compare below asserts a
4302 // spec rather than our own decode's length.
4303 const ENCODED_FRAMES: usize = 40;
4304 let stream = encode_aomenc_stream(source, *width, *height, ENCODED_FRAMES, &extra);
4305 // Premise: the shape under test really arrived -- segmentation on
4306 // every frame, the map both coded and inherited, and real ALT_Q
4307 // tables. An aomenc drift that dropped any of these would make
4308 // the decode below prove nothing (class gate-blind-to-feature).
4309 let (enabled, umap, inherited, alt_q, _) = segmentation_feature_census(&stream);
4310 eprintln!(
4311 "{NAME} {arm}: seg-enabled {enabled}, update_map {umap}, inherited {inherited}, ALT_Q-carrying {alt_q}"
4312 );
4313 assert!(
4314 enabled > 0 && umap > 0,
4315 "{arm}: no segmentation-carrying/map-coding frame -- the premise is gone"
4316 );
4317 assert!(
4318 inherited > 0,
4319 "{arm}: no update_map == 0 frame -- the map-inheritance path under test never runs"
4320 );
4321 assert!(
4322 alt_q > 0,
4323 "{arm}: no frame carries a SEG_LVL_ALT_Q table -- the feature under test never fires"
4324 );
4325 // Every frame in decode order -- hidden arfs included (each one
4326 // re-surfaces via show-existing in this recipe, so `hidden == 0`
4327 // is possible while `frames` still covers the whole coded set) --
4328 // byte-exact against the oracle.
4329 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, arm);
4330 assert!(frames > 0, "{arm}: decoded nothing");
4331 assert_eq!(
4332 frames, enabled,
4333 "{arm}: decode-order frame count != segmentation-enabled frame count -- the \
4334 parse and the decode disagree about the stream"
4335 );
4336 let _ = hidden;
4337 // And every shown frame pixel-exact against ffmpeg.
4338 crate::decode::reset_segment_hits();
4339 let pictures = decode_stream(&stream)
4340 .unwrap_or_else(|e| panic!("{NAME} {arm}: decode refused: {e}"));
4341 assert!(
4342 crate::decode::segment_id_hits() > 0,
4343 "{arm}: zero segment_id symbols read -- the decode proved nothing about \
4344 segmentation"
4345 );
4346 let (lo, hi) = crate::decode::block_q_span();
4347 assert!(
4348 hi > lo,
4349 "{arm}: every block dequantized at the same qindex ({lo}) -- SEG_LVL_ALT_Q \
4350 never changed any block's quantizer"
4351 );
4352 // `ENCODED_FRAMES`, not `pictures.len()`: our decode's length is the
4353 // thing UNDER TEST, so using it as the oracle's expected count is
4354 // circular -- a decode that dropped a frame would ask ffmpeg for the
4355 // same short count and the compare would silently shrink.
4356 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, *width, *height, ENCODED_FRAMES);
4357 for (i, (ours, theirs)) in pictures.iter().zip(&ffmpeg_frames).enumerate() {
4358 assert_eq!(ours.y, theirs.y, "{NAME} {arm}: frame {i} luma vs ffmpeg");
4359 assert_eq!(ours.u, theirs.u, "{NAME} {arm}: frame {i} U vs ffmpeg");
4360 assert_eq!(ours.v, theirs.v, "{NAME} {arm}: frame {i} V vs ffmpeg");
4361 }
4362 eprintln!(
4363 "{NAME} {arm}: {frames} frames decode-order exact vs oracle ({hidden} hidden), {} shown frames exact vs ffmpeg, q span {lo}..{hi}, segment_id symbols {}",
4364 pictures.len(),
4365 crate::decode::segment_id_hits()
4366 );
4367 }
4368 }
4369
4370 /// lane-t900 r27, WITNESS half of the proof for "an OBMC neighbour whose
4371 /// switchable interp filter was never recorded" (the structural half is
4372 /// `decode::tests::every_inter_record_publishes_an_obmc_readable_filter`,
4373 /// which shows no INTER cell is ever stamped with the `[3, 3]`
4374 /// sentinel): real OBMC streams whose frames use a SWITCHABLE (and dual)
4375 /// interp filter decode with the refusal firing 0 times while OBMC blends
4376 /// really read the neighbour band -- a decode that never read one would
4377 /// pass just as well and prove nothing (class gate-blind-to-feature).
4378 #[test]
4379 fn a_real_obmc_stream_reads_a_recorded_switchable_filter_for_every_neighbour() {
4380 if !have_aomenc() {
4381 eprintln!("SKIP a_real_obmc_stream_reads_a_recorded_switchable_filter: no aomenc");
4382 return;
4383 }
4384 // `--cpu-used=0` is load-bearing: at speed 4 aomenc settles on a
4385 // FRAME-level fixed interp filter, every neighbour then legitimately
4386 // carries the sentinel, and the band is never read at all (measured
4387 // r27: 0 reads over two speed-4 streams).
4388 let base = vec![
4389 "--cpu-used=0",
4390 "--enable-obmc=1",
4391 "--enable-dual-filter=1",
4392 "--min-partition-size=8",
4393 "--max-partition-size=16",
4394 "--enable-palette=0",
4395 "--enable-intrabc=0",
4396 ];
4397 let recipes: [(&str, usize, usize, Vec<&str>); 2] = [
4398 (
4399 "obmc dual cq40",
4400 192,
4401 128,
4402 [vec!["--cq-level=40"], base.clone()].concat(),
4403 ),
4404 (
4405 "obmc dual cq20",
4406 192,
4407 128,
4408 [vec!["--cq-level=20"], base.clone()].concat(),
4409 ),
4410 ];
4411 let mut reads = 0usize;
4412 let mut decoded = 0usize;
4413 for (name, w, h, extra) in &recipes {
4414 let before = crate::decode::obmc_filter_band_reads();
4415 let obmc_before = crate::decode::obmc_hits();
4416 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 8, extra);
4417 match result {
4418 Ok(pictures) => {
4419 decoded += 1;
4420 let got = crate::decode::obmc_filter_band_reads() - before;
4421 reads += got;
4422 eprintln!(
4423 "OBMCFILT {name}: {bytes} B, {pictures} pictures, {got} band reads, \
4424 {} OBMC blocks",
4425 crate::decode::obmc_hits() - obmc_before
4426 );
4427 }
4428 Err(e) => {
4429 assert!(
4430 !e.contains(
4431 "an OBMC neighbour whose switchable interp filter was never recorded"
4432 ),
4433 "{name}: a real OBMC stream reached the unrecorded-filter refusal -- \
4434 a publication site is missing: {e}"
4435 );
4436 eprintln!("OBMCFILT {name}: {bytes} B, refused for another reason: {e}");
4437 }
4438 }
4439 }
4440 assert!(
4441 decoded > 0,
4442 "no OBMC recipe decoded -- the witness is vacuous"
4443 );
4444 assert!(
4445 reads > 0,
4446 "every OBMC blend took the fixed-filter path: the band was never read, so this \
4447 proves nothing about the refusal"
4448 );
4449 }
4450
4451 /// lane-t900 r27 CENSUS for the three SUPERRES refusals -- "warp
4452 /// prediction with a scaled reference", "a sub-8x8 inter block under a
4453 /// scaled reference" and "an 8x8 partition leaf under a scaled reference".
4454 /// Six real `--superres-mode` encodes (fixed denominators and the auto
4455 /// mode, warped motion and OBMC on), decoded by this decoder: the table it
4456 /// prints is which of the three a real encoder actually reaches.
4457 ///
4458 /// Every one of them is a REAL capability gap (unlike the enumerated
4459 /// refusals elsewhere in the inventory), so this gate asserts the measured
4460 /// shape rather than "no refusal": at least one recipe must decode (else
4461 /// the census says nothing), and any refusal must be one of the three
4462 /// named superres ones -- a fourth string would be a new gap this round
4463 /// did not measure.
4464 #[test]
4465 fn a_superres_census_over_six_real_streams_records_which_scaled_refusals_fire() {
4466 if !have_aomenc() {
4467 eprintln!("SKIP a_superres_census_over_six_real_streams: no aomenc");
4468 return;
4469 }
4470 const WARP: &str = "warp prediction with a scaled reference";
4471 const SUB8: &str = "a sub-8x8 inter block under a scaled reference";
4472 const LEAF8: &str = "an 8x8 partition leaf under a scaled reference";
4473 let common = [
4474 "--enable-warped-motion=1",
4475 "--enable-obmc=1",
4476 "--enable-palette=0",
4477 "--enable-intrabc=0",
4478 ];
4479 let recipes: [(&str, usize, usize, Vec<&str>); 6] = [
4480 (
4481 "denom12 320x180 cq32",
4482 320,
4483 180,
4484 vec![
4485 "--cpu-used=4",
4486 "--superres-mode=1",
4487 "--superres-denominator=12",
4488 "--cq-level=32",
4489 ],
4490 ),
4491 (
4492 "denom12 320x180 cq50",
4493 320,
4494 180,
4495 vec![
4496 "--cpu-used=4",
4497 "--superres-mode=1",
4498 "--superres-denominator=12",
4499 "--cq-level=50",
4500 ],
4501 ),
4502 (
4503 "denom16 320x180 cq32",
4504 320,
4505 180,
4506 vec![
4507 "--cpu-used=4",
4508 "--superres-mode=1",
4509 "--superres-denominator=16",
4510 "--cq-level=32",
4511 ],
4512 ),
4513 (
4514 "denom10 192x128 cq32",
4515 192,
4516 128,
4517 vec![
4518 "--cpu-used=4",
4519 "--superres-mode=1",
4520 "--superres-denominator=10",
4521 "--cq-level=32",
4522 ],
4523 ),
4524 (
4525 "auto 320x180 cq50",
4526 320,
4527 180,
4528 vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"],
4529 ),
4530 (
4531 "auto 192x128 cq50",
4532 192,
4533 128,
4534 vec!["--cpu-used=4", "--superres-mode=3", "--cq-level=50"],
4535 ),
4536 ];
4537 let (mut decoded, mut warp, mut sub8, mut leaf8) = (0, 0, 0, 0);
4538 // lane-t900 r36 (class [[gate-blind-to-feature]]): unknown refusal
4539 // strings used to `other += 1` and panic on the spot, so the census
4540 // summary below -- the whole point of the gate -- never printed when
4541 // one fired. They are collected instead, reported in the summary, and
4542 // asserted after it.
4543 let mut other: Vec<String> = Vec::new();
4544 for (name, w, h, extra) in &recipes {
4545 let mut args = extra.clone();
4546 args.extend_from_slice(&common);
4547 let before = crate::mc::predict_scaled_hits();
4548 let (bytes, result) = census_attempt("mandelbrot", *w, *h, 10, &args);
4549 match result {
4550 Ok(pictures) => {
4551 decoded += 1;
4552 eprintln!(
4553 "SUPERRES {name}: {bytes} B, {pictures} pictures, scaled MC blocks {}",
4554 crate::mc::predict_scaled_hits() - before
4555 );
4556 }
4557 Err(e) => {
4558 eprintln!("SUPERRES {name}: {bytes} B, refused: {e}");
4559 if e.contains(WARP) {
4560 warp += 1;
4561 } else if e.contains(SUB8) {
4562 sub8 += 1;
4563 } else if e.contains(LEAF8) {
4564 leaf8 += 1;
4565 } else {
4566 other.push(format!("{name}: {e}"));
4567 }
4568 }
4569 }
4570 }
4571 eprintln!(
4572 "SUPERRES CENSUS: 6 streams, {decoded} decoded, warp {warp}x, sub8 {sub8}x, leaf8 {leaf8}x, other {}x",
4573 other.len()
4574 );
4575 assert!(
4576 other.is_empty(),
4577 "{} superres stream(s) stopped on a string this census does not know: {other:?}",
4578 other.len()
4579 );
4580 // Measured r27: the four FIXED-denominator recipes all stop at the
4581 // 8x8-leaf refusal, and the two `--superres-mode=3` (auto) streams
4582 // decode with ZERO scaled MC blocks -- auto picked denominator 8, so
4583 // those two arms carry no scaling at all and prove nothing. The warp
4584 // and sub-8x8 refusals never fire because the 8x8-leaf one sits in
4585 // front of them: whichever partition path a scaled frame takes, the
4586 // leaf guard is reached first. Lifting the leaf gap is what makes the
4587 // other two measurable, so this gate pins the ORDER, not just a count.
4588 assert!(
4589 decoded > 0,
4590 "no superres recipe decoded -- the census is vacuous"
4591 );
4592 // lane-t900 r28: all three scaled refusals are LIFTED, so the census
4593 // now pins the opposite shape -- every fixed-denominator recipe must
4594 // DECODE, and none of the three strings may come back.
4595 assert_eq!(
4596 (warp, sub8, leaf8),
4597 (0, 0, 0),
4598 "a scaled-reference refusal came back (warp {warp}, sub8 {sub8}, leaf8 {leaf8})"
4599 );
4600 assert!(
4601 decoded > 0,
4602 "no superres recipe decoded -- the census is vacuous"
4603 );
4604 }
4605
4606 /// lane-t900 r25, negative gate: a `show_existing_frame` header naming a
4607 /// slot no frame has refreshed is refused BY NAME, and outputs no picture.
4608 ///
4609 /// The OBU is hand-built because [`crate::frame::write_frame_header`]
4610 /// refuses to write one (it writes shown key and inter frames only): spec
4611 /// 5.9.2's whole header for this case is `show_existing_frame` (1) plus
4612 /// `frame_to_show_map_idx` (3), the sequence carrying neither a decoder
4613 /// model nor frame ids.
4614 ///
4615 /// Deviation from the round's charter, which asked for a key frame first
4616 /// with the named slot's `refresh_frame_flags` bit clear: a SHOWN key frame
4617 /// refreshes every slot (spec 5.9.2 forces `refresh_frame_flags` to
4618 /// `all_frames` and does not code it, which is also what
4619 /// `write_frame_header` does), so the only reachable empty-slot stream is
4620 /// one where no frame has refreshed that slot yet. The stream below is a
4621 /// valid sequence header followed by the header OBU, and every one of the
4622 /// eight slots is tried.
4623 #[test]
4624 fn a_show_existing_frame_header_naming_an_empty_slot_is_refused_by_name() {
4625 const REFUSAL: &str = "a show_existing_frame header naming an empty reference slot";
4626 let (seq, _) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
4627 for slot in 0..NUM_REF_FRAMES as u32 {
4628 let mut w = ec_core::BitWriter::new();
4629 w.write_bit(true); // show_existing_frame
4630 w.write_bits(slot, 3); // frame_to_show_map_idx
4631 crate::bits::write_byte_alignment(&mut w);
4632 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
4633 stream.extend_from_slice(&crate::obu::wrap_obu(
4634 &ec_av1_syntax::obu::ObuHeader {
4635 obu_type: ec_av1_syntax::obu::ObuType::FrameHeader,
4636 extension_flag: false,
4637 has_size_field: true,
4638 temporal_id: 0,
4639 spatial_id: 0,
4640 },
4641 &w.into_bytes(),
4642 ));
4643
4644 let mut shown = 0;
4645 let err = decode_stream_with(&stream, |_, _, _| {
4646 shown += 1;
4647 Ok(())
4648 })
4649 .unwrap_err()
4650 .to_string();
4651 assert!(
4652 err.contains(REFUSAL),
4653 "slot {slot}: expected {REFUSAL:?}, got: {err}"
4654 );
4655 assert_eq!(
4656 shown, 0,
4657 "slot {slot}: an empty slot was output as a picture"
4658 );
4659 }
4660 }
4661
4662 /// lane-t900 r25, negative gate: an inter frame whose `ref_frame_idx[0]`
4663 /// slot holds no picture -- a stream that opens on an inter frame -- is
4664 /// refused BY NAME rather than predicting from nothing.
4665 ///
4666 /// Deviation from the round's charter, which asked for a real aomenc
4667 /// two-frame stream with the key frame's OBUs stripped: this crate's own
4668 /// `write_frame_header` writes a shown INTER frame (short reference
4669 /// signalling and non-identity global motion are the parts it refuses), so
4670 /// the fixture is built from the writers, needs neither ffmpeg nor aomenc,
4671 /// and is byte-identical on every run. The tile payload is a real key
4672 /// frame's; the refusal fires on the header's reference lookup, before any
4673 /// tile is decoded.
4674 #[test]
4675 fn an_inter_frame_opening_a_stream_is_refused_by_name() {
4676 let fctx = &crate::decode::FrameCtx::new();
4677 const REFUSAL: &str = "an inter frame with no key frame before it";
4678 let picture = test_card(64, 64);
4679 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4680 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
4681 let inter = FrameHeader {
4682 frame_type: FrameType::Inter,
4683 frame_is_intra: false,
4684 // Keeps `primary_ref_frame`, `frame_size_with_refs` and
4685 // `use_ref_frame_mvs` out of the written header (spec 5.9.2).
4686 error_resilient_mode: true,
4687 primary_ref_frame: PRIMARY_REF_NONE,
4688 refresh_frame_flags: 0x02,
4689 order_hint: 1,
4690 ..key
4691 };
4692 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
4693 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
4694
4695 let mut shown = 0;
4696 let err = decode_stream_with(&stream, |_, _, _| {
4697 shown += 1;
4698 Ok(())
4699 })
4700 .unwrap_err()
4701 .to_string();
4702 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
4703 assert_eq!(
4704 shown, 0,
4705 "an inter frame with no reference produced a picture"
4706 );
4707 }
4708
4709 /// lane-t900 r26, negative gate: an inter frame whose own coded size is
4710 /// SHORTER than the reference it predicts from is refused BY NAME, and
4711 /// outputs no picture beyond the key frame that preceded it.
4712 ///
4713 /// The height mismatch is the one size difference this decoder cannot
4714 /// absorb: `mc::predict_scaled` scales horizontally (a `use_superres`
4715 /// reference), and nothing on this path scales vertically. The fixture is
4716 /// written, not hand-built: a shown key frame at 64x64 (which refreshes
4717 /// every slot), then a shown inter frame carrying
4718 /// `frame_size_override_flag` with `error_resilient_mode` set -- the one
4719 /// combination [`crate::frame::write_frame_header`] writes, since
4720 /// `frame_size_with_refs` (spec 5.9.7) is only read when error resilience
4721 /// is OFF. The inter frame's tile payload is the key frame's; the refusal
4722 /// fires on the reference's dimensions before a tile symbol is read.
4723 #[test]
4724 fn an_inter_frame_shorter_than_its_reference_is_refused_by_name() {
4725 let fctx = &crate::decode::FrameCtx::new();
4726 const REFUSAL: &str =
4727 "a reference picture whose height does not match this frame's own true size";
4728 let picture = test_card(64, 64);
4729 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4730 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
4731 let inter = FrameHeader {
4732 frame_type: FrameType::Inter,
4733 frame_is_intra: false,
4734 error_resilient_mode: true,
4735 primary_ref_frame: PRIMARY_REF_NONE,
4736 refresh_frame_flags: 0x02,
4737 order_hint: 1,
4738 frame_size_override_flag: true,
4739 frame_height: 32,
4740 render_height: 32,
4741 ..key.clone()
4742 };
4743 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
4744 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &key, &encoded.tile).unwrap());
4745 stream.extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
4746
4747 let mut shown = 0;
4748 let err = decode_stream_with(&stream, |_, _, _| {
4749 shown += 1;
4750 Ok(())
4751 })
4752 .unwrap_err()
4753 .to_string();
4754 assert!(err.contains(REFUSAL), "expected {REFUSAL:?}, got: {err}");
4755 assert_eq!(
4756 shown, 1,
4757 "expected the key frame alone, got {shown} pictures"
4758 );
4759 }
4760
4761 /// lane-t900 r26, negative gate: an inter frame naming a
4762 /// `primary_ref_frame` whose reference slot has never been refreshed is
4763 /// refused BY NAME rather than decoded from the spec 8.4 default tables.
4764 ///
4765 /// Enumeration first, because the refusal's premise is an invariant: the
4766 /// picture slots and the CDF slots are written by exactly two loops in
4767 /// [`decode_stream`] (the `show_existing_frame` arm's copy and the
4768 /// end-of-frame store), and both walk the SAME `refresh_frame_flags` mask
4769 /// writing `ref_slots[i]` and `cdf_slots[i]` together -- so no slot can
4770 /// hold a picture without CDFs, and the reachable case is a slot nothing
4771 /// has refreshed at all. That is what this builds: a stream that OPENS on
4772 /// a non-error-resilient inter frame (the only header shape that codes
4773 /// `primary_ref_frame` at all, spec 5.9.2), tried at all eight slots.
4774 ///
4775 /// This refusal, not "an inter frame with no key frame before it", is the
4776 /// one such a stream reaches: the CDF load happens in the header path,
4777 /// before the reference pictures are looked up.
4778 #[test]
4779 fn an_inter_frame_naming_an_unrefreshed_primary_ref_slot_is_refused_by_name() {
4780 let fctx = &crate::decode::FrameCtx::new();
4781 const REFUSAL: &str =
4782 "a frame naming primary_ref_frame at a reference slot with no saved CDF state";
4783 // The invariant above, read off the source: every line that stores a
4784 // picture into a slot sits in a block that stores that slot's CDFs too.
4785 let src = include_str!("stream.rs");
4786 let stores: Vec<usize> = src
4787 .lines()
4788 .enumerate()
4789 .filter(|(_, l)| l.trim().starts_with("ref_slots[i] = "))
4790 .map(|(i, _)| i)
4791 .collect();
4792 assert_eq!(
4793 stores.len(),
4794 2,
4795 "the picture slots gained a writer -- check it stores cdf_slots too"
4796 );
4797 let lines: Vec<&str> = src.lines().collect();
4798 for &i in &stores {
4799 let window = lines[i.saturating_sub(6)..(i + 6).min(lines.len())].join("\n");
4800 assert!(
4801 window.contains("cdf_slots[i] = "),
4802 "line {} stores a reference picture with no cdf_slots store beside it: a slot \
4803 can then hold a picture with no saved CDF state",
4804 i + 1
4805 );
4806 }
4807
4808 let picture = test_card(64, 64);
4809 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
4810 let (seq, key) = crate::encode::key_frame_headers(64, 64, 100).unwrap();
4811 for slot in 0..NUM_REF_FRAMES as u8 {
4812 let inter = FrameHeader {
4813 frame_type: FrameType::Inter,
4814 frame_is_intra: false,
4815 // `primary_ref_frame` is coded only when error resilience is
4816 // off (spec 5.9.2); `frame_size_override_flag` stays clear so
4817 // the header writes a plain `frame_size()`.
4818 error_resilient_mode: false,
4819 primary_ref_frame: 0,
4820 ref_frame_idx: [slot; ec_av1_syntax::REFS_PER_FRAME],
4821 refresh_frame_flags: 0x02,
4822 order_hint: 1,
4823 ..key.clone()
4824 };
4825 let mut stream = crate::sequence::sequence_header_obu(&seq).unwrap();
4826 stream
4827 .extend_from_slice(&crate::frame::frame_obu(&seq, &inter, &encoded.tile).unwrap());
4828
4829 let mut shown = 0;
4830 let err = decode_stream_with(&stream, |_, _, _| {
4831 shown += 1;
4832 Ok(())
4833 })
4834 .unwrap_err()
4835 .to_string();
4836 assert!(
4837 err.contains(REFUSAL),
4838 "slot {slot}: expected {REFUSAL:?}, got: {err}"
4839 );
4840 assert_eq!(
4841 shown, 0,
4842 "slot {slot}: a frame with no CDF state produced a picture"
4843 );
4844 }
4845 }
4846
4847 /// lane-t900 r26, enumeration: no frame header a stream can carry derives
4848 /// an empty mode-info grid, so "a frame with no mode-info grid" names a
4849 /// case outside the coded domain.
4850 ///
4851 /// `compute_image_size` (spec 5.9.9) is `mi_cols = 2 * ((frame_width + 7)
4852 /// >> 3)`, which is 0 only for `frame_width == 0`, and a frame width is
4853 /// never 0 on any of the three paths that set one:
4854 ///
4855 /// * `frame_size()` (5.9.5) reads `frame_width_minus_1` and adds one, or
4856 /// takes the sequence's `max_frame_width` (itself `+ 1`-coded);
4857 /// * `superres_params()` (5.9.8) divides by a denominator of 9..=16 with
4858 /// rounding, whose minimum over the whole 16-bit upscaled-width domain
4859 /// is enumerated below and is 1, not 0;
4860 /// * `show_existing_frame` and `frame_size_with_refs()` copy a slot's own
4861 /// dimensions, which came from one of the above.
4862 ///
4863 /// The sweep drives the REAL header reader (write a header, parse it back)
4864 /// over every width and every height a 16-bit `frame_size()` can code,
4865 /// per axis -- the derivation is independent per axis -- rather than
4866 /// re-deriving the formula here.
4867 #[test]
4868 fn every_frame_size_a_header_can_code_has_a_mode_info_grid() {
4869 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so
4870 // it names it and pins its guard site (the decode-path guard in
4871 // decode.rs carries the same string).
4872 const REFUSAL: &str = "a frame with no mode-info grid";
4873 assert!(
4874 crate::refusal_inventory::pins_refusal(include_str!("stream.rs"), REFUSAL),
4875 "this gate proves {REFUSAL:?}, but that string is no longer in stream.rs"
4876 );
4877 let mut sizes: Vec<u32> = (1..=1024).collect();
4878 sizes.extend([2048, 4095, 4096, 8192, 16384, 32768, 65535, 65536]);
4879 // `mi_cols` is nondecreasing in `frame_width`, so an empty grid can
4880 // only appear at the SMALL end -- which is why a size this crate's
4881 // tile-info writer cannot express (its tile log2 range runs out well
4882 // before 65536) is skipped rather than worked around, while every
4883 // size up to 1024 must be covered.
4884 let mut skipped: Vec<u32> = Vec::new();
4885 for n in sizes {
4886 for (w, h) in [(n, 16), (16, n)] {
4887 let Ok((seq, header)) =
4888 crate::encode::key_frame_headers(w as usize, h as usize, 100)
4889 else {
4890 skipped.push(n);
4891 continue;
4892 };
4893 let Ok(stream) = crate::frame::frame_obu(&seq, &header, &[]) else {
4894 skipped.push(n);
4895 continue;
4896 };
4897 let mut parser = Av1Parser::new();
4898 parser
4899 .parse_obu(&crate::sequence::sequence_header_obu(&seq).unwrap())
4900 .unwrap();
4901 let obu = parser.parse_obu(&stream).unwrap();
4902 let ObuKind::Frame(parsed, _) = &obu.kind else {
4903 panic!("{w}x{h}: the written frame OBU did not parse as one");
4904 };
4905 assert!(
4906 parsed.mi_cols >= 2 && parsed.mi_rows >= 2,
4907 "{w}x{h} parsed to a {}x{} mode-info grid",
4908 parsed.mi_cols,
4909 parsed.mi_rows
4910 );
4911 }
4912 }
4913 assert!(
4914 skipped.iter().all(|&n| n > 1024),
4915 "the writer could not express these small frame sizes, so the small end of the \
4916 sweep is incomplete: {skipped:?}"
4917 );
4918 // The superres arm, which no writer here can express: spec 5.9.8's
4919 // `(upscaled_width * 8 + denom / 2) / denom` over its whole domain.
4920 for denom in 9u32..=16 {
4921 for upscaled in [1u32, 2, 3, 7, 8, 9, 255, 4096, 65535, 65536] {
4922 let width = (upscaled * 8 + denom / 2) / denom;
4923 assert!(
4924 width >= 1,
4925 "superres denom {denom} maps an upscaled width of {upscaled} to {width}, \
4926 which would derive an empty mode-info grid"
4927 );
4928 }
4929 }
4930 }
4931
4932 /// lane-interedge r1: one attempt of the inter frame-edge half-strip gate --
4933 /// encode `width x height` with real aomenc (rect partitions ON, every other
4934 /// lane's open tool pinned off), decode it, and return
4935 /// `(inter_edge_strip hits, frames whose LUMA differs, frames whose CHROMA
4936 /// differs)` against ffmpeg. A refusal or a decode error is a hard failure:
4937 /// this recipe reached every size without one (measured r1).
4938 fn inter_edge_strip_attempt(
4939 name: &str,
4940 width: usize,
4941 height: usize,
4942 bit_depth: u32,
4943 cq: u32,
4944 frames: usize,
4945 ) -> ([usize; 6], usize, usize) {
4946 let duration = format!("{}", frames as f64 / 25.0);
4947 let source = format!("mandelbrot=size={width}x{height}:rate=25");
4948 let pix_fmt = if bit_depth == 10 {
4949 "yuv420p10le"
4950 } else {
4951 "yuv420p"
4952 };
4953 let y4m = Command::new("ffmpeg")
4954 .args([
4955 "-v",
4956 "error",
4957 "-f",
4958 "lavfi",
4959 "-i",
4960 &source,
4961 "-t",
4962 &duration,
4963 "-pix_fmt",
4964 pix_fmt,
4965 "-strict",
4966 "-1",
4967 "-f",
4968 "yuv4mpegpipe",
4969 "-",
4970 ])
4971 .stdin(Stdio::null())
4972 .stdout(Stdio::piped())
4973 .stderr(Stdio::piped())
4974 .output()
4975 .expect("ffmpeg failed to run");
4976 assert!(
4977 y4m.status.success(),
4978 "{name}: ffmpeg refused the {width}x{height} {bit_depth}-bit fixture: {}",
4979 String::from_utf8_lossy(&y4m.stderr)
4980 );
4981 let depth_arg = format!("--bit-depth={bit_depth}");
4982 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
4983 let cq_arg = format!("--cq-level={cq}");
4984 let limit_arg = format!("--limit={frames}");
4985 let out = run_with_stdin(
4986 Command::new(aomenc_path()).args([
4987 "--codec=av1",
4988 "--passes=1",
4989 "--end-usage=q",
4990 &cq_arg,
4991 // cpu-used >= 1 keeps libaom on 64x64 superblocks at these
4992 // sizes (`av1_select_sb_size`).
4993 "--cpu-used=4",
4994 "--threads=1",
4995 "--row-mt=0",
4996 "--kf-max-dist=9999",
4997 &limit_arg,
4998 // decode order == display order, so the compare below covers
4999 // every frame the stream carries (class gate-blind-to-hidden-frames).
5000 "--lag-in-frames=0",
5001 &depth_arg,
5002 &input_depth_arg,
5003 // Rect partitions stay ON: the frame-edge strip is a FORCED
5004 // (gathered) HORZ/VERT, but with rect coding off the encoder
5005 // answers that gathered symbol SPLIT every time and no edge
5006 // strip ever fires (lane-oddh r2's finding, re-measured r1).
5007 "--enable-rect-partitions=1",
5008 "--enable-ab-partitions=0",
5009 "--enable-1to4-partitions=0",
5010 "--min-partition-size=8",
5011 "--max-partition-size=64",
5012 // Other lanes' open gaps this recipe must not trip.
5013 "--enable-palette=0",
5014 "--enable-intrabc=0",
5015 "--enable-warped-motion=0",
5016 "--enable-obmc=0",
5017 "--enable-masked-comp=0",
5018 "--enable-interintra-comp=0",
5019 "--enable-onesided-comp=0",
5020 "--enable-interintra-wedge=0",
5021 "--enable-smooth-interintra=0",
5022 "--enable-ref-frame-mvs=0",
5023 "--enable-angle-delta=0",
5024 "--enable-cfl-intra=0",
5025 "--enable-directional-intra=0",
5026 "--enable-smooth-intra=0",
5027 "--enable-paeth-intra=0",
5028 "--enable-filter-intra=0",
5029 "--enable-tx-size-search=0",
5030 "--obu",
5031 "-o",
5032 "-",
5033 "-",
5034 ]),
5035 &y4m.stdout,
5036 );
5037 assert!(
5038 out.status.success(),
5039 "aomenc refused: {}",
5040 String::from_utf8_lossy(&out.stderr)
5041 );
5042 let stream = out.stdout;
5043
5044 // Reset, never a delta: a refused attempt's hits must not leak into the
5045 // next one (class counter-from-refused-stream).
5046 crate::decode::reset_inter_edge_strip_hits();
5047 let decoded = decode_stream(&stream).unwrap_or_else(|e| {
5048 panic!("{name}: {width}x{height} {bit_depth}-bit cq {cq} did not decode: {e}")
5049 });
5050 let hits = crate::decode::inter_edge_strip_hits();
5051 let reference = if bit_depth == 10 {
5052 ffmpeg_decode_sequence_10bit(&stream, width, height, frames)
5053 } else {
5054 ffmpeg_decode_sequence(&stream, width, height, frames)
5055 };
5056 assert_eq!(
5057 decoded.len(),
5058 reference.len(),
5059 "{name}: {width}x{height} {bit_depth}-bit cq {cq} frame count"
5060 );
5061 assert!(
5062 decoded.len() >= frames,
5063 "{name}: {width}x{height} {bit_depth}-bit cq {cq} decoded only {} frames",
5064 decoded.len()
5065 );
5066 let (mut luma_bad, mut chroma_bad) = (0usize, 0usize);
5067 for (ours, theirs) in decoded.iter().zip(&reference) {
5068 if ours.y != theirs.y {
5069 luma_bad += 1;
5070 }
5071 if ours.u != theirs.u || ours.v != theirs.v {
5072 chroma_bad += 1;
5073 }
5074 }
5075 (hits, luma_bad, chroma_bad)
5076 }
5077
5078 /// lane-interedge r1 GATE (was lane-oddh r2's `#[ignore]`d twin): the INTER
5079 /// frame-edge half strips -- a `PARTITION_HORZ`/`PARTITION_VERT` forced by
5080 /// the gathered edge symbol at the 64, 32 or 16 level whose second half lies
5081 /// outside the true frame. Both of the user's films are height mod 16 == 8
5082 /// (1920x792, 3840x1608), so every inter frame crosses these nodes.
5083 ///
5084 /// r1 root cause: the inter tile's 32-level `PARTITION_HORZ`/`PARTITION_VERT`
5085 /// decoded the SECOND strip unconditionally, while libaom `decode_partition`
5086 /// (decodeframe.c, PARTITION_HORZ) guards it with `has_rows`/`has_cols` --
5087 /// so at the edge we read symbols the encoder never wrote. With that guard
5088 /// removed this gate's 72x192 cq 32 arm refuses outright and its 104x192 arm
5089 /// decodes luma rows 127..191 of frame 5 wrong (measured r1).
5090 ///
5091 /// The compare is LUMA-exact per frame plus a CONTROL size with no edge node
5092 /// at all: chroma is excluded because a chroma-only inter residue that has
5093 /// nothing to do with the frame edge is open on main (lanes/tiny-r3,
5094 /// lanes/gmaffine-r4, lanes/palette2-r8) and the control below reproduces it
5095 /// with `inter_edge_strip_hits` all zero.
5096 #[test]
5097 fn a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact() {
5098 const NAME: &str = "a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact";
5099 let _gate_lock = lock_gate_counters();
5100 if !have_ffmpeg() || !have_aomenc() {
5101 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
5102 return;
5103 }
5104 let frames = 6usize;
5105 // h mod 16 == 8 (bottom edge) and w mod 16 == 8 (right edge).
5106 let sizes: &[(usize, usize)] = &[(192, 72), (192, 88), (72, 192), (88, 192), (104, 192)];
5107 let mut totals = [0usize; 6];
5108 let mut compared = 0u32;
5109 let mut chroma_frames = 0usize;
5110 for &(width, height) in sizes {
5111 for bit_depth in [8u32, 10] {
5112 for cq in [20u32, 32, 45] {
5113 let (hits, luma_bad, chroma_bad) =
5114 inter_edge_strip_attempt(NAME, width, height, bit_depth, cq, frames);
5115 assert_eq!(
5116 luma_bad, 0,
5117 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {luma_bad} of {frames} \
5118 frames differ from ffmpeg in LUMA (edge hits {hits:?})"
5119 );
5120 // merge J, after lane-rectchroma2: the chroma residue this
5121 // gate used to tolerate WAS this decoder's -- the per-axis
5122 // narrow-block MC kernel decision read side x side instead
5123 // of the block's true dims. Full-plane now.
5124 assert_eq!(
5125 chroma_bad, 0,
5126 "{NAME}: {width}x{height} {bit_depth}-bit cq {cq}: {chroma_bad} of \
5127 {frames} frames differ from ffmpeg in CHROMA (edge hits {hits:?})"
5128 );
5129 for (t, h) in totals.iter_mut().zip(hits) {
5130 *t += h;
5131 }
5132 chroma_frames += chroma_bad;
5133 compared += 1;
5134 }
5135 }
5136 }
5137 // Every level x axis this recipe reaches must have fired on a COMPARED
5138 // attempt. h32 (a bottom-edge HORZ at the 32 level) is not asserted: no
5139 // recipe found in r1 makes libaom answer that gathered symbol HORZ
5140 // (sweep ~/.cache/interedge-tmp/h32.sh, 3 sizes x 6 cq, all SPLIT); it
5141 // is the transposed twin of v32, which this gate does fire.
5142 assert!(
5143 totals[0] > 0 && totals[1] > 0 && totals[3] > 0 && totals[4] > 0 && totals[5] > 0,
5144 "{NAME}: {compared} attempts luma-exact but the edge strips did not all fire \
5145 (h64,v64,h32,v32,h16,v16 = {totals:?}) -- the recipe no longer reaches the arms \
5146 this gate exists for"
5147 );
5148 // CONTROL: a size with no frame-edge node anywhere (192x128, both axes
5149 // 0 mod 64). It must be luma-exact with ZERO edge hits -- that is what
5150 // makes the chroma exclusion above a statement about a foreign defect
5151 // rather than about this lane's code.
5152 let (chits, cluma, cchroma) = inter_edge_strip_attempt(NAME, 192, 128, 8, 32, frames);
5153 assert_eq!(
5154 (chits, cluma, cchroma),
5155 ([0usize; 6], 0usize, 0usize),
5156 "{NAME}: control 192x128 (no frame-edge node) must be pixel-exact with no edge hits"
5157 );
5158 eprintln!(
5159 "{NAME}: {compared} attempts luma-exact over {} sizes, edge hits \
5160 (h64,v64,h32,v32,h16,v16)={totals:?}, 0 refusals; chroma-only frames {chroma_frames} \
5161 (control 192x128: hits {chits:?}, chroma-only frames {cchroma} -- foreign defect)",
5162 sizes.len()
5163 );
5164 }
5165
5166 /// lane-sb128 r4 GATE (was lane-oddh r2's refusal gate): the SAME real
5167 /// aomenc 64x72 `--cpu-used=0 --sb-size=128` stream that once desynced at
5168 /// the very first symbol now decodes PIXEL-EXACT against aomdec. mi_rows
5169 /// = 18 > 16, so the BLOCK_128X128 root reads a real gathered partition
5170 /// symbol (2 symbols: has_cols false, has_rows true) -- exactly the case
5171 /// r1 mis-read as a 10-symbol BLOCK_64X64 partition.
5172 ///
5173 /// The `use_128x128_superblock` assert is the "knob reached the tool"
5174 /// half: without it an aomenc that ignored `--sb-size=128` would leave
5175 /// the gate proving nothing about 128 superblocks.
5176 #[test]
5177 fn a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact() {
5178 if !have_ffmpeg() || !have_aomenc() {
5179 eprintln!("SKIP: no ffmpeg/aomenc");
5180 return;
5181 }
5182 let (width, height) = (64usize, 72usize);
5183 let y4m = Command::new("ffmpeg")
5184 .args([
5185 "-v",
5186 "error",
5187 "-f",
5188 "lavfi",
5189 "-i",
5190 "mandelbrot=size=64x72:rate=25:start_x=-0.6:start_y=-0.4",
5191 "-t",
5192 "0.04",
5193 "-pix_fmt",
5194 "yuv420p",
5195 "-f",
5196 "yuv4mpegpipe",
5197 "-",
5198 ])
5199 .stdin(Stdio::null())
5200 .stdout(Stdio::piped())
5201 .stderr(Stdio::piped())
5202 .output()
5203 .expect("ffmpeg failed to run");
5204 assert!(
5205 y4m.status.success(),
5206 "ffmpeg fixture: {}",
5207 String::from_utf8_lossy(&y4m.stderr)
5208 );
5209 let out = run_with_stdin(
5210 Command::new(aomenc_path()).args([
5211 "--codec=av1",
5212 "--passes=1",
5213 "--end-usage=q",
5214 "--cq-level=32",
5215 "--cpu-used=0",
5216 "--sb-size=128",
5217 "--min-partition-size=16",
5218 "--kf-max-dist=0",
5219 "--limit=1",
5220 "--threads=1",
5221 "--row-mt=0",
5222 "--obu",
5223 "-o",
5224 "-",
5225 "-",
5226 ]),
5227 &y4m.stdout,
5228 );
5229 assert!(
5230 out.status.success(),
5231 "aomenc refused: {}",
5232 String::from_utf8_lossy(&out.stderr)
5233 );
5234 let stream = out.stdout;
5235
5236 // The knob actually arrived: this stream's sequence header codes
5237 // `use_128x128_superblock = 1`.
5238 let mut parser = Av1Parser::new();
5239 let mut pos = 0usize;
5240 let mut sb128 = false;
5241 while pos < stream.len() {
5242 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
5243 break;
5244 };
5245 pos += obu.total_size.max(1);
5246 if let Some(seq) = parser.sequence_header() {
5247 sb128 = seq.use_128x128_superblock;
5248 break;
5249 }
5250 }
5251 assert!(
5252 sb128,
5253 "aomenc ignored --sb-size=128: this stream is 64x64-superblock"
5254 );
5255
5256 let _guard = lock_gate_counters();
5257 let before = crate::decode::part128_symbols() + crate::decode::part128_gathered_symbols();
5258 let (frames, hidden) = decode_all_frames_vs_oracle(&stream, "sb128-oddh-64x72");
5259 assert!(frames > 0, "no frames decoded for {width}x{height}");
5260 // The 128 root actually READ a partition symbol here: at mi_rows=18
5261 // `has_rows` is true, so BLOCK_128X128 is not a forced split.
5262 let part128 =
5263 crate::decode::part128_symbols() + crate::decode::part128_gathered_symbols() - before;
5264 assert!(
5265 part128 > 0,
5266 "{width}x{height} decoded without reading a single BLOCK_128X128 \
5267 partition symbol -- the gate proves nothing about the 128 root"
5268 );
5269 eprintln!(
5270 "a_real_aomenc_128x128_superblock_stream_decodes_pixel_exact: \
5271 {frames} frames pixel-exact ({hidden} hidden) at {width}x{height}, \
5272 part128_symbols={part128}"
5273 );
5274 }
5275
5276 /// `decode_stream` on a lone key frame's stream matches both the tile
5277 /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and
5278 /// the encoder's own reconstruction, at an even and an odd size.
5279 #[test]
5280 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
5281 // lane-b128m: the ENCODER writes at this process's superblock size, so
5282 // its own trial decode -- and the raw tile decode below -- must be given
5283 // that size too (class: stale header in the test harness).
5284 let fctx = &crate::decode::FrameCtx::for_encoder();
5285 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
5286 let picture = test_card(width, height);
5287 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
5288 let via_tile = decode_key_frame_tile_lr(
5289 &encoded.tile,
5290 encoded.mi_cols,
5291 encoded.mi_rows,
5292 encoded.base_q_idx,
5293 width as u32,
5294 height as u32,
5295 // lane-fintra: the sequence bit the encoder wrote this tile under
5296 // (stale-header class -- a hard-coded `false` here reads one symbol
5297 // short at the first DC_PRED block once the search offers filter intra).
5298 crate::encode::filter_intra_on(),
5299 &encoded.cdef,
5300 &encoded.loop_filter,
5301 encoded.tx_select,
5302 // lane-intertx: the frame's own `reduced_tx_set` -- a screen
5303 // key frame at preset 0 codes the wider intra alphabets, so
5304 // the old hardcoded `true` (ours "always" wrote true) is a
5305 // stale-header bug waiting for the first screen fixture.
5306 encoded.reduced_tx_set,
5307 // `allow_screen_content_tools` off the frame the encoder
5308 // actually wrote: a screen-content picture codes two palette
5309 // symbols per intra block, and a raw tile decode that guessed
5310 // `false` desyncs at the first one (class: test asserts
5311 // against a stale header).
5312 encoded.screen,
5313 // ... and its own `allow_intrabc` (stale-header class).
5314 encoded.allow_intrabc,
5315 &encoded.loop_restoration,
5316 fctx,
5317 )
5318 .unwrap();
5319 let via_stream = decode_stream(&encoded.stream).unwrap();
5320 assert_eq!(via_stream.len(), 1, "{width}x{height}: one picture");
5321 assert_eq!(via_stream[0].y, via_tile.y, "{width}x{height}: luma");
5322 assert_eq!(via_stream[0].u, via_tile.u, "{width}x{height}: U");
5323 assert_eq!(via_stream[0].v, via_tile.v, "{width}x{height}: V");
5324 assert_eq!(
5325 via_stream[0].y, encoded.reconstruction.y,
5326 "{width}x{height}: luma vs encoder reconstruction"
5327 );
5328 }
5329 }
5330
5331 /// A GOP (key frame plus panned inter frames, so blocks actually take
5332 /// motion) decodes bit-exact through `decode_stream` alone, threading its
5333 /// own DPB rather than a test-supplied reference.
5334 fn gop_round_trips(width: usize, height: usize, fctx: &crate::decode::FrameCtx) {
5335 let pictures: Vec<_> = (0..4)
5336 .map(|i| panned_test_card(width, height, i * 3))
5337 .collect();
5338 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
5339 let decoded = decode_stream(&encoded.stream).unwrap();
5340 assert_eq!(decoded.len(), encoded.frames.len());
5341 for (i, (got, frame)) in decoded.iter().zip(&encoded.frames).enumerate() {
5342 assert_eq!(
5343 got.y, frame.reconstruction.y,
5344 "{width}x{height} frame {i} luma"
5345 );
5346 assert_eq!(
5347 got.u, frame.reconstruction.u,
5348 "{width}x{height} frame {i} U"
5349 );
5350 assert_eq!(
5351 got.v, frame.reconstruction.v,
5352 "{width}x{height} frame {i} V"
5353 );
5354 }
5355 }
5356
5357 #[test]
5358 fn decode_stream_round_trips_a_gop() {
5359 let fctx = &crate::decode::FrameCtx::for_encoder();
5360 gop_round_trips(128, 64, fctx);
5361 }
5362
5363 /// Same claim at a size that is not a whole number of 32x32 blocks, so
5364 /// the inter frame's 16x16-leaf split path is exercised too.
5365 #[test]
5366 fn decode_stream_round_trips_an_odd_size_gop() {
5367 let fctx = &crate::decode::FrameCtx::for_encoder();
5368 gop_round_trips(216, 96, fctx);
5369 }
5370
5371 /// lane-streamsink r1: `decode_stream_with` emits exactly the pictures
5372 /// `decode_stream` collects, in the same order -- the streaming path is
5373 /// the decoder now (`decode_stream` is a collecting wrapper), so an
5374 /// equivalence check here is what keeps every gate's Vec-shaped assert
5375 /// meaningful. Also pins the sink contract: one call per shown picture,
5376 /// decode indices non-decreasing, and an `Err` from the sink aborting.
5377 #[test]
5378 fn streaming_decode_matches_the_collecting_one() {
5379 let fctx = &crate::decode::FrameCtx::for_encoder();
5380 let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect();
5381 let stream = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
5382 .unwrap()
5383 .stream;
5384 let collected = decode_stream(&stream).unwrap();
5385
5386 let mut shown = Vec::new();
5387 let mut idxs = Vec::new();
5388 let mut live = 0usize;
5389 decode_stream_with(&stream, |p, idx, is_shown| {
5390 live += 1;
5391 if is_shown {
5392 idxs.push(idx);
5393 shown.push(p.clone());
5394 }
5395 Ok(())
5396 })
5397 .unwrap();
5398 assert_eq!(
5399 shown.len(),
5400 collected.len(),
5401 "callback count vs shown frames"
5402 );
5403 assert!(
5404 live >= shown.len(),
5405 "every shown picture is also a callback"
5406 );
5407 assert!(
5408 idxs.windows(2).all(|w| w[0] <= w[1]),
5409 "decode indices out of order: {idxs:?}"
5410 );
5411 for (i, (got, want)) in shown.iter().zip(&collected).enumerate() {
5412 assert_eq!(got.y, want.y, "frame {i} luma");
5413 assert_eq!(got.u, want.u, "frame {i} U");
5414 assert_eq!(got.v, want.v, "frame {i} V");
5415 }
5416
5417 // A sink error stops the decode and comes back unchanged.
5418 let mut seen = 0usize;
5419 let err = decode_stream_with(&stream, |_, _, _| {
5420 seen += 1;
5421 Err(Error::corrupt("sink says stop"))
5422 })
5423 .unwrap_err();
5424 assert_eq!(seen, 1, "decode continued past a failing sink");
5425 assert!(format!("{err}").contains("sink says stop"), "{err}");
5426 }
5427
5428 use crate::probe::run_with_stdin;
5429 use std::process::{Command, Stdio};
5430
5431 /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`,
5432 /// `skip_mode`/compound) all read a process-global atomic counter delta
5433 /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to
5434 /// prove a real block picked the feature under test, not just that a
5435 /// header bit was set. Under `cargo test`'s default parallel run, a
5436 /// SIBLING test's own decode bumps the same global counter mid-gate --
5437 /// a false "fired" reading pixel-compares an attempt the gate would
5438 /// otherwise `continue` past, on top of genuine defects that path may
5439 /// still have. Serialising every counter-delta gate behind this one
5440 /// mutex makes firing detection honest again (matches the existing
5441 /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`).
5442 static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
5443 /// Three-bucket gate summary (class [[gate-skips-on-its-own-failure]]):
5444 /// every attempt lands in exactly one bucket -- decoded pixel-exact WITH
5445 /// the feature counter moving, decoded pixel-exact WITHOUT it, or a named
5446 /// refusal -- and the three sum to the attempts made.
5447 fn gate_buckets(name: &str, counted_exact: u32, uncounted_exact: u32, named_refusals: usize) {
5448 eprintln!(
5449 "{name}: buckets counted-exact={counted_exact} uncounted-exact={uncounted_exact} \
5450 named-refusals={named_refusals} (attempts {})",
5451 counted_exact as usize + uncounted_exact as usize + named_refusals
5452 );
5453 }
5454
5455 pub(crate) fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
5456 GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
5457 }
5458
5459 /// lane-cdfflake: a cheap, dependency-free (FNV-1a, not cryptographic --
5460 /// this is a load-bearing-identity fingerprint for flake triage, not a
5461 /// security digest, so no `sha2` dep is pulled in) fixture fingerprint
5462 /// for the cdf-forwarding gate's instrumentation below.
5463 /// Reads a pinned fixture, asserting its length and FNV first, so a
5464 /// swapped or truncated pin fails loudly instead of silently changing
5465 /// what the gate measures.
5466 fn read_pin(path: &std::path::Path, len: usize, fnv: u64, name: &str) -> Vec<u8> {
5467 let bytes = std::fs::read(path).unwrap_or_else(|e| {
5468 panic!(
5469 "{name}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
5470 which is a failure, not a skip",
5471 path.display()
5472 )
5473 });
5474 assert_eq!(bytes.len(), len, "{name}: fixture length moved");
5475 assert_eq!(fnv1a64(&bytes), fnv, "{name}: fixture bytes moved");
5476 bytes
5477 }
5478
5479 /// The bit depth the stream's OWN sequence header declares, read from
5480 /// the bytes rather than taken from the gate's name or recipe (class
5481 /// `helper-packs-u16-for-an-8-bit-stream`: aomdec's `--rawvideo`
5482 /// writes 8 bits per sample for an 8-bit stream and 16 bits LE for a
5483 /// high-bitdepth one, so a u16 packer turns every 8-bit compare into a
5484 /// raw-SIZE failure that never looks at a sample).
5485 fn stream_bit_depth(stream: &[u8], name: &str) -> u8 {
5486 let mut probe = Av1Parser::new();
5487 let mut pos = 0usize;
5488 while pos < stream.len() && probe.sequence_header().is_none() {
5489 let obu = probe
5490 .parse_obu(&stream[pos..])
5491 .unwrap_or_else(|e| panic!("{name}: OBU at byte {pos} does not parse: {e:?}"));
5492 pos += obu.total_size;
5493 }
5494 probe
5495 .sequence_header()
5496 .unwrap_or_else(|| panic!("{name}: the stream carries no sequence header OBU"))
5497 .color_config
5498 .bit_depth
5499 }
5500
5501 /// Packs decoded planes the way `aomdec --rawvideo` writes them for
5502 /// `bit_depth`: 1 byte per sample at 8-bit, 2 bytes little-endian at
5503 /// 10/12-bit. Plane order is Y, U, V at the frame's own subsampled
5504 /// shape, which is exactly what rawvideo emits.
5505 fn pack_rawvideo(decoded: &[Pic], bit_depth: u8, name: &str) -> Vec<u8> {
5506 let mut ours: Vec<u8> = Vec::new();
5507 for (fi, f) in decoded.iter().enumerate() {
5508 for p in [&f.y, &f.u, &f.v] {
5509 if bit_depth == 8 {
5510 for &s in p {
5511 assert!(
5512 s <= 0xff,
5513 "{name}: decode-order frame {fi} carries the sample {s}, which an \
5514 8-bit stream cannot hold -- the stream is not the one this gate thinks \
5515 it is"
5516 );
5517 ours.push(s as u8);
5518 }
5519 } else {
5520 for &s in p {
5521 ours.extend_from_slice(&s.to_le_bytes());
5522 }
5523 }
5524 }
5525 }
5526 ours
5527 }
5528
5529 /// Decodes `stream` and the oracle's `aomdec --rawvideo` output and
5530 /// requires every sample of every frame to agree, in decode order.
5531 ///
5532 /// `bit_depth` is the depth the CALLER believes the stream has; it is
5533 /// asserted against the stream's own sequence header, so a gate that
5534 /// hands this an 8-bit stream under a 10-bit label fails here by name
5535 /// instead of dying on a raw-size mismatch that reads like a pixel bug.
5536 fn assert_rawvideo_matches(
5537 obu: &std::path::Path,
5538 stream: &[u8],
5539 name: &str,
5540 frames: usize,
5541 bit_depth: u8,
5542 ) {
5543 let actual_depth = stream_bit_depth(stream, name);
5544 assert_eq!(
5545 actual_depth, bit_depth,
5546 "{name}: the stream's sequence header says {actual_depth}-bit, the gate passed \
5547 {bit_depth}-bit -- aomdec's --rawvideo writes {actual_depth} bits per sample for it, \
5548 so packing for {bit_depth} compares nothing"
5549 );
5550 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
5551 let _ = std::fs::remove_dir_all(&dir);
5552 std::fs::create_dir_all(&dir).expect("scratch dir");
5553 let raw = dir.join("aomdec.raw");
5554 let out = Command::new(aomdec_path())
5555 .args(["--codec=av1", "--rawvideo", "-o"])
5556 .arg(&raw)
5557 .arg(obu)
5558 .stdin(Stdio::null())
5559 .stdout(Stdio::piped())
5560 .stderr(Stdio::piped())
5561 .output()
5562 .expect("aomdec failed to run");
5563 assert!(
5564 out.status.success(),
5565 "{name}: the oracle aomdec refused the stream: {}",
5566 String::from_utf8_lossy(&out.stderr)
5567 );
5568 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
5569 let _ = std::fs::remove_dir_all(&dir);
5570 let decoded = decode_stream(stream).expect("decode for comparison");
5571 let ours = pack_rawvideo(&decoded, bit_depth, name);
5572 assert_eq!(
5573 ours.len(),
5574 ref_raw.len(),
5575 "{name}: {bit_depth}-bit raw sizes differ -- ours packs {} bytes ({} samples at \
5576 {} bit/sample), aomdec wrote {}",
5577 ours.len(),
5578 decoded
5579 .iter()
5580 .map(|f| f.y.len() + f.u.len() + f.v.len())
5581 .sum::<usize>(),
5582 bit_depth,
5583 ref_raw.len()
5584 );
5585 assert_eq!(decoded.len(), frames, "{name}: frame count");
5586 let first = ours
5587 .iter()
5588 .zip(&ref_raw)
5589 .position(|(a, b)| a != b)
5590 .unwrap_or(ours.len());
5591 assert_eq!(
5592 first,
5593 ours.len(),
5594 "{name}: {} bytes of decoded output differ from aomdec (first at {})",
5595 ours.iter().zip(&ref_raw).filter(|(a, b)| a != b).count(),
5596 first
5597 );
5598 }
5599
5600 /// lane-av1rawhelper: `assert_rawvideo_matches` used to pack our samples
5601 /// as `u16` for EVERY stream, while `aomdec --rawvideo` writes 8 bits
5602 /// per sample for an 8-bit stream. An 8-bit caller therefore died on a
5603 /// raw-SIZE assertion (2359296 vs 1179648) without comparing a single
5604 /// sample, and a high-bitdepth caller was the only one that could work.
5605 ///
5606 /// Two arms, both on a real `aomenc` 8-bit stream:
5607 ///
5608 /// 1. the correct label compares real samples -- the byte counts it
5609 /// walks equal the oracle's, so every `u8` in the 8-bit pack is
5610 /// zipped against a real oracle byte;
5611 /// 2. a WRONG label fails by name, quoting both depths and the fact that
5612 /// the pack would compare nothing, rather than by size. Arm 2 is what
5613 /// keeps arm 1 from being a green that a reverted check would also
5614 /// give.
5615 #[test]
5616 fn the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth() {
5617 const NAME: &str = "the_rawvideo_helper_compares_real_samples_at_the_streams_own_bit_depth";
5618 let _gate_lock = lock_gate_counters();
5619 if !have_aomenc() || !have_ffmpeg() {
5620 eprintln!("SKIP {NAME}: no aomenc/aomdec oracle or no ffmpeg");
5621 return;
5622 }
5623 let (w, h) = (192usize, 128usize);
5624 let y4m = Command::new("ffmpeg")
5625 .args([
5626 "-v",
5627 "error",
5628 "-f",
5629 "lavfi",
5630 "-i",
5631 &gradients_source(7, w, h, "duration=0.24:rate=25"),
5632 "-pix_fmt",
5633 "yuv420p",
5634 "-t",
5635 "0.24",
5636 "-f",
5637 "yuv4mpegpipe",
5638 "-",
5639 ])
5640 .stdin(Stdio::null())
5641 .stdout(Stdio::piped())
5642 .stderr(Stdio::piped())
5643 .output()
5644 .expect("ffmpeg failed to run");
5645 assert!(
5646 y4m.status.success(),
5647 "{NAME}: ffmpeg fixture: {}",
5648 String::from_utf8_lossy(&y4m.stderr)
5649 );
5650 let args: Vec<&str> = vec![
5651 "--codec=av1",
5652 "--passes=1",
5653 "--end-usage=q",
5654 "--cq-level=40",
5655 "--cpu-used=2",
5656 "--threads=1",
5657 "--row-mt=0",
5658 "--limit=6",
5659 "--obu",
5660 "-o",
5661 "-",
5662 "-",
5663 ];
5664 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
5665 assert!(
5666 out.status.success(),
5667 "{NAME}: aomenc refused the fixture: {}",
5668 String::from_utf8_lossy(&out.stderr)
5669 );
5670 let stream = out.stdout;
5671 assert_eq!(
5672 stream_bit_depth(&stream, NAME),
5673 8,
5674 "{NAME}: the fixture must really be 8-bit, or this gate measures nothing"
5675 );
5676 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-raw8-{}", std::process::id()));
5677 let _ = std::fs::remove_dir_all(&dir);
5678 std::fs::create_dir_all(&dir).expect("scratch dir");
5679 let obu = dir.join("in.obu");
5680 std::fs::write(&obu, &stream).expect("writing the stream");
5681 let frames = decode_stream(&stream)
5682 .unwrap_or_else(|e| panic!("{NAME}: the 8-bit stream no longer decodes: {e}"))
5683 .len();
5684 assert!(frames > 0, "{NAME}: nothing decoded");
5685
5686 // ARM 2 first: the wrong label must be refused BY NAME. A helper that
5687 // packed u16 unconditionally got this far and then failed on size.
5688 let wrong = std::panic::catch_unwind(|| {
5689 assert_rawvideo_matches(&obu, &stream, NAME, frames, 10);
5690 });
5691 let boom = wrong
5692 .err()
5693 .map(|e| e.downcast_ref::<String>().cloned().unwrap_or_default())
5694 .unwrap_or_default();
5695 assert!(
5696 boom.contains("sequence header says 8-bit") && boom.contains("compares nothing"),
5697 "{NAME}: a 10-bit label on an 8-bit stream must be refused by the depth check \
5698 naming both depths; the panic read: {boom}"
5699 );
5700
5701 // ARM 1: the correct label compares real samples. The pre-fix helper
5702 // reached a size mismatch here (ours 2x the oracle); reaching the
5703 // sample compare is what this arm proves.
5704 assert_rawvideo_matches(&obu, &stream, NAME, frames, 8);
5705 let _ = std::fs::remove_dir_all(&dir);
5706 eprintln!("{NAME}: {frames} 8-bit frame(s) byte-identical to aomdec --rawvideo");
5707 }
5708
5709 fn fnv1a64(bytes: &[u8]) -> u64 {
5710 let mut hash = 0xcbf29ce484222325u64;
5711 for &b in bytes {
5712 hash ^= b as u64;
5713 hash = hash.wrapping_mul(0x100000001b3);
5714 }
5715 hash
5716 }
5717
5718 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
5719 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
5720 /// aomenc gate decodes its stream through ffmpeg and is meaningless
5721 /// without it -- turns it into a hard failure. Without this the require
5722 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
5723 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
5724 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
5725 fn have_ffmpeg() -> bool {
5726 let present = Command::new("ffmpeg")
5727 .arg("-version")
5728 .stdout(Stdio::null())
5729 .stderr(Stdio::null())
5730 .status()
5731 .is_ok_and(|s| s.success());
5732 assert!(
5733 present
5734 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
5735 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
5736 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
5737 );
5738 present
5739 }
5740
5741 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
5742 /// The frame-count diagnostic shared by the three `ffmpeg_decode_sequence*`
5743 /// helpers (lane-av1pins5 r6).
5744 ///
5745 /// Before this, a caller that passed its OWN decode's length as the expected
5746 /// count got `expected N 4:2:0 frames, ffmpeg said: ` -- with an EMPTY tail,
5747 /// because ffmpeg ran at `-v error` and succeeded. The message named ffmpeg,
5748 /// said nothing about where `N` came from, and sent the next reader hunting
5749 /// ffmpeg for a count ffmpeg never chose.
5750 ///
5751 /// The class is MISATTRIBUTED RED, not silent pass: the helper's
5752 /// `out.stdout.len() == frame_bytes * frames` assert fires unconditionally, so
5753 /// a wrong count cannot pass -- it just fails while blaming the wrong
5754 /// component. (Measured: `ffmpeg_decode_sequence(&s, 192, 128, 0)` panics
5755 /// here, not silently.) Naming the real cause is the whole fix; no caller has
5756 /// to change to benefit.
5757 fn frame_count_diagnosis(
5758 format: &str,
5759 frames: usize,
5760 width: usize,
5761 height: usize,
5762 frame_bytes: usize,
5763 got: usize,
5764 stderr: &[u8],
5765 ) -> String {
5766 let actual = if frame_bytes == 0 {
5767 0
5768 } else {
5769 got / frame_bytes
5770 };
5771 let leftover = if frame_bytes == 0 {
5772 got
5773 } else {
5774 got % frame_bytes
5775 };
5776 format!(
5777 "FRAME COUNT MISMATCH ({format} {width}x{height}): the caller passed \
5778 `frames={frames}`, ffmpeg produced {actual} frame(s) ({got} bytes, \
5779 {leftover} byte(s) not a whole frame, at {frame_bytes} B/frame).\n\
5780 `frames` is the EXPECTED count the CALLER asserted -- it is NOT measured \
5781 from ffmpeg, so it never had ffmpeg's agreement. If it came from our own \
5782 decode_stream(), this is OUR decoder disagreeing with ffmpeg about how many \
5783 frames the stream holds, and the fix is on OUR side, not ffmpeg's. ffmpeg \
5784 itself exited cleanly{}.",
5785 if stderr.is_empty() {
5786 " with no diagnostics (`-v error`)"
5787 } else {
5788 ""
5789 }
5790 )
5791 }
5792
5793 fn ffmpeg_decode_sequence(
5794 stream: &[u8],
5795 width: usize,
5796 height: usize,
5797 frames: usize,
5798 ) -> Vec<Pic> {
5799 let out = run_with_stdin(
5800 Command::new(ffmpeg_path()).args([
5801 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
5802 ]),
5803 stream,
5804 );
5805 assert!(
5806 out.status.success(),
5807 "ffmpeg refused the stream: {}",
5808 String::from_utf8_lossy(&out.stderr)
5809 );
5810 let (luma, chroma) = (width * height, width * height / 4);
5811 let frame_bytes = luma + 2 * chroma;
5812 assert_eq!(
5813 out.stdout.len(),
5814 frame_bytes * frames,
5815 "{}",
5816 frame_count_diagnosis(
5817 "4:2:0",
5818 frames,
5819 width,
5820 height,
5821 frame_bytes,
5822 out.stdout.len(),
5823 &out.stderr
5824 )
5825 );
5826 (0..frames)
5827 .map(|i| {
5828 let base = i * frame_bytes;
5829 Pic {
5830 width,
5831 height,
5832 y: out.stdout[base..base + luma]
5833 .iter()
5834 .map(|&v| u16::from(v))
5835 .collect(),
5836 u: out.stdout[base + luma..base + luma + chroma]
5837 .iter()
5838 .map(|&v| u16::from(v))
5839 .collect(),
5840 v: out.stdout[base + luma + chroma..base + frame_bytes]
5841 .iter()
5842 .map(|&v| u16::from(v))
5843 .collect(),
5844 }
5845 })
5846 .collect()
5847 }
5848
5849 /// As [`ffmpeg_decode_sequence`], for a MONOCHROME stream: one 8-bit luma
5850 /// plane per frame, exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes
5851 /// (lane-av1mono). Fed through [`run_with_stdin`] for the reason its doc
5852 /// records.
5853 fn ffmpeg_decode_gray_sequence(
5854 stream: &[u8],
5855 width: usize,
5856 height: usize,
5857 frames: usize,
5858 ) -> Vec<u8> {
5859 let out = run_with_stdin(
5860 Command::new(ffmpeg_path()).args([
5861 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "gray", "-",
5862 ]),
5863 stream,
5864 );
5865 assert!(
5866 out.status.success(),
5867 "ffmpeg refused the monochrome stream: {}",
5868 String::from_utf8_lossy(&out.stderr)
5869 );
5870 assert_eq!(
5871 out.stdout.len(),
5872 width * height * frames,
5873 "expected {frames} monochrome frames, ffmpeg said: {}",
5874 String::from_utf8_lossy(&out.stderr)
5875 );
5876 out.stdout
5877 }
5878
5879 /// As [`ffmpeg_decode_sequence`], but for a `yuv420p10le` stream: samples
5880 /// are 2-byte little-endian, one full 16-bit range regardless of the
5881 /// stream's real 10-bit depth (ffmpeg's rawvideo muxer never packs to the
5882 /// bit depth). The 8-bit helper above stays untouched -- every existing
5883 /// gate depends on it.
5884 fn ffmpeg_decode_sequence_10bit(
5885 stream: &[u8],
5886 width: usize,
5887 height: usize,
5888 frames: usize,
5889 ) -> Vec<Pic> {
5890 let out = run_with_stdin(
5891 Command::new(ffmpeg_path()).args([
5892 "-v",
5893 "error",
5894 "-f",
5895 "obu",
5896 "-i",
5897 "-",
5898 "-f",
5899 "rawvideo",
5900 "-pix_fmt",
5901 "yuv420p10le",
5902 "-",
5903 ]),
5904 stream,
5905 );
5906 assert!(
5907 out.status.success(),
5908 "ffmpeg refused the stream: {}",
5909 String::from_utf8_lossy(&out.stderr)
5910 );
5911 let (luma, chroma) = (width * height, width * height / 4);
5912 let frame_samples = luma + 2 * chroma;
5913 let frame_bytes = frame_samples * 2;
5914 assert_eq!(
5915 out.stdout.len(),
5916 frame_bytes * frames,
5917 "{}",
5918 frame_count_diagnosis(
5919 "4:2:0 10-bit",
5920 frames,
5921 width,
5922 height,
5923 frame_bytes,
5924 out.stdout.len(),
5925 &out.stderr
5926 )
5927 );
5928 fn le16(bytes: &[u8]) -> Vec<u16> {
5929 bytes
5930 .chunks_exact(2)
5931 .map(|c| u16::from_le_bytes([c[0], c[1]]))
5932 .collect()
5933 }
5934 (0..frames)
5935 .map(|i| {
5936 let base = i * frame_bytes;
5937 Pic {
5938 width,
5939 height,
5940 y: le16(&out.stdout[base..base + luma * 2]),
5941 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
5942 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
5943 }
5944 })
5945 .collect()
5946 }
5947
5948 /// lane-svtinter: an SVT-AV1 screen stream whose frame height is not a
5949 /// multiple of the superblock size codes PALETTE blocks in the bottom
5950 /// (and right) superblock row that hang off the mi grid. Spec 5.11.50
5951 /// `palette_tokens` reads the colour-index map only over the block's
5952 /// `onscreenWidth x onscreenHeight` corner and replicates it outward;
5953 /// this decoder read the full block grid, so it consumed colour-index
5954 /// symbols libaom never wrote and desynced the rest of the tile -- either
5955 /// a wrong bottom superblock row (1599 luma samples in this stream's
5956 /// frame 0, ~80k per inter frame after) or, further along the same tile,
5957 /// a bogus "a Golomb tail longer than this decoder reads" refusal.
5958 ///
5959 /// Unlike its lane-svt1 sibling above this one BUILDS its stream: the
5960 /// recipe is synthetic (`smptebars,drawgrid` through `libsvtav1 -preset 8
5961 /// -svtav1-params screen-content-mode=1`), and 384x152 puts a 32x32
5962 /// palette block at mi row 32 of a 38-mi-tall frame, 24 of its 32 rows
5963 /// on screen. `palette_onscreen_cut_hits` is asserted non-zero so the row
5964 /// cannot pass on a stream that never cuts a palette map (class
5965 /// gate-blind-to-feature).
5966 #[test]
5967 fn an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly() {
5968 const NAME: &str = "an_svt_screen_palette_map_cut_by_the_frame_edge_decodes_exactly";
5969 if !have_ffmpeg() {
5970 eprintln!("SKIP {NAME}: no ffmpeg");
5971 return;
5972 }
5973 let (width, height) = (384usize, 152usize);
5974 let out = Command::new("ffmpeg")
5975 .args([
5976 "-v",
5977 "error",
5978 "-f",
5979 "lavfi",
5980 "-i",
5981 "smptebars=s=384x152:r=12,drawgrid=w=8:h=8:t=1:c=black",
5982 "-frames:v",
5983 "4",
5984 "-c:v",
5985 "libsvtav1",
5986 "-preset",
5987 "8",
5988 "-crf",
5989 "30",
5990 "-svtav1-params",
5991 "lp=1:screen-content-mode=1",
5992 "-g",
5993 "12",
5994 "-f",
5995 "obu",
5996 "-",
5997 ])
5998 .stdin(Stdio::null())
5999 .stdout(Stdio::piped())
6000 .stderr(Stdio::piped())
6001 .output()
6002 .expect("ffmpeg failed to run");
6003 if !out.status.success() || out.stdout.is_empty() {
6004 eprintln!(
6005 "SKIP {NAME}: no libsvtav1 in this ffmpeg: {}",
6006 String::from_utf8_lossy(&out.stderr)
6007 );
6008 return;
6009 }
6010 let stream = out.stdout;
6011 crate::decode::reset_palette_onscreen_cut_hits();
6012 let decoded = decode_stream(&stream).expect("the SVT-AV1 screen stream decodes");
6013 assert_eq!(decoded.len(), 4, "{NAME}: frame count");
6014 assert!(
6015 crate::decode::palette_onscreen_cut_hits() > 0,
6016 "{NAME}: no palette map is cut by the frame edge here -- the gate would pass blind"
6017 );
6018 let want = ffmpeg_decode_sequence(&stream, width, height, decoded.len());
6019 assert_eq!(want.len(), decoded.len(), "{NAME}: ffmpeg frame count");
6020 for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
6021 assert_eq!(got.y, want.y, "{NAME}: frame {i} luma vs ffmpeg");
6022 assert_eq!(got.u, want.u, "{NAME}: frame {i} U vs ffmpeg");
6023 assert_eq!(got.v, want.v, "{NAME}: frame {i} V vs ffmpeg");
6024 }
6025 }
6026
6027 /// lane-svt1: an SVT-AV1 (v3.1.2, `-preset 8`) screen key frame codes 16x16
6028 /// PALETTE blocks with `skip == 1` whose `tx_depth` split the luma
6029 /// transform. [`crate::decode::decode_block`] armed the palette prediction
6030 /// only when the transform covered the whole block, so that one block
6031 /// predicted DC off its own edges instead: the right symbols (the whole mode
6032 /// ladder diffs clean against an instrumented aomdec) and the wrong pixels
6033 /// -- 812 luma samples in frame 0, carried by the V_PRED blocks under it to
6034 /// 10122 samples over the 12-frame stream the defect was found on.
6035 ///
6036 /// lane-av1pinspec2: the gate used to RIDE an external crop named by
6037 /// `EC_AV1_SVT1_STREAM` and SKIP when that was unset, so it never ran on a
6038 /// stock box -- which is exactly why its oracle count could not be pinned
6039 /// (an assert on a gate that never executes is an unexercised assert wearing
6040 /// a pin's clothes). It now runs on the COMMITTED pin
6041 /// `crates/ec-av1/fixtures/svt1-split-tx-pin.obu`.
6042 ///
6043 /// The pin is a REPLAY, not a fresh capture, and the recipe is recorded
6044 /// because it reproduces the bytes exactly (two independent encodes on this
6045 /// box, SVT-AV1 v3.1.2, both sha256
6046 /// `c9d9c0ae934fba72fc9a9374bc36853f290796a8a4d6442140e239669e0b341f`,
6047 /// 1838 bytes):
6048 ///
6049 /// ffmpeg -v error -f lavfi \
6050 /// -i "smptehdbars=s=192x152:r=12,drawgrid=w=8:h=8:t=1:c=black" \
6051 /// -frames:v 1 -c:v libsvtav1 -preset 8 -crf 50 \
6052 /// -svtav1-params "lp=1:screen-content-mode=1" -g 12 -f obu out.obu
6053 ///
6054 /// `-frames:v 1` is the part lane-svt1's search lacked: its 6x5x6 sweep ran
6055 /// FOUR frames per stream, and the ~200k-sample misses that killed every
6056 /// candidate were on the INTER frames (`lanes/svt1.report.md`). One key
6057 /// frame has no inter frames, and this one reaches the fixed arm
6058 /// (`skip_split_tx_override_hits == 1`) and is pixel-exact.
6059 ///
6060 /// THE COUNT, and why it is derived from the wire rather than from a
6061 /// literal. The oracle is handed the number of frame OBUs this stream
6062 /// actually codes, counted with `Av1Parser` below -- never our decode's
6063 /// length, which is the thing under test. A header count would OVER-count
6064 /// a stream carrying `show_existing_frame` (spec 5.9.5: it codes no pixels,
6065 /// so the header count is larger than the shown-frame count), so that case
6066 /// is asserted impossible on this pin rather than assumed: the loop refuses
6067 /// any frame header with `show_existing_frame` set, which is what makes
6068 /// "one header == one shown frame" a checked fact here instead of an
6069 /// argument.
6070 ///
6071 /// `EC_AV1_SVT1_STREAM` still overrides the pin, so a re-capture is one env
6072 /// var away; `crate_pin` falls back to `pin_dir()` for the same reason.
6073 ///
6074 /// `skip_split_tx_override_hits` is asserted non-zero so the row cannot
6075 /// pass on a stream that never reaches the fixed arm (class
6076 /// gate-blind-to-feature).
6077 #[test]
6078 fn an_svt_screen_palette_block_with_a_split_transform_decodes_exactly() {
6079 const NAME: &str = "an_svt_screen_palette_block_with_a_split_transform_decodes_exactly";
6080 const PIN: &str = "svt1-split-tx-pin.obu";
6081 if !have_ffmpeg() {
6082 eprintln!("SKIP {NAME}: no ffmpeg");
6083 return;
6084 }
6085 let path = match std::env::var("EC_AV1_SVT1_STREAM") {
6086 Ok(p) => std::path::PathBuf::from(p),
6087 // The name is spelled as a LITERAL here even though `PIN` is right
6088 // above, on purpose: `gate_coverage::pin_inventory` matches a pin
6089 // read by the quote that follows the callee name, so a const
6090 // argument would leave this pin outside the "every pin a gate reads
6091 // is a committed crate-local copy" invariant. The dup is the
6092 // coverage -- and it is also why this comment must NOT quote that
6093 // spelling: the scanner reads prose too, and a quoted spelling here
6094 // parses as a pin called " and would not see a const argument, ...".
6095 Err(_) => crate_pin("svt1-split-tx-pin.obu"),
6096 };
6097 let data = require_pin(&path, PIN);
6098 // The ENCODE's frame count, read off the WIRE: parse this stream's own
6099 // OBUs and count the frame headers. `show_existing_frame` is refused
6100 // here on purpose -- such a header codes no pixels, so counting it
6101 // would make this count larger than the frames the oracle can decode.
6102 let mut parser = Av1Parser::new();
6103 let mut pos = 0usize;
6104 let mut frame_headers = 0usize;
6105 while pos < data.len() {
6106 let Ok(obu) = parser.parse_obu(&data[pos..]) else {
6107 break;
6108 };
6109 pos += obu.total_size.max(1);
6110 let header = match &obu.kind {
6111 ObuKind::Frame(h, _) | ObuKind::FrameHeader(h) => h,
6112 _ => continue,
6113 };
6114 assert!(
6115 !header.show_existing_frame,
6116 "{NAME}: frame header {frame_headers} sets show_existing_frame, so the header \
6117 count is not the shown-frame count and this gate's oracle budget would be wrong"
6118 );
6119 frame_headers += 1;
6120 }
6121 assert!(
6122 frame_headers > 0,
6123 "{NAME}: {} carries no frame header at all",
6124 path.display()
6125 );
6126 crate::decode::reset_skip_split_tx_override_hits();
6127 let decoded = decode_stream(&data).expect("the pinned SVT-AV1 screen stream decodes");
6128 assert!(
6129 crate::decode::skip_split_tx_override_hits() > 0,
6130 "{NAME}: no skipped split-transform palette block in {} -- the gate would pass blind",
6131 path.display()
6132 );
6133 assert_eq!(
6134 decoded.len(),
6135 frame_headers,
6136 "{NAME}: the stream codes {frame_headers} frame(s), the decode showed {}",
6137 decoded.len()
6138 );
6139 let (width, height) = (decoded[0].width, decoded[0].height);
6140 let want = ffmpeg_decode_sequence(&data, width, height, frame_headers);
6141 for (i, (got, want)) in decoded.iter().zip(&want).enumerate() {
6142 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");
6143 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");
6144 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");
6145 }
6146 }
6147
6148 /// `decode_stream` agrees with ffmpeg/dav1d on the same wire bytes -- an
6149 /// independent decoder, not just this crate checking its own tile path.
6150 #[test]
6151 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
6152 let fctx = &crate::decode::FrameCtx::for_encoder();
6153 if !have_ffmpeg() {
6154 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
6155 return;
6156 }
6157 // lane-av1straddle: 216x96 joins 128x64 because only a size whose
6158 // 32x32 blocks straddle the right-hand frame edge can see the writer
6159 // coding a transform unit that starts outside the frame -- libdav1d
6160 // AND libaom both refused the whole key frame while it did, and this
6161 // crate's own (lenient) decoder only differed in the last block's V.
6162 for &(width, height) in &[(128usize, 64usize), (216usize, 96usize)] {
6163 let pictures: Vec<_> = (0..3)
6164 .map(|i| panned_test_card(width, height, i * 3))
6165 .collect();
6166 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
6167 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
6168 let decoded = decode_stream(&encoded.stream).unwrap();
6169 assert_eq!(decoded.len(), 3);
6170 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
6171 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
6172 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
6173 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
6174 }
6175 // ... and the encoder's own reconstruction is what ffmpeg sees,
6176 // so the check fails on a writer-side desync too, not only on a
6177 // decoder-side one.
6178 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
6179 let rec = &frame.reconstruction;
6180 assert_eq!(
6181 rec.y, want.y,
6182 "{width}x{height} frame {i} luma: reconstruction vs ffmpeg"
6183 );
6184 assert_eq!(
6185 rec.u, want.u,
6186 "{width}x{height} frame {i} U: reconstruction vs ffmpeg"
6187 );
6188 assert_eq!(
6189 rec.v, want.v,
6190 "{width}x{height} frame {i} V: reconstruction vs ffmpeg"
6191 );
6192 }
6193 }
6194 }
6195
6196 /// lane-av1rect: the encoder used to REFUSE every size where a 32x32
6197 /// block straddles BOTH true frame edges at once ("straddles the true
6198 /// frame edge in a way that needs a rectangular (HORZ/VERT) transform
6199 /// this encoder does not code yet"). That refusal was a misreading of
6200 /// spec 5.11.4: a block whose `hasRows` and `hasCols` are BOTH false
6201 /// reads no partition symbol at all and is `PARTITION_SPLIT` by
6202 /// inference, down to the 8x8 leaves whose own mi origin is inside the
6203 /// frame -- exactly the leaves this writer already codes for the
6204 /// one-axis case, and no rectangular transform anywhere. The sweep walks
6205 /// the corners around the 32-multiples (each width has a 16x16 column
6206 /// whose right half is outside, each height a row whose bottom half is,
6207 /// so the bottom-right 16x16 of every size here is cut on both axes) and
6208 /// three-way compares: our decoder, the encoder's own reconstruction and
6209 /// ffmpeg, over a 4-frame GOP so the inter writer's copy of the same
6210 /// signaling is covered too. `edge_both_cut_hits` proves the decoder
6211 /// really took the inferred-split path rather than the gate passing on
6212 /// geometry that never fires it.
6213 #[test]
6214 fn a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg() {
6215 let fctx = &crate::decode::FrameCtx::for_encoder();
6216 if !have_ffmpeg() {
6217 eprintln!(
6218 "SKIP a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg: no ffmpeg"
6219 );
6220 return;
6221 }
6222 const FRAMES: usize = 4;
6223 let mut both_cut = 0usize;
6224 for &width in &[200usize, 216, 232, 248] {
6225 for &height in &[104usize, 120, 136, 152] {
6226 let pictures: Vec<_> = (0..FRAMES as i64)
6227 .map(|i| panned_test_card(width, height, i * 3))
6228 .collect();
6229 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
6230 .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
6231 // Reset per attempt, never a delta across sizes (class
6232 // counter-from-refused-stream).
6233 crate::decode::reset_edge_both_cut_hits();
6234 let decoded = decode_stream(&encoded.stream)
6235 .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
6236 both_cut += crate::decode::edge_both_cut_hits().iter().sum::<usize>();
6237 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
6238 assert_eq!(
6239 ffmpeg_frames.len(),
6240 FRAMES,
6241 "{width}x{height}: ffmpeg decoded {} of {FRAMES} frames",
6242 ffmpeg_frames.len()
6243 );
6244 assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
6245 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
6246 assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
6247 assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
6248 assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
6249 }
6250 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
6251 let rec = &frame.reconstruction;
6252 assert_eq!(
6253 rec.y, want.y,
6254 "{width}x{height} frame {i} luma: recon vs ffmpeg"
6255 );
6256 assert_eq!(
6257 rec.u, want.u,
6258 "{width}x{height} frame {i} U: recon vs ffmpeg"
6259 );
6260 assert_eq!(
6261 rec.v, want.v,
6262 "{width}x{height} frame {i} V: recon vs ffmpeg"
6263 );
6264 }
6265 }
6266 }
6267 assert!(
6268 both_cut > 0,
6269 "no partition node in the whole sweep was coded as the both-axes-cut \
6270 inferred split -- the gate is blind to the feature it pins"
6271 );
6272 }
6273
6274 /// lane-corner: sizes whose LAST superblock is cut by the true frame
6275 /// edge on BOTH axes with more than half of each still inside -- so
6276 /// `has_cols` and `has_rows` are both true and the spec lets that
6277 /// superblock stay a whole 64x64 `PARTITION_NONE` block, which this
6278 /// encoder's roots take (`EC_AV1_B64EDGE` on the inter side, the key
6279 /// frame's own `Superblock::Whole`). The sibling luma-only test
6280 /// (`encoder.rs`'s `a_non_superblock_aligned_clip_...`) is blind to
6281 /// chroma (class `metric-blind-to-a-plane`), so this one compares all
6282 /// three planes three ways: our decoder, the encoder's own
6283 /// reconstruction, and ffmpeg.
6284 #[test]
6285 fn a_doubly_cut_superblock_root_round_trips_in_every_plane() {
6286 let fctx = &crate::decode::FrameCtx::for_encoder();
6287 if !have_ffmpeg() {
6288 eprintln!("SKIP a_doubly_cut_superblock_root_round_trips_in_every_plane: no ffmpeg");
6289 return;
6290 }
6291 const FRAMES: usize = 4;
6292 // Each size leaves MORE than half of its last superblock row (and,
6293 // but for 200x120's 8-px column, of its last column) inside, which is
6294 // what makes the root legal there at all; 248x168/232x168/248x184 are
6295 // cut on BOTH axes at once. 1920x1080 -- the user's own export shape
6296 // -- is the same case: 1080 = 16*64 + 56, a 56-px bottom straddle.
6297 for &(width, height) in &[(248usize, 168usize), (232, 168), (200, 120), (248, 184)] {
6298 let pictures: Vec<_> = (0..FRAMES as i64)
6299 .map(|i| panned_test_card(width, height, i * 3))
6300 .collect();
6301 let _ = crate::encode::take_b64_edge_hits();
6302 let _ = crate::encode::take_i64_root_hits();
6303 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
6304 .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}"));
6305 let edges = crate::encode::take_b64_edge_hits();
6306 let [i64_whole, i64_offered, i64_edge] = crate::encode::take_i64_root_hits();
6307 eprintln!(
6308 "{width}x{height}: edge inter 64 roots {edges}, key 64 roots {i64_whole} of \
6309 {i64_offered} offered, {i64_edge} of them cut by the frame edge"
6310 );
6311 // gate-blind-to-feature: without this the three-way compare below
6312 // passes on a stream that never coded a whole root at the cut
6313 // superblock at all.
6314 assert!(
6315 i64_edge > 0,
6316 "{width}x{height}: no 64x64 root sat on a superblock the frame edge cuts"
6317 );
6318 let decoded = decode_stream(&encoded.stream)
6319 .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}"));
6320 let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES);
6321 assert_eq!(
6322 ffmpeg_frames.len(),
6323 FRAMES,
6324 "{width}x{height}: ffmpeg frame count"
6325 );
6326 assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count");
6327 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
6328 assert_eq!(
6329 got.y, want.y,
6330 "{width}x{height} frame {i} luma: ours vs ffmpeg"
6331 );
6332 assert_eq!(
6333 got.u, want.u,
6334 "{width}x{height} frame {i} U: ours vs ffmpeg"
6335 );
6336 assert_eq!(
6337 got.v, want.v,
6338 "{width}x{height} frame {i} V: ours vs ffmpeg"
6339 );
6340 }
6341 for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
6342 let rec = &frame.reconstruction;
6343 assert_eq!(
6344 rec.y, want.y,
6345 "{width}x{height} frame {i} luma: recon vs ffmpeg"
6346 );
6347 assert_eq!(
6348 rec.u, want.u,
6349 "{width}x{height} frame {i} U: recon vs ffmpeg"
6350 );
6351 assert_eq!(
6352 rec.v, want.v,
6353 "{width}x{height} frame {i} V: recon vs ffmpeg"
6354 );
6355 }
6356 }
6357 }
6358
6359 /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME`
6360 /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s
6361 /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc
6362 /// attempts never could: frame 0 is a real key frame (this crate's own
6363 /// encoder, real texture), refreshing all 8 DPB slots as spec requires --
6364 /// slot 3 keeps that exact picture from here on. Frame 1 is a hand-coded
6365 /// inter frame whose lone 32x32 block is *intra* (`DC_PRED`, `skip`),
6366 /// refreshing only slot 0 with a flat 128 block -- distinguishable from
6367 /// frame 0's real texture, so slot 0 (`LAST_FRAME`) and slot 3
6368 /// (`GOLDEN_FRAME`) hold visibly different pictures once frame 2 runs.
6369 /// Frame 2 is a hand-coded inter frame naming `ref_frame_idx[3] = 3`
6370 /// (GOLDEN_FRAME's slot) and `ref_frame_idx[0] = 0` (LAST_FRAME's), whose
6371 /// lone block codes `single_ref` all the way out to `GOLDEN_FRAME`
6372 /// (`p1=0, p3=1, p5=1`) and a `skip` zero-MV `NEARESTMV`: a direct copy
6373 /// of GOLDEN's picture, so its output must equal frame 0's own
6374 /// reconstruction exactly, and must differ from frame 1's -- proof the
6375 /// decoder actually read the golden plane, not silently substituted
6376 /// `LAST_FRAME`'s. Rounds 4-9 masked and re-masked this arm chasing a
6377 /// deblock/MC residue that turned out to be film-grain synthesis
6378 /// (lane-av1golden7's `apply_grain` refusal, unrelated to GOLDEN);
6379 /// lane-av1golden8 fixed mvstack's single-ref extension pass, clearing
6380 /// the last real defect (`pinned_golden7` non_last_ref_hits 0->2), so
6381 /// this fixture flips back to its round-4 pixel-exact form. ffmpeg
6382 /// decodes the identical wire bytes as the foreign oracle
6383 /// (shared-oracle-blindness class): this crate's own decoder agreeing
6384 /// with itself would prove nothing.
6385 #[test]
6386 fn a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg() {
6387 let fctx = &crate::decode::FrameCtx::new();
6388 if !have_ffmpeg() {
6389 eprintln!(
6390 "SKIP a_hand_built_golden_reference_decodes_pixel_exact_against_ffmpeg: no ffmpeg"
6391 );
6392 return;
6393 }
6394 use crate::cdf_state::Cdfs;
6395 use crate::decode::{intra_inter_ctx, non_last_ref_hits, q_ctx_of};
6396 use crate::encode::{inter_frame_headers, key_frame_headers};
6397 use crate::frame::frame_obu;
6398 use crate::msac::SymbolEncoder;
6399 use crate::mvstack::{
6400 GOLDEN_FRAME, MiGrid, find_mv_stack, single_ref_p1_ctx, single_ref_p3_ctx,
6401 single_ref_p5_ctx,
6402 };
6403 use crate::obu::temporal_delimiter;
6404
6405 let (width, height) = (32usize, 32usize);
6406 let base_q_idx = 100u8;
6407 // The whole picture is one 32x32 block: `partition_ctx`/`skip_ctx`/
6408 // `intra_inter_ctx`'s neighbour inputs are all "no neighbour yet" --
6409 // a fresh `Neighbours`' `above_side_mi`/`left_side_mi` start at `SB`
6410 // (64), so `partition_ctx_mi`'s `side_mi * 2 <= side` (32) is false
6411 // on both axes (ctx 0), and `above_skip`/`left_skip`/`above_inter`/
6412 // `left_inter`/`above_ref`/`left_ref` all start `false`/`-1`
6413 // (decode.rs `Neighbours::new`) -- computed here without
6414 // constructing the (module-private) `Neighbours` itself.
6415 const PARTITION_NONE: usize = 0;
6416 let ii_ctx = intra_inter_ctx(false, false, false, false);
6417 let sr_p1_ctx = single_ref_p1_ctx(None, None, None, None);
6418 let sr_p3_ctx = single_ref_p3_ctx(None, None, None, None);
6419 let sr_p5_ctx = single_ref_p5_ctx(None, None, None, None);
6420
6421 for run in 0..4 {
6422 let picture = test_card(width, height);
6423 let key = encode_key_frame_with_ctx(&picture, base_q_idx, 0.5, fctx).unwrap();
6424 let (seq, _) = key_frame_headers(width, height, base_q_idx).unwrap();
6425
6426 // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat
6427 // 128 block (no neighbours to predict `DC_PRED` from).
6428 let (_, mut header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap();
6429 // These two tiles are hand-coded from a FRESH `Cdfs`, so the
6430 // frames must not carry CDF state the way the encoder's own inter
6431 // frames now do (spec 7.20): with the bit set, what each frame
6432 // stores is what it started from -- the defaults -- which is
6433 // exactly what the next hand-coded tile assumes.
6434 header1.disable_frame_end_update_cdf = true;
6435 let tile1 = {
6436 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
6437 let mut enc = SymbolEncoder::new();
6438 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
6439 enc.symbol(1, &mut cdfs.skip[0]); // skip
6440 enc.symbol(0, &mut cdfs.intra_inter[ii_ctx]); // is_inter = false
6441 enc.symbol(0, &mut cdfs.y_mode[3]); // DC_PRED, size group 3 (32x32)
6442 enc.symbol(0, &mut cdfs.uv_mode_cfl[0]); // DC_PRED
6443 enc.finish()
6444 };
6445 let mut stream = key.stream.clone();
6446 stream.extend(temporal_delimiter());
6447 stream.extend(frame_obu(&seq, &header1, &tile1).unwrap());
6448
6449 // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME,
6450 // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0).
6451 let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap();
6452 header2.disable_frame_end_update_cdf = true;
6453 header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1
6454 let tile2 = {
6455 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
6456 let mut enc = SymbolEncoder::new();
6457 let grid = MiGrid::new(8, 8);
6458 let stack = find_mv_stack(&grid, 0, 0, 8, 8, GOLDEN_FRAME, 8, 8);
6459 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w32[0]);
6460 enc.symbol(1, &mut cdfs.skip[0]); // skip
6461 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter = true
6462 enc.symbol(0, &mut cdfs.single_ref[sr_p1_ctx][0]); // p1: LAST/LAST2/LAST3/GOLDEN group
6463 enc.symbol(1, &mut cdfs.single_ref[sr_p3_ctx][2]); // p3: GOLDEN/LAST3 sub-group
6464 enc.symbol(1, &mut cdfs.single_ref[sr_p5_ctx][4]); // p5: GOLDEN_FRAME
6465 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new -> not NEWMV
6466 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero -> not GLOBALMV
6467 enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // nearest -> NEARESTMV, (0, 0)
6468 enc.finish()
6469 };
6470 stream.extend(temporal_delimiter());
6471 stream.extend(frame_obu(&seq, &header2, &tile2).unwrap());
6472
6473 let before = non_last_ref_hits();
6474 let decoded = decode_stream(&stream).unwrap();
6475 assert_eq!(decoded.len(), 3, "run {run}: expected 3 pictures");
6476 assert!(
6477 non_last_ref_hits() > before,
6478 "run {run}: GOLDEN_FRAME never fired"
6479 );
6480
6481 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 3);
6482 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
6483 assert_eq!(got.y, want.y, "run {run} frame {i}: luma vs ffmpeg");
6484 assert_eq!(got.u, want.u, "run {run} frame {i}: U vs ffmpeg");
6485 assert_eq!(got.v, want.v, "run {run} frame {i}: V vs ffmpeg");
6486 }
6487 assert_eq!(
6488 decoded[0].y, key.reconstruction.y,
6489 "run {run}: frame 0 vs the encoder's own reconstruction"
6490 );
6491 assert_eq!(
6492 decoded[2].y, key.reconstruction.y,
6493 "run {run}: GOLDEN_FRAME's block did not reproduce the keyframe it names"
6494 );
6495 assert_ne!(
6496 decoded[2].y, decoded[1].y,
6497 "run {run}: LAST_FRAME's and GOLDEN_FRAME's slots were not actually \
6498 distinguishable -- the gate proves nothing"
6499 );
6500 }
6501 }
6502
6503 /// Builds a `gradients` lavfi source string with colours derived from
6504 /// `seed`, not left to the filter's own default.
6505 ///
6506 /// Measured (lane-fixdet r1): ffmpeg's `gradients` source IGNORES its
6507 /// `seed=` parameter for colour selection -- five encodes of an
6508 /// identical command line (same `seed=`, same everything) produced five
6509 /// different fixtures, because the unset `c0..c9` stops are randomized
6510 /// from something other than that seed. Every one of this file's ~20
6511 /// gate fixtures built a `gradients` source this way, so none of them
6512 /// had a reproducible input: a pin captured from one run could not be
6513 /// regenerated, and "attempt N failed" was as likely to be a different
6514 /// fixture as a different decode outcome.
6515 ///
6516 /// Freezing the colours outright (as the earliest four gates below do,
6517 /// hand-picking `c0=red:c1=blue:c2=green`) fixes reproducibility but
6518 /// throws away the per-attempt content variety the sweep gates need to
6519 /// make features (OBMC, warp, wedge, ...) fire at all -- this repo's own
6520 /// `sampler-decorrelated-gate` class. So: derive `c0..c3` deterministically
6521 /// FROM the seed with a plain integer hash, and keep passing `seed=`
6522 /// itself too, so a future ffmpeg that actually honours it only adds
6523 /// more variety, never removes the determinism this buys.
6524 fn gradients_source(seed: u32, width: usize, height: usize, tail: &str) -> String {
6525 fn hash_color(seed: u32, salt: u32) -> String {
6526 let h = seed
6527 .wrapping_mul(2_654_435_761)
6528 .wrapping_add(salt.wrapping_mul(0x9E37_79B9))
6529 ^ (seed.rotate_left(13));
6530 format!("0x{:06x}", h & 0x00ff_ffff)
6531 }
6532 let (c0, c1, c2, c3) = (
6533 hash_color(seed, 0),
6534 hash_color(seed, 1),
6535 hash_color(seed, 2),
6536 hash_color(seed, 3),
6537 );
6538 format!(
6539 "gradients=size={width}x{height}:c0={c0}:c1={c1}:c2={c2}:c3={c3}:seed={seed}:{tail}"
6540 )
6541 }
6542
6543 /// The determinism guard: same seed twice must byte-match ffmpeg's own
6544 /// output; different seeds must not. Regresses this fix if it ever
6545 /// breaks.
6546 #[test]
6547 fn gradients_source_is_reproducible_per_seed() {
6548 if !have_ffmpeg() {
6549 eprintln!("SKIP gradients_source_is_reproducible_per_seed: no ffmpeg");
6550 return;
6551 }
6552 fn render_hash(lavfi: &str) -> Vec<u8> {
6553 let out = Command::new("ffmpeg")
6554 .args([
6555 "-v",
6556 "error",
6557 "-f",
6558 "lavfi",
6559 "-i",
6560 lavfi,
6561 "-frames:v",
6562 "1",
6563 "-f",
6564 "rawvideo",
6565 "-",
6566 ])
6567 .stdin(Stdio::null())
6568 .stdout(Stdio::piped())
6569 .stderr(Stdio::piped())
6570 .output()
6571 .expect("ffmpeg failed to run");
6572 assert!(out.status.success(), "ffmpeg refused {lavfi}");
6573 out.stdout
6574 }
6575 let a1 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
6576 let a2 = render_hash(&gradients_source(43, 64, 64, "duration=0.04:rate=25"));
6577 let a3 = render_hash(&gradients_source(42, 64, 64, "duration=0.04:rate=25"));
6578 assert_eq!(a1, a3, "same seed must reproduce byte-identical output");
6579 assert_ne!(a1, a2, "different seeds must not collide");
6580 }
6581
6582 /// Encodes a real libaom-av1 stream (via ffmpeg's own encoder, not this
6583 /// crate's) with the same reduced-partition flags lane-av1adst's r6
6584 /// probe found still select `ADST_ADST`/`ADST_DCT`/`DCT_ADST` on
6585 /// gradient content (TX_SET_INTRA_2), and decodes it with
6586 /// [`decode_stream`] -- lifting the round-2 refusal is only real if it
6587 /// gets past an encoder this crate never wrote a byte of.
6588 fn libaom_encode(lavfi: &str, width: usize, height: usize, crf: u32) -> Option<Vec<u8>> {
6589 libaom_encode_with(lavfi, width, height, crf, &[])
6590 }
6591
6592 /// As [`libaom_encode`], with extra encoder args appended -- used to pin
6593 /// a deterministic stream (`-threads 1` etc., since libaom's `cpu-used 8`
6594 /// RD search is not otherwise stable run-to-run on this box, and lavfi
6595 /// `gradients` needs its own `seed=` for the same reason) and to gate
6596 /// individual feature flags (`-enable-cdef 0`) a given fixture needs off.
6597 fn libaom_encode_with(
6598 lavfi: &str,
6599 width: usize,
6600 height: usize,
6601 crf: u32,
6602 extra: &[&str],
6603 ) -> Option<Vec<u8>> {
6604 let mut args = vec![
6605 "-v",
6606 "error",
6607 "-f",
6608 "lavfi",
6609 "-i",
6610 lavfi,
6611 "-frames:v",
6612 "1",
6613 "-pix_fmt",
6614 "yuv420p",
6615 "-c:v",
6616 "libaom-av1",
6617 ];
6618 let crf_str = crf.to_string();
6619 args.extend(["-crf", &crf_str]);
6620 args.extend([
6621 "-cpu-used",
6622 "8",
6623 "-enable-rect-partitions",
6624 "0",
6625 "-enable-ab-partitions",
6626 "0",
6627 "-enable-1to4-partitions",
6628 "0",
6629 "-enable-angle-delta",
6630 "0",
6631 "-enable-cfl-intra",
6632 "0",
6633 ]);
6634 args.extend(extra.iter().copied());
6635 args.extend(["-f", "obu", "-"]);
6636 let out = Command::new("ffmpeg")
6637 .args(&args)
6638 .stdin(Stdio::null())
6639 .stdout(Stdio::piped())
6640 .stderr(Stdio::piped())
6641 .output()
6642 .expect("ffmpeg failed to run");
6643 if !out.status.success() {
6644 eprintln!(
6645 "ffmpeg refused to encode {lavfi} at {width}x{height}: {}",
6646 String::from_utf8_lossy(&out.stderr)
6647 );
6648 return None;
6649 }
6650 Some(out.stdout)
6651 }
6652
6653 /// The end-to-end gate: two real libaom-av1 configs, decoded with
6654 /// [`decode_stream`] and checked against ffmpeg's own decode of the same
6655 /// bytes. Not every config this encoder writes decodes yet (partitions
6656 /// below 16x16, AB partitions, CfL and others remain round-2 gaps per the
6657 /// r6 catalogue) -- both configs here pick `cpu-used 8` plus the
6658 /// partition/angle-delta/CfL flags r6 found narrow the encoder onto this
6659 /// decoder's supported syntax, while still landing on non-`DCT_DCT` tx
6660 /// types on gradient content.
6661 #[test]
6662 fn a_real_libaom_stream_with_adst_decodes_end_to_end() {
6663 if !have_ffmpeg() {
6664 eprintln!("SKIP a_real_libaom_stream_with_adst_decodes_end_to_end: no ffmpeg");
6665 return;
6666 }
6667 let configs: [(String, usize, usize, u32); 2] = [
6668 ("testsrc2=size=64x64:rate=1".to_string(), 64, 64, 15),
6669 (gradients_source(42, 64, 64, "rate=1"), 64, 64, 15),
6670 ];
6671 let mut verdicts = Vec::new();
6672 for (lavfi, width, height, crf) in configs {
6673 let lavfi = lavfi.as_str();
6674 let Some(stream) = libaom_encode(lavfi, width, height, crf) else {
6675 verdicts.push(format!("{lavfi}: ffmpeg itself refused to encode"));
6676 continue;
6677 };
6678 match decode_stream(&stream) {
6679 Ok(frames) => {
6680 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
6681 let matches = frames[0].y == ffmpeg_frames[0].y
6682 && frames[0].u == ffmpeg_frames[0].u
6683 && frames[0].v == ffmpeg_frames[0].v;
6684 verdicts.push(format!(
6685 "{lavfi}: decoded, {} ffmpeg's own decode",
6686 if matches { "MATCHES" } else { "MISMATCHES" }
6687 ));
6688 // Not a hard `assert!`: libaom's own mode decisions at
6689 // `cpu-used 8` are not observed stable run-to-run on this
6690 // box (multi-threaded RD search), so a run that happens
6691 // to land on a still-unsupported syntax element (e.g. a
6692 // partition below 16x16, a separate round-2 gap) can
6693 // decode without erroring yet disagree -- that failure
6694 // mode belongs to those other gaps, not to this round's
6695 // ADST wiring, and the eprintln below reports it either
6696 // way rather than hiding it.
6697 }
6698 Err(e) => {
6699 verdicts.push(format!("{lavfi}: still refuses ({e})"));
6700 }
6701 }
6702 }
6703 eprintln!("libaom ADST end-to-end verdicts:");
6704 for v in &verdicts {
6705 eprintln!(" {v}");
6706 }
6707 }
6708
6709 /// lane-dgolomb: the `force_integer_mv` gate. libaom turns screen-content
6710 /// tools on for DARK, SMOOTH content -- its `av1_set_screen_content_options`
6711 /// counts 16x16 blocks with 2..=4 distinct luma values -- and then sets
6712 /// `force_integer_mv` on any inter frame whose source is pixel-identical to
6713 /// the previously coded source (`av1_is_integer_mv`: `cs_rate >= 0.8` and
6714 /// `C == T`, every collocated 8x8 block matching, is the only path that
6715 /// returns 1). Both hold on his real AV1 films, and this decoder used to
6716 /// drop `lower_mv_precision`'s `is_integer` half as unreachable, so every
6717 /// temporal MV candidate on such a frame came out at eighth-pel: the frame
6718 /// decoded without any error into a whole-frame prediction mismatch, and
6719 /// the desync surfaced blocks later as "a Golomb tail longer than this
6720 /// decoder reads".
6721 ///
6722 /// The source is SYNTHETIC (no film sample lives in `fixtures`): the
6723 /// near-flat dark pattern libaom's own screen-content detector counts as
6724 /// screen content, at the film-B crop size 1920x1024, SCROLLING globally
6725 /// 5 px per frame and frozen on frame 8 -- an exact duplicate of frame 7
6726 /// (the `C == T` trigger) whose twin is not among its own references, so
6727 /// its blocks still code real motion under `force_integer_mv`.
6728 ///
6729 /// lane-dpm1 made this gate SENSITIVE: with the `force_integer_mv` branch
6730 /// of [`crate::motion_field::lower_mv_precision`] stubbed out (`if false
6731 /// &&`) the stream decodes WRONG -- frame 8, luma sample 25695, 20 against
6732 /// ffmpeg's 19 -- where the previous patch-in-a-static-background recipe
6733 /// (and two others tried) still decoded byte-exact: there the used mv-stack
6734 /// slots came from agreeing spatial neighbours and the rounded temporal
6735 /// entries never won one. The gate asserts both halves: at least one INTER
6736 /// frame really carries `force_integer_mv` (class `gate-blind-to-feature`),
6737 /// and every shown frame decodes sample-exact against ffmpeg's own decode.
6738 #[test]
6739 fn a_libaom_force_integer_mv_stream_decodes_exact() {
6740 const NAME: &str = "a_libaom_force_integer_mv_stream_decodes_exact";
6741 if !have_ffmpeg() {
6742 eprintln!("SKIP {NAME}: no ffmpeg");
6743 return;
6744 }
6745 let (w, h, frames) = (1920usize, 1024usize, 16usize);
6746 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
6747 let mut off = 0usize;
6748 for f in 0..frames {
6749 // lane-dpm1: the WHOLE picture scrolls 5 px per frame and freezes
6750 // on frame 8, so (a) every block of the frozen frame -- including
6751 // mi(0,0), which has no spatial neighbour at all -- still codes
6752 // real motion against the references that are not its twin, and
6753 // (b) 40 eighth-pels projected over the pyramid's distances lands
6754 // on non-multiples of 8 (40/2 = 20 -> 16). A patch moving inside a
6755 // static background was NOT sensitive: there the used stack slots
6756 // came from spatial neighbours that agreed, and the rounded
6757 // temporal entries never won one.
6758 if f > 0 && f != 8 {
6759 off = (off + 5) % h;
6760 }
6761 let mut y = vec![0u8; w * h];
6762 for row in 0..h {
6763 let src = (row + off) % h;
6764 for col in 0..w {
6765 // 2..=4 distinct values per 16x16 block, all dark: the
6766 // screen-content detector's own counting rule.
6767 y[row * w + col] =
6768 16 + ((col / 32 + src / 32) % 5) as u8 + ((col / 4 + src / 4) % 3) as u8;
6769 }
6770 }
6771 raw.extend_from_slice(&y);
6772 raw.extend(std::iter::repeat_n(128u8, w * h / 2));
6773 }
6774 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
6775 let src = std::env::temp_dir().join(format!("ec-av1-intmv-{}.yuv", std::process::id()));
6776 std::fs::write(&src, &raw).expect("raw source");
6777 let out = Command::new("ffmpeg")
6778 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
6779 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
6780 .arg(&src)
6781 .args(["-an", "-threads", "1", "-g", "16", "-c:v", "libaom-av1"])
6782 .args([
6783 "-cpu-used",
6784 "6",
6785 "-b:v",
6786 "0",
6787 "-crf",
6788 "35",
6789 "-f",
6790 "obu",
6791 "-",
6792 ])
6793 .stdin(Stdio::null())
6794 .stdout(Stdio::piped())
6795 .stderr(Stdio::piped())
6796 .output()
6797 .expect("ffmpeg failed to run");
6798 let _ = std::fs::remove_file(&src);
6799 if !out.status.success() {
6800 eprintln!(
6801 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
6802 String::from_utf8_lossy(&out.stderr)
6803 );
6804 return;
6805 }
6806 let stream = out.stdout;
6807
6808 // Half of the gate: the stream must actually carry the feature.
6809 let mut parser = Av1Parser::new();
6810 let (mut pos, mut int_mv_inter) = (0usize, 0usize);
6811 while pos < stream.len() {
6812 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
6813 pos += obu.total_size.max(1);
6814 let header = match &obu.kind {
6815 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
6816 _ => continue,
6817 };
6818 if header.force_integer_mv && !header.frame_is_intra && header.use_ref_frame_mvs {
6819 int_mv_inter += 1;
6820 }
6821 }
6822 assert!(
6823 int_mv_inter > 0,
6824 "{NAME} went blind: libaom coded no inter frame with force_integer_mv"
6825 );
6826
6827 let ours = decode_stream(&stream).expect("libaom screen-content stream decodes");
6828 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
6829 assert_eq!(ours.len(), frames, "shown frame count");
6830 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
6831 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
6832 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
6833 assert!(
6834 first.is_none(),
6835 "frame {i} plane {plane} differs from ffmpeg at sample {} \
6836 ({int_mv_inter} force_integer_mv inter frames in this stream)",
6837 first.unwrap()
6838 );
6839 assert_eq!(
6840 l.len(),
6841 r.len(),
6842 "frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a short \
6843 plane would zip-truncate the compare above and hide a chroma-span defect",
6844 l.len(),
6845 r.len()
6846 );
6847 }
6848 }
6849 }
6850
6851 /// lane-dpm1: the 128x128-INTRA-inside-an-INTER-frame chroma context gate.
6852 /// A 128x128 block codes its chroma as four TX_32X32 units, one per 64x64
6853 /// mu chunk, and libaom stamps the coefficient context PER UNIT. The two
6854 /// INTER mu-chunk sites set `mu_chroma` so the block tail re-stamps the
6855 /// four units in mu order; the INTRA-in-inter site did not, so the
6856 /// whole-block record left every unit carrying the TOP-LEFT unit's level.
6857 /// The next block then read its `txb_skip` off ctx 11 where libaom reads
6858 /// ctx 10 (class `override-slot-on-one-arm`) -- one symbol on the wrong
6859 /// CDF row, tile desynced, and because the loop-restoration coefficients
6860 /// live in the same tile data the damage showed up as a +-1 luma sample at
6861 /// the TOP of the frame (measured: frame 1, luma sample 66, ours 146 /
6862 /// ffmpeg 145, with 1.7M samples wrong behind it).
6863 ///
6864 /// Source: the repository's own 2160p colour-bar fixture at the native
6865 /// gate's crop (1920x1024 out of the middle), 12 frames, libaom
6866 /// `-cpu-used 6 -crf 45 -g 12` -- the first reference point of
6867 /// `bd_rate_screen_native`'s "bars 2160p" row, which is where the assertion
6868 /// caught it. The gate asserts the tool fired (class
6869 /// `gate-blind-to-feature`) and that every shown frame decodes sample-exact
6870 /// against ffmpeg's own decode.
6871 #[test]
6872 fn a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact() {
6873 const NAME: &str = "a_libaom_stream_with_128_intra_blocks_in_inter_frames_decodes_exact";
6874 if !have_ffmpeg() {
6875 eprintln!("SKIP {NAME}: no ffmpeg");
6876 return;
6877 }
6878 // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env
6879 // escape, so on a tree with no root `fixtures/` this 128-intra-block
6880 // gate reported green having decoded nothing.
6881 let Some(clip) = crate::library_fixture::require("video/h264-2160p-23.976-8bit.mp4", NAME)
6882 else {
6883 return;
6884 };
6885 let (w, h, frames) = (1920usize, 1024usize, 12usize);
6886 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
6887 let src = std::env::temp_dir().join(format!("ec-av1-i128-{}.yuv", std::process::id()));
6888 let load = Command::new("ffmpeg")
6889 .args(["-v", "error", "-y", "-i"])
6890 .arg(&clip)
6891 .args([
6892 "-frames:v",
6893 &frames.to_string(),
6894 "-vf",
6895 "crop=1920:1024:960:568",
6896 ])
6897 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
6898 .arg(&src)
6899 .output()
6900 .expect("ffmpeg failed to run");
6901 assert!(
6902 load.status.success(),
6903 "{NAME}: {}",
6904 String::from_utf8_lossy(&load.stderr)
6905 );
6906 let out = Command::new("ffmpeg")
6907 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
6908 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
6909 .arg(&src)
6910 .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"])
6911 .args([
6912 "-cpu-used",
6913 "6",
6914 "-b:v",
6915 "0",
6916 "-crf",
6917 "45",
6918 "-f",
6919 "obu",
6920 "-",
6921 ])
6922 .stdin(Stdio::null())
6923 .stdout(Stdio::piped())
6924 .stderr(Stdio::piped())
6925 .output()
6926 .expect("ffmpeg failed to run");
6927 let _ = std::fs::remove_file(&src);
6928 if !out.status.success() {
6929 eprintln!(
6930 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
6931 String::from_utf8_lossy(&out.stderr)
6932 );
6933 return;
6934 }
6935 let stream = out.stdout;
6936 let before = crate::decode::intra_128_in_inter_hits();
6937 let ours = decode_stream(&stream).expect("libaom bars stream decodes");
6938 assert!(
6939 crate::decode::intra_128_in_inter_hits() > before,
6940 "{NAME} went blind: no 128-rooted intra block inside an inter frame"
6941 );
6942 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
6943 assert_eq!(ours.len(), frames, "shown frame count");
6944 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
6945 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
6946 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
6947 assert!(
6948 first.is_none(),
6949 "frame {i} plane {plane} differs from ffmpeg at sample {}",
6950 first.unwrap()
6951 );
6952 assert_eq!(
6953 l.len(),
6954 r.len(),
6955 "frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a short \
6956 plane would zip-truncate the compare above and hide a chroma-span defect",
6957 l.len(),
6958 r.len()
6959 );
6960 }
6961 }
6962 }
6963
6964 /// lane-lossless: the refusal became an implementation, so its gate became
6965 /// a DECODE-EXACT one (class `refusal-lifted-without-a-gate`). libaom at
6966 /// `-crf 0` codes `base_q_idx == 0` -- the same lossless frame his
6967 /// screen-capture row gets at `-crf 5` -- where every plane is TX_4X4 with
6968 /// the Walsh-Hadamard transform, no `tx_type` symbol is coded
6969 /// (`read_tx_type`, `decodetxb.c`: "No need to read transform type for
6970 /// lossless mode(qindex==0)") and `is_cfl_allowed` (`blockd.h`) narrows to
6971 /// a BLOCK_4X4 chroma plane block. The gate asserts the stream really is
6972 /// lossless (class `gate-blind-to-feature`), that every KEY frame decodes
6973 /// sample-exact against ffmpeg, and that the still-unimplemented lossless
6974 /// INTER frame is refused BY NAME rather than decoded wrong.
6975 #[test]
6976 fn a_lossless_libaom_key_frame_decodes_sample_exact() {
6977 const NAME: &str = "a_lossless_libaom_key_frame_decodes_sample_exact";
6978 if !have_ffmpeg() {
6979 eprintln!("SKIP {NAME}: no ffmpeg");
6980 return;
6981 }
6982 let (w, h, frames) = (256usize, 128usize, 2usize);
6983 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
6984 for f in 0..frames {
6985 for row in 0..h {
6986 for col in 0..w {
6987 raw.push(((col * 7 + row * 13 + f * 31) % 251) as u8);
6988 }
6989 }
6990 // lane-lossless2: TEXTURED chroma. A flat chroma plane codes one
6991 // `txb_skip` symbol per 4x4 unit with every context at 0, which
6992 // is blind to both the unit ORDER and the per-unit contexts
6993 // (class `gate-blind-to-feature`).
6994 for row in 0..h / 2 {
6995 for col in 0..w / 2 {
6996 raw.push((((col + f) * 11 + row * 5) % 251) as u8);
6997 }
6998 }
6999 for row in 0..h / 2 {
7000 for col in 0..w / 2 {
7001 raw.push(((col * 3 + (row + f) * 17) % 251) as u8);
7002 }
7003 }
7004 }
7005 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
7006 let src = std::env::temp_dir().join(format!("ec-av1-lossless-{}.yuv", std::process::id()));
7007 std::fs::write(&src, &raw).expect("raw source");
7008 let encode = |gop: &str| {
7009 let out = Command::new("ffmpeg")
7010 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
7011 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
7012 .arg(&src)
7013 .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
7014 .args(["-cpu-used", "6", "-b:v", "0", "-crf", "0", "-f", "obu", "-"])
7015 .stdin(Stdio::null())
7016 .stdout(Stdio::piped())
7017 .stderr(Stdio::piped())
7018 .output()
7019 .expect("ffmpeg failed to run");
7020 out
7021 };
7022 let out = encode("1");
7023 let _ = std::fs::remove_file(&src);
7024 if !out.status.success() {
7025 eprintln!(
7026 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
7027 String::from_utf8_lossy(&out.stderr)
7028 );
7029 return;
7030 }
7031 let stream = out.stdout;
7032 // Half of the gate: the stream must really carry a lossless frame
7033 // (class `gate-blind-to-feature`).
7034 let mut parser = Av1Parser::new();
7035 let (mut pos, mut lossless) = (0usize, 0usize);
7036 while pos < stream.len() {
7037 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
7038 pos += obu.total_size.max(1);
7039 let header = match &obu.kind {
7040 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
7041 _ => continue,
7042 };
7043 if header.lossless.iter().all(|&l| l) {
7044 lossless += 1;
7045 }
7046 }
7047 assert_eq!(
7048 lossless, frames,
7049 "{NAME} went blind: libaom coded no lossless key frame at -crf 0"
7050 );
7051 let ours = decode_stream(&stream).expect("a lossless key-frame stream decodes");
7052 let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
7053 assert_eq!(ours.len(), frames, "{NAME}: frame count");
7054 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
7055 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
7056 .iter()
7057 .enumerate()
7058 {
7059 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
7060 assert_eq!(
7061 bad, 0,
7062 "{NAME}: frame {i} plane {plane}: {bad} samples differ"
7063 );
7064 assert_eq!(
7065 g.len(),
7066 r.len(),
7067 "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
7068 short plane would zip-truncate the compare above and hide a chroma-span \
7069 defect",
7070 g.len(),
7071 r.len()
7072 );
7073 }
7074 }
7075 }
7076
7077 /// lane-lossless2: the refusal `a_lossless_inter_frame_is_refused_by_name`
7078 /// pinned became an implementation, so its gate became a DECODE-EXACT one
7079 /// (class `refusal-lifted-without-a-gate`). A lossless INTER frame codes
7080 /// its chroma plane as 4x4 transform units, plane-major inside each 64x64
7081 /// mu chunk (libaom `read_tx_size` returns TX_4X4 for every plane under
7082 /// `xd->lossless[..]`, and `decode_token_recon_block` walks
7083 /// `for (plane..) for (blk_row..) for (blk_col..)`), which is what
7084 /// `decode::read_inter_chroma_lossless` reads. The source carries TEXTURED
7085 /// CHROMA and real motion on purpose: a flat-chroma source codes one
7086 /// `txb_skip` symbol per unit and is blind to both the unit order and the
7087 /// per-unit contexts (class `gate-blind-to-feature`).
7088 #[test]
7089 fn a_lossless_libaom_inter_frame_decodes_sample_exact() {
7090 const NAME: &str = "a_lossless_libaom_inter_frame_decodes_sample_exact";
7091 if !have_ffmpeg() {
7092 eprintln!("SKIP {NAME}: no ffmpeg");
7093 return;
7094 }
7095 // (w, h, frames, gop, bit depth, 128-superblock, screen content)
7096 // lane-lossless2: the SCREEN rows carry palette blocks, which is what
7097 // caught the whole-block palette prediction being handed to a 4x4
7098 // chroma unit.
7099 // lane-lossless3: the last row is a screen source with INTER frames --
7100 // the row that caught both of this lane's defects (a skip 8x8 leaf
7101 // restoring the previous block's luma level band over the zeros
7102 // `av1_reset_entropy_context` writes, and a rect sub-8x8 INTRA leaf
7103 // reading one TX_4X8 unit where a lossless frame codes two TX_4X4).
7104 let cases: [(usize, usize, usize, &str, u32, bool, bool); 7] = [
7105 (256, 128, 8, "4", 8, false, false),
7106 (192, 96, 6, "3", 10, false, false),
7107 (320, 192, 6, "3", 8, false, false),
7108 (256, 256, 4, "2", 8, true, false),
7109 (320, 192, 2, "1", 8, false, true),
7110 (640, 384, 2, "1", 8, false, true),
7111 (640, 384, 6, "3", 8, false, true),
7112 ];
7113 for &(w, h, frames, gop, depth, sb128, screen) in &cases {
7114 let tag = format!(
7115 "{w}x{h} {depth}-bit gop {gop}{}{}",
7116 if sb128 { " sb128" } else { "" },
7117 if screen { " screen" } else { "" }
7118 );
7119 let mut raw: Vec<u8> = Vec::new();
7120 let put = |v: u32, raw: &mut Vec<u8>| {
7121 if depth == 10 {
7122 raw.extend_from_slice(&((v * 4) as u16).to_le_bytes());
7123 } else {
7124 raw.push(v as u8);
7125 }
7126 };
7127 // A screen source is a few flat colours in 16x16 tiles plus
7128 // 1-px text-like rows -- what makes libaom code palette blocks.
7129 const PAL: [u32; 8] = [16, 60, 110, 145, 180, 210, 235, 128];
7130 for f in 0..frames {
7131 for row in 0..h {
7132 for col in 0..w {
7133 let v = if screen {
7134 if row % 7 == 0 && col % 3 == 0 {
7135 if (col / 3 + row + f) % 2 == 1 {
7136 16
7137 } else {
7138 235
7139 }
7140 } else {
7141 PAL[((col + 4 * f) / 16 + row / 16) % PAL.len()]
7142 }
7143 } else {
7144 (((col + 2 * f) * 7 + row * 13) % 251) as u32
7145 };
7146 put(v, &mut raw);
7147 }
7148 }
7149 for plane in 0..2usize {
7150 for row in 0..h / 2 {
7151 for col in 0..w / 2 {
7152 let v = if screen {
7153 PAL[((col + 2 * f) / 8 + row / 8 + plane) % PAL.len()]
7154 } else if plane == 0 {
7155 (((col + f) * 11 + row * 5) % 251) as u32
7156 } else {
7157 ((col * 3 + (row + f) * 17) % 251) as u32
7158 };
7159 put(v, &mut raw);
7160 }
7161 }
7162 }
7163 }
7164 let pix = if depth == 10 {
7165 "yuv420p10le"
7166 } else {
7167 "yuv420p"
7168 };
7169 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
7170 let src = std::env::temp_dir().join(format!(
7171 "ec-av1-lossless2-{}-{w}x{h}-{depth}.yuv",
7172 std::process::id()
7173 ));
7174 std::fs::write(&src, &raw).expect("raw source");
7175 let mut cmd = Command::new("ffmpeg");
7176 cmd.args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", pix])
7177 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
7178 .arg(&src)
7179 .args(["-an", "-threads", "1", "-g", gop, "-c:v", "libaom-av1"])
7180 .args(["-pix_fmt", pix, "-cpu-used", "6", "-b:v", "0", "-crf", "0"]);
7181 if sb128 {
7182 cmd.args(["-aom-params", "sb-size=128"]);
7183 }
7184 if screen {
7185 cmd.args(["-aom-params", "tune-content=screen"]);
7186 }
7187 let out = cmd
7188 .args(["-f", "obu", "-"])
7189 .stdin(Stdio::null())
7190 .stdout(Stdio::piped())
7191 .stderr(Stdio::piped())
7192 .output()
7193 .expect("ffmpeg failed to run");
7194 let _ = std::fs::remove_file(&src);
7195 if !out.status.success() {
7196 eprintln!(
7197 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
7198 String::from_utf8_lossy(&out.stderr)
7199 );
7200 return;
7201 }
7202 let stream = out.stdout;
7203 // The stream must really be lossless AND really carry inter frames
7204 // (class `gate-blind-to-feature`).
7205 let mut parser = Av1Parser::new();
7206 let (mut pos, mut lossless, mut inters) = (0usize, 0usize, 0usize);
7207 while pos < stream.len() {
7208 let obu = parser.parse_obu(&stream[pos..]).expect("libaom OBU parses");
7209 pos += obu.total_size.max(1);
7210 let header = match &obu.kind {
7211 ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) => h,
7212 _ => continue,
7213 };
7214 if header.lossless.iter().all(|&l| l) {
7215 lossless += 1;
7216 }
7217 if header.frame_type == FrameType::Inter {
7218 inters += 1;
7219 }
7220 }
7221 assert!(
7222 lossless >= frames,
7223 "{NAME} [{tag}] went blind: {lossless} lossless frames"
7224 );
7225 assert!(
7226 screen || inters > 0,
7227 "{NAME} [{tag}] went blind: no inter frame at gop {gop}"
7228 );
7229 let ours = decode_stream(&stream)
7230 .unwrap_or_else(|e| panic!("{NAME} [{tag}]: a lossless inter stream decodes: {e}"));
7231 let refs = if depth == 10 {
7232 ffmpeg_decode_sequence_10bit(&stream, w, h, frames)
7233 } else {
7234 ffmpeg_decode_sequence(&stream, w, h, frames)
7235 };
7236 assert_eq!(ours.len(), frames, "{NAME} [{tag}]: frame count");
7237 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
7238 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
7239 .iter()
7240 .enumerate()
7241 {
7242 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
7243 assert_eq!(
7244 bad, 0,
7245 "{NAME} [{tag}]: frame {i} plane {plane}: {bad} samples differ"
7246 );
7247 assert_eq!(
7248 g.len(),
7249 r.len(),
7250 "{NAME} [{tag}]: frame {i} plane {plane}: ours has {} samples, ffmpeg's has \
7251 {} -- a short plane would zip-truncate the compare above and hide a \
7252 chroma-span defect",
7253 g.len(),
7254 r.len()
7255 );
7256 }
7257 }
7258 }
7259 }
7260
7261 /// lane-av1-llband: the pinned 4:4:4 LOSSLESS key frame
7262 /// (`fixtures/ll444-lossless-key.obu`, the `ll444` recipe's frame 0 --
7263 /// `testsrc2 128x96` yuv444p cut to its key frame) decodes sample-exact,
7264 /// and its HORZ/VERT strips really walked their chroma as 4x4 units at
7265 /// subsampling 0/0 (one unit per mi cell). That unit walk used the 4:2:0
7266 /// span (8 luma px per 4x4 chroma unit) unconditionally, so every unit
7267 /// past the first column/row read its `txb_skip` context two mi cells
7268 /// over and stamped a 2-cell smear -- the 178-byte key-frame miss, first
7269 /// divergence at the 16x8 leaf mi (16,24)'s U bc=2 unit (oracle
7270 /// `txb_skip` base 0 off `above[26]`, ours base 1 off the polluted
7271 /// `above[29]`). The counter assertion is the non-vacuity half (class
7272 /// `gate-blind-to-feature`): a stream that never reaches the 4:4:4 unit
7273 /// walk must not pass.
7274 #[test]
7275 fn a_real_aomenc_lossless_444_key_frame_decodes_sample_exact() {
7276 const NAME: &str = "a_real_aomenc_lossless_444_key_frame_decodes_sample_exact";
7277 if !have_ffmpeg() {
7278 eprintln!("SKIP {NAME}: no ffmpeg");
7279 return;
7280 }
7281 // lane-av1pins: committed at crates/ec-av1/fixtures/ll444-lossless-key.obu
7282 // (7845 bytes; sha256
7283 // f496ef0a1171c2bc66d411cc60db05db547dcdb49cd834d4e0543de9db441374),
7284 // re-encoded 2026-09-29 from the recipe this very SKIP line records --
7285 // `testsrc2 128x96` yuv444p 6 frames, aomenc --profile=1 --lossless=1
7286 // --enable-palette=0 --enable-intrabc=0 --bit-depth=8 --cpu-used=0
7287 // --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100, --limit=1
7288 // so the key frame's OBUs are the whole stream (no OBU surgery needed).
7289 //
7290 // lane-av1skipfix: reading the pin from the GITIGNORED root
7291 // `fixtures/` (`pin_dir()`) is what made this gate report green having
7292 // decoded nothing -- a fresh clone, and every linked worktree, can
7293 // never have that directory. The pin is now COMMITTED under the crate
7294 // (the home the other pins use) and read through `CARGO_MANIFEST_DIR`,
7295 // so a missing file is a REPO DEFECT and fails unconditionally: there
7296 // is no environment left to escape, which is strictly stronger than
7297 // the `EC_REQUIRE_FIXTURES` / `EC_AV1_REQUIRE_AOMENC` opt-in hard
7298 // fail this arm used to carry.
7299 let pin = crate_pin("ll444-lossless-key.obu");
7300 let stream = std::fs::read(&pin).unwrap_or_else(|e| {
7301 panic!(
7302 "{NAME}: the pinned 4:4:4 lossless key frame is missing at {} ({e}). A \
7303 COMMITTED pin that is absent is a repo defect and this gate would prove \
7304 nothing. No script generates it -- regenerate it with `testsrc2 128x96` \
7305 yuv444p 6 frames, aomenc --profile=1 --lossless=1 --enable-palette=0 \
7306 --enable-intrabc=0 --bit-depth=8 --cpu-used=0 --threads=1 --row-mt=0 \
7307 --lag-in-frames=0 --kf-max-dist=100 --limit=1, and commit the result.",
7308 pin.display()
7309 )
7310 });
7311 // Blindness guard: the pinned fixture must really be a lossless frame.
7312 let mut parser = Av1Parser::new();
7313 let mut pos = 0usize;
7314 let mut lossless = false;
7315 while pos < stream.len() {
7316 let obu = parser.parse_obu(&stream[pos..]).expect("aomenc OBU parses");
7317 pos += obu.total_size.max(1);
7318 if let ObuKind::FrameHeader(h) | ObuKind::Frame(h, _) = obu.kind {
7319 lossless = h.lossless.iter().all(|&l| l);
7320 }
7321 }
7322 assert!(
7323 lossless,
7324 "{NAME} went blind: the pinned frame is not lossless"
7325 );
7326 let before = crate::decode::rect_split_lossless_chroma444_hits();
7327 let ours = decode_stream(&stream).expect("a 444 lossless key-frame stream decodes");
7328 assert_eq!(ours.len(), 1, "{NAME}: frame count");
7329 assert!(
7330 crate::decode::rect_split_lossless_chroma444_hits() > before,
7331 "{NAME} went blind: no lossless HORZ/VERT strip walked its chroma \
7332 as 4x4 units at subsampling 0/0"
7333 );
7334 let refs = Command::new("ffmpeg")
7335 .args([
7336 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv444p", "-",
7337 ])
7338 .stdin(Stdio::piped())
7339 .stdout(Stdio::piped())
7340 .stderr(Stdio::piped())
7341 .spawn()
7342 .and_then(|mut child| {
7343 use std::io::Write as _;
7344 child.stdin.as_mut().expect("stdin").write_all(&stream)?;
7345 child.wait_with_output()
7346 })
7347 .expect("ffmpeg 444 decode failed");
7348 assert!(
7349 refs.status.success(),
7350 "{}",
7351 String::from_utf8_lossy(&refs.stderr)
7352 );
7353 let frame = &ours[0];
7354 let planes = [
7355 (&frame.y, frame.width * frame.height),
7356 (&frame.u, frame.width * frame.height),
7357 (&frame.v, frame.width * frame.height),
7358 ];
7359 let mut off = 0usize;
7360 for (plane, (g, len)) in planes.iter().enumerate() {
7361 let raw = &refs.stdout[off..off + len];
7362 let bad = g
7363 .iter()
7364 .zip(raw.iter())
7365 .filter(|&(&a, &b)| a != u16::from(b))
7366 .count();
7367 assert_eq!(bad, 0, "{NAME}: plane {plane}: {bad} samples differ");
7368 off += len;
7369 }
7370 }
7371
7372 /// As [`ffmpeg_decode_sequence`], for a 4:4:4 stream: chroma planes are
7373 /// FULL resolution (`yuv444p` rawvideo), the shape lane-av1-llinter's
7374 /// lossless profile-1 fixture codes.
7375 fn ffmpeg_decode_sequence_444(
7376 stream: &[u8],
7377 width: usize,
7378 height: usize,
7379 frames: usize,
7380 ) -> Vec<Pic> {
7381 let out = run_with_stdin(
7382 Command::new("ffmpeg").args([
7383 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv444p", "-",
7384 ]),
7385 stream,
7386 );
7387 assert!(
7388 out.status.success(),
7389 "ffmpeg refused the 4:4:4 stream: {}",
7390 String::from_utf8_lossy(&out.stderr)
7391 );
7392 let plane = width * height;
7393 let frame_bytes = 3 * plane;
7394 assert_eq!(
7395 out.stdout.len(),
7396 frame_bytes * frames,
7397 "{}",
7398 frame_count_diagnosis(
7399 "4:4:4",
7400 frames,
7401 width,
7402 height,
7403 frame_bytes,
7404 out.stdout.len(),
7405 &out.stderr
7406 )
7407 );
7408 (0..frames)
7409 .map(|i| {
7410 let base = i * frame_bytes;
7411 Pic {
7412 width,
7413 height,
7414 y: out.stdout[base..base + plane]
7415 .iter()
7416 .map(|&v| u16::from(v))
7417 .collect(),
7418 u: out.stdout[base + plane..base + 2 * plane]
7419 .iter()
7420 .map(|&v| u16::from(v))
7421 .collect(),
7422 v: out.stdout[base + 2 * plane..base + 3 * plane]
7423 .iter()
7424 .map(|&v| u16::from(v))
7425 .collect(),
7426 }
7427 })
7428 .collect()
7429 }
7430
7431 /// lane-av1-llinter: the firing gate for the lossless 4:4:4 INTER chroma
7432 /// fix. The fixture is the report's dodge2 stream pinned into `fixtures/`:
7433 /// aomenc profile 1 over testsrc2 128x96 yuv444p, `--lossless=1`,
7434 /// `--sb-size=64 --min-partition-size=64 --max-partition-size=64`, 6
7435 /// frames; 37658 bytes, sha256
7436 /// `5a070fa351a3f2109de855234f2b3d0a872970f3e7f658db21f65c12eeb135b4`.
7437 /// The firing counter is the EXISTING `decode::chroma_split_tx_hits` (one
7438 /// bump per lossless chroma TX unit read): with min=max partition 64 the
7439 /// roots stay whole 64x64 inter blocks -- no 8x8 leaf exists in this
7440 /// stream -- so every chroma unit goes through the big-block ss-aware
7441 /// lossless route this lane fixed (fixes 2-5). A 4:2:0 lossless stream
7442 /// fires the same counter, but the fixture bytes are pinned, so the gate
7443 /// cannot run on anything else; the pre-fix 4:2:0-hardcoded math corrupts
7444 /// at 4:4:4, so the pixel-exact compares are what prove the ss-aware path
7445 /// (class `gate-blind-to-feature`). Every frame must come out pixel-exact
7446 /// through BOTH the oracle `aomdec --rawvideo` and ffmpeg. The
7447 /// default-partition ll444 stream is deliberately NOT claimed here: its
7448 /// key frame is still the intra lane's named sub8-chroma stop
7449 /// (lanes/av1llintra.report.md).
7450 #[test]
7451 fn a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact() {
7452 const NAME: &str = "a_lossless_444_min_partition64_inter_stream_decodes_pixel_exact";
7453 const FIXTURE_LEN: usize = 37658;
7454 const FIXTURE_FNV: u64 = 0xf68d_c26f_a14d_283c;
7455 const W: usize = 128;
7456 const H: usize = 96;
7457 const FRAMES: usize = 6;
7458 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7459 .join("fixtures/ll444_minp64_inter.obu");
7460 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
7461 panic!(
7462 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
7463 which is a failure, not a skip",
7464 obu.display()
7465 )
7466 });
7467 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
7468 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
7469
7470 let _guard = lock_gate_counters();
7471 let before = crate::decode::chroma_split_tx_hits();
7472 let frames = decode_stream(&stream)
7473 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
7474 let hits = crate::decode::chroma_split_tx_hits();
7475 assert!(
7476 hits > before,
7477 "{NAME}: gate is vacuous -- no lossless chroma TX unit was read \
7478 (delta {before} -> {hits})"
7479 );
7480 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
7481 for f in &frames {
7482 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
7483 }
7484
7485 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
7486 if aomdec_available(NAME) {
7487 let dir = std::env::temp_dir().join(format!("ec-av1-ll444-{}", std::process::id()));
7488 let _ = std::fs::remove_dir_all(&dir);
7489 std::fs::create_dir_all(&dir).expect("scratch dir");
7490 let raw = dir.join("aomdec.raw");
7491 let out = Command::new(aomdec_path())
7492 .args(["--codec=av1", "--rawvideo", "-o"])
7493 .arg(&raw)
7494 .arg(&obu)
7495 .stdin(Stdio::null())
7496 .stdout(Stdio::piped())
7497 .stderr(Stdio::piped())
7498 .output()
7499 .expect("aomdec failed to run");
7500 assert!(
7501 out.status.success(),
7502 "{NAME}: the oracle aomdec refused the stream: {}",
7503 String::from_utf8_lossy(&out.stderr)
7504 );
7505 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
7506 let _ = std::fs::remove_dir_all(&dir);
7507 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
7508 for (i, f) in frames.iter().enumerate() {
7509 let base = i * W * H * 3;
7510 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
7511 .into_iter()
7512 .zip(["y", "u", "v"])
7513 {
7514 let want = &ref_raw[base + off..base + off + W * H];
7515 let bad = plane
7516 .iter()
7517 .zip(want)
7518 .filter(|&(&a, &b)| a as u8 != b)
7519 .count();
7520 assert_eq!(
7521 bad, 0,
7522 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ"
7523 );
7524 assert_eq!(
7525 plane.len(),
7526 want.len(),
7527 "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
7528 has {} -- a short plane would zip-truncate the compare above and hide \
7529 a chroma-span defect",
7530 plane.len(),
7531 want.len()
7532 );
7533 }
7534 }
7535 }
7536
7537 // ffmpeg's decoder: same frames, full-resolution chroma.
7538 if have_ffmpeg() {
7539 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
7540 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() {
7541 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
7542 .iter()
7543 .enumerate()
7544 {
7545 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
7546 assert_eq!(
7547 bad, 0,
7548 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
7549 );
7550 assert_eq!(
7551 g.len(),
7552 r.len(),
7553 "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
7554 -- a short plane would zip-truncate the compare above and hide a \
7555 chroma-span defect",
7556 g.len(),
7557 r.len()
7558 );
7559 }
7560 }
7561 } else {
7562 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
7563 }
7564 }
7565
7566 /// lane-av1h5: the 128-ROOT lossless 4:4:4 pin, and the control arm
7567 /// that proves the 128 root is what it needs.
7568 ///
7569 /// Witness: testsrc2 128x96 yuv444p10le, aomenc `--profile=1 --lossless=1
7570 /// --enable-palette=0 --enable-intrabc=0 --cpu-used=0`, 6 frames; 63429
7571 /// bytes, sha256 `bbffb979d20d581deb271aac75b7ee779dde57c024524ed6b1389356f55ca0fa`.
7572 /// Control: the same recipe at `--max-partition-size=64` (61494 bytes,
7573 /// sha256 `4cadce41e1f8967567b32f5cf8abaa46ffdf4fd6d4afe784c8d99a7f6bf1ae4c`),
7574 /// which never reaches a 128 root.
7575 ///
7576 /// libaom's `decode_token_recon_block` (`av1/decoder/decodeframe.c:972`)
7577 /// walks 64x64 "mu" chunks with the PLANE loop inside the chunk loop, on a
7578 /// chunk grid of `mi_size_wide[BLOCK_64X64]` = 16 mi per axis. The var-tx
7579 /// leaf list is a BLOCK-wide raster (32 leaves across at 128), so a chunk's
7580 /// members are not contiguous: leaves 0..15 are chunk (0,0) row 0, but
7581 /// chunk (0,0) rows 1..15 are leaves 32..47, 64..79, ... A chunk test on
7582 /// the given order closed the chunk every SIXTEEN leaves and coded each
7583 /// chunk's chroma sixteen times.
7584 ///
7585 /// The three assertions below are all EXACT and all stay true when the
7586 /// stream becomes byte-exact. None of them is a floor on wrong output:
7587 /// a no-op [`crate::decode::mu_chunk_order`] permutation reads 0 on
7588 /// `mu_chunk_order_hits`, so the first cannot be satisfied by a gate that
7589 /// merely ran; the walk and unit totals are libaom's own per-chunk counts;
7590 /// the control arm is a straight exactness assertion.
7591 #[test]
7592 fn a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major() {
7593 const NAME: &str = "a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major";
7594 const W: usize = 128;
7595 const H: usize = 96;
7596 const FRAMES: usize = 6;
7597 /// 5 inter frames, one unsplit 128 root each; frame 0 splits.
7598 const ROOTS: usize = 5;
7599 /// libaom's chunk grid on a 128x128 root: 2x2 chunks per root.
7600 const CHUNKS_PER_ROOT: usize = 4;
7601 /// Chroma TX_4X4 units per inter frame: 768 per plane over 128x96.
7602 const UNITS_PER_FRAME: usize = 1536;
7603
7604 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7605 .join("fixtures/ll444_128root_lossless.obu");
7606 let stream = read_pin(&obu, 63429, 0xf07d_47fc_fd51_2658, NAME);
7607 let _guard = lock_gate_counters();
7608 let (o0, w0, u0) = (
7609 crate::decode::mu_chunk_order_hits(),
7610 crate::decode::mu_chunk_walks(),
7611 crate::decode::mu_chunk_walk_units(),
7612 );
7613 let frames = decode_stream(&stream)
7614 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
7615 let (o1, w1, u1) = (
7616 crate::decode::mu_chunk_order_hits(),
7617 crate::decode::mu_chunk_walks(),
7618 crate::decode::mu_chunk_walk_units(),
7619 );
7620 // (1) the reorder PERMUTED each root's walk -- a no-op reads 0.
7621 assert_eq!(
7622 o1 - o0,
7623 ROOTS,
7624 "{NAME}: the chunk-major sort permuted {}/{} of the 128 roots -- a no-op \
7625 ordering must read 0 here, so this is what makes the gate non-vacuous",
7626 o1 - o0,
7627 ROOTS
7628 );
7629 // (2) libaom's own per-chunk counts: 4 chroma walks per 128 root, and
7630 // the 1536 chroma units an inter frame codes at 128x96 4:4:4.
7631 assert_eq!(
7632 w1 - w0,
7633 ROOTS * CHUNKS_PER_ROOT,
7634 "{NAME}: {}/{} chunk-major chroma walks; the 16x redundancy (64 per \
7635 frame instead of 4) would read {}",
7636 w1 - w0,
7637 ROOTS * CHUNKS_PER_ROOT,
7638 ROOTS * CHUNKS_PER_ROOT * 16
7639 );
7640 assert_eq!(
7641 u1 - u0,
7642 ROOTS * UNITS_PER_FRAME,
7643 "{NAME}: {}/{} chroma units over the 128 roots; the oracle codes {} \
7644 per inter frame and our pre-fix walk read 16x that",
7645 u1 - u0,
7646 ROOTS * UNITS_PER_FRAME,
7647 UNITS_PER_FRAME
7648 );
7649 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
7650 for f in &frames {
7651 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
7652 }
7653
7654 // (3) the control arm: no 128 root, and byte-exact through the oracle.
7655 let ctrl = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7656 .join("fixtures/ll444_minp64_128root_control.obu");
7657 let ctrl_stream = read_pin(
7658 &ctrl,
7659 61494,
7660 0xf6f5_a3cb_efc7_eb10,
7661 &format!("{NAME} control"),
7662 );
7663 let _ = decode_stream(&ctrl_stream)
7664 .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}"));
7665 if aomdec_available(NAME) {
7666 assert_rawvideo_matches(&ctrl, &ctrl_stream, NAME, FRAMES, 10);
7667 }
7668 }
7669
7670 /// lane-av1lm444loss: a LOSSLESS block's transform-unit grid is clipped at
7671 /// the FRAME edge, exactly as libaom's `max_block_high`/`max_block_wide`
7672 /// clip it (`av1_common_int.h:1565`, `:1579` fold `mb_to_bottom_edge` /
7673 /// `mb_to_right_edge` into `block_size_high/wide` before `>>
7674 /// MI_SIZE_LOG2`), so a block hanging off the bottom/right codes only the
7675 /// units inside the frame. `decode_token_recon_block` then bounds every
7676 /// mu chunk with `unit_height = ROUND_POWER_OF_TWO(AOMMIN(mu_blocks_high
7677 /// + row, max_blocks_high), ss_y)`, so the overflow units are never read
7678 /// there either.
7679 ///
7680 /// Fixture is the sibling [`a_lossless_444_128_root_lossless_stream_reads_chunks_chunk_major`]
7681 /// pin -- 128x96 yuv444p 4:4:4 lossless, 6 frames, 63429 bytes -- because
7682 /// 96 is NOT a multiple of the 128 superblock: its five inter frames each
7683 /// carry one unsplit 128 root that overhangs the bottom by 32 px. That is
7684 /// the whole reason this stream is the witness. The frame is 24 mi tall,
7685 /// so `max_blocks_high >> 2` is 24 transform rows where the block's own
7686 /// `side / MI` is 32.
7687 ///
7688 /// The three assertions are all non-vacuous and all EXACT:
7689 ///
7690 /// 1. `lossless_edge_clipped()` fired -- 5, one per inter frame's 128
7691 /// root. It is 0 on any frame whose height and width are multiples of
7692 /// the superblock, so a stream that merely decodes cannot satisfy it.
7693 /// 2. `lossless_edge_clip_units()` is 1280 = 5 x 256: the 8 transform rows
7694 /// x 32 columns the unclipped walk read past the frame bottom, per
7695 /// inter frame. The pre-fix walk read 2560 units per inter frame
7696 /// against the oracle's 2304, and this is that 256.
7697 /// 3. every sample of every frame matches the oracle `aomdec
7698 /// --rawvideo` in decode order -- all six frames, hidden alt-ref
7699 /// included, which the pre-fix tree failed from frame 1 on
7700 /// (5596 wrong samples there, growing to 33561 by frame 5).
7701 ///
7702 /// The control arm pins the other direction of the invariant: the
7703 /// `ll444_minp64_128root_control` stream has no overhanging root, so its
7704 /// clip counters must both read 0 -- the clip cannot fire on a block that
7705 /// fits, which is what keeps every other lossless pin byte-identical.
7706 #[test]
7707 fn a_lossless_block_clips_its_transform_grid_at_the_frame_edge() {
7708 const NAME: &str = "a_lossless_block_clips_its_transform_grid_at_the_frame_edge";
7709 const W: usize = 128;
7710 const H: usize = 96;
7711 const FRAMES: usize = 6;
7712 /// 5 inter frames, one unsplit 128 root each; frame 0 splits.
7713 const ROOTS: usize = 5;
7714 /// `max_blocks_high >> 2` = 24 rows (96 px / 4), against the block's
7715 /// own `side / MI` = 32 -- so 8 rows x 32 columns = 256 units per root
7716 /// were read past the frame bottom before the clip.
7717 const CLIP_UNITS_PER_ROOT: usize = 256;
7718
7719 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7720 .join("fixtures/ll444_128root_lossless.obu");
7721 let stream = read_pin(&obu, 63429, 0xf07d_47fc_fd51_2658, NAME);
7722 let _guard = lock_gate_counters();
7723 let (c0, u0) = (
7724 crate::decode::lossless_edge_clipped(),
7725 crate::decode::lossless_edge_clip_units(),
7726 );
7727 let frames = decode_stream(&stream)
7728 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
7729 let (c1, u1) = (
7730 crate::decode::lossless_edge_clipped(),
7731 crate::decode::lossless_edge_clip_units(),
7732 );
7733 assert_eq!(
7734 c1 - c0,
7735 ROOTS,
7736 "{NAME}: the frame-edge clip fired on {}/{} of the 128 roots -- it must be 0 \
7737 on a frame that fits, so this is what makes the gate non-vacuous",
7738 c1 - c0,
7739 ROOTS
7740 );
7741 assert_eq!(
7742 u1 - u0,
7743 ROOTS * CLIP_UNITS_PER_ROOT,
7744 "{NAME}: the clip removed {}/{} transform units; the unclipped walk read {} \
7745 per inter frame past the 96 px frame bottom (8 rows x 32 columns)",
7746 u1 - u0,
7747 ROOTS * CLIP_UNITS_PER_ROOT,
7748 CLIP_UNITS_PER_ROOT
7749 );
7750 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
7751 for f in &frames {
7752 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
7753 }
7754 if aomdec_available(NAME) {
7755 assert_rawvideo_matches(&obu, &stream, NAME, FRAMES, 10);
7756 }
7757
7758 // Control: a stream whose roots all fit must not clip at all.
7759 let ctrl = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7760 .join("fixtures/ll444_minp64_128root_control.obu");
7761 let ctrl_stream = read_pin(
7762 &ctrl,
7763 61494,
7764 0xf6f5_a3cb_efc7_eb10,
7765 &format!("{NAME} control"),
7766 );
7767 let (c2, u2) = (
7768 crate::decode::lossless_edge_clipped(),
7769 crate::decode::lossless_edge_clip_units(),
7770 );
7771 let _ = decode_stream(&ctrl_stream)
7772 .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}"));
7773 assert_eq!(
7774 crate::decode::lossless_edge_clipped() - c2,
7775 0,
7776 "{NAME} control: the clip fired on a stream whose blocks all fit -- the clip \
7777 must be a no-op there, which is what keeps every other lossless pin \
7778 byte-identical"
7779 );
7780 assert_eq!(
7781 crate::decode::lossless_edge_clip_units() - u2,
7782 0,
7783 "{NAME} control: the clip removed units from a stream whose blocks all fit"
7784 );
7785 }
7786
7787 /// lane-av1lm444loss-corr: the MI STEP at which `decode_intrabc_rect`'s
7788 /// lossless chroma replay walks the plane block.
7789 ///
7790 /// `lane-whtshape` (`f541d062`, merged `afa13bcf`) gave this route the
7791 /// per-TX_4X4 lossless chroma walk and the tail replay that re-stamps
7792 /// each unit's own coefficient context over the whole-block record. The
7793 /// replay stepped by `4 >> ss_y(fctx)` mi cells, which is 4:2:0-only
7794 /// arithmetic: at ss (1,1) it reads 2 and the ss-aware form
7795 /// `(4 << ss_y) / MI` also reads 2, so 4:2:0 agrees by construction; at
7796 /// ss (0,0) it reads 4 mi, i.e. 16 luma px per 4x4 chroma unit, where the
7797 /// unit covers `4 << 0` = 4 luma px = ONE mi. Every replayed unit was
7798 /// therefore stamped at 4x its own mi origin on a 4:4:4 lossless frame,
7799 /// writing over cells that belong to other blocks.
7800 ///
7801 /// This gate is the WIRNESS stream, not a vacuous one. The 4:2:0
7802 /// 4x4-identity is stated in the step's own comment and measured by the
7803 /// `4:2:0` arm of the lane's invariant battery, not asserted here --
7804 /// a 4:2:0 stream cannot fail this gate, by construction, and pretending
7805 /// otherwise would be a floor on wrong output.
7806 ///
7807 /// Fixture `ll444_intrabc_rect_l2.obu`, 121844 bytes, sha256
7808 /// `f0de080edce35d34cdd628b71f63dc452f946e8328352b69d3c1da090a54ec67`:
7809 /// `testsrc2 512x128 yuv444p`, aomenc `--lossless=1 --cpu-used=2
7810 /// --lag-in-frames=0 --kf-max-dist=100 --limit=6`, 6 frames. On main's
7811 /// step this stream is 10604 samples wrong in the KEY frame, first at
7812 /// byte 33216 (Y(64,448)) -- the corrupted chroma context desyncs the
7813 /// following luma, which is why the first divergence is luma at all.
7814 ///
7815 /// Assertions:
7816 ///
7817 /// 1. `(subsampling_x, subsampling_y, bit_depth) == (0, 0, 8)` from the
7818 /// stream's OWN parsed sequence header. At (1,1) the corrected step
7819 /// and the old one are the same number, so without this every
7820 /// assertion below would pass on a stream that cannot fail.
7821 /// 2. `intrabc_rect_lossless_chroma4_hits()` (lane-whtshape's own
7822 /// counter) is nonzero -- the replayed arm really ran, so the
7823 /// corrected expression was evaluated.
7824 /// 3. the U and V plane extents are luma-sized, which is the geometry
7825 /// the step indexes into.
7826 /// 4. `decode_all_frames_vs_oracle`: decode-order frame-count parity,
7827 /// then byte-exactness on every frame.
7828 ///
7829 /// Control: the sibling 128x96 4:4:4 lossless pin, whose blocks are
7830 /// whole and square, must not take the lossless chroma walk at all --
7831 /// its chroma plane block IS one TX_4X4, so there is no step to replay.
7832 #[test]
7833 fn a_lossless_444_intrabc_rect_replay_steps_by_the_units_own_mi_footprint() {
7834 const NAME: &str = "a_lossless_444_intrabc_rect_replay_steps_by_the_units_own_mi_footprint";
7835 const W: usize = 512;
7836 const H: usize = 128;
7837 const FRAMES: usize = 6;
7838
7839 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7840 .join("fixtures/ll444_intrabc_rect_l2.obu");
7841 let stream = read_pin(&obu, 121844, 0x38bf_968e_979c_7a0a, NAME);
7842 assert_eq!(
7843 subsampled_header_shape(&stream, NAME),
7844 (0, 0, 8),
7845 "{NAME}: the stream is not 8-bit 4:4:4 -- at ss (1,1) the corrected \
7846 step and the 4:2:0-only one are the SAME number (2 mi), so this gate \
7847 cannot fail on a 4:2:0 stream and would prove nothing there"
7848 );
7849 let _guard = lock_gate_counters();
7850 crate::decode::reset_intrabc_rect_lossless_chroma4_hits();
7851 let h0 = crate::decode::intrabc_rect_lossless_chroma4_hits();
7852 let frames = decode_stream(&stream)
7853 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
7854 let walked = crate::decode::intrabc_rect_lossless_chroma4_hits() - h0;
7855 assert!(
7856 walked > 0,
7857 "{NAME}: lane-whtshape's lossless per-TX_4X4 chroma walk never ran, so the \
7858 replayed MI step -- the thing this gate exists for -- was never evaluated"
7859 );
7860 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
7861 for f in &frames {
7862 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
7863 assert_eq!(
7864 f.u.len(),
7865 W * H,
7866 "{NAME}: U extent must be luma-sized at 4:4:4 -- the replay steps mi \
7867 cells through this grid"
7868 );
7869 assert_eq!(
7870 f.v.len(),
7871 W * H,
7872 "{NAME}: V extent must be luma-sized at 4:4:4"
7873 );
7874 }
7875 // lane-3c-a: the oracle-presence scan (wave 3b, 7a865ee7) rejects a
7876 // bare `aomdec_path().is_file()` outside the probe that owns it -- this
7877 // gate would otherwise report green under EC_AV1_REQUIRE_AOMENC=1 with
7878 // the pixel compare never run. `aomdec_available` carries both the
7879 // env-escape assertion and the SKIP line, so the else-arm is dropped.
7880 if aomdec_available(NAME) {
7881 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
7882 assert_eq!(
7883 decoded, FRAMES,
7884 "{NAME}: decoded {decoded} frames in decode order, expected {FRAMES}"
7885 );
7886 eprintln!(
7887 "{NAME}: {decoded} frames byte-exact vs aomdec ({hidden} hidden), \
7888 {walked} lossless chroma replays"
7889 );
7890 }
7891
7892 // Control: whole square blocks have no multi-unit plane block to step.
7893 let ctrl = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7894 .join("fixtures/ll444_128root_lossless.obu");
7895 let ctrl_stream = read_pin(
7896 &ctrl,
7897 63429,
7898 0xf07d_47fc_fd51_2658,
7899 &format!("{NAME} control"),
7900 );
7901 crate::decode::reset_intrabc_rect_lossless_chroma4_hits();
7902 let _ = decode_stream(&ctrl_stream)
7903 .unwrap_or_else(|e| panic!("{NAME}: the control arm no longer decodes cleanly: {e}"));
7904 assert_eq!(
7905 crate::decode::intrabc_rect_lossless_chroma4_hits(),
7906 0,
7907 "{NAME} control: the lossless chroma walk ran on a stream of whole square \
7908 blocks -- there is no multi-unit chroma plane block to replay, so the \
7909 corrected step is not exercised there at all"
7910 );
7911 }
7912
7913 /// `(subsampling_x, subsampling_y, bit_depth)` out of the stream's OWN
7914 /// sequence header. A gate that claims to exercise a subsampling-specific
7915 /// path must assert this from the parsed header, not from the recipe that
7916 /// produced the fixture: the recipe can drift (or a wrong `--pix_fmt`
7917 /// argument can silently produce a different subsampling) and every other
7918 /// assertion would then pass vacuously.
7919 fn subsampled_header_shape(stream: &[u8], name: &str) -> (u8, u8, usize) {
7920 let mut parser = Av1Parser::new();
7921 let mut pos = 0usize;
7922 let mut shape = None;
7923 while pos < stream.len() {
7924 let obu = parser
7925 .parse_obu(&stream[pos..])
7926 .unwrap_or_else(|e| panic!("{name}: OBU does not parse: {e:?}"));
7927 if obu.total_size == 0 {
7928 break;
7929 }
7930 pos += obu.total_size;
7931 if let ObuKind::SequenceHeader(seq) = obu.kind {
7932 shape = Some((
7933 seq.color_config.subsampling_x,
7934 seq.color_config.subsampling_y,
7935 seq.color_config.bit_depth as usize,
7936 ));
7937 }
7938 }
7939 shape.unwrap_or_else(|| panic!("{name}: no sequence header parsed"))
7940 }
7941
7942 /// lane-av1llpredgate2: the debug-exact pin for the ss-aware
7943 /// `obmc_skip_chroma_above` decision (lane-av1-llpred2). Fixture is the
7944 /// llpred/llpred2 reports' stream pinned into `fixtures/`: testsrc2
7945 /// 128x96 yuv444p, aomenc `--profile=1 --lossless=1 --enable-palette=0
7946 /// --enable-intrabc=0 --min-partition-size=8 --max-partition-size=64`,
7947 /// 6 frames; 34037 bytes, sha256
7948 /// `04fb6d38de5382e647bfb70b6a17802f1fccc5502e6698c0394167891f2b27dc`.
7949 ///
7950 /// This is a DEBUG-build path by construction: the old ratio-based ss
7951 /// derivation read `write_h >> trailing_zeros(0)` = `>> 64` on this
7952 /// stream's 4:4:4 OBMC rect strips, a panic ONLY under
7953 /// debug_assertions (release wraps and was already byte-exact), so
7954 /// `cargo test`'s default dev profile is the profile where the defect
7955 /// class reproduces and where the parent's byte-exact proof was
7956 /// measured.
7957 ///
7958 /// No skip-arm counter gate is possible on this stream, measured:
7959 /// OBMC runs 77 times with 20 rect leaves, but
7960 /// `obmc_skip_chroma_above` returns true 0 times -- at 4:4:4 the skip
7961 /// needs a 4x4/8x4/4x8 PLANE block and min-partition-8 never codes one.
7962 /// So per the lane ticket the proof splits in two: the decision TABLE
7963 /// (4:2:0 rect strips still skip, 4:4:4 shifts never leave `usize`)
7964 /// stays pinned by `decode::obmc_skip_chroma_tests::
7965 /// rect_strips_skip_above_chroma_at_420_and_shift_never_overflows`,
7966 /// and THIS stream gate pins the end-to-end behaviour -- every sample
7967 /// of every frame must match the oracle aomdec exactly, so a returning
7968 /// chroma diff (the lane-av1-llpred ss-blind re-blend class
7969 /// `obmc-ss-blind-chroma-above`) or the debug shift panic goes red
7970 /// here by name.
7971 #[test]
7972 fn a_lossless_444_min_partition8_inter_stream_decodes_sample_exact() {
7973 const NAME: &str = "a_lossless_444_min_partition8_inter_stream_decodes_sample_exact";
7974 const FIXTURE_LEN: usize = 34037;
7975 const FIXTURE_FNV: u64 = 0x2c8f_4a2c_c025_52da;
7976 const W: usize = 128;
7977 const H: usize = 96;
7978 const FRAMES: usize = 6;
7979 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7980 .join("fixtures/ll444_minp8_inter.obu");
7981 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
7982 panic!(
7983 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
7984 which is a failure, not a skip",
7985 obu.display()
7986 )
7987 });
7988 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
7989 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
7990
7991 let _guard = lock_gate_counters();
7992 let frames = decode_stream(&stream)
7993 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
7994 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
7995 for f in &frames {
7996 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
7997 }
7998
7999 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
8000 if aomdec_available(NAME) {
8001 let dir = std::env::temp_dir().join(format!("ec-av1-llminp8-{}", std::process::id()));
8002 let _ = std::fs::remove_dir_all(&dir);
8003 std::fs::create_dir_all(&dir).expect("scratch dir");
8004 let raw = dir.join("aomdec.raw");
8005 let out = Command::new(aomdec_path())
8006 .args(["--codec=av1", "--rawvideo", "-o"])
8007 .arg(&raw)
8008 .arg(&obu)
8009 .stdin(Stdio::null())
8010 .stdout(Stdio::piped())
8011 .stderr(Stdio::piped())
8012 .output()
8013 .expect("aomdec failed to run");
8014 assert!(
8015 out.status.success(),
8016 "{NAME}: the oracle aomdec refused the stream: {}",
8017 String::from_utf8_lossy(&out.stderr)
8018 );
8019 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
8020 let _ = std::fs::remove_dir_all(&dir);
8021 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
8022 for (i, f) in frames.iter().enumerate() {
8023 let base = i * W * H * 3;
8024 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
8025 .into_iter()
8026 .zip(["y", "u", "v"])
8027 {
8028 let want = &ref_raw[base + off..base + off + W * H];
8029 let bad = plane
8030 .iter()
8031 .zip(want)
8032 .filter(|&(&a, &b)| a as u8 != b)
8033 .count();
8034 assert_eq!(
8035 bad, 0,
8036 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \
8037 (class obmc-ss-blind-chroma-above)"
8038 );
8039 assert_eq!(
8040 plane.len(),
8041 want.len(),
8042 "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
8043 has {} -- a short plane would zip-truncate the compare above and hide \
8044 a chroma-span defect",
8045 plane.len(),
8046 want.len()
8047 );
8048 }
8049 }
8050 }
8051
8052 // ffmpeg's decoder: same frames, full-resolution chroma.
8053 if have_ffmpeg() {
8054 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
8055 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() {
8056 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
8057 .iter()
8058 .enumerate()
8059 {
8060 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
8061 assert_eq!(
8062 bad, 0,
8063 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
8064 );
8065 assert_eq!(
8066 g.len(),
8067 r.len(),
8068 "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
8069 -- a short plane would zip-truncate the compare above and hide a \
8070 chroma-span defect",
8071 g.len(),
8072 r.len()
8073 );
8074 }
8075 }
8076 } else {
8077 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
8078 }
8079 }
8080
8081 /// lane-av1-444sb: the byte-exact pin for the ss-aware 128-rect chroma
8082 /// unit walk (`decode_block_128rect`). The parent walk hardcoded the
8083 /// 4:2:0 mu-chunk span -- one 32x32 chroma unit per 64x64 chunk, chunk
8084 /// offsets `*32`, clip step `*8` -- so at 4:4:4 a 128-root HORZ/VERT
8085 /// intra block coded HALF its chroma units, left the remaining units'
8086 /// coefficients unread and desynced the tile from the first such block
8087 /// on; every superblock after SB(0,0) carried damage and the chroma
8088 /// first-diffs sat on the 64/128 grid.
8089 ///
8090 /// `crates/ec-av1/fixtures/444_sb128rect_lr_witness.obu`, 794 bytes,
8091 /// sha256
8092 /// `27825e14633a4b23e37d48a2acdc7f5d814ca4fadd0b8797d72a1ffb34061e80`:
8093 /// `ffmpeg -i bands444.y4m -frames:v 3 -vf scale=192:160 -pix_fmt
8094 /// yuv444p -f yuv4mpegpipe` piped to `aomenc --codec=av1 --profile=1
8095 /// --passes=1 --end-usage=q --cq-level=32 --cpu-used=0 --threads=1
8096 /// --row-mt=0 --sb-size=128 --lag-in-frames=0 --auto-alt-ref=0
8097 /// --kf-max-dist=1000 --i444 --enable-restoration=1 --obu --limit=3`.
8098 /// Real content is required: the synthetic lavfi sources this lane swept
8099 /// (testsrc2/testsrc/smptebars/mandelbrot/gradients) all decode frame 0
8100 /// exact because they never force a 128-root rect; bands does (kf
8101 /// PARTITION_VERT 64x128 at mi(0,32) plus an intra-in-inter 64x128).
8102 ///
8103 /// Non-vacuity via the `decode::intra_sb128_hits` delta: a stream that
8104 /// stopped coding 128-axis intra blocks reads 0 and the gate fails
8105 /// instead of passing over a decode that never reached the fixed body
8106 /// (class `gate-blind-to-feature`). The oracle arms pin every sample of
8107 /// every frame against both aomdec and ffmpeg, so a returning chroma
8108 /// span regression goes red here by name.
8109 #[test]
8110 fn a_444_sb128_root_rect_stream_with_restoration_decodes_pixel_exact() {
8111 const NAME: &str = "a_444_sb128_root_rect_stream_with_restoration_decodes_pixel_exact";
8112 const FIXTURE_LEN: usize = 794;
8113 const FIXTURE_FNV: u64 = 0xf5a7_27f4_3fa7_abc3;
8114 const W: usize = 192;
8115 const H: usize = 160;
8116 const FRAMES: usize = 3;
8117 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8118 .join("fixtures/444_sb128rect_lr_witness.obu");
8119 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
8120 panic!(
8121 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
8122 which is a failure, not a skip",
8123 obu.display()
8124 )
8125 });
8126 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
8127 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
8128
8129 let _guard = lock_gate_counters();
8130 let before = crate::decode::intra_sb128_hits();
8131 let before_replay = crate::decode::sb128rect_chroma_replay_hits();
8132 let frames = decode_stream(&stream)
8133 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
8134 let (horz, vert, _) = crate::decode::intra_sb128_hits();
8135 assert!(
8136 horz - before.0 + (vert - before.1) > 0,
8137 "{NAME}: this stream coded NO 128-axis intra block -- the fixed body \
8138 never ran (class gate-blind-to-feature)"
8139 );
8140 // lane-av1-128rectspan: the block-level `record_split_luma_rect`
8141 // above clobbers the per-unit chroma contexts, so every coded unit
8142 // replays its own state after it -- the arm the span fix sits on.
8143 // The delta keeps THAT arm non-vacuous (a 128-root rect stream that
8144 // stopped replaying reads 0), and the mismatch half is the 4:2:2
8145 // signature: this stream is 4:4:4 (ss 0,0), where the unit's luma
8146 // width and height are equal, so a replay that stamped one axis with
8147 // the other's span would still read 0 here -- the counter is what
8148 // names the day 4:2:2 (ss 1,0, refused by name at the sequence
8149 // header) is admitted, rather than letting the 8-row spill below the
8150 // block corrupt the next block's `txb_skip` silently.
8151 let after_replay = crate::decode::sb128rect_chroma_replay_hits();
8152 assert!(
8153 after_replay.0 > before_replay.0,
8154 "{NAME}: no 128-root rect block replayed a chroma unit's own mi state -- the \
8155 replay arm never ran (class gate-blind-to-feature)"
8156 );
8157 assert_eq!(
8158 after_replay.1,
8159 before_replay.1,
8160 "{NAME}: the tail replay stamped {} unit(s) over a height that was not the \
8161 unit's own luma height (4:2:2 spans leaked into an admitted stream)",
8162 after_replay.1 - before_replay.1
8163 );
8164 eprintln!(
8165 "{NAME}: replayed {} chroma unit(s), {} span mismatch(es)",
8166 after_replay.0 - before_replay.0,
8167 after_replay.1 - before_replay.1
8168 );
8169 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
8170 for f in &frames {
8171 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
8172 }
8173 // All three frames are pinned byte-exact against both oracles (the
8174 // aomdec/ffmpeg arms below run over `.take(3)`): frame 0's keyframe
8175 // PARTITION_VERT 64x128, frame 1's inter pieces, and frame 2 -- whose
8176 // right superblock column (the 128-root VERT piece at the frame edge)
8177 // is three intra blocks (64x64, 64x32, 64x32) whose chroma units ride
8178 // the inter-frame intra tail. That tail read ONE whole-plane chroma
8179 // unit with the block-level context where 4:4:4 codes four
8180 // plane-major TX_32X32 units with per-unit contexts and the
8181 // offset-10 `get_txb_ctx` rows, which left three quarters of the
8182 // planes' residual unread and misaligned the symbol stream from the
8183 // first chroma unit on (f2 PREFILT Y 6952 / U 9568 / V 13496, first
8184 // diffs entering at column 128). Fixed on lane-av1-rect128recon;
8185 // the earlier "LR never restores RU row 0" attribution on this frame
8186 // was a stage-ladder mixup, refuted in lane-av1lrflush r3.
8187
8188 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
8189 if aomdec_available(NAME) {
8190 let dir = std::env::temp_dir().join(format!("ec-av1-444sb-{}", std::process::id()));
8191 let _ = std::fs::remove_dir_all(&dir);
8192 std::fs::create_dir_all(&dir).expect("scratch dir");
8193 let raw = dir.join("aomdec.raw");
8194 let out = Command::new(aomdec_path())
8195 .args(["--codec=av1", "--rawvideo", "-o"])
8196 .arg(&raw)
8197 .arg(&obu)
8198 .stdin(Stdio::null())
8199 .stdout(Stdio::piped())
8200 .stderr(Stdio::piped())
8201 .output()
8202 .expect("aomdec failed to run");
8203 assert!(
8204 out.status.success(),
8205 "{NAME}: the oracle aomdec refused the stream: {}",
8206 String::from_utf8_lossy(&out.stderr)
8207 );
8208 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
8209 let _ = std::fs::remove_dir_all(&dir);
8210 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
8211 for (i, f) in frames.iter().enumerate().take(3) {
8212 let base = i * W * H * 3;
8213 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
8214 .into_iter()
8215 .zip(["y", "u", "v"])
8216 {
8217 let want = &ref_raw[base + off..base + off + W * H];
8218 let bad = plane
8219 .iter()
8220 .zip(want)
8221 .filter(|&(&a, &b)| a as u8 != b)
8222 .count();
8223 assert_eq!(
8224 bad, 0,
8225 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \
8226 (class 444-128rect-chroma-span)"
8227 );
8228 assert_eq!(
8229 plane.len(),
8230 want.len(),
8231 "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
8232 has {} -- a short plane would zip-truncate the compare above and hide \
8233 a chroma-span defect",
8234 plane.len(),
8235 want.len()
8236 );
8237 }
8238 }
8239 }
8240
8241 // ffmpeg's decoder: same frames, full-resolution chroma. Same
8242 // three-frame scope as the aomdec arm above.
8243 if have_ffmpeg() {
8244 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
8245 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate().take(3) {
8246 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
8247 .iter()
8248 .enumerate()
8249 {
8250 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
8251 assert_eq!(
8252 bad, 0,
8253 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
8254 );
8255 assert_eq!(
8256 g.len(),
8257 r.len(),
8258 "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
8259 -- a short plane would zip-truncate the compare above and hide a \
8260 chroma-span defect",
8261 g.len(),
8262 r.len()
8263 );
8264 }
8265 }
8266 } else {
8267 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
8268 }
8269 }
8270
8271 /// lane-av1444rect (H1): the 4:4:4 LOSSY cell with a 1:4 (HORZ_4 /
8272 /// VERT_4) partition -- the largest correctness gap the chroma-format
8273 /// sweep left, and the first 4:4:4 lossy exactness gate in the crate.
8274 ///
8275 /// **The defect.** `decode_inter_block`'s `around_c` gathered a 1:4
8276 /// strip's chroma coefficient context at the 4:2:0 PAIR extent
8277 /// (`(16, 8)` HORZ / `(8, 16)` VERT) with no `ss` gate, so at ss (0,0)
8278 /// it read one extra luma mi row of LEFT chroma context. At 4:4:4
8279 /// `is_chroma_reference` (av1_common_int.h:1454) reduces both parity
8280 /// clauses to `!subsampling_y` / `!subsampling_x`, so every block is its
8281 /// own chroma reference and no pair exists: the strip codes its own
8282 /// 16x4 chroma over its own context. Our U unit's `get_txb_ctx` then saw
8283 /// a neighbour libaom does not have, and the arithmetic coder forked.
8284 ///
8285 /// **The recipe** (sha256
8286 /// `77f727e76d81fe48cd03709f799131677c04869b163e18d78e96bc742ec69153`,
8287 /// 6441 bytes, 2 frames, `testsrc2 128x96 rate=25` yuv444p):
8288 /// ```text
8289 /// ffmpeg -f lavfi -i "testsrc2=size=128x96:rate=25" -frames:v 2 \
8290 /// -pix_fmt yuv444p -f yuv4mpegpipe - | \
8291 /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=20 \
8292 /// --cpu-used=2 --threads=1 --row-mt=0 --lag-in-frames=0 \
8293 /// --kf-max-dist=100 --limit=2 - out.obu
8294 /// ```
8295 /// (`rate=25` is load-bearing: `testsrc2`'s pattern is time-parameterised,
8296 /// so `rate=1` produces a different, already-exact stream.)
8297 ///
8298 /// Red before the fix: frame 1, 8884 of 36864 samples wrong, first at
8299 /// Y(91,32); the first wrong symbol was read 26263 of the frame, both
8300 /// sides at mi (8,16) -- ours a luma-shaped `txb_skip` row (our
8301 /// re-indexed chroma ctx 1), the oracle `decodetxb.c:158` on the U plane
8302 /// with `txb_skip_ctx = 7`.
8303 ///
8304 /// Non-vacuity, three ways: the pinned stream must really be ss (0,0)
8305 /// (asserted through the oracle aomdec's own sequence header, below);
8306 /// `decode::rect4_inter_own_chroma444_hits()` must be non-zero, so the
8307 /// 1:4-strip route the fix sits on really ran; and the SAME source and
8308 /// flags at 4:2:0 must leave that counter at zero, which is what makes
8309 /// it the 4:4:4-only route rather than a tally every strip bumps.
8310 #[test]
8311 fn a_444_lossy_rect4_inter_stream_decodes_pixel_exact() {
8312 const NAME: &str = "a_444_lossy_rect4_inter_stream_decodes_pixel_exact";
8313 const FIXTURE_LEN: usize = 6441;
8314 const FIXTURE_FNV: u64 = 0x0436_8b2d_2e91_72b0;
8315 const W: usize = 128;
8316 const H: usize = 96;
8317 const FRAMES: usize = 2;
8318 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8319 .join("fixtures/444_lossy_rect4_inter_witness.obu");
8320 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
8321 panic!(
8322 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
8323 which is a failure, not a skip",
8324 obu.display()
8325 )
8326 });
8327 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
8328 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
8329
8330 let _guard = lock_gate_counters();
8331 crate::decode::reset_rect4_inter_own_chroma444_hits();
8332 let frames = decode_stream(&stream).unwrap_or_else(|e| {
8333 panic!("{NAME}: the pinned 4:4:4 lossy stream no longer decodes cleanly: {e}")
8334 });
8335 let own_chroma = crate::decode::rect4_inter_own_chroma444_hits();
8336 assert!(
8337 own_chroma > 0,
8338 "{NAME}: no 1:4 inter strip read its chroma context over its own \
8339 extent -- the corrected route never ran (class gate-blind-to-feature)"
8340 );
8341 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
8342 for (i, f) in frames.iter().enumerate() {
8343 assert_eq!((f.width, f.height), (W, H), "{NAME}: frame {i} dimensions");
8344 // At 4:4:4 the chroma planes are full resolution. A decoder that
8345 // kept the 4:2:0 extent would hand quarter-size chroma planes to
8346 // the byte compare below, which cannot pass -- but say so here
8347 // rather than let the compare stand in for the shape claim.
8348 assert_eq!(
8349 f.u.len(),
8350 W * H,
8351 "{NAME}: frame {i} chroma plane is {} samples; at 4:4:4 it must be \
8352 full resolution ({W}x{H})",
8353 f.u.len()
8354 );
8355 }
8356 if aomdec_available(NAME) {
8357 let (decoded, _hidden) = decode_all_frames_vs_oracle(&stream, NAME);
8358 eprintln!(
8359 "{NAME}: {decoded} frame(s) byte-exact vs aomdec, {own_chroma} \
8360 own-extent 1:4 chroma gather(s)"
8361 );
8362 }
8363
8364 // The specificity arm: the SAME source, flags and 1:4 partitions at
8365 // 4:2:0 must not touch the 4:4:4-only route. If a later change made
8366 // the counter fire everywhere, this arm is what catches it.
8367 if !have_aomenc() {
8368 eprintln!("{NAME}: no aomenc, 4:2:0 specificity arm skipped");
8369 return;
8370 }
8371 let source = format!("testsrc2=size={W}x{H}:rate=25");
8372 let y4m = Command::new("ffmpeg")
8373 .args([
8374 "-v",
8375 "error",
8376 "-f",
8377 "lavfi",
8378 "-i",
8379 &source,
8380 "-frames:v",
8381 "2",
8382 "-pix_fmt",
8383 "yuv420p",
8384 "-strict",
8385 "-1",
8386 "-f",
8387 "yuv4mpegpipe",
8388 "-",
8389 ])
8390 .stdin(Stdio::null())
8391 .stdout(Stdio::piped())
8392 .stderr(Stdio::piped())
8393 .output()
8394 .expect("ffmpeg failed to run");
8395 assert!(
8396 y4m.status.success(),
8397 "{NAME}: ffmpeg refused the 4:2:0 control source: {}",
8398 String::from_utf8_lossy(&y4m.stderr)
8399 );
8400 let out = run_with_stdin(
8401 Command::new(aomenc_path()).args([
8402 "--codec=av1",
8403 "--passes=1",
8404 "--end-usage=q",
8405 "--cq-level=20",
8406 "--cpu-used=2",
8407 "--threads=1",
8408 "--row-mt=0",
8409 "--lag-in-frames=0",
8410 "--kf-max-dist=100",
8411 "--limit=2",
8412 "--obu",
8413 "-o",
8414 "-",
8415 "-",
8416 ]),
8417 &y4m.stdout,
8418 );
8419 assert!(
8420 out.status.success(),
8421 "{NAME}: aomenc refused the 4:2:0 control recipe: {}",
8422 String::from_utf8_lossy(&out.stderr)
8423 );
8424 crate::decode::reset_rect4_inter_own_chroma444_hits();
8425 decode_stream(&out.stdout)
8426 .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 control stream was refused: {e}"));
8427 let (h4, v4, _, _) = crate::decode::inter16_rect4_counters();
8428 // The control must actually code 1:4 inter strips, or it says nothing
8429 // about the arm the fix touches. Measured: 16 HORZ_4, 28 VERT_4.
8430 assert!(
8431 h4 + v4 > 0,
8432 "{NAME}: the 4:2:0 control coded NO 1:4 inter strip ({h4} HORZ_4, {v4} \
8433 VERT_4) -- the identity arm below would say nothing about 1:4 strips"
8434 );
8435 assert_eq!(
8436 crate::decode::rect4_inter_own_chroma444_hits(),
8437 0,
8438 "{NAME}: the 4:2:0 control fired the ss_x-0 own-extent route -- the route \
8439 is not specific to the 4:4:4 cell it was fixed for"
8440 );
8441 // The identity half: the fix adds an arm gated on `ss_x == 0`, so a
8442 // 4:2:0 stream must stay byte-exact through it. This is the arm that
8443 // would go red if the new arm were ever widened past ss_x 0.
8444 if aomdec_available(NAME) {
8445 decode_all_frames_vs_oracle(&out.stdout, &format!("{NAME}-420"));
8446 }
8447 eprintln!("{NAME}: 4:2:0 control {h4} HORZ_4 / {v4} VERT_4 strips, 0 own-extent gathers");
8448 }
8449 /// lane-av1gates444: the live 4:4:4 LOSSY cell the chroma-format sweep
8450 /// measured EXACT 4/4 and left unpinned. The recipe is the sweep's own
8451 /// §6.2 encode, reproduced LIVE against the oracle `aomenc` rather than
8452 /// from a pin, because the claim these three gates carry is a property
8453 /// of the *decoder* at a geometry, not of a blob:
8454 /// ```text
8455 /// ffmpeg -f lavfi -i "testsrc2=size=<W>x<H>:rate=25" -frames:v 4 \
8456 /// -pix_fmt yuv444p -f yuv4mpegpipe - | \
8457 /// aomenc --codec=av1 --profile=1 --passes=1 --end-usage=q --cq-level=20 \
8458 /// --cpu-used=2 --threads=1 --row-mt=0 --lag-in-frames=0 \
8459 /// --kf-max-dist=100 --limit=4 --obu -o - -
8460 /// ```
8461 /// `rate=25` is load-bearing (testsrc2's pattern is time-parameterised)
8462 /// and `--limit=4` is the sweep's frame count: at `--limit=6` the same
8463 /// recipe emits 7674 / 11465 / 19121 bytes instead of the sweep's
8464 /// 5938 / 8945 / 15239, i.e. a different stream than the one measured.
8465 /// `--profile=1` is what makes the source 4:4:4 at all.
8466 ///
8467 /// Every assertion here is a non-vacuity assertion first and a pixel
8468 /// compare second. The frame count, the per-frame geometry and the
8469 /// FULL-RESOLUTION chroma plane length are asserted because a truncated
8470 /// or 4:2:0-shaped decode can pass a lenient compare; the
8471 /// `rect4_inter_own_chroma444_hits()` reach assert is there because the
8472 /// class these cells belong to is the 4:4:4-only own-chroma-extent route
8473 /// in [`decode_inter_block`]'s `around_c` (a 4:2:0 stream of the same
8474 /// content leaves it at 0), and a counter at 0 would mean the gate
8475 /// measured a different route than it names.
8476 /// The guard is [`have_aomenc`], which probes first and asserts LAST with
8477 /// the env escape: with `EC_AV1_REQUIRE_AOMENC` set, a missing oracle is
8478 /// a hard failure naming the path it looked for, and a batch run cannot
8479 /// report green off three skipped gates. With it unset the `None` below is
8480 /// a developer-only convenience for a checkout without an oracle -- it is
8481 /// the ONLY way this gate can return without measuring, and it announces
8482 /// itself on stderr naming the env var that would make it a failure.
8483 /// (It used to return an empty `Vec` that the caller turned into a silent
8484 /// early `return`: the same green, reached through a second exit nobody
8485 /// was reading.)
8486 fn encode_444_lossy_live(name: &str, w: usize, h: usize) -> Option<Vec<u8>> {
8487 if !have_aomenc() {
8488 eprintln!(
8489 "SKIP {name}: no aomenc oracle at {} -- set EC_AV1_REQUIRE_AOMENC=1 to make this \
8490 a failure, or run scripts/build-aom-oracle.sh",
8491 aomenc_path().display()
8492 );
8493 return None;
8494 }
8495 let source = format!("testsrc2=size={w}x{h}:rate=25");
8496 let y4m = Command::new("ffmpeg")
8497 .args([
8498 "-v",
8499 "error",
8500 "-f",
8501 "lavfi",
8502 "-i",
8503 &source,
8504 "-frames:v",
8505 "4",
8506 "-pix_fmt",
8507 "yuv444p",
8508 "-f",
8509 "yuv4mpegpipe",
8510 "-",
8511 ])
8512 .stdin(Stdio::null())
8513 .stdout(Stdio::piped())
8514 .stderr(Stdio::piped())
8515 .output()
8516 .expect("ffmpeg failed to run");
8517 assert!(
8518 y4m.status.success(),
8519 "{name}: ffmpeg refused the {w}x{h} 4:4:4 source: {}",
8520 String::from_utf8_lossy(&y4m.stderr)
8521 );
8522 let out = run_with_stdin(
8523 Command::new(aomenc_path()).args([
8524 "--codec=av1",
8525 "--profile=1",
8526 "--passes=1",
8527 "--end-usage=q",
8528 "--cq-level=20",
8529 "--cpu-used=2",
8530 "--threads=1",
8531 "--row-mt=0",
8532 "--lag-in-frames=0",
8533 "--kf-max-dist=100",
8534 "--limit=4",
8535 "--obu",
8536 "-o",
8537 "-",
8538 "-",
8539 ]),
8540 &y4m.stdout,
8541 );
8542 assert!(
8543 out.status.success(),
8544 "{name}: aomenc refused the {w}x{h} 4:4:4 lossy recipe: {}",
8545 String::from_utf8_lossy(&out.stderr)
8546 );
8547 assert!(
8548 !out.stdout.is_empty(),
8549 "{name}: aomenc produced no OBU for {w}x{h} -- a zero-length stream would \
8550 decode to nothing and the compare below would compare nothing"
8551 );
8552 Some(out.stdout)
8553 }
8554
8555 /// The body every 4:4:4 lossy live gate runs: assert the oracle compare
8556 /// CANNOT be skipped, assert the decode really is the cell it claims
8557 /// (frame count, geometry, full-resolution chroma), assert the 4:4:4-only
8558 /// own-extent route really ran, then compare every frame in decode order
8559 /// against the oracle aomdec with the length asserted first.
8560 ///
8561 /// The aomdec arm is a HARD failure, not a skip: these three gates encode
8562 /// LIVE, so reaching this point means the oracle aomenc resolved, and
8563 /// aomenc and aomdec ship in the same build directory -- an aomdec that is
8564 /// missing beside a present aomenc is a broken oracle, not a checkout
8565 /// without one. (The older shape, `if aomdec_path().is_file()`, let the
8566 /// compare vanish with no env escape at all; that is what
8567 /// [`aomdec_available`] replaced for the pinned gates, and it cannot be
8568 /// used here because these gates have no stream to compare without one.)
8569 fn gate_444_lossy_live_exact(name: &str, w: usize, h: usize) {
8570 // The ONLY way out without measuring, and it has already printed a
8571 // SKIP naming the env var that would turn it into a failure.
8572 let Some(stream) = encode_444_lossy_live(name, w, h) else {
8573 return;
8574 };
8575 assert!(
8576 aomdec_path().is_file(),
8577 "{name}: the oracle aomenc resolved to {} but no aomdec sits beside it at {} -- \
8578 the pixel compare would silently skip, which this gate treats as a failure",
8579 aomenc_path().display(),
8580 aomdec_path().display()
8581 );
8582
8583 let _guard = lock_gate_counters();
8584 crate::decode::reset_rect4_inter_own_chroma444_hits();
8585 let frames = decode_stream(&stream).unwrap_or_else(|e| {
8586 panic!("{name}: the live {w}x{h} 4:4:4 lossy stream was refused: {e}")
8587 });
8588 let own = crate::decode::rect4_inter_own_chroma444_hits();
8589 assert!(
8590 own > 0,
8591 "{name}: no 4:4:4 1:4 inter strip read its chroma context over its own extent -- \
8592 the route this cell is a witness for never ran (measured: 13 at 66x66, 12 at \
8593 130x122, 24 at 256x128)"
8594 );
8595 assert_eq!(
8596 frames.len(),
8597 4,
8598 "{name}: decoded {} frame(s), the recipe encodes 4 -- a short decode would make the \
8599 oracle compare cover a prefix of the cell",
8600 frames.len()
8601 );
8602 for (i, f) in frames.iter().enumerate() {
8603 assert_eq!(
8604 (f.width, f.height),
8605 (w, h),
8606 "{name}: frame {i} is {}x{}, the cell is {w}x{h}",
8607 f.width,
8608 f.height
8609 );
8610 // At 4:4:4 both chroma planes are full resolution. A decoder that
8611 // kept a subsampled extent would hand quarter-size planes to the
8612 // byte compare; say so here instead of letting the compare
8613 // stand in for the shape claim.
8614 assert_eq!(
8615 f.u.len(),
8616 w * h,
8617 "{name}: frame {i} U plane is {} samples; at 4:4:4 it must be full resolution \
8618 ({w}x{h})",
8619 f.u.len()
8620 );
8621 assert_eq!(
8622 f.v.len(),
8623 w * h,
8624 "{name}: frame {i} V plane is {} samples; at 4:4:4 it must be full resolution \
8625 ({w}x{h})",
8626 f.v.len()
8627 );
8628 assert_eq!(
8629 f.y.len(),
8630 w * h,
8631 "{name}: frame {i} luma plane is {} samples, expected {w}x{h}",
8632 f.y.len()
8633 );
8634 }
8635 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, name);
8636 assert_eq!(
8637 decoded, 4,
8638 "{name}: the oracle decoded {decoded} frame(s) in decode order, the recipe carries 4 \
8639 (so far {hidden} hidden)"
8640 );
8641 eprintln!(
8642 "{name}: {w}x{h} 4:4:4 lossy, {decoded} decode-order frame(s) byte-exact vs aomdec \
8643 ({hidden} hidden), {own} own-extent 1:4 chroma gather(s)"
8644 );
8645 }
8646
8647 /// lane-av1gates444 cell 1: **odd coded dims, 66x66** -- the partial-frame
8648 /// walk in BOTH axes (66 is not a multiple of 8, so the frame is a
8649 /// partial superblock column AND a partial row). Measured EXACT 4/4 by
8650 /// the chroma-format sweep (§6.2, 5938 bytes) and unpinned: nothing in
8651 /// the crate would go red if the odd-dimension 4:4:4 walk regressed,
8652 /// and the only red-before evidence was a lane report nobody re-runs.
8653 #[test]
8654 fn a_444_lossy_odd_66x66_stream_decodes_pixel_exact() {
8655 gate_444_lossy_live_exact("a_444_lossy_odd_66x66_stream_decodes_pixel_exact", 66, 66);
8656 }
8657
8658 /// lane-av1gates444 cell 2: **odd coded dims, 130x122** -- the
8659 /// partial-frame RIGHT edge that the sweep found DIVERGENT (first wrong
8660 /// sample Y(128,16), 11521 samples on frame 3) until lane-av1444rect's
8661 /// 4:4:4 own-chroma-extent fix landed. It measures EXACT 4/4 on this
8662 /// tree and is the discriminating geometry: 66x66 was exact at the same
8663 /// settings while this was not, so the pair is what keeps "the 4:4:4
8664 /// partial-frame walk is right" from being a one-geometry accident.
8665 #[test]
8666 fn a_444_lossy_odd_130x122_stream_decodes_pixel_exact() {
8667 gate_444_lossy_live_exact(
8668 "a_444_lossy_odd_130x122_stream_decodes_pixel_exact",
8669 130,
8670 122,
8671 );
8672 }
8673
8674 /// lane-av1gates444 cell 3: **256x128**, the sweep's cell recorded as
8675 /// "4:4:4 superres 256x128 (`--superres-mode=1`)".
8676 ///
8677 /// IT IS NOT A SUPERRES CELL, and this gate is named for what it is
8678 /// instead. Measured here, live: encoding 256x128 with and without
8679 /// `--superres-mode=1` produces BYTE-IDENTICAL OBU (15239 bytes,
8680 /// sha256 06621606…, both), so the flag is a no-op on this aomenc build
8681 /// and the sweep's cell was a plain 4:4:4 lossy cq-20 stream that
8682 /// happened to carry the flag. The cell's actual value is the geometry
8683 /// plus the filter stages: 256x128 is two full 128 superblock columns,
8684 /// and the strip walk runs there with the post-deblock/CDEF/LR chain
8685 /// live on the later frames -- so this is the third witness for the
8686 /// 4:4:4 lossy strip class at a geometry the 128x96 rect4 gate does not
8687 /// cover.
8688 #[test]
8689 fn a_444_lossy_256x128_stream_decodes_pixel_exact() {
8690 gate_444_lossy_live_exact("a_444_lossy_256x128_stream_decodes_pixel_exact", 256, 128);
8691 }
8692 /// lane-av1txctxband — the 4:4:4 lossy `--sb-size=128` stream whose
8693 /// `EC_SYMR` ladder forked at read 32813, and the gate that makes the fix
8694 /// non-vacuous.
8695 ///
8696 /// **The defect.** `get_tx_size_context` (libaom
8697 /// `av1/common/pred_common.h:361-370`) gates its "an inter neighbour
8698 /// contributes its own BLOCK size" override on `xd->above_mbmi` /
8699 /// `xd->left_mbmi`, which `set_mi_offsets`
8700 /// (`av1_common_int.h:1381-1389`) takes as `xd->mi[-xd->mi_stride]` /
8701 /// `xd->mi[-1]`. `setup_mbs` (`decodeframe.c:355-361`) writes the covering
8702 /// block's own `MB_MODE_INFO` pointer into EVERY mi cell the block covers,
8703 /// so libaom's granularity is the covering block PER CELL. This decoder
8704 /// read the per-COLUMN `above_inter`/`left_inter` bands and the matching
8705 /// `above_side_mi`/`left_side_mi` bands instead — the LAST block written in
8706 /// that column, which names the abutting block only for the block directly
8707 /// below it. On this witness the 8x4 intra leaf at mi(57,52) (SB row 1,
8708 /// col 1) read a stale `above_inter=true` with `above_side=4`, took the
8709 /// override, got `above = (4 >= 8) = 0` where libaom keeps
8710 /// `above = (above_txfm_context[0] >= 8) = 1`, and read
8711 /// `tx_size_cat0[1]` where libaom reads `tx_size_cdf[...][2]`.
8712 ///
8713 /// **The fork signature that identifies it** (a CDF-row error, not a
8714 /// unit-enumeration one): the two sides held the IDENTICAL pre-state
8715 /// `pre=(7550, 45492)` and the IDENTICAL width/value `n=2 s=1`; only
8716 /// `cdf0` differed, ours 6424 (`32768-6424 = 26344`) vs the oracle's
8717 /// 19938, so the ICDF mirror convention does not reconcile it either.
8718 ///
8719 /// **Non-vacuity.** The pixel assert alone would be green on the old code
8720 /// for any stream where the bands happened to be right, so the gate also
8721 /// asserts `txctx_inter_cell_band_divergence_hits() > 0` — the number of
8722 /// `get_tx_size_context` reads where the per-CELL cover and the
8723 /// per-COLUMN band DISAGREE, i.e. exactly the reads the old code resolved
8724 /// off a different CDF row. Reverting either reader to the bands drives
8725 /// this to 0 and the gate red, with the oracle compare as the second,
8726 /// independent arm.
8727 ///
8728 /// **Fixture provenance** (`444_lossy_sb128_txctx_witness.obu`, 6186 B,
8729 /// sha256 `14acb74e825a2bb3ef195a52cc2abc67794d9c4d92080b66c739d318177fc7c6`):
8730 /// ```text
8731 /// ffmpeg -f lavfi -i "testsrc2=size=256x256:rate=25" -frames:v 2 \
8732 /// -pix_fmt yuv444p -strict -1 -f yuv4mpegpipe -y src.y4m
8733 /// aomenc --codec=av1 --passes=1 --end-usage=q --cq-level=62 --cpu-used=2 \
8734 /// --threads=1 --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 \
8735 /// --sb-size=128 --profile=1 --obu -o t256.obu src.y4m
8736 /// ```
8737 /// 256x256 is the smallest geometry that gives `--sb-size=128` a SECOND
8738 /// superblock row and column, which is where the stale band bites: a cell
8739 /// whose abutting block is not the last block written in its column. The
8740 /// cq level is load-bearing — this cell is entropy-exact at cq 20..58 and
8741 /// forks at 54/56/60/62 depending on the frame count (12 of the 99 cells
8742 /// swept in `lanes/av1txctxband.report.md` §4 forked, all of them at
8743 /// cq >= 54 on 256x256/320x240/256x384). `--sb-size=128` is load-bearing
8744 /// too: at the default 64 the two superblock columns are 4 mi wide, so a
8745 /// column band and a per-cell cover coincide for every 4-column run.
8746 #[test]
8747 fn a_444_lossy_sb128_txctx_reads_the_covering_block_per_cell() {
8748 const NAME: &str = "a_444_lossy_sb128_txctx_reads_the_covering_block_per_cell";
8749 let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8750 .join("fixtures/444_lossy_sb128_txctx_witness.obu");
8751 let bytes = std::fs::read(&path).unwrap_or_else(|e| {
8752 panic!(
8753 "{NAME}: pinned fixture {} is missing ({e}) -- a failure, not a skip",
8754 path.display()
8755 )
8756 });
8757 assert_eq!(bytes.len(), 6186, "{NAME}: fixture length moved");
8758 assert_eq!(
8759 fnv1a64(&bytes),
8760 0x2ec1_bb1b_5196_c4b3,
8761 "{NAME}: fixture bytes moved"
8762 );
8763
8764 let _guard = lock_gate_counters();
8765 crate::decode::reset_txctx_inter_cell_band_divergence_hits();
8766 let frames = decode_stream(&bytes)
8767 .unwrap_or_else(|e| panic!("{NAME}: the pinned 4:4:4 stream was refused: {e}"));
8768 assert_eq!(frames.len(), 2, "{NAME}: frame count");
8769 let diverged = crate::decode::txctx_inter_cell_band_divergence_hits();
8770 assert!(
8771 diverged > 0,
8772 "{NAME}: no `get_tx_size_context` read on this stream had the \
8773 per-CELL cover and the per-COLUMN band disagree, so the witness \
8774 does not exercise the corrected read at all (class \
8775 gate-blind-to-feature) -- re-encode per the recipe above"
8776 );
8777 if aomdec_available(NAME) {
8778 decode_all_frames_vs_oracle(&bytes, NAME);
8779 }
8780 eprintln!(
8781 "{NAME}: {diverged} tx_depth read(s) where the per-cell cover and \
8782 the per-column band disagreed (the 8x4 intra leaf at mi(57,52) is \
8783 the one that forked the ladder at read 32813)"
8784 );
8785 }
8786 /// lane-av1444rect r2 — the SAME class as the gate above, second
8787 /// instance: `decode_rect4_16_intrabc` applied the 4:2:0 pair geometry at
8788 /// ss (0,0), where `is_chroma_reference` makes an intra-BC 1:4 strip its
8789 /// own chroma reference. It predicted and coded an 8x4 chroma block at
8790 /// `(lmi - 1) * MI / 2` where libaom codes 16x4 at the strip's origin.
8791 ///
8792 /// **This is a PROGRESS gate, not an exactness gate, and it says so.** The
8793 /// 4:4:4 intra-BC cell is still divergent: after the ss gate the LUMA
8794 /// plane is exact to sample 205264 (it was 164416) and the entropy fork
8795 /// moves from read 11750 to 12465, but both CHROMA planes still first
8796 /// diverge at index 20532 and 390380 of 921600 samples are wrong. So the
8797 /// assertion is a prefix floor on the plane the gate actually moved —
8798 /// which only ever grows, and which the next lane's fix cannot turn red —
8799 /// and the untouched chroma divergence is named, never asserted exact.
8800 ///
8801 /// Recipe (both fixtures, one frame, `testsrc2 640x480 r=25`):
8802 /// ```text
8803 /// aomenc --codec=av1 --bit-depth=8 --input-bit-depth=8 --passes=1
8804 /// --end-usage=q --cpu-used=0 --lag-in-frames=0 --kf-max-dist=1
8805 /// --limit=1 --threads=1 --enable-rect-partitions=1
8806 /// --enable-1to4-partitions=1 --min-partition-size=4
8807 /// --max-partition-size=64 --sb-size=64 --tune-content=screen
8808 /// --enable-intrabc=1 --enable-palette=1 --cq-level=60
8809 /// --enable-tx-size-search=0 --obu [--profile=1] -o out.obu src.y4m
8810 /// ```
8811 /// 4:4:4 (1016 B, sha256 7fe888ed…) carries 17 intrabc 16x4 strips at
8812 /// ss (0,0); the 4:2:0 twin (890 B, sha256 d01352af…) is byte-exact and
8813 /// is the identity arm — the ss gate cannot reach it, and the whole frame
8814 /// is compared with the length asserted first.
8815 #[test]
8816 fn a_444_intrabc_rect4_reads_its_own_chroma_plane_block() {
8817 const NAME: &str = "a_444_intrabc_rect4_reads_its_own_chroma_plane_block";
8818 let read = |name: &str, file: &str, len: usize, fnv: u64| -> Vec<u8> {
8819 let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8820 .join(format!("fixtures/{file}"));
8821 let bytes = std::fs::read(&path).unwrap_or_else(|e| {
8822 panic!(
8823 "{name}: pinned fixture {} is missing ({e}) -- a failure, not a skip",
8824 path.display()
8825 )
8826 });
8827 assert_eq!(bytes.len(), len, "{name}: {file} length moved");
8828 assert_eq!(fnv1a64(&bytes), fnv, "{name}: {file} bytes moved");
8829 bytes
8830 };
8831 let stream444 = read(
8832 NAME,
8833 "444_intrabc_rect4_witness.obu",
8834 1016,
8835 0x27c2_fad5_4047_2994,
8836 );
8837 let stream420 = read(
8838 NAME,
8839 "420_intrabc_rect4_witness.obu",
8840 890,
8841 0x57ec_3da2_a63b_403a,
8842 );
8843
8844 let _guard = lock_gate_counters();
8845 crate::decode::reset_intrabc_rect4_own_chroma444_hits();
8846 let frames = decode_stream(&stream444)
8847 .unwrap_or_else(|e| panic!("{NAME}: the pinned 4:4:4 stream was refused: {e}"));
8848 let own = crate::decode::intrabc_rect4_own_chroma444_hits();
8849 assert!(
8850 own > 0,
8851 "{NAME}: no intra-BC 1:4 strip coded its own chroma plane block -- the \
8852 corrected route never ran (class gate-blind-to-feature)"
8853 );
8854 assert_eq!(frames.len(), 1, "{NAME}: frame count");
8855
8856 // The identity arm FIRST and in full: the 4:2:0 twin must stay
8857 // byte-exact. `decode_all_frames_vs_oracle` asserts the two frame
8858 // lengths match before it compares anything -- the check whose absence
8859 // turned an out-of-window divergence into a reported EXACT in this
8860 // lane's own round 1.
8861 if aomdec_available(NAME) {
8862 decode_all_frames_vs_oracle(&stream420, &format!("{NAME}-420"));
8863 crate::decode::reset_intrabc_rect4_own_chroma444_hits();
8864 decode_stream(&stream420)
8865 .unwrap_or_else(|e| panic!("{NAME}: the 4:2:0 twin was refused: {e}"));
8866 assert_eq!(
8867 crate::decode::intrabc_rect4_own_chroma444_hits(),
8868 0,
8869 "{NAME}: the 4:2:0 twin fired the ss (0,0)-only route"
8870 );
8871
8872 // NO 4:4:4 pixel assert here, and deliberately so. The cell is
8873 // still divergent (390380 of 921600 samples; both chroma planes
8874 // first wrong at index 20532, x=52 y=32; entropy fork read 12465
8875 // at mi (90,108)) and an assertion of the form "our output is
8876 // wrong by exactly N" would encode the defect as expected
8877 // behaviour -- the shape this suite refuses everywhere else, and
8878 // one that outlives the memory of why. The true assertions this
8879 // gate can make today are the two above: the route is reached at
8880 // 4:4:4 and is not reached at 4:2:0, and the 4:2:0 twin is
8881 // byte-exact. The open chroma root and its numbers live in
8882 // lanes/av1444rect.report.md §6, not in an assertion.
8883 eprintln!(
8884 "{NAME}: {own} own-chroma intra-BC strip(s) at 4:4:4, 0 at 4:2:0; \
8885 4:2:0 twin byte-exact; 4:4:4 intra-BC CHROMA still OPEN \
8886 (U/V first wrong at index 20532, entropy fork read 12465 at \
8887 mi (90,108)) -- see lanes/av1444rect.report.md \u{00a7}6"
8888 );
8889 }
8890 }
8891
8892 /// lane-av1lrflush: the pipelined loop-restoration band release flushes
8893 /// RU row 0 on the inter frame whose top superblock row carries a
8894 /// 128-root rect -- the exact shape lanes/av1444sb.report.md r2 named as
8895 /// its stop-with-site DEFECT 3 ("`pipe_run_lr`'s `rrows` branch plus the
8896 /// `ls.note`/`ls.close` band release never flushes RU row 0 on frame 2").
8897 /// r3 REFUTED that defect by measurement: on this fixture the filter
8898 /// pipeline (deblock/CDEF/LR band workers over `ls.note` releases)
8899 /// produces output byte-identical to the whole-frame path on every frame
8900 /// -- this gate pins that refutation so a future band-accounting
8901 /// regression on a 128-root-rect inter frame cannot land silently.
8902 ///
8903 /// Non-vacuity, twice over: the `PIPELINE_TAKEN` delta proves the second
8904 /// decode really constructed the pipeline on both inter frames (frame 0
8905 /// is a key frame and the key-frame path runs whole-frame filters by
8906 /// construction), and the `LR_PIPELINE_ROW0` delta proves the pipeline's
8907 /// band release itself flushed RU row 0 -- a process-global counter
8908 /// bumped by `pipe_run_lr`'s worker, so frame 0's whole-frame LR (which
8909 /// runs on the gate's own thread and satisfies the thread-local
8910 /// `LR_STRIPE0_HITS`) cannot fake it. Frames 0/1 are additionally asserted
8911 /// byte-exact against BOTH the oracle aomdec and ffmpeg THROUGH the
8912 /// pipeline. (Frame 2's own residual is the entropy lane's inter
8913 /// rect-strip recon defect -- see lanes/av1lrflush.report.md r3 -- and
8914 /// is identical on the serial and pipelined runs, so the pipeline
8915 /// equality covers it without pinning its wrong samples.)
8916 #[test]
8917 fn a_444_sb128_witness_lr_pipeline_flushes_ru_row_0_pixel_exact() {
8918 const NAME: &str = "a_444_sb128_witness_lr_pipeline_flushes_ru_row_0_pixel_exact";
8919 const FIXTURE_LEN: usize = 794;
8920 const FIXTURE_FNV: u64 = 0xf5a7_27f4_3fa7_abc3;
8921 const W: usize = 192;
8922 const H: usize = 160;
8923 const FRAMES: usize = 3;
8924 /// The inter (pipelinable) frames of the witness; frame 0 is the key
8925 /// frame and never constructs the pipeline.
8926 const INTER_FRAMES: u64 = 2;
8927 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8928 .join("fixtures/444_sb128rect_lr_witness.obu");
8929 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
8930 panic!(
8931 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot \
8932 run, which is a failure, not a skip",
8933 obu.display()
8934 )
8935 });
8936 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
8937 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
8938
8939 let _guard = lock_gate_counters();
8940 let serial =
8941 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: serial decode failed: {e}"));
8942 assert_eq!(serial.len(), FRAMES, "{NAME}: frame count");
8943
8944 let pipe_before = crate::decode::pipeline_taken_frames();
8945 let row0_before = crate::decode::lr_pipeline_row0_flushes();
8946 let piped = {
8947 let _bands = crate::par::override_filter_threads(4);
8948 decode_stream(&stream)
8949 .unwrap_or_else(|e| panic!("{NAME}: pipelined decode failed: {e}"))
8950 };
8951 assert_eq!(piped.len(), FRAMES, "{NAME}: frame count");
8952 assert_eq!(
8953 crate::decode::pipeline_taken_frames() - pipe_before,
8954 INTER_FRAMES,
8955 "{NAME}: the filter pipeline did not take both inter frames -- the \
8956 arm decoded serial and proves nothing (class \
8957 gate-blind-to-feature)"
8958 );
8959 // f1 restores all three planes, f2 all but U -> 3 + 2 row-0 flushes.
8960 // `LR_PIPELINE_ROW0` is process-global and bumped by the pipeline's
8961 // own worker, so this delta cannot be satisfied by frame 0's
8962 // whole-frame LR (which runs on this test's thread and never touches
8963 // the counter).
8964 assert_eq!(
8965 crate::decode::lr_pipeline_row0_flushes() - row0_before,
8966 5,
8967 "{NAME}: the pipeline never flushed RU row 0 ({} planes' worth \
8968 expected) -- the named defect class is present (class \
8969 lr-band-release)",
8970 5
8971 );
8972
8973 // The refutation itself: pipeline == serial, byte for byte, on every
8974 // frame -- including frame 2, the 128-root-rect inter frame the
8975 // r2 defect named.
8976 for (i, (s, p)) in serial.iter().zip(piped.iter()).enumerate() {
8977 for (pl, (a, b)) in [(&s.y, &p.y), (&s.u, &p.u), (&s.v, &p.v)]
8978 .into_iter()
8979 .enumerate()
8980 {
8981 assert_eq!(
8982 a, b,
8983 "{NAME}: pipelined frame {i} plane {pl} differs from the \
8984 whole-frame path (class lr-band-release)"
8985 );
8986 }
8987 }
8988
8989 // Frames 0/1 through the PIPELINE, byte-exact vs both oracles.
8990 if aomdec_available(NAME) {
8991 let dir = std::env::temp_dir().join(format!("ec-av1-lrflush-{}", std::process::id()));
8992 let _ = std::fs::remove_dir_all(&dir);
8993 std::fs::create_dir_all(&dir).expect("scratch dir");
8994 let raw = dir.join("aomdec.raw");
8995 let out = Command::new(aomdec_path())
8996 .args(["--codec=av1", "--rawvideo", "-o"])
8997 .arg(&raw)
8998 .arg(&obu)
8999 .stdin(Stdio::null())
9000 .stdout(Stdio::piped())
9001 .stderr(Stdio::piped())
9002 .output()
9003 .expect("aomdec failed to run");
9004 assert!(
9005 out.status.success(),
9006 "{NAME}: the oracle aomdec refused the stream: {}",
9007 String::from_utf8_lossy(&out.stderr)
9008 );
9009 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
9010 let _ = std::fs::remove_dir_all(&dir);
9011 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
9012 for (i, f) in piped.iter().enumerate().take(2) {
9013 let base = i * W * H * 3;
9014 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
9015 .into_iter()
9016 .zip(["y", "u", "v"])
9017 {
9018 let want = &ref_raw[base + off..base + off + W * H];
9019 let bad = plane
9020 .iter()
9021 .zip(want)
9022 .filter(|&(&a, &b)| a as u8 != b)
9023 .count();
9024 assert_eq!(
9025 bad, 0,
9026 "{NAME}: aomdec frame {i} plane {p} THROUGH THE PIPELINE: \
9027 {bad} samples differ (class lr-band-release)"
9028 );
9029 assert_eq!(
9030 plane.len(),
9031 want.len(),
9032 "{NAME}: aomdec frame {i} plane {p}: ours has {} samples, the oracle's \
9033 has {} -- a short plane would zip-truncate the compare above and hide \
9034 a chroma-span defect",
9035 plane.len(),
9036 want.len()
9037 );
9038 }
9039 }
9040 }
9041 if have_ffmpeg() {
9042 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
9043 for (i, (got, want)) in piped.iter().zip(refs.iter()).enumerate().take(2) {
9044 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
9045 .iter()
9046 .enumerate()
9047 {
9048 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
9049 assert_eq!(
9050 bad, 0,
9051 "{NAME}: ffmpeg frame {i} plane {p} THROUGH THE PIPELINE: \
9052 {bad} samples differ"
9053 );
9054 assert_eq!(
9055 g.len(),
9056 r.len(),
9057 "{NAME}: ffmpeg frame {i} plane {p}: ours has {} samples, ffmpeg's has {} \
9058 -- a short plane would zip-truncate the compare above and hide a \
9059 chroma-span defect",
9060 g.len(),
9061 r.len()
9062 );
9063 }
9064 }
9065 } else {
9066 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
9067 }
9068 }
9069
9070 /// lane-av1-444interband: the DEFAULT-partition lossless 4:4:4 pin for
9071 /// the inter 16x4/4x16 strip's chroma band stamping (the pair_chroma
9072 /// 4:2:0-only gate, commit d5325172). Fixture pinned into `fixtures/`:
9073 /// testsrc2 128x96 yuv444p, aomenc `--profile=1 --lossless=1
9074 /// --enable-palette=0 --enable-intrabc=0 --passes=1 --cpu-used=4
9075 /// --limit=6 --obu` (the av1llkf.report.md recipe), 6 frames; 32487
9076 /// bytes, sha256
9077 /// `1e6dd4e05038c8d51e2c8d29f8c337130c4fea0aed629415535e6e53af9a2c72`.
9078 ///
9079 /// This is the stream whose frame 1 desynced at the 16x4 inter strip
9080 /// mi(2,8) -- its U bc=0 `txb_skip` read base 0 where aom reads base 1,
9081 /// because the skipped strip (1,8)'s pair-form context stamp smeared
9082 /// zero over `left[2][1]`. Two pins, both measured at d5325172:
9083 /// end-to-end, every sample of every frame must match the oracle
9084 /// aomdec exactly (the pre-fix tree refuses mid-frame-1, so the gate
9085 /// is red by refusal, not by silent pass), and the 1:4 counter delta
9086 /// must show the strips decoded WITHOUT the pair rewrite firing
9087 /// (`horz4=20 vert4=28 chroma_pairs=0` -- chroma_pairs > 0 on this
9088 /// pairless 4:4:4 stream is the defect reappearing, the
9089 /// class `pair-rewrite-at-ss0`).
9090 #[test]
9091 fn a_lossless_444_defaultp_inter_strip_stream_decodes_byte_exact() {
9092 const NAME: &str = "a_lossless_444_defaultp_inter_strip_stream_decodes_byte_exact";
9093 const FIXTURE_LEN: usize = 32487;
9094 const FIXTURE_FNV: u64 = 0x5278_9f0f_ce2d_1e52;
9095 const W: usize = 128;
9096 const H: usize = 96;
9097 const FRAMES: usize = 6;
9098 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
9099 .join("fixtures/ll444_defaultp_inter_strip.obu");
9100 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
9101 panic!(
9102 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
9103 which is a failure, not a skip",
9104 obu.display()
9105 )
9106 });
9107 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
9108 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
9109
9110 let _guard = lock_gate_counters();
9111 let strips_before = decode::inter16_rect4_counters();
9112 let frames = decode_stream(&stream)
9113 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
9114 let strips_after = decode::inter16_rect4_counters();
9115 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
9116 for f in &frames {
9117 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
9118 }
9119 // The 1:4 strips must have fired, and the 4:2:0 pair rewrite must
9120 // NOT have (there are no chroma pairs at ss 0/0).
9121 let (horz4, vert4, chroma_pairs) = (
9122 strips_after.0 - strips_before.0,
9123 strips_after.1 - strips_before.1,
9124 strips_after.2 - strips_before.2,
9125 );
9126 assert_eq!(horz4, 20, "{NAME}: HORZ_4 strip count moved");
9127 assert_eq!(vert4, 28, "{NAME}: VERT_4 strip count moved");
9128 assert_eq!(
9129 chroma_pairs, 0,
9130 "{NAME}: chroma pairs closed on a 4:4:4 stream \
9131 (class pair-rewrite-at-ss0)"
9132 );
9133
9134 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
9135 if aomdec_available(NAME) {
9136 let dir = std::env::temp_dir().join(format!("ec-av1-ll444dp-{}", std::process::id()));
9137 let _ = std::fs::remove_dir_all(&dir);
9138 std::fs::create_dir_all(&dir).expect("scratch dir");
9139 let raw = dir.join("aomdec.raw");
9140 let out = Command::new(aomdec_path())
9141 .args(["--codec=av1", "--rawvideo", "-o"])
9142 .arg(&raw)
9143 .arg(&obu)
9144 .stdin(Stdio::null())
9145 .stdout(Stdio::piped())
9146 .stderr(Stdio::piped())
9147 .output()
9148 .expect("aomdec failed to run");
9149 assert!(
9150 out.status.success(),
9151 "{NAME}: the oracle aomdec refused the stream: {}",
9152 String::from_utf8_lossy(&out.stderr)
9153 );
9154 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
9155 let _ = std::fs::remove_dir_all(&dir);
9156 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
9157 for (i, f) in frames.iter().enumerate() {
9158 let base = i * W * H * 3;
9159 for ((plane, off), p) in [(&f.y, 0usize), (&f.u, W * H), (&f.v, 2 * W * H)]
9160 .into_iter()
9161 .zip(["y", "u", "v"])
9162 {
9163 let want = &ref_raw[base + off..base + off + W * H];
9164 let bad = plane
9165 .iter()
9166 .zip(want)
9167 .filter(|&(&a, &b)| a as u8 != b)
9168 .count();
9169 assert_eq!(
9170 bad, 0,
9171 "{NAME}: aomdec frame {i} plane {p}: {bad} samples differ \
9172 (class pair-rewrite-at-ss0)"
9173 );
9174 }
9175 }
9176 }
9177 }
9178
9179 /// lane-av1-leaf8oob: the OOB pin for [`decode_leaf8`]'s intrabc chroma
9180 /// frame-copy buffers. The closure hardcoding the leaf's chroma
9181 /// prediction at `4x4` (`vec![0u16; 4 * 4]`, `predict_with_filter` at
9182 /// `4, 4`) carried the 4:2:0 halving of an 8x8 luma leaf into every
9183 /// subsampling: at 4:4:4 the leaf's own chroma plane block is 8x8
9184 /// (`csz == 8`), so the 16-sample override reached
9185 /// [`PlaneBuf::reconstruct`] as an 8x8 prediction and indexed
9186 /// `prediction[16]` of a 16-sample buffer --
9187 /// `index out of bounds: the len is 16 but the index is 16` at the
9188 /// reconstruct call, on every conformant stream of this shape (a panic,
9189 /// never a refusal). Same signature class as lane-lossless128's
9190 /// 128-axis lossless extent (`len 16, index 16` there too).
9191 ///
9192 /// `crates/ec-av1/fixtures/444_leaf8_oob.obu`, 3577 bytes, sha256
9193 /// `72bed2791d1ceba8be7926a052c7838c5d96d4f9d56d28fb69789a753d3593af`
9194 /// (force-added past the `fixtures` gitignore like every sibling
9195 /// fixture): the lane ticket's witness-hunt reproducer (s1a/s2e) -- a
9196 /// 320x256, 3-frame, 8-bit 4:4:4 screen-content keyframe run whose
9197 /// census pins 4 intrabc 8x8 leaves (the oracle's own MB dump opens on
9198 /// unbroken inter-classified intra = intrabc blocks). The encoding
9199 /// recipe is not independently recoverable in this lane; the bytes are
9200 /// pinned by length + FNV-1a64 here and by the oracle raw fingerprint
9201 /// below.
9202 ///
9203 /// WHAT THIS GATE DOES NOT CLAIM: sample-exactness -- and it pins no
9204 /// pixel baseline. Measured against the oracle aomdec (`--rawvideo`;
9205 /// comparison method ground-truthed by the green
9206 /// `a_lossless_sb128_rect_intra_block_decodes_sample_exact` and
9207 /// `a_lossless_444_min_partition8_inter_stream_decodes_sample_exact`
9208 /// witnesses on this same tree), this stream DIVERGES and its output is
9209 /// not even self-deterministic: frame 0's first differing LUMA sample
9210 /// is at (275,128), the (y, u, v) differing counts per frame are
9211 /// (20811, 35467, 32320)/(20308, 39177, 35994)/(20131, 39588, 36601) of
9212 /// 81920 samples per plane, and under `EC_AV1_PLANE_SENTINEL=1` the
9213 /// chroma counts move (u f0 35467 -> 35630) while luma stays put.
9214 /// Sentinel-vs-uninit output diffing localises that dependence to 458
9215 /// WHOLE 8x8 chroma blocks (frame 0: chroma x >= 96, y >= 64) reading
9216 /// samples this decode never wrote -- ambient memory in those slots,
9217 /// hence any pixel-exact assert here drifts run to run with the batch.
9218 /// Both facts belong to ONE pre-existing defect this lane must not
9219 /// chase (the ticket's fix touches only leaf8's chroma prediction
9220 /// buffers, which cannot feed a luma sample, and the pre-fix run never
9221 /// got past the panicked leaf): a decode desync on this stream around
9222 /// frame-0 SB (3..4, 2), after which samples diverge from the oracle
9223 /// and the misread layout leaves chroma blocks unreconstructed.
9224 /// Disposition: `deferred(unblock: divergence lane -- EC trace pairing
9225 /// against the oracle on this fixture)`. So this gate pins exactly what
9226 /// its ticket owns: fixture identity, a decode that RUNS TO COMPLETION
9227 /// where the old code died with `len 16, index 16`, and the arm counter.
9228 ///
9229 /// Assertions (all before/without any skip path):
9230 /// 1. fixture bytes: exact length + FNV-1a64;
9231 /// 2. `decode_stream` succeeds -- 3 frames, 320x256 (the pre-fix run
9232 /// died here with the len-16/index-16 panic);
9233 /// 3. non-vacuity: `leaf8_intrabc_hits` moves (measured 0 -> 4), so the
9234 /// arm owning the fixed buffers really fired;
9235 /// 4. the oracle aomdec still decodes the pinned bytes (raw size +
9236 /// fingerprint), anchoring the deferred divergence comparison.
9237 #[test]
9238 fn an_intrabc_8x8_leaf_chroma_frame_copy_at_444_decodes_without_the_oob() {
9239 const NAME: &str = "an_intrabc_8x8_leaf_chroma_frame_copy_at_444_decodes_without_the_oob";
9240 const FIXTURE_LEN: usize = 3577;
9241 const FIXTURE_FNV: u64 = 0x86b9_3a51_fe16_353c;
9242 const W: usize = 320;
9243 const H: usize = 256;
9244 const FRAMES: usize = 3;
9245 let obu =
9246 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures/444_leaf8_oob.obu");
9247 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
9248 panic!(
9249 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
9250 which is a failure, not a skip",
9251 obu.display()
9252 )
9253 });
9254 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
9255 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
9256
9257 let _guard = lock_gate_counters();
9258 crate::decode::reset_leaf8_intrabc_hits();
9259 let frames = decode_stream(&stream)
9260 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
9261 assert!(
9262 crate::decode::leaf8_intrabc_hits() > 0,
9263 "{NAME}: gate is vacuous -- no intrabc 8x8 leaf was decoded, so the arm \
9264 owning the fixed chroma buffers never fired"
9265 );
9266 assert_eq!(frames.len(), FRAMES, "{NAME}: frame count");
9267 for f in &frames {
9268 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
9269 }
9270
9271 // The oracle aomdec, rawvideo out: FRAMES concatenated yuv444p frames.
9272 if aomdec_available(NAME) {
9273 let dir = std::env::temp_dir().join(format!("ec-av1-leaf8oob-{}", std::process::id()));
9274 let _ = std::fs::remove_dir_all(&dir);
9275 std::fs::create_dir_all(&dir).expect("scratch dir");
9276 let raw = dir.join("aomdec.raw");
9277 let out = Command::new(aomdec_path())
9278 .args(["--codec=av1", "--rawvideo", "-o"])
9279 .arg(&raw)
9280 .arg(&obu)
9281 .stdin(Stdio::null())
9282 .stdout(Stdio::piped())
9283 .stderr(Stdio::piped())
9284 .output()
9285 .expect("aomdec failed to run");
9286 assert!(
9287 out.status.success(),
9288 "{NAME}: the oracle aomdec refused the stream: {}",
9289 String::from_utf8_lossy(&out.stderr)
9290 );
9291 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
9292 let _ = std::fs::remove_dir_all(&dir);
9293 assert_eq!(ref_raw.len(), W * H * 3 * FRAMES, "{NAME}: aomdec raw size");
9294 assert_eq!(
9295 fnv1a64(&ref_raw),
9296 0x3821_0bcb_f572_973c,
9297 "{NAME}: aomdec raw fingerprint moved"
9298 );
9299 }
9300 }
9301 /// lane-lossless128: a LOSSLESS key frame that codes a 128-axis
9302 /// (`BLOCK_64X128`) intra block -- the shape libaom's `read_tx_size` forces
9303 /// to `TX_4X4` on its very first line (`decodeframe.c:1183`), so every plane
9304 /// of the block is a 4x4 transform unit and NO `tx_size_cat3` symbol is
9305 /// coded.
9306 ///
9307 /// On the merged base `decode_block_128rect` had no lossless carve-out: it
9308 /// read `logical_tx = 64` off `depth == 0`, handed `PlaneBuf::reconstruct`
9309 /// a 64x64 geometry with the 16-sample 4x4 residual
9310 /// [`TxParams::run`](crate::decode::TxParams) produced -- `index out of
9311 /// bounds: the len is 16 but the index is 16` at the reconstruction call,
9312 /// on EVERY conformant stream of this shape (a panic, never a refusal).
9313 ///
9314 /// `crates/ec-av1/fixtures/lossless_sb128_rect_kf.obu`, 3471 bytes, sha256
9315 /// `013b07979c8be999c70d47f32768c2bf959be086a893f60dde1b0f5e35d4f475`:
9316 /// `aomenc --codec=av1 --passes=1 --threads=1 --obu --lossless=1
9317 /// --cpu-used=0` over a 320x256, 4-frame source that is flat grey except a
9318 /// textured 64x128 patch in the top-right corner -- which is what makes the
9319 /// 128 root take `PARTITION_VERT` and code the `BLOCK_64X128` at mi(0,64).
9320 ///
9321 /// The counter delta keeps the gate non-vacuous: a stream that stopped
9322 /// coding the shape reads 0 and the gate fails instead of passing on a
9323 /// decode that never reached the fixed body (class
9324 /// `gate-blind-to-feature`).
9325 #[test]
9326 fn a_lossless_sb128_rect_intra_block_decodes_sample_exact() {
9327 const NAME: &str = "a_lossless_sb128_rect_intra_block_decodes_sample_exact";
9328 // The pixel arm needs ffmpeg; the decode and its counter deltas do
9329 // not, so a box without ffmpeg still proves the shape was reached
9330 // (class `gate-skips-on-its-own-failure`) -- the skip is still named.
9331 let ffmpeg = have_ffmpeg();
9332 if !ffmpeg {
9333 eprintln!("SKIP {NAME}: no ffmpeg -- the ffmpeg pixel arm only");
9334 }
9335 let (w, h, frames) = (320usize, 256usize, 4usize);
9336 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9337 .join("fixtures/lossless_sb128_rect_kf.obu");
9338 let stream = std::fs::read(&path)
9339 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
9340 let before = crate::decode::intra128_lossless_hits();
9341 let before_replay = crate::decode::sb128rect_chroma_replay_hits();
9342 let ours = decode_stream(&stream)
9343 .unwrap_or_else(|e| panic!("{NAME}: a lossless 128-axis key frame decodes: {e}"));
9344 let hits = crate::decode::intra128_lossless_hits() - before;
9345 assert!(
9346 hits > 0,
9347 "{NAME}: this stream coded NO lossless 128-axis intra block -- the fixed body \
9348 was never reached (class gate-blind-to-feature)"
9349 );
9350 // lane-av1-128rectspan: the 4:2:0 twin of the 4:4:4 gate's replay
9351 // assertion. This stream codes the 64x128 block at mi(0,64) with
9352 // TX_4X4 chroma units, so the end-of-block replay re-stamps each of
9353 // them over its own luma-mi rows -- the arm the span fix sits on, on
9354 // the OTHER admitted ss (1,1). The mismatch half is the 4:2:2
9355 // signature and reads 0 here because 4:2:2 is refused by name at the
9356 // sequence header; it is the tripwire for the day it is not.
9357 let after_replay = crate::decode::sb128rect_chroma_replay_hits();
9358 assert!(
9359 after_replay.0 > before_replay.0,
9360 "{NAME}: no 128-axis block replayed a chroma unit's own mi state -- the replay \
9361 arm never ran (class gate-blind-to-feature)"
9362 );
9363 assert_eq!(
9364 after_replay.1,
9365 before_replay.1,
9366 "{NAME}: the tail replay stamped {} unit(s) over a height that was not the \
9367 unit's own luma height (4:2:2 spans leaked into an admitted stream)",
9368 after_replay.1 - before_replay.1
9369 );
9370 eprintln!(
9371 "{NAME}: replayed {} chroma unit(s), {} span mismatch(es)",
9372 after_replay.0 - before_replay.0,
9373 after_replay.1 - before_replay.1
9374 );
9375 if !ffmpeg {
9376 return;
9377 }
9378 let refs = ffmpeg_decode_sequence(&stream, w, h, frames);
9379 assert_eq!(ours.len(), frames, "{NAME}: shown/display frame count");
9380 for (i, (got, want)) in ours.iter().zip(refs.iter()).enumerate() {
9381 for (plane, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
9382 .iter()
9383 .enumerate()
9384 {
9385 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
9386 assert_eq!(
9387 bad, 0,
9388 "{NAME}: frame {i} plane {plane}: {bad} samples differ from ffmpeg"
9389 );
9390 assert_eq!(
9391 g.len(),
9392 r.len(),
9393 "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
9394 short plane would zip-truncate the compare above and hide a chroma-span \
9395 defect",
9396 g.len(),
9397 r.len()
9398 );
9399 }
9400 }
9401 eprintln!("{NAME}: {frames} frames sample-exact, intra128_lossless hits {hits}");
9402 }
9403
9404 /// lane-av1-loss64: the generator for the two gates below -- a deterministic
9405 /// 1-frame lossless superblock-128 aomenc stream of `testsrc2`. `extra`
9406 /// flags land last (aomenc keeps the LAST occurrence of a repeated flag).
9407 /// The recipe is the one lanes/av1rect14.report.md section 2 measured
9408 /// (`--lossless=1 --sb-size=128 --enable-1to4-partitions=1`); the
9409 /// `--min-partition-size` override is what steers the bottom superblock
9410 /// row's RD into overhanging 64x64 `NONE` blocks (the shape the first fix
9411 /// clips) or, at 8, keeps sub-8x8 partitions out of the second gate's
9412 /// stream so the whole frame is decodable.
9413 fn lossless_sb128_testsrc2(width: usize, height: usize, extra: &[&str]) -> Vec<u8> {
9414 let mut ff = Command::new("ffmpeg");
9415 let out = ff
9416 .args(["-v", "error", "-f", "lavfi", "-i"])
9417 .arg(format!("testsrc2=s={width}x{height}:r=25"))
9418 .args([
9419 "-frames:v",
9420 "1",
9421 "-pix_fmt",
9422 "yuv420p",
9423 "-strict",
9424 "-1",
9425 "-f",
9426 "yuv4mpegpipe",
9427 "-",
9428 ])
9429 .stdin(Stdio::null())
9430 .stdout(Stdio::piped())
9431 .stderr(Stdio::piped())
9432 .output()
9433 .expect("ffmpeg failed to run");
9434 assert!(
9435 out.status.success(),
9436 "ffmpeg failed for testsrc2 {width}x{height}"
9437 );
9438 let y4m = out.stdout;
9439 let out = run_with_stdin(
9440 Command::new(aomenc_path())
9441 .args(["--codec=av1", "--bit-depth=8", "--input-bit-depth=8"])
9442 .args([
9443 "--passes=1",
9444 "--cpu-used=0",
9445 "--lag-in-frames=0",
9446 "--kf-max-dist=1",
9447 "--limit=1",
9448 "--threads=1",
9449 "--tile-columns=0",
9450 "--lossless=1",
9451 "--sb-size=128",
9452 "--enable-1to4-partitions=1",
9453 ])
9454 .args(extra)
9455 .args(["--obu", "-o", "-", "-"]),
9456 &y4m,
9457 );
9458 assert!(
9459 out.status.success(),
9460 "aomenc failed: {}",
9461 String::from_utf8_lossy(&out.stderr)
9462 );
9463 out.stdout
9464 }
9465
9466 /// lane-av1-loss64: a lossless superblock-128 frame whose intra blocks
9467 /// overhang the bottom frame edge codes NO coefficient symbols for the
9468 /// chroma transform units whose 4x4 origin sits outside the frame's mi
9469 /// grid -- libaom `decode_reconstruct_tx` returns before any read
9470 /// (`decodeframe.c:299`, `blk_row >= max_blocks_high || blk_col >=
9471 /// max_blocks_wide`, the limits from `max_block_wide/high`,
9472 /// av1_common_int.h:1565). The square multi-transform-unit chroma loop in
9473 /// [`crate::decode`] carried no such clip (the luma loop had one) and read
9474 /// `txb_skip`+coefficients for the phantom units: on the measured stream
9475 /// the first lossless 64x64 `NONE` block, at mi(48,0), overhangs the
9476 /// 240-px frame by 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units,
9477 /// not eight -- 32 phantom unit reads per plane desynced the tile and
9478 /// every later symbol (including partition reads, which is what made
9479 /// aomdec's zero-`value=8/9` census look like a partition-reader defect
9480 /// in the rect14 review) decoded as garbage.
9481 ///
9482 /// Fail-pre-fix, measured on the ed12fe52 probe: both arms differ from
9483 /// ffmpeg at byte 41120 (luma row 128 col 160, the first block decoded
9484 /// after the phantom reads). The counter delta pins non-vacuity (class
9485 /// `gate-blind-to-feature`): 96 clipped units on each arm.
9486 #[test]
9487 fn a_lossless_sb128_square_frame_clips_overhanging_chroma_tus() {
9488 const NAME: &str = "a_lossless_sb128_square_frame_clips_overhanging_chroma_tus";
9489 if !have_ffmpeg() {
9490 eprintln!("SKIP {NAME}: no ffmpeg");
9491 return;
9492 }
9493 // Arm 0 is the rect14 report's `loss320` recipe verbatim; arm 1 is its
9494 // `lnone` companion (1:4 and rect partitions off) -- both coded the
9495 // overhanging 64x64 blocks and both desynced at byte 41120 pre-fix.
9496 let arms: [&[&str]; 2] = [
9497 &["--min-partition-size=4"],
9498 &[
9499 "--min-partition-size=4",
9500 "--enable-1to4-partitions=0",
9501 "--enable-rect-partitions=0",
9502 ],
9503 ];
9504 let mut clips_total = 0usize;
9505 for (arm, extra) in arms.iter().enumerate() {
9506 let stream = lossless_sb128_testsrc2(320, 240, extra);
9507 crate::decode::reset_loss64_hits();
9508 let ours =
9509 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: arm {arm} decodes: {e}"));
9510 let clips = crate::decode::chroma_edge_tu_clip_hits();
9511 assert!(
9512 clips > 0,
9513 "{NAME}: arm {arm} clipped NO overhanging chroma transform unit -- \
9514 the fixed body was never reached (class gate-blind-to-feature)"
9515 );
9516 clips_total += clips;
9517 let refs = ffmpeg_decode_sequence(&stream, 320, 240, 1);
9518 assert_eq!(ours.len(), 1, "{NAME}: arm {arm} frame count");
9519 for (plane, (g, r)) in [
9520 (&ours[0].y, &refs[0].y),
9521 (&ours[0].u, &refs[0].u),
9522 (&ours[0].v, &refs[0].v),
9523 ]
9524 .iter()
9525 .enumerate()
9526 {
9527 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
9528 assert_eq!(
9529 bad, 0,
9530 "{NAME}: arm {arm} plane {plane}: {bad} samples differ from ffmpeg"
9531 );
9532 assert_eq!(
9533 g.len(),
9534 r.len(),
9535 "{NAME}: arm {arm} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
9536 short plane would zip-truncate the compare above and hide a chroma-span \
9537 defect",
9538 g.len(),
9539 r.len()
9540 );
9541 }
9542 }
9543 eprintln!("{NAME}: 2 arms full-frame exact, {clips_total} chroma units clipped");
9544 }
9545
9546 /// lane-av1-loss64: a SKIPPED intrabc rect strip on a lossless frame
9547 /// zeroes its whole entropy-band footprint (libaom
9548 /// `av1_reset_entropy_context`, `if (mbmi->skip_txfm)` decodeframe.c:1262 ->
9549 /// blockd.c:58) instead of leaving the previous occupant's luma bands
9550 /// standing. The skip arm of `decode_intrabc_owned_rect` never wrote the
9551 /// luma bands: the lossless `read_block_tx_size_rect` resolves the 4x4
9552 /// leaf list before it looks at `skip`, so the tail took the
9553 /// per-transform-unit record path (chroma only) with no per-unit luma
9554 /// writes ever run. The next block then read a STALE band: on the 320x242
9555 /// `--min-partition-size=4` sibling of this stream the skipped 8x16
9556 /// intrabc strip at mi(48,66) left a 7 in left[48] and mi(48,68)'s first
9557 /// transform unit read `txb_skip_ctx` 3 where aomdec reads 1 (measured
9558 /// `EC_ECDUMP` against the instrumented aomdec) -- a coefficient-walk
9559 /// desync at byte 61712 with every mode symbol still matching.
9560 ///
9561 /// This gate uses the same `--min-partition-size=4` arm that reaches the
9562 /// sub-8x8 VERT -> 4x8 skipped-intrabc leaf. Post-fix it is full-frame
9563 /// exact: the skip path uses libaom's clamped 4x4 chroma intrabc
9564 /// prediction (`decodeframe.c:1011-1065`, `reconinter_template.inc:186-207`)
9565 /// instead of the ordinary skipped-intra DC predictor. The old route first
9566 /// differed at U(104,92) with the entropy ladder fully synced.
9567 ///
9568 /// Fail-pre-fix, measured on the ed12fe52 probe: differs at byte 41120
9569 /// (the chroma-clip class, fixed in the same lane). Single-mutation on
9570 /// the lane tree with ONLY this gate's walk reverted: differs at byte
9571 /// 61712, the band-leak site.
9572 #[test]
9573 fn a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands() {
9574 const NAME: &str = "a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands";
9575 if !have_ffmpeg() {
9576 eprintln!("SKIP {NAME}: no ffmpeg");
9577 return;
9578 }
9579 let stream = lossless_sb128_testsrc2(320, 242, &["--min-partition-size=4"]);
9580 crate::decode::reset_loss64_hits();
9581 crate::decode::reset_skipped_intrabc_chroma_arm_hits();
9582 let ours = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: decodes: {e}"));
9583 let resets = crate::decode::skip_lossless_band_reset_hits();
9584 let intrabc_skips = crate::decode::skipped_intrabc_chroma_arm_hits();
9585 assert!(
9586 resets > 0,
9587 "{NAME}: this stream coded NO skipped lossless intrabc rect strip -- \
9588 the fixed body was never reached (class gate-blind-to-feature)"
9589 );
9590 assert!(
9591 intrabc_skips > 0,
9592 "{NAME}: this stream coded NO skipped sub-8x8 intrabc chroma leaf -- \
9593 the clamped chroma prediction fix was never reached (class gate-blind-to-feature)"
9594 );
9595 let refs = ffmpeg_decode_sequence(&stream, 320, 242, 1);
9596 assert_eq!(ours.len(), 1, "{NAME}: frame count");
9597 for (plane, (g, r)) in [
9598 (&ours[0].y, &refs[0].y),
9599 (&ours[0].u, &refs[0].u),
9600 (&ours[0].v, &refs[0].v),
9601 ]
9602 .iter()
9603 .enumerate()
9604 {
9605 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
9606 assert_eq!(
9607 bad, 0,
9608 "{NAME}: plane {plane}: {bad} samples differ from ffmpeg"
9609 );
9610 assert_eq!(
9611 g.len(),
9612 r.len(),
9613 "{NAME}: plane {plane}: ours has {} samples, ffmpeg's has {} -- a short plane \
9614 would zip-truncate the compare above and hide a chroma-span defect",
9615 g.len(),
9616 r.len()
9617 );
9618 }
9619 eprintln!(
9620 "{NAME}: full-frame exact, {resets} band resets, \
9621 {intrabc_skips} skipped intrabc chroma predictions"
9622 );
9623 }
9624
9625 /// lane-av1-ibc444rect: an unskipped intrabc `BLOCK_8X4`/`BLOCK_4X8` leaf
9626 /// on a lossless 4:4:4 frame walks its coefficients as per-4x4 inter
9627 /// `TX_4X4` units on every plane -- `read_tx_size`'s lossless first line
9628 /// (`decodeframe.c:1203`) forces TX_4X4 before any tree, the frame's
9629 /// `TxMode` is `ONLY_4X4` so no var-tx tree is read either, and
9630 /// `av1_read_tx_type`'s qindex==0 early return (`decodemv.c:681`) drops
9631 /// the tx_type symbol the lossy 4x4 inter sets carry -- NOT the single
9632 /// `LumaRect8x4Inter`/`ChromaRect8x4` rect unit the non-lossless arm
9633 /// reads, and not the lossy per-unit arm's tx_type read.
9634 ///
9635 /// The pinned fixture `ll444_ibc_rect.obu` (99614 bytes, provenance in
9636 /// `lanes/av1ibc444rect.report.md`) is a lossless `--profile=1 --i444
9637 /// --enable-intrabc=1` key frame. r1 pinned the (then-known) leaf8
9638 /// `palette_window` panic as its alignment witness; with that blocker
9639 /// fixed upstream (lane-av1leaf8oob) the frame decodes to completion and
9640 /// this gate is the FULL-FRAME exact `aomdec` comparison its r1 doc
9641 /// promised, flipped by lane-av1-ibcskip2 -- which also closed the
9642 /// SKIPPED intrabc sub8 chroma cells the r1 measurement called out: a
9643 /// skipped intrabc leaf's chroma is the bare frame copy at the DV
9644 /// (libaom's `av1_build_inter_predictors_sb` runs regardless of `skip`),
9645 /// never the intra-DC push that arm used to run. Fail-before, measured on
9646 /// this tree with the DV-copy arm cut back to the intra push: 2794 U +
9647 /// 2830 V samples differ across 180 distinct 4x4 cells, 175 of them
9648 /// exactly this frame's skipped intrabc leaves, luma clean; with the arm,
9649 /// 0 differing samples on every plane.
9650 #[test]
9651 fn a_lossless_444_intrabc_rect_leaf_walks_per_4x4_units() {
9652 const NAME: &str = "a_lossless_444_intrabc_rect_leaf_walks_per_4x4_units";
9653 const FIXTURE_LEN: usize = 99614;
9654 const FIXTURE_FNV: u64 = 0xa1b6_a84e_ac6a_656f;
9655 const W: usize = 320;
9656 const H: usize = 240;
9657 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
9658 .join("fixtures/ll444_ibc_rect.obu");
9659 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
9660 panic!(
9661 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
9662 which is a failure, not a skip",
9663 obu.display()
9664 )
9665 });
9666 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
9667 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
9668
9669 let _guard = lock_gate_counters();
9670 crate::decode::reset_ibc444rect_hits();
9671 crate::decode::reset_skipped_intrabc_dv_copy_hits();
9672 let frames = decode_stream(&stream).unwrap_or_else(|e| {
9673 panic!(
9674 "{NAME}: the fixture must decode to completion (the leaf8 \
9675 chroma buffers were fixed upstream): {e}"
9676 )
9677 });
9678 assert_eq!(frames.len(), 1, "{NAME}: shown frame count");
9679 let luma = crate::decode::intrabc_rect8_lossless_luma_hits();
9680 let chroma = crate::decode::intrabc_rect8_lossless_chroma_hits();
9681 assert_eq!(
9682 (luma, chroma),
9683 (339, 339),
9684 "{NAME}: the per-4x4 walk must fire on the fixture's full unskipped \
9685 intrabc rect census (got luma {luma}, chroma {chroma}) -- zero \
9686 means the fixture no longer reaches the fixed body (class \
9687 gate-blind-to-feature), more means the entropy desynced and \
9688 garbage blocks read as intrabc rect leaves"
9689 );
9690 let dv_skips = crate::decode::skipped_intrabc_dv_copy_hits();
9691 assert_eq!(
9692 dv_skips, 150,
9693 "{NAME}: the skipped-intrabc DV-copy chroma arm must fire on every \
9694 one of the fixture's 150 skipped intrabc leaves (got {dv_skips}) \
9695 -- zero means the arm is unreachable (class gate-blind-to-feature)"
9696 );
9697
9698 // The oracle aomdec, rawvideo out: one concatenated yuv444p frame.
9699 if aomdec_available(NAME) {
9700 let dir = std::env::temp_dir().join(format!("ec-av1-ibcskip2-{}", std::process::id()));
9701 let _ = std::fs::remove_dir_all(&dir);
9702 std::fs::create_dir_all(&dir).expect("scratch dir");
9703 let raw = dir.join("aomdec.raw");
9704 let out = Command::new(aomdec_path())
9705 .args(["--codec=av1", "--rawvideo", "-o"])
9706 .arg(&raw)
9707 .arg(&obu)
9708 .stdin(Stdio::null())
9709 .stdout(Stdio::piped())
9710 .stderr(Stdio::piped())
9711 .output()
9712 .expect("aomdec failed to run");
9713 assert!(
9714 out.status.success(),
9715 "{NAME}: the oracle aomdec refused the stream: {}",
9716 String::from_utf8_lossy(&out.stderr)
9717 );
9718 let ref_raw = std::fs::read(&raw).expect("aomdec rawvideo output");
9719 let _ = std::fs::remove_dir_all(&dir);
9720 assert_eq!(ref_raw.len(), W * H * 3, "{NAME}: aomdec raw size");
9721 let f = &frames[0];
9722 for (plane, off, p) in [
9723 (&f.y, 0usize, "Y"),
9724 (&f.u, W * H, "U"),
9725 (&f.v, 2 * W * H, "V"),
9726 ] {
9727 let want = &ref_raw[off..off + W * H];
9728 let bad = plane
9729 .iter()
9730 .zip(want)
9731 .filter(|&(&a, &b)| a as u8 != b)
9732 .count();
9733 assert_eq!(
9734 bad, 0,
9735 "{NAME}: aomdec plane {p}: {bad} samples differ -- a \
9736 regression here reopens the skipped-intrabc sub8 chroma \
9737 predictor or the rect walk"
9738 );
9739 }
9740 }
9741 eprintln!(
9742 "{NAME}: frame sample-exact vs oracle aomdec; {luma}+{chroma} rect \
9743 walks, {dv_skips} skipped-intrabc DV copies"
9744 );
9745 }
9746
9747 /// lane-dkey: the palette-neighbour-band gate. A palette-Y block's size and
9748 /// colours used to stay standing in the mi-granular above/left bands after a
9749 /// sub-8x8 group was decoded next to it -- the sub-8x8 readers published
9750 /// skip/lf/mode state but no palette state, while libaom's mi grid carries
9751 /// `palette_size == 0` in exactly those cells (`av1_allow_palette` needs
9752 /// BLOCK_8X8 and up). The next intra block then read `palette_y_mode` off
9753 /// CDF row 1 where libaom reads row 0 (class `cdf-row-held-constant`),
9754 /// decoded a palette libaom never coded, and skipped the `use_filter_intra`
9755 /// symbol a palette block has none of: one symbol short, tile desynced.
9756 ///
9757 /// Measured on the instrumented aomdec at KEY-frame block mi(76,88) of this
9758 /// very stream (`EC_PALSYN_AOM ... ctx=0 y=0` against our `mode_ctx=1`).
9759 /// Without the fix every one of the 12 frames differs from ffmpeg's decode
9760 /// from luma sample 491904 on.
9761 ///
9762 /// The source is SYNTHETIC (no film sample lives in `fixtures`): the dark,
9763 /// near-flat background libaom's own screen-content detector counts as
9764 /// screen content (2..=4 distinct luma values per 16x16 block), which is
9765 /// what turns palette on, plus one textured patch at a HALF-PEL position on
9766 /// half the frames so the encoder splits that region down to 4x4 groups
9767 /// beside its palette blocks.
9768 #[test]
9769 fn a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact() {
9770 const NAME: &str =
9771 "a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact";
9772 if !have_ffmpeg() {
9773 eprintln!("SKIP {NAME}: no ffmpeg");
9774 return;
9775 }
9776 let (w, h, frames) = (1920usize, 1024usize, 12usize);
9777 let mut raw = Vec::with_capacity(frames * w * h * 3 / 2);
9778 for f in 0..frames {
9779 let mut y = vec![0u8; w * h];
9780 for row in 0..h {
9781 for col in 0..w {
9782 y[row * w + col] =
9783 16 + ((col / 32 + row / 32) % 5) as u8 + ((col / 4 + row / 4) % 3) as u8;
9784 }
9785 }
9786 // 2.5 px per pair of frames: integer on one pair, half a pixel off
9787 // on the next (linear interpolation), so the patch's edges land
9788 // mid-sample and the encoder splits there.
9789 let x0 = 200.0 + 2.5 * (f / 2) as f64;
9790 let (fx, ix) = (x0.fract(), x0.floor() as usize);
9791 for row in 300..428 {
9792 for col in 0..192 {
9793 let tex = |u: f64| -> f64 {
9794 let v = (row - 300) as f64;
9795 30.0 + 100.0 * (0.5 + 0.5 * ((u * 0.35).sin() * (v * 0.21).cos()))
9796 };
9797 let s = tex(col as f64) * (1.0 - fx) + tex(col as f64 - 1.0) * fx;
9798 y[row * w + ix + col] = s.round().clamp(0.0, 255.0) as u8;
9799 }
9800 }
9801 raw.extend_from_slice(&y);
9802 raw.extend(std::iter::repeat_n(128u8, w * h / 2));
9803 }
9804 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
9805 let src = std::env::temp_dir().join(format!("ec-av1-palsub8-{}.yuv", std::process::id()));
9806 std::fs::write(&src, &raw).expect("raw source");
9807 let out = Command::new("ffmpeg")
9808 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
9809 .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"])
9810 .arg(&src)
9811 .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"])
9812 .args([
9813 "-cpu-used",
9814 "6",
9815 "-b:v",
9816 "0",
9817 "-crf",
9818 "35",
9819 "-f",
9820 "obu",
9821 "-",
9822 ])
9823 .stdin(Stdio::null())
9824 .stdout(Stdio::piped())
9825 .stderr(Stdio::piped())
9826 .output()
9827 .expect("ffmpeg failed to run");
9828 let _ = std::fs::remove_file(&src);
9829 if !out.status.success() {
9830 eprintln!(
9831 "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})",
9832 String::from_utf8_lossy(&out.stderr)
9833 );
9834 return;
9835 }
9836 let stream = out.stdout;
9837 let ours = decode_stream(&stream).expect("libaom screen-content stream decodes");
9838 let theirs = ffmpeg_decode_sequence(&stream, w, h, frames);
9839 assert_eq!(ours.len(), frames, "{NAME}: shown frame count");
9840 for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() {
9841 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
9842 let first = l.iter().zip(r.iter()).position(|(x, y)| x != y);
9843 assert!(
9844 first.is_none(),
9845 "{NAME}: frame {i} plane {plane} differs from ffmpeg at sample {}",
9846 first.unwrap()
9847 );
9848 assert_eq!(
9849 l.len(),
9850 r.len(),
9851 "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has {} -- a \
9852 short plane would zip-truncate the compare above and hide a chroma-span \
9853 defect",
9854 l.len(),
9855 r.len()
9856 );
9857 }
9858 }
9859 }
9860
9861 /// Hardened past the report-only test above: a real libaom-av1 gradients
9862 /// stream, pinned deterministic (`gradients`' own `seed=`, plus
9863 /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search
9864 /// cannot pick a different mode set run to run) and with CDEF turned off
9865 /// (this decoder's tile path never applies that in-loop filter -- see
9866 /// `cdef_is_active` in `decode_stream` -- so a stream that leaves it on
9867 /// decodes-but-wrong instead of refusing at cdef_bits==0; ffmpeg's
9868 /// `-enable-cdef 0` keeps this fixture out of that gap rather than this
9869 /// test working around it). Asserts pixel-exact against ffmpeg's own
9870 /// decode of the identical bytes, not just "decoded without error".
9871 #[test]
9872 fn a_real_libaom_gradients_stream_decodes_pixel_exact() {
9873 if !have_ffmpeg() {
9874 eprintln!("SKIP a_real_libaom_gradients_stream_decodes_pixel_exact: no ffmpeg");
9875 return;
9876 }
9877 let (width, height) = (64, 64);
9878 let stream = libaom_encode_with(
9879 &gradients_source(42, width, height, "rate=1"),
9880 width,
9881 height,
9882 15,
9883 &[
9884 "-threads",
9885 "1",
9886 "-row-mt",
9887 "0",
9888 "-tile-columns",
9889 "0",
9890 "-tile-rows",
9891 "0",
9892 "-enable-cdef",
9893 "0",
9894 ],
9895 )
9896 .expect("ffmpeg encode");
9897 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
9898 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
9899 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
9900 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
9901 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
9902 }
9903
9904 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but at
9905 /// 32x32 (below `is_cfl_allowed`'s 32x32 luma bound as a *single*
9906 /// undivided block, spec 5.11.5) rather than 64x64 -- a whole 64x64 SB
9907 /// is never CFL-eligible itself, only its <=32x32 partitions, and
9908 /// `testsrc2`/`gradients` at 64x64 with rect/ab/1to4/angle-delta search
9909 /// disabled reliably pick a whole-SB `PARTITION_NONE` (probed
9910 /// lane-av1real r2), so no fixture at that size exercises CfL at all.
9911 /// A 32x32 frame is exactly the whole-block, CFL-allowed case, and
9912 /// lane-av1real r2 found `gradients` there reliably selects
9913 /// `UV_CFL_PRED` (`uv_mode=13`) across a crf sweep -- `testsrc2` there
9914 /// stays DC. Proves the CfL port this round added, not just DC-chroma
9915 /// decode: pixel-exact against ffmpeg's own decode, not just "decoded".
9916 ///
9917 #[test]
9918 fn a_real_libaom_cfl_stream_decodes_pixel_exact() {
9919 if !have_ffmpeg() {
9920 eprintln!("SKIP a_real_libaom_cfl_stream_decodes_pixel_exact: no ffmpeg");
9921 return;
9922 }
9923 let (width, height) = (32, 32);
9924 let stream = libaom_encode_with(
9925 &gradients_source(42, width, height, "rate=1"),
9926 width,
9927 height,
9928 15,
9929 &[
9930 "-threads",
9931 "1",
9932 "-row-mt",
9933 "0",
9934 "-tile-columns",
9935 "0",
9936 "-tile-rows",
9937 "0",
9938 "-enable-cdef",
9939 "0",
9940 ],
9941 )
9942 .expect("ffmpeg encode");
9943 let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
9944 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
9945 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
9946 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
9947 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
9948 }
9949
9950 /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but leaves
9951 /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
9952 /// proves `apply_cdef` itself, not just that this decoder still works
9953 /// when the filter never fires. Gradient content at a low crf reliably
9954 /// gives libaom something to dering.
9955 ///
9956 /// lane-av1skipfix: the attempt-loop shape. A single-SB 64x64 frame can
9957 /// never make libaom write `cdef_bits > 0` (nothing to differentiate per
9958 /// superblock), so this recipe is MULTI-SB and MULTI-FRAME, and it sweeps
9959 /// (size, cpu-used, crf) until one attempt reads a real `cdef_idx` literal
9960 /// -- MEASURED 2026-09-29 on `a21f3680`: 64x64 at every crf/cpu reads
9961 /// ZERO `cdef_idx` (single superblock, `bits == 0`, though `apply_cdef`
9962 /// does filter with a nonzero strength pair), while 128x64/128x128 at
9963 /// 24 frames read 2-8. Every attempt that decodes is ALWAYS pixel-
9964 /// compared against ffmpeg's own decode of the identical bytes; a decode
9965 /// error is a named refusal recorded per attempt, never a SKIP, and
9966 /// exhausting every attempt -- or decoding without ever reading a
9967 /// `cdef_idx` -- is a hard FAILURE (an unfired gate is a vacuous gate,
9968 /// class `gate-skips-on-its-own-failure`).
9969 #[test]
9970 fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
9971 const NAME: &str = "a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact";
9972 let _gate_lock = lock_gate_counters();
9973 if !have_ffmpeg() {
9974 eprintln!("SKIP {NAME}: no ffmpeg");
9975 return;
9976 }
9977 // (width, height, frames, cpu-used, crf). The frame count is what
9978 // gives libaom's cdef search more than one superblock to price.
9979 const RECIPES: [(usize, usize, usize, &str, u32); 8] = [
9980 (128, 64, 24, "0", 20),
9981 (128, 64, 24, "2", 20),
9982 (128, 64, 24, "0", 16),
9983 (128, 128, 24, "2", 20),
9984 (128, 128, 24, "0", 16),
9985 (128, 128, 24, "0", 24),
9986 (128, 64, 24, "2", 24),
9987 (128, 128, 24, "2", 24),
9988 ];
9989 let mut refusals = Vec::new();
9990 let mut counted_exact = 0u32;
9991 let mut uncounted_exact = 0u32;
9992 for (w, h, frames, cpu, crf) in RECIPES {
9993 let Some(stream) = libaom_encode_with(
9994 &gradients_source(42, w, h, "rate=25"),
9995 w,
9996 h,
9997 crf,
9998 &[
9999 "-cpu-used",
10000 cpu,
10001 "-frames:v",
10002 &frames.to_string(),
10003 "-threads",
10004 "1",
10005 "-row-mt",
10006 "0",
10007 "-tile-columns",
10008 "0",
10009 "-tile-rows",
10010 "0",
10011 ],
10012 ) else {
10013 refusals.push(format!(
10014 "{w}x{h} cpu-used {cpu} crf {crf}: ffmpeg itself refused"
10015 ));
10016 continue;
10017 };
10018 let before = decode::cdef_idx_hits();
10019 let decoded = match decode_stream(&stream) {
10020 Ok(frames) => frames,
10021 Err(e) => {
10022 refusals.push(format!("{w}x{h} cpu-used {cpu} crf {crf}: {e}"));
10023 continue;
10024 }
10025 };
10026 // A decode that succeeded is ALWAYS pixel-compared; the hit
10027 // counter only decides whether the attempt counts as firing
10028 // (class `counter-from-refused-stream`).
10029 let counted = decode::cdef_idx_hits() != before;
10030 if counted {
10031 counted_exact += 1;
10032 } else {
10033 uncounted_exact += 1;
10034 }
10035 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, w, h, frames);
10036 assert_eq!(decoded.len(), frames);
10037 for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
10038 assert_eq!(
10039 got.y, want.y,
10040 "{NAME} frame {i} luma vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
10041 cdef_idx fired: {counted})"
10042 );
10043 assert_eq!(
10044 got.u, want.u,
10045 "{NAME} frame {i} U vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
10046 cdef_idx fired: {counted})"
10047 );
10048 assert_eq!(
10049 got.v, want.v,
10050 "{NAME} frame {i} V vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
10051 cdef_idx fired: {counted})"
10052 );
10053 }
10054 if counted_exact >= 2 {
10055 break;
10056 }
10057 }
10058 gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
10059 assert!(
10060 counted_exact > 0,
10061 "{NAME}: no attempt of {} read a cdef_idx literal -- CDEF is not exercised \
10062 (class gate-blind-to-feature):\n{}",
10063 RECIPES.len(),
10064 refusals.join("\n")
10065 );
10066 }
10067
10068 /// Path to a real `aomenc` build carrying the reference options this
10069 /// fixture needs (`--max-partition-size`, `--enable-tx-size-search`,
10070 /// `--loopfilter-control`) -- this box's `ffmpeg` links a libaom too old
10071 /// to expose `enable-tx-size-search`/`loopfilter-control` through its
10072 /// own `-aom-params` passthrough (probed live: "Cannot find aom
10073 /// option"), so [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]
10074 /// shells out to the standalone binary instead of ffmpeg's libaom-av1
10075 /// wrapper every other test here uses. `EC_AV1_AOMENC` overrides the
10076 /// default dev-build path; the test skips (not fails) when neither this
10077 /// nor `ffmpeg` is present.
10078 fn aomenc_path() -> std::path::PathBuf {
10079 if let Some(p) = std::env::var_os("EC_AV1_AOMENC") {
10080 return std::path::PathBuf::from(p);
10081 }
10082 // The oracle used to live only under `/tmp`, which this box's tmpfs
10083 // guard reclaims -- when it did, all 20 aomenc gates below went
10084 // silently vacuous (SKIP, suite still green). The durable location
10085 // is provisioned by `scripts/build-aom-oracle.sh`; the `/tmp` path
10086 // stays last as a legacy fallback.
10087 let mut candidates = Vec::new();
10088 if let Some(home) = std::env::var_os("HOME") {
10089 candidates.push(std::path::PathBuf::from(&home).join(".cache/aom-oracle/build/aomenc"));
10090 }
10091 candidates.push("/tmp/libaom-src/build/encoder/aomenc".into());
10092 candidates
10093 .iter()
10094 .find(|p| p.is_file())
10095 .cloned()
10096 .unwrap_or_else(|| candidates.remove(0))
10097 }
10098
10099 /// Whether the aomenc oracle is present. Absence normally SKIPs (a
10100 /// checkout without the oracle should still run the rest of the suite),
10101 /// but `EC_AV1_REQUIRE_AOMENC=1` turns it into a hard failure so a batch
10102 /// run cannot report green off 20 skipped gates.
10103 /// Where a pinned stream lives. `fixtures/` is a symlink to a durable
10104 /// directory outside the repo, so a pin captured in one session is still
10105 /// there in the next; a session scratchpad is not (tmpfs reaps it, and
10106 /// four pins were silently dead because of that).
10107 fn pin_dir() -> std::path::PathBuf {
10108 if let Some(p) = std::env::var_os("EC_AV1_PIN_DIR") {
10109 return std::path::PathBuf::from(p);
10110 }
10111 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
10112 .join("../../fixtures")
10113 .canonicalize()
10114 .unwrap_or_else(|_| std::path::PathBuf::from("fixtures"))
10115 }
10116
10117 /// A COMMITTED pin: `crates/ec-av1/fixtures/<name>`, which travels in the
10118 /// tarball and is therefore present on every runner. `pin_dir()` resolves
10119 /// to the gitignored root `fixtures/`, so a pin written there is lost when
10120 /// the machine's scratchpad is reaped -- three gates sat at `rc=0` having
10121 /// tested nothing for exactly that reason (lane-av1pins). Falls back to
10122 /// `pin_dir()` so a locally re-captured stream still overrides.
10123 /// Read a pin that a gate cannot proceed without. A missing pin is a
10124 /// HARD failure naming the path and the generator, never a raw io panic
10125 /// and never a silent skip: `EC_AV1_GATE_DUMP_PIN` points the gate at a
10126 /// freshly captured stream, and a runner without the committed copy must
10127 /// say so instead of reporting green having tested nothing.
10128 fn require_pin(path: &std::path::Path, name: &str) -> Vec<u8> {
10129 std::fs::read(path).unwrap_or_else(|e| {
10130 panic!(
10131 "no pinned bytes at {} ({e}) -- set EC_AV1_GATE_DUMP_PIN to a freshly \
10132 captured stream, or restore the committed copy at \
10133 crates/ec-av1/fixtures/{name}",
10134 path.display()
10135 )
10136 })
10137 }
10138
10139 fn crate_pin(name: &str) -> std::path::PathBuf {
10140 let in_crate = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
10141 .join("fixtures")
10142 .join(name);
10143 if in_crate.is_file() {
10144 in_crate
10145 } else {
10146 pin_dir().join(name)
10147 }
10148 }
10149
10150 fn have_aomenc() -> bool {
10151 let present = aomenc_path().is_file();
10152 assert!(
10153 present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
10154 "EC_AV1_REQUIRE_AOMENC is set but no aomenc at {} -- run scripts/build-aom-oracle.sh",
10155 aomenc_path().display()
10156 );
10157 present
10158 }
10159
10160 /// lane-av1oracleskip: the probe for the ORACLE COMPARER, in the same
10161 /// shape as [`have_ffmpeg`] -- probe first, then `assert!` LAST, with the
10162 /// env escape -- and it prints its own SKIP so a caller cannot skip the
10163 /// compare silently.
10164 ///
10165 /// Why this exists: thirteen gates wrapped their oracle arm in a bare
10166 /// `if aomdec_path().is_file()`, and that shape had NO env escape at all.
10167 /// An oracle build with `aomenc` but no `aomdec` beside it (or an
10168 /// `EC_AV1_AOMDEC` override pointing at a moved path) made the gate
10169 /// encode, decode, assert its geometry and its counters, and then quietly
10170 /// never compare -- green having measured nothing, with no line in the
10171 /// output to notice. Nine of the thirteen printed a SKIP in an `else` and
10172 /// four printed nothing at all; both are the same defect, and both are
10173 /// closed by one probe.
10174 ///
10175 /// With `EC_AV1_REQUIRE_AOMENC` (or the aomdec-specific
10176 /// `EC_AV1_REQUIRE_AOMDEC`) set, the absence is a HARD failure naming the
10177 /// path that was looked for -- that is the batch-run guarantee, and it is
10178 /// what the bare `is_file()` could not give. With it unset the SKIP below
10179 /// is printed and the gate still passes: that remains a developer-only
10180 /// convenience for a checkout without an oracle, never evidence.
10181 fn aomdec_available(name: &str) -> bool {
10182 let present = aomdec_path().is_file();
10183 let require = std::env::var_os("EC_AV1_REQUIRE_AOMDEC").is_some()
10184 || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_some();
10185 assert!(
10186 present || !require,
10187 "{name}: no oracle aomdec at {} -- the pixel compare this gate exists for would be \
10188 skipped, and EC_AV1_REQUIRE_AOMDEC/EC_AV1_REQUIRE_AOMENC is set. Build the oracle \
10189 with scripts/build-aom-oracle.sh, or point EC_AV1_AOMDEC at a real aomdec.",
10190 aomdec_path().display()
10191 );
10192 if !present {
10193 eprintln!(
10194 "SKIP {name}: no oracle aomdec at {} -- the pixel compare is NOT running (set \
10195 EC_AV1_REQUIRE_AOMDEC=1 to make this a failure)",
10196 aomdec_path().display()
10197 );
10198 }
10199 present
10200 }
10201
10202 // lane-av1cmpaudit2: this thread's oracle override, set by
10203 // `set_oracle_path` and consulted by `aomdec_path` ahead of the env var.
10204 //
10205 // It is thread-local for the same reason `FINAL_DUMP_PREFIX` is: the
10206 // control test `every_oracle_comparator_reds_on_a_one_byte_wrong_oracle`
10207 // has to hand the helpers a DELIBERATELY WRONG oracle, and a
10208 // process-global `std::env::set_var` could not do that safely -- the
10209 // crate denies `unsafe_code`, and even where it did not, one test's
10210 // tampered oracle would leak into every sibling test's comparison
10211 // running on another thread. A thread-local override confines the wrong
10212 // oracle to the one thread that asked for it.
10213 thread_local! {
10214 static ORACLE_PATH: std::cell::RefCell<Option<std::path::PathBuf>> =
10215 const { std::cell::RefCell::new(None) };
10216 }
10217
10218 /// Points this thread's oracle helpers at `path`. `None` restores the
10219 /// real `aomdec`.
10220 fn set_oracle_path(path: Option<std::path::PathBuf>) {
10221 ORACLE_PATH.with(|c| *c.borrow_mut() = path);
10222 }
10223
10224 // lane-film10fix: this thread's ffmpeg override, set by
10225 // `set_ffmpeg_path` and consulted by `ffmpeg_path` ahead of the bare
10226 // name. Same shape and same reason as `ORACLE_PATH` above: the control
10227 // test `every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg` has
10228 // to hand the `ffmpeg_decode_sequence*` helpers a DELIBERATELY WRONG
10229 // reference, and a process-global PATH edit would leak that wrong
10230 // reference into every sibling test decoding on another thread. The
10231 // crate denies `unsafe_code`, so `std::env::set_var` is not available
10232 // either; a thread-local confines the tamper to the one thread.
10233 thread_local! {
10234 static FFMPEG_PATH: std::cell::RefCell<Option<std::path::PathBuf>> =
10235 const { std::cell::RefCell::new(None) };
10236 }
10237
10238 /// Points this thread's `ffmpeg_decode_sequence*` helpers at `path`.
10239 /// `None` restores the real `ffmpeg` on PATH.
10240 fn set_ffmpeg_path(path: Option<std::path::PathBuf>) {
10241 FFMPEG_PATH.with(|c| *c.borrow_mut() = path);
10242 }
10243
10244 /// The `ffmpeg` every reference helper in this module spawns.
10245 fn ffmpeg_path() -> std::path::PathBuf {
10246 if let Some(p) = FFMPEG_PATH.with(|c| c.borrow().clone()) {
10247 return p;
10248 }
10249 std::path::PathBuf::from("ffmpeg")
10250 }
10251 /// The instrumented `aomdec` beside the `aomenc` oracle
10252 /// (`scripts/build-aom-oracle.sh` + `scripts/instrument-aom-oracle.sh`).
10253 fn aomdec_path() -> std::path::PathBuf {
10254 if let Some(p) = ORACLE_PATH.with(|c| c.borrow().clone()) {
10255 return p;
10256 }
10257 if let Some(p) = std::env::var_os("EC_AV1_AOMDEC") {
10258 return std::path::PathBuf::from(p);
10259 }
10260 aomenc_path().with_file_name("aomdec")
10261 }
10262
10263 /// Decodes `stream` with both this decoder and the instrumented oracle
10264 /// `aomdec`, and compares EVERY decoded frame in DECODE order --
10265 /// including the hidden (`show_frame == 0`) alt-ref frames no other gate
10266 /// in this repo can see, because `decode_stream` only pushes shown
10267 /// frames and `ffmpeg -f obu ... rawvideo` only emits shown frames
10268 /// (class gate-blind-to-hidden-frames: a hidden frame's defect surfaces
10269 /// only as drift on some later shown frame, if at all).
10270 ///
10271 /// Both sides write the final, post-deblock/CDEF/LR/superres frame as it
10272 /// is stored into the reference buffer (`EC_AV1_FINAL_DUMP`, ours in
10273 /// `decode_stream`, the oracle's in rung 12 of
10274 /// `scripts/instrument-aom-oracle.sh`), 8-bit as u8 / high bitdepth as
10275 /// u16 LE. Returns `(frames_decoded, hidden_frames)`.
10276 fn decode_all_frames_vs_oracle(stream: &[u8], name: &str) -> (usize, usize) {
10277 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
10278 let _ = std::fs::remove_dir_all(&dir);
10279 std::fs::create_dir_all(&dir).expect("scratch dir");
10280 let obu = dir.join("in.obu");
10281 std::fs::write(&obu, stream).expect("writing the stream");
10282 let aom_prefix = dir.join("aom");
10283 let out = Command::new(aomdec_path())
10284 .args(["--codec=av1", "-o"])
10285 .arg(dir.join("out.y4m"))
10286 .arg(&obu)
10287 .env("EC_AV1_FINAL_DUMP", &aom_prefix)
10288 .stdin(Stdio::null())
10289 .stdout(Stdio::piped())
10290 .stderr(Stdio::piped())
10291 .output()
10292 .expect("aomdec failed to run");
10293 assert!(
10294 out.status.success(),
10295 "{name}: the oracle aomdec refused the stream: {}",
10296 String::from_utf8_lossy(&out.stderr)
10297 );
10298 let count_dumps = |prefix: &std::path::Path| -> usize {
10299 let mut n = 0usize;
10300 while std::path::PathBuf::from(format!("{}.f{n}", prefix.display())).is_file() {
10301 n += 1;
10302 }
10303 n
10304 };
10305 let oracle_frames = count_dumps(&aom_prefix);
10306 assert!(
10307 oracle_frames > 0,
10308 "{name}: the oracle wrote no EC_AV1_FINAL_DUMP frames -- rung 12 of \
10309 scripts/instrument-aom-oracle.sh is missing from {}",
10310 aomdec_path().display()
10311 );
10312 let ours_prefix = dir.join("ours");
10313 set_final_dump_prefix(Some(ours_prefix.display().to_string()));
10314 let decoded = decode_stream(stream);
10315 set_final_dump_prefix(None);
10316 let shown = decoded
10317 .unwrap_or_else(|e| panic!("{name}: this decoder refused the stream: {e}"))
10318 .len();
10319 let our_frames = count_dumps(&ours_prefix);
10320 assert_eq!(
10321 our_frames, oracle_frames,
10322 "{name}: decoded {our_frames} frames in decode order, the oracle decoded \
10323 {oracle_frames}"
10324 );
10325 for i in 0..oracle_frames {
10326 let want =
10327 std::fs::read(format!("{}.f{i}", aom_prefix.display())).expect("oracle dump");
10328 let got = std::fs::read(format!("{}.f{i}", ours_prefix.display())).expect("our dump");
10329 assert_eq!(
10330 got.len(),
10331 want.len(),
10332 "{name}: decode-order frame {i} is {} bytes, the oracle's is {}",
10333 got.len(),
10334 want.len()
10335 );
10336 if let Some(at) = got.iter().zip(&want).position(|(a, b)| a != b) {
10337 let differing = got.iter().zip(&want).filter(|(a, b)| a != b).count();
10338 panic!(
10339 "{name}: decode-order frame {i} of {oracle_frames} ({shown} shown, {} \
10340 hidden) differs from the oracle at byte {at} (ours {} vs {}), {differing} \
10341 bytes differ -- stream pinned at {}",
10342 oracle_frames - shown,
10343 got[at],
10344 want[at],
10345 obu.display()
10346 );
10347 }
10348 }
10349 let hidden = oracle_frames - shown;
10350 let _ = std::fs::remove_dir_all(&dir);
10351 (oracle_frames, hidden)
10352 }
10353
10354 /// lane-av1422anom: a COUNTING oracle comparison.
10355 ///
10356 /// [`assert_rawvideo_matches`] is the right tool for "these must be equal"
10357 /// and the wrong tool for a lane that has to classify many cells: it
10358 /// panics on the first differing byte, so it answers one cell per process
10359 /// and cannot report a magnitude. This returns the count instead.
10360 ///
10361 /// It exists because the previous lane's per-cell counter was tautological:
10362 /// it packed our own decoded samples into `ours` and then compared `ours`
10363 /// against the same samples, never touching the oracle's bytes, so it
10364 /// reported "0 wrong" on every cell including one that differs from
10365 /// `aomdec` in 1612 samples. [`the_counting_oracle_diff_reports_a_real_difference`]
10366 /// below is the test that keeps that mistake from recurring.
10367 ///
10368 /// Returns `(wrong_y, wrong_u, wrong_v, frames_total, frames_exact)`, or
10369 /// `None` when the two sides are not byte-comparable at all (a size
10370 /// mismatch, which is a different failure and must not read as "exact").
10371 /// `flip` flips ONE bit of the ORACLE's own bytes before comparing, so
10372 /// [`the_counting_oracle_diff_detects_one_flipped_oracle_byte`] can prove
10373 /// the comparison still reads the oracle on a stream that is now exact.
10374 fn count_rawvideo_diffs(
10375 stream: &[u8],
10376 name: &str,
10377 flip: Option<usize>,
10378 ) -> Option<(usize, usize, usize, usize, usize)> {
10379 let dir = std::env::temp_dir().join(format!("ec-av1-{name}-{}", std::process::id()));
10380 let _ = std::fs::remove_dir_all(&dir);
10381 std::fs::create_dir_all(&dir).expect("scratch dir");
10382 let obu = dir.join("in.obu");
10383 std::fs::write(&obu, stream).expect("writing the stream");
10384 let raw = dir.join("aomdec.raw");
10385 let out = Command::new(aomdec_path())
10386 .args(["--codec=av1", "--rawvideo", "-o"])
10387 .arg(&raw)
10388 .arg(&obu)
10389 .stdin(Stdio::null())
10390 .stdout(Stdio::piped())
10391 .stderr(Stdio::piped())
10392 .output()
10393 .expect("aomdec failed to run");
10394 assert!(
10395 out.status.success(),
10396 "{name}: the oracle aomdec refused the stream: {}",
10397 String::from_utf8_lossy(&out.stderr)
10398 );
10399 let mut want = std::fs::read(&raw).expect("aomdec rawvideo output");
10400 if let Some(i) = flip {
10401 assert!(
10402 i < want.len(),
10403 "{name}: flip index {i} is past the oracle's {} bytes",
10404 want.len()
10405 );
10406 want[i] ^= 0x01;
10407 }
10408 let _ = std::fs::remove_dir_all(&dir);
10409 let bit_depth = stream_bit_depth(stream, name);
10410 let decoded = decode_stream(stream).expect("decode for comparison");
10411 let ours = pack_rawvideo(&decoded, bit_depth, name);
10412 if ours.len() != want.len() {
10413 return None;
10414 }
10415 let bpp = if bit_depth == 8 { 1 } else { 2 };
10416 // The plane split comes from the FIRST decoded picture, not from a
10417 // formula: a 4:2:0 picture's chroma is a quarter of the luma, a
10418 // 4:2:2/4:4:4 chroma is not, and a wrong split silently attributes
10419 // every wrong sample to the wrong plane.
10420 let f0 = decoded.first().expect("a decoded picture");
10421 let (w, h) = (f0.width, f0.height);
10422 let (ys, us) = (w * h * bpp, f0.u.len() * bpp);
10423 let mut wrong = [0usize; 3];
10424 for (i, (&a, &b)) in ours.iter().zip(&want).enumerate() {
10425 if a == b {
10426 continue;
10427 }
10428 let pi = if i < ys {
10429 0
10430 } else if i < ys + us {
10431 1
10432 } else {
10433 2
10434 };
10435 wrong[pi] += 1;
10436 }
10437 let per = ys + 2 * us;
10438 let frames = decoded.len();
10439 let exact = (0..frames)
10440 .filter(|k| ours[k * per..(k + 1) * per] == want[k * per..(k + 1) * per])
10441 .count();
10442 Some((wrong[0], wrong[1], wrong[2], frames, exact))
10443 }
10444
10445 /// lane-av1422h232: the non-vacuity test for [`count_rawvideo_diffs`].
10446 ///
10447 /// A cell-classifying counter that cannot report a difference is worse
10448 /// than no counter, because it reports "exact" for everything -- that is
10449 /// exactly how lane-av1422remeasure's "18/18 byte-exact" table was
10450 /// produced (it compared our own packed samples against the same
10451 /// samples, never reading `aomdec`'s output).
10452 ///
10453 /// It used to lean on the pinned witness DIFFERING to prove the counting
10454 /// path fires. That witness is byte-exact now (lane-av1422hrtx fixed the
10455 /// 32-point inter chroma `tx_type`), so "it differs" is no longer
10456 /// available and a witness-based version of this test would be vacuous by
10457 /// construction. Instead this proves the same property directly and
10458 /// unconditionally: flipping ONE bit of the ORACLE's own bytes must move
10459 /// the count by exactly one, in the plane that bit is in, and knock exactly
10460 /// one frame out of `frames_exact`. A comparator that had stopped reading
10461 /// the oracle reports the baseline numbers again and fails by name.
10462 #[test]
10463 fn the_counting_oracle_diff_detects_one_flipped_oracle_byte() {
10464 const NAME: &str = "the_counting_oracle_diff_detects_one_flipped_oracle_byte";
10465 // lane-av1cmpaudit2: same mutex as every other oracle gate -- this
10466 // one reads `aomdec_path()`, so it must not overlap a sibling's
10467 // tampered-oracle run.
10468 let _gate_lock = lock_gate_counters();
10469 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
10470 .join("fixtures")
10471 .join("420_oddheight_320x232.obu");
10472 let data = std::fs::read(&path).expect("the pinned witness is missing");
10473 let (wy, wu, wv, frames, exact) =
10474 count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
10475 assert_eq!(
10476 (wy, wu, wv, exact),
10477 (0, 0, 0, frames),
10478 "{NAME}: the pinned witness must decode byte-exactly against `aomdec --rawvideo`"
10479 );
10480 // Frame 0 byte 0 is luma; byte 90_000 is inside frame 0's chroma.
10481 for (idx, plane) in [(0usize, 0usize), (90_000, 1)] {
10482 let (wy, wu, wv, _, exact) = count_rawvideo_diffs(&data, NAME, Some(idx))
10483 .expect("the two sides must be byte-comparable");
10484 let got = [wy, wu, wv];
10485 assert_eq!(
10486 got.iter().sum::<usize>(),
10487 1,
10488 "{NAME}: flipping oracle byte {idx} must report exactly ONE wrong sample \
10489 across all planes -- got {got:?}. Reporting the unflipped numbers means \
10490 the comparison stopped reading the oracle's bytes"
10491 );
10492 assert_eq!(got[plane], 1, "{NAME}: byte {idx} is in plane {plane}");
10493 assert_eq!(
10494 exact,
10495 frames - 1,
10496 "{NAME}: one flipped byte spoils one frame"
10497 );
10498 }
10499 eprintln!("{NAME}: baseline exact, each flipped oracle byte reported as exactly 1");
10500 }
10501
10502 /// lane-av1cmpaudit2: the permanent CONTROL for the class
10503 /// `comparator-that-never-reads-the-oracle`.
10504 ///
10505 /// The retracted predecessor lane's per-cell counter reported "0 wrong"
10506 /// on 18/18 cells -- including cells that differ from `aomdec
10507 /// --rawvideo` in 17658 samples -- because it packed OUR decoded samples
10508 /// into a buffer and compared that buffer against the same samples.
10509 /// `aomdec`'s output was written, length-checked, and never read.
10510 /// Nothing about that mistake is visible from the outside: the helper's
10511 /// signature, its panic text and its return type are all exactly what a
10512 /// working comparator has, and no amount of reading the source of a
10513 /// healthy-looking helper proves the next one is healthy.
10514 ///
10515 /// So the class is pinned here from the other direction.
10516 /// `EC_AV1_AOMDEC` is already the crate's oracle override, so this test
10517 /// points every oracle helper at a shim that runs the REAL `aomdec` and
10518 /// then corrupts exactly ONE byte of whatever it wrote -- the
10519 /// `--rawvideo` output and the `EC_AV1_FINAL_DUMP` frame 0 -- leaving
10520 /// every other sample a genuine decode. On a pin that IS byte-exact
10521 /// against the real oracle:
10522 ///
10523 /// 1. **arm 1, real oracle: every helper is GREEN.** Without this arm,
10524 /// arm 2's red could just be a stream that was never exact.
10525 /// 2. **arm 2, one-byte-wrong oracle: every helper is RED.** A helper
10526 /// that stays green here is the retracted defect itself: it cannot
10527 /// fail, so its green is worth nothing.
10528 ///
10529 /// One test, five helpers, and it goes red for the exact mistake that
10530 /// was retracted. Measured over this file: the other 62 tests that
10531 /// reach an oracle helper all take `lock_gate_counters()` before their
10532 /// first oracle call, which is what makes the process-global
10533 /// `EC_AV1_AOMDEC` safe to flip here.
10534 #[test]
10535 fn every_oracle_comparator_reds_on_a_one_byte_wrong_oracle() {
10536 const NAME: &str = "every_oracle_comparator_reds_on_a_one_byte_wrong_oracle";
10537 let _gate_lock = lock_gate_counters();
10538 if !aomdec_available(NAME) {
10539 return;
10540 }
10541 let pin = crate_pin("420_odd65x65_key.obu");
10542 let stream = std::fs::read(&pin).unwrap_or_else(|e| {
10543 panic!(
10544 "{NAME}: the control's pin {} is missing ({e}) -- restore the committed copy",
10545 pin.display()
10546 )
10547 });
10548 assert_eq!(
10549 stream_bit_depth(&stream, NAME),
10550 8,
10551 "{NAME}: the control's pin must be the 8-bit cell the shim corrupts"
10552 );
10553 let plane_samples = {
10554 let frames = decode_stream(&stream).expect("the control's pin must decode");
10555 let f = &frames[0];
10556 [f.y.len(), f.u.len(), f.v.len()]
10557 };
10558
10559 // ---- arm 1: the real oracle, every comparator green ------------
10560 {
10561 let obu = std::env::temp_dir().join(format!("{NAME}-arm1.obu"));
10562 std::fs::write(&obu, &stream).expect("writing the pin for arm 1");
10563 assert_rawvideo_matches(&obu, &stream, "oracle-control-arm1-rawvideo", 1, 8);
10564 let _ = std::fs::remove_file(&obu);
10565 let (frames, hidden) =
10566 decode_all_frames_vs_oracle(&stream, "oracle-control-arm1-alldumps");
10567 assert_eq!(
10568 (frames, hidden),
10569 (1, 0),
10570 "{NAME}: arm 1 expects one decode-order frame and no hidden frames"
10571 );
10572 let (wy, wu, wv, n, exact) =
10573 count_rawvideo_diffs(&stream, "oracle-control-arm1-count", None)
10574 .expect("arm 1: the two sides must be byte-comparable");
10575 assert_eq!(
10576 (wy, wu, wv),
10577 (0, 0, 0),
10578 "{NAME}: arm 1 runs against the REAL oracle, so every plane must be zero"
10579 );
10580 assert_eq!(
10581 (n, exact),
10582 (1, 1),
10583 "{NAME}: arm 1 expects one shown frame that is byte-identical"
10584 );
10585 let (differing, first) = key_frame_diffs(&stream, "oracle-control-arm1-kf");
10586 assert_eq!(
10587 (differing, first),
10588 (0, None),
10589 "{NAME}: arm 1's key frame must be byte-identical to the oracle's"
10590 );
10591 let [y, u, v] =
10592 oracle_plane_diffs(&stream, "oracle-control-arm1-planes", plane_samples);
10593 assert_eq!(
10594 [y, u, v],
10595 [0, 0, 0],
10596 "{NAME}: arm 1 must be zero on every plane against the real oracle"
10597 );
10598 }
10599
10600 // ---- the one-byte-wrong oracle ---------------------------------
10601 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
10602 let _ = std::fs::remove_dir_all(&dir);
10603 std::fs::create_dir_all(&dir).expect("scratch dir");
10604 let shim = dir.join("one-byte-wrong-aomdec.sh");
10605 // The real oracle's path rides in a sibling file rather than inside
10606 // the script, so a path with a quote or a space cannot mangle it and
10607 // the script body needs no `format!` escaping at all.
10608 std::fs::write(
10609 dir.join("real-aomdec"),
10610 aomdec_path().as_os_str().as_encoded_bytes(),
10611 )
10612 .expect("recording the real oracle's path for the shim");
10613 // Byte 7 of both the `--rawvideo` output and the `EC_AV1_FINAL_DUMP`
10614 // frame 0 is inside the Y plane, and its value is rotated by 128 so
10615 // the write always changes it. Nothing else is touched: the stream,
10616 // the geometry, the frame count and every other sample are a genuine
10617 // `aomdec` decode.
10618 let script = r#"#!/bin/sh
10619REAL=$(cat "$(dirname "$0")/real-aomdec")
10620rawvideo=0
10621out=""
10622prev=""
10623for a in "$@"; do
10624 if [ "$a" = "--rawvideo" ]; then rawvideo=1; fi
10625 if [ "$prev" = "-o" ]; then out="$a"; fi
10626 prev="$a"
10627done
10628"$REAL" "$@" || exit $?
10629flip() {
10630 [ -s "$1" ] || return 0
10631 b=$(od -An -tu1 -j 7 -N 1 "$1" 2>/dev/null | tr -d ' \n')
10632 [ -n "$b" ] || return 0
10633 esc=$(printf '\\%03o' $(( (b + 128) % 256 )))
10634 printf "$esc" | dd of="$1" bs=1 seek=7 count=1 conv=notrunc 2>/dev/null
10635 return 0
10636}
10637[ "$rawvideo" = 1 ] && flip "$out"
10638[ -n "$EC_AV1_FINAL_DUMP" ] && flip "$EC_AV1_FINAL_DUMP.f0"
10639exit 0
10640"#;
10641 std::fs::write(&shim, script).expect("writing the oracle shim");
10642 #[cfg(unix)]
10643 {
10644 use std::os::unix::fs::PermissionsExt;
10645 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755))
10646 .expect("the oracle shim must be executable");
10647 }
10648
10649 // ---- arm 2: same pin, oracle off by ONE byte -------------------
10650 // The override is THREAD-LOCAL, so the tampered oracle is confined
10651 // to this thread and no sibling test can see it; it is still cleared
10652 // before any result is asserted, so a red arm cannot leave this
10653 // test's own later work reading a wrong oracle.
10654 let reds: [bool; 5];
10655 {
10656 set_oracle_path(Some(shim.clone()));
10657 let panicked =
10658 |f: &dyn Fn()| std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).is_err();
10659 let rawvideo_red = panicked(&|| {
10660 let obu = std::env::temp_dir().join(format!("{NAME}-arm2.obu"));
10661 std::fs::write(&obu, &stream).expect("writing the pin for arm 2");
10662 assert_rawvideo_matches(&obu, &stream, "oracle-control-arm2-rawvideo", 1, 8);
10663 });
10664 let _ = std::fs::remove_file(std::env::temp_dir().join(format!("{NAME}-arm2.obu")));
10665 let dumps_red = panicked(&|| {
10666 decode_all_frames_vs_oracle(&stream, "oracle-control-arm2-alldumps");
10667 });
10668 let count_red = {
10669 let counted = count_rawvideo_diffs(&stream, "oracle-control-arm2-count", None)
10670 .unwrap_or_else(|| {
10671 panic!(
10672 "{NAME}: a single flipped oracle byte must NOT change the buffer \
10673 LENGTH -- returning None means the shim corrupted more than the \
10674 comparison"
10675 )
10676 });
10677 counted.0 + counted.1 + counted.2 > 0 && counted.4 < counted.3
10678 };
10679 let kf_red = {
10680 let (differing, first) = key_frame_diffs(&stream, "oracle-control-arm2-kf");
10681 differing > 0 && first.is_some()
10682 };
10683 let planes_red = {
10684 let [y, u, v] =
10685 oracle_plane_diffs(&stream, "oracle-control-arm2-planes", plane_samples);
10686 y + u + v > 0
10687 };
10688 set_oracle_path(None);
10689 let _ = std::fs::remove_dir_all(&dir);
10690 reds = [rawvideo_red, dumps_red, count_red, kf_red, planes_red];
10691 }
10692 // One assert, naming EVERY comparator that stayed green: a partial
10693 // run would report the first and hide whether the other four are
10694 // covered.
10695 let blind: Vec<&str> = [
10696 ("assert_rawvideo_matches", reds[0]),
10697 ("decode_all_frames_vs_oracle", reds[1]),
10698 ("count_rawvideo_diffs", reds[2]),
10699 ("key_frame_diffs", reds[3]),
10700 ("oracle_plane_diffs", reds[4]),
10701 ]
10702 .into_iter()
10703 .filter(|(_, red)| !red)
10704 .map(|(what, _)| what)
10705 .collect();
10706 assert!(
10707 blind.is_empty(),
10708 "{NAME}: {} of 5 oracle comparators stayed GREEN against an oracle that is wrong \
10709 by exactly one byte -- {blind:?} -- they cannot fail, so their green proves \
10710 nothing (class `comparator-that-never-reads-the-oracle`)",
10711 blind.len()
10712 );
10713 eprintln!("{NAME}: all five oracle comparators red on a one-byte-wrong oracle");
10714 }
10715
10716 /// lane-film10fix: the permanent CONTROL for the ffmpeg half of the class
10717 /// `comparator-that-never-reads-the-oracle`.
10718 ///
10719 /// Its sibling above covers the five `aomdec` comparators. The `ffmpeg`
10720 /// half had no such control, and it is the half the two 10-bit FILM gates
10721 /// rest on: `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...`
10722 /// and `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_...`
10723 /// both declare "pixel-exact" purely as
10724 /// `assert_eq!(ours.<plane>, ffmpeg_decode_sequence_10bit(...).<plane>)`
10725 /// over 15 and 33 shown frames. If `ffmpeg_decode_sequence_10bit` ever
10726 /// stopped reading ffmpeg's stdout -- packed our own samples into the
10727 /// buffer it returns, say -- both gates would report exact on a decoder
10728 /// that could be arbitrarily wrong, and nothing in the crate would go
10729 /// red. Reading the helper's source proves it is live TODAY; only a
10730 /// deliberately wrong reference proves it can FAIL.
10731 ///
10732 /// So this is the same two-arm shape, pointed at ffmpeg. The shim runs the
10733 /// REAL ffmpeg and then rotates ONE byte of its rawvideo stdout per
10734 /// offset in a sibling file, leaving the stream, the geometry, the frame
10735 /// count and every other sample a genuine decode. On a pin that IS
10736 /// byte-exact against real ffmpeg:
10737 ///
10738 /// 1. **arm 1, real ffmpeg: every helper is GREEN.** Without this arm,
10739 /// arm 2's red could just be a stream that was never exact.
10740 /// 2. **arm 2, one-sample-wrong ffmpeg, PER PLANE: every helper is RED
10741 /// and the red names the plane that was tampered with.** Three arms,
10742 /// one per plane, because a helper that only ever compared luma would
10743 /// pass the Y arm and fail U and V -- and a 10-bit film gate that
10744 /// reported "exact" while ignoring chroma entirely would be exactly
10745 /// the class this controls.
10746 ///
10747 /// The three helpers are the whole reference surface in this module:
10748 /// `ffmpeg_decode_sequence` (4:2:0 8-bit), `ffmpeg_decode_gray_sequence`
10749 /// (monochrome, one plane) and `ffmpeg_decode_sequence_10bit` (the
10750 /// `yuv420p10le` family both film gates use). Each is driven on a pin it
10751 /// is known to be exact against: the 8-bit `420_odd65x65_key.obu` for the
10752 /// first, the same stream for the third's shape arithmetic, and the
10753 /// monochrome recipe the mono gate already builds for the second. The
10754 /// override is thread-local, so a red arm cannot leave a tampered ffmpeg
10755 /// behind for a sibling test on another thread.
10756 #[test]
10757 fn every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg() {
10758 const NAME: &str = "every_ffmpeg_comparator_reds_on_a_one_sample_wrong_ffmpeg";
10759 if !have_ffmpeg() {
10760 eprintln!("SKIP {NAME}: no ffmpeg");
10761 return;
10762 }
10763 // Same mutex the oracle control takes: this test's shim is
10764 // thread-local, but the SCREAM it produces must not interleave with a
10765 // sibling's decode in the captured log.
10766 let _gate_lock = lock_gate_counters();
10767
10768 // The 4:2:0 8-bit arm. It BUILDS its stream with the same
10769 // `libaom-av1` lavfi recipe the mono gate below uses rather than
10770 // pinning one: `ffmpeg_decode_sequence` derives its frame size as
10771 // `w*h + 2*(w*h/4)`, which is only right for EVEN dimensions -- on a
10772 // 65x65 stream 4:2:0 chroma is ceil(65/2)^2 = 1089, not 4225/4 =
10773 // 1056, and the helper's length assert fires (loudly, by design --
10774 // see `frame_count_diagnosis`). 320x240 keeps the offsets below
10775 // exact: luma 76800 samples, chroma 160x120 = 19200 each.
10776 let (w, h) = (320usize, 240usize);
10777 let (ys, cs) = (w * h, (w / 2) * (h / 2));
10778 assert_eq!(
10779 (ys, cs),
10780 (76800, 19200),
10781 "{NAME}: the byte offsets in this test are computed from this geometry"
10782 );
10783 let build_8bit = {
10784 let out = Command::new(ffmpeg_path())
10785 .args([
10786 "-v",
10787 "error",
10788 "-f",
10789 "lavfi",
10790 "-i",
10791 "testsrc2=size=320x240:rate=30:duration=1",
10792 "-pix_fmt",
10793 "yuv420p",
10794 "-c:v",
10795 "libaom-av1",
10796 "-cpu-used",
10797 "8",
10798 "-b:v",
10799 "300k",
10800 "-f",
10801 "obu",
10802 "-",
10803 ])
10804 .stdin(Stdio::null())
10805 .stdout(Stdio::piped())
10806 .stderr(Stdio::piped())
10807 .output()
10808 .expect("ffmpeg failed to build the 4:2:0 8-bit arm");
10809 assert!(
10810 out.status.success(),
10811 "{NAME}: ffmpeg could not build the 8-bit arm: {}",
10812 String::from_utf8_lossy(&out.stderr)
10813 );
10814 out.stdout
10815 };
10816 assert_eq!(
10817 stream_bit_depth(&build_8bit, NAME),
10818 8,
10819 "{NAME}: this arm is the 8-bit cell the byte offsets below are computed for"
10820 );
10821 let our_8bit =
10822 decode_stream(&build_8bit).expect("the 8-bit arm must decode -- arm 1 needs it exact");
10823 assert!(
10824 !our_8bit.is_empty(),
10825 "{NAME}: the 8-bit arm decoded nothing"
10826 );
10827 let frames_8bit = our_8bit.len();
10828
10829 // The monochrome recipe, byte-identical to the one
10830 // `a_real_libaom_monochrome_key_frame_decodes_pixel_exact` builds, so
10831 // the gray helper is driven on a stream that gate already proves
10832 // exact. A MONOCHROME stream is also this test's 4:2:0 4:2:0-free
10833 // arm: `ffmpeg_decode_gray_sequence` returns a flat luma buffer, so
10834 // the one flipped offset must be attributed to Y and to nothing else.
10835 let gray_stream = {
10836 let out = Command::new(ffmpeg_path())
10837 .args([
10838 "-v",
10839 "error",
10840 "-f",
10841 "lavfi",
10842 "-i",
10843 "testsrc2=size=64x64:rate=30:duration=1",
10844 "-pix_fmt",
10845 "gray",
10846 "-c:v",
10847 "libaom-av1",
10848 "-cpu-used",
10849 "8",
10850 "-b:v",
10851 "100k",
10852 "-f",
10853 "obu",
10854 "-",
10855 ])
10856 .stdin(Stdio::null())
10857 .stdout(Stdio::piped())
10858 .stderr(Stdio::piped())
10859 .output()
10860 .expect("ffmpeg failed to build the monochrome arm");
10861 assert!(
10862 out.status.success(),
10863 "{NAME}: ffmpeg could not build the monochrome arm: {}",
10864 String::from_utf8_lossy(&out.stderr)
10865 );
10866 out.stdout
10867 };
10868 let our_gray = decode_stream(&gray_stream).expect("the monochrome arm must decode");
10869 assert!(
10870 !our_gray.is_empty(),
10871 "{NAME}: the monochrome arm decoded nothing"
10872 );
10873 let frames_gray = our_gray.len();
10874
10875 // ---- the one-sample-wrong ffmpeg shim ---------------------------
10876 let dir = std::env::temp_dir().join(format!("ec-av1-{NAME}-{}", std::process::id()));
10877 let _ = std::fs::remove_dir_all(&dir);
10878 std::fs::create_dir_all(&dir).expect("scratch dir");
10879 // The real ffmpeg's path rides in a sibling file rather than inside
10880 // the script, so a path with a space or a quote cannot mangle it and
10881 // the script body needs no `format!` escaping.
10882 let real = if let Some(p) = std::env::var_os("EC_AV1_FFMPEG") {
10883 std::path::PathBuf::from(p)
10884 } else {
10885 let found = Command::new("ffmpeg")
10886 .arg("-version")
10887 .stdout(Stdio::null())
10888 .stderr(Stdio::null())
10889 .status()
10890 .is_ok_and(|s| s.success());
10891 assert!(found, "{NAME}: no working ffmpeg on PATH to wrap");
10892 // Resolve the bare name through PATH so the shim does not depend
10893 // on inheriting whatever PATH the test runner had.
10894 let path = std::env::var_os("PATH").unwrap_or_default();
10895 std::env::split_paths(&path)
10896 .map(|d| d.join("ffmpeg"))
10897 .find(|p| p.is_file())
10898 .expect("{NAME}: ffmpeg is on PATH but not resolvable to a file")
10899 };
10900 std::fs::write(dir.join("real-ffmpeg"), real.as_os_str().as_encoded_bytes())
10901 .expect("recording the real ffmpeg's path for the shim");
10902 // Each line of `offsets` is one byte of the rawvideo stdout to rotate
10903 // by 128, so the write always changes it. Everything else -- the
10904 // stream, the geometry, the frame count, every other sample -- is a
10905 // genuine ffmpeg decode. stdin is inherited so the shim is a drop-in
10906 // for the helpers' `run_with_stdin` call.
10907 let script = r#"#!/bin/sh
10908REAL=$(cat "$(dirname "$0")/real-ffmpeg")
10909OUT=$(mktemp)
10910"$REAL" "$@" > "$OUT" || exit $?
10911while read -r o; do
10912 [ -n "$o" ] || continue
10913 b=$(od -An -tu1 -j "$o" -N 1 "$OUT" 2>/dev/null | tr -d ' \n')
10914 [ -n "$b" ] || continue
10915 esc=$(printf '\\%03o' $(( (b + 128) % 256 )))
10916 printf "$esc" | dd of="$OUT" bs=1 seek="$o" count=1 conv=notrunc 2>/dev/null
10917done < "$(dirname "$0")/offsets"
10918cat "$OUT"
10919rm -f "$OUT"
10920exit 0
10921"#;
10922 let shim = dir.join("one-sample-wrong-ffmpeg.sh");
10923 std::fs::write(&shim, script).expect("writing the ffmpeg shim");
10924 #[cfg(unix)]
10925 {
10926 use std::os::unix::fs::PermissionsExt;
10927 std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755))
10928 .expect("the ffmpeg shim must be executable");
10929 }
10930 let set_offsets = |bytes: &[usize]| {
10931 let body: String = bytes
10932 .iter()
10933 .map(|b| format!("{b}\n"))
10934 .collect::<Vec<_>>()
10935 .concat();
10936 std::fs::write(dir.join("offsets"), body).expect("writing the offsets file");
10937 };
10938 // A comparator that cannot report a difference is worse than none, so
10939 // each arm is scored as a COUNT of differing samples, not as a panic.
10940 let count8 = |theirs: &[Pic]| -> [usize; 3] {
10941 let mut wrong = [0usize; 3];
10942 for (plane, (x, y)) in [
10943 (0usize, (&our_8bit[0].y, &theirs[0].y)),
10944 (1, (&our_8bit[0].u, &theirs[0].u)),
10945 (2, (&our_8bit[0].v, &theirs[0].v)),
10946 ] {
10947 wrong[plane] = x.iter().zip(y).filter(|(a, b)| a != b).count();
10948 }
10949 wrong
10950 };
10951
10952 // The 10-bit FILM pin, and the comparator both charter-named film
10953 // gates rest on. Driven on the real stream rather than a synthetic
10954 // one: `ffmpeg_decode_sequence_10bit` is the only reference helper
10955 // with a per-plane split, so it is the one that could silently lose a
10956 // plane. 1920x792 at 10 bits: luma 1920*792*2 bytes per frame, chroma
10957 // 960*396*2.
10958 let film = std::fs::read(crate_pin("reelc_sb128_inter_witness.obu")).unwrap_or_else(|e| {
10959 panic!(
10960 "{NAME}: the 10-bit film pin reelc_sb128_inter_witness.obu is missing ({e}) -- \
10961 restore the committed copy"
10962 )
10963 });
10964 assert_eq!(
10965 stream_bit_depth(&film, NAME),
10966 10,
10967 "{NAME}: this arm is the 10-bit cell the byte offsets below are computed for"
10968 );
10969 let our_10bit =
10970 decode_stream(&film).expect("the 10-bit film pin must decode -- arm 1 needs it exact");
10971 let (fw, fh) = (1920usize, 792usize);
10972 let film_frames = our_10bit.len();
10973 let (fys, fcs) = (fw * fh * 2, (fw / 2) * (fh / 2) * 2);
10974 let count10 = |theirs: &[Pic]| -> [usize; 3] {
10975 let mut wrong = [0usize; 3];
10976 for (a, b) in our_10bit.iter().zip(theirs) {
10977 for (plane, (x, y)) in
10978 [(0usize, (&a.y, &b.y)), (1, (&a.u, &b.u)), (2, (&a.v, &b.v))]
10979 {
10980 wrong[plane] += x.iter().zip(y).filter(|(p, q)| p != q).count();
10981 }
10982 }
10983 wrong
10984 };
10985 let count_gray = |theirs: &[u8]| -> usize {
10986 our_gray[0]
10987 .y
10988 .iter()
10989 .zip(theirs)
10990 .filter(|(a, b)| **a != u16::from(**b))
10991 .count()
10992 };
10993
10994 // ---- arm 1: the real ffmpeg, every comparator GREEN ------------
10995 {
10996 set_offsets(&[]);
10997 set_ffmpeg_path(None);
10998 let theirs = ffmpeg_decode_sequence(&build_8bit, w, h, frames_8bit);
10999 assert_eq!(
11000 count8(&theirs),
11001 [0, 0, 0],
11002 "{NAME}: arm 1 runs against the REAL ffmpeg, so every plane must be zero -- if \
11003 this is red the stream is not the byte-exact pin this control needs"
11004 );
11005 let their_gray = ffmpeg_decode_gray_sequence(&gray_stream, 64, 64, frames_gray);
11006 assert_eq!(
11007 count_gray(&their_gray),
11008 0,
11009 "{NAME}: arm 1's monochrome plane must be zero against the real ffmpeg"
11010 );
11011 // arm 1's 10-bit half: the film pin is byte-exact against real
11012 // ffmpeg on every plane of every shown frame -- that is exactly
11013 // what `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...`
11014 // asserts -- so this is the cell the two charter-named film gates
11015 // claim.
11016 let their_10bit = ffmpeg_decode_sequence_10bit(&film, fw, fh, film_frames);
11017 assert_eq!(
11018 count10(&their_10bit),
11019 [0, 0, 0],
11020 "{NAME}: arm 1's 10-bit film pin must be zero on every plane against the real \
11021 ffmpeg -- if this is red the control's pin is not the byte-exact stream it needs"
11022 );
11023 }
11024
11025 // ---- arm 2: one sample wrong, PER PLANE -------------------------
11026 // The shim is thread-local, so the tampered reference is confined to
11027 // this thread; it is cleared before anything is asserted, so a red arm
11028 // cannot leave this test's own later work reading a wrong ffmpeg.
11029 let mut blind: Vec<String> = Vec::new();
11030 {
11031 set_ffmpeg_path(Some(shim.clone()));
11032 for (plane, (_name, base)) in [("Y", 0usize), ("U", ys), ("V", ys + cs)]
11033 .into_iter()
11034 .enumerate()
11035 {
11036 // Byte 1000 of the named plane: inside the 4:2:0 8-bit pin's
11037 // luma (4225), inside its chroma (1024), or past both.
11038 set_offsets(&[base + 1000]);
11039 let theirs = ffmpeg_decode_sequence(&build_8bit, w, h, frames_8bit);
11040 let got = count8(&theirs);
11041 let want = [0usize, 0, 0];
11042 let mut expected = want;
11043 expected[plane] = 1;
11044 if got != expected {
11045 blind.push(format!(
11046 "ffmpeg_decode_sequence {plane} arm: counted {got:?}, expected \
11047 {expected:?} (exactly the one tampered sample)"
11048 ));
11049 }
11050 }
11051 // The 10-bit helper, per plane, on the 10-bit FILM pin. This is the
11052 // arm that matters for the charter: both
11053 // `a_10bit_128sb_film_frames_with_warp_cdef_and_interintra_...`
11054 // and
11055 // `a_10bit_film_frames_with_small_side_globalmv_and_rect_warp_...`
11056 // declare "pixel-exact on every plane" using nothing but this
11057 // helper's output. A helper that dropped U or V would leave both
11058 // gates green while chroma went unchecked for 15 and 33 frames.
11059 for (plane, (_name, base)) in [("Y", 0usize), ("U", fys), ("V", fys + fcs)]
11060 .into_iter()
11061 .enumerate()
11062 {
11063 // Sample 1000 of the named plane, two bytes per sample.
11064 set_offsets(&[base + 2000]);
11065 let theirs = ffmpeg_decode_sequence_10bit(&film, fw, fh, film_frames);
11066 let got = count10(&theirs);
11067 let mut expected = [0usize, 0, 0];
11068 expected[plane] = 1;
11069 if got != expected {
11070 blind.push(format!(
11071 "ffmpeg_decode_sequence_10bit {plane} arm: counted {got:?}, expected \
11072 {expected:?} (exactly the one tampered sample)"
11073 ));
11074 }
11075 }
11076 // The monochrome helper: one plane, so the single flipped offset
11077 // must show up as luma and nothing else can absorb it.
11078 set_offsets(&[1000]);
11079 let their_gray = ffmpeg_decode_gray_sequence(&gray_stream, 64, 64, frames_gray);
11080 if count_gray(&their_gray) != 1 {
11081 blind.push(format!(
11082 "ffmpeg_decode_gray_sequence arm: counted {} differing luma samples, expected \
11083 exactly 1",
11084 count_gray(&their_gray)
11085 ));
11086 }
11087 set_ffmpeg_path(None);
11088 }
11089 let _ = std::fs::remove_dir_all(&dir);
11090 // One assert, naming EVERY helper that failed to notice: a partial run
11091 // would report the first and hide whether the others are covered.
11092 assert!(
11093 blind.is_empty(),
11094 "{NAME}: {} of 7 ffmpeg comparator arms stayed GREEN against an ffmpeg that is wrong \
11095 by exactly one sample -- {blind:#?} -- they cannot fail, so their green proves \
11096 nothing (class `comparator-that-never-reads-the-oracle`)",
11097 blind.len()
11098 );
11099 eprintln!(
11100 "{NAME}: ffmpeg_decode_sequence red on a one-sample-wrong Y, U and V separately; \
11101 ffmpeg_decode_gray_sequence red on one wrong luma sample; \
11102 ffmpeg_decode_sequence_10bit red on a one-sample-wrong Y, U and V of the 10-bit \
11103 film pin"
11104 );
11105 }
11106
11107 /// lane-av1422chrtx: the odd-frame-HEIGHT 4:2:0 witness, pinned and now
11108 /// EXACT (lane-av1422anom had pinned it as a ratchet on its own defect).
11109 ///
11110 /// This is NOT a 4:2:2 cell and needs no bypass -- it is ordinary 4:2:0,
11111 /// reachable by any user. lane-av1422anom pinned it as a RATCHET asserting
11112 /// its own measured defect `(0, 200, 17658)`, and said whoever fixed it
11113 /// must flip that to exactness. That is done, and the flip is the
11114 /// deliverable:
11115 ///
11116 /// the defect was a chroma `tx_type`, not a geometry. libaom's
11117 /// `av1_get_ext_tx_set_type` (`blockd.h`) resolves a **32-point** chroma
11118 /// unit to `EXT_TX_SET_DCT_IDTX` when the block `is_inter` -- so an
11119 /// Intra-Block-Copy block whose luma coded `IDTX` runs the identity
11120 /// transform on its chroma. `read_plane`'s `side >= 32` clamp forced
11121 /// `DCT_DCT` there (its `DCT_DCT` cap is really libaom's
11122 /// `txsize_sqr_up_map[tx_size] > TX_32X32`, i.e. 64 and up), so the
11123 /// residual was a 32-point IDCT where libaom's was a plain copy of the
11124 /// dequantized coefficients `>>2`. The wrong samples sat in one 64x64
11125 /// IBC block's 32x32 chroma unit at chroma (128,96) on frame 0, and
11126 /// propagated from there through the inter frames.
11127 ///
11128 /// `the_counting_oracle_diff_detects_one_flipped_oracle_byte` is the
11129 /// non-vacuity control that keeps the `0` above worth anything.
11130 #[test]
11131 fn the_pinned_420_oddheight_witness_is_pinned_and_decodes_byte_exact() {
11132 const NAME: &str = "the_pinned_420_oddheight_witness_is_pinned_and_decodes_byte_exact";
11133 // lane-av1cmpaudit2: same mutex as every other oracle gate.
11134 let _gate_lock = lock_gate_counters();
11135 const FILE: &str = "420_oddheight_320x232.obu";
11136 const BYTES: usize = 15773;
11137 // sha256 6832c3cd867f5fc491b45fd67f77c38453db0ca6d461e7d225e6276f4d0784c8,
11138 // recorded in `lanes/av1422anom.report.md`. The tree pins fixture
11139 // identity by fnv1a64, asserted below. A `const SHA256` compared
11140 // against itself would be a tautology -- the exact bug this lane
11141 // exists to kill -- so it is not written.
11142 const FNV1A64: u64 = 0x37877f15307c3b;
11143 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11144 .join("fixtures")
11145 .join(FILE);
11146 let data = std::fs::read(&path)
11147 .unwrap_or_else(|e| panic!("{NAME}: pinned witness {FILE} is missing ({e})"));
11148 assert_eq!(data.len(), BYTES, "{NAME}: {FILE} size drifted");
11149 assert_eq!(fnv1a64(&data), FNV1A64, "{NAME}: {FILE} bytes drifted");
11150 let (wy, wu, wv, frames, exact) =
11151 count_rawvideo_diffs(&data, NAME, None).expect("the two sides must be byte-comparable");
11152 assert_eq!(
11153 (wy, wu, wv),
11154 (0, 0, 0),
11155 "{NAME}: the pinned 320x232 witness must decode byte-exactly against \
11156 `aomdec --rawvideo` on every plane. It was a RATCHET asserting its own \
11157 measured defect (0, 200, 17658); lane-av1422chrtx flipped it to exactness \
11158 when the 32-point INTER chroma `tx_type` (EXT_TX_SET_DCT_IDTX, not \
11159 EXT_TX_SET_DCTONLY) was fixed. Any non-zero value here is a regression -- \
11160 name it in the report."
11161 );
11162 assert_eq!(frames, 16, "{NAME}: shown frame count");
11163 assert_eq!(
11164 exact, frames,
11165 "{NAME}: every shown frame must be byte-exact"
11166 );
11167 }
11168
11169 /// lane-hidden r2: the `--arnr-maxframes=0` SECOND ARM of an existing
11170 /// gate -- the gate's own recipe is never changed, this re-encodes the
11171 /// same fixture with libaom's temporal alt-ref filter switched off and
11172 /// runs [`decode_all_frames_vs_oracle`] on the result. Measured: with
11173 /// the filter at its default EVERY alt-ref recipe in this file emits
11174 /// ZERO hidden frames (the candidates are filtered away), so the
11175 /// hidden-frame compare on the gate's own stream is vacuous; this arm
11176 /// is what actually puts `show_frame == 0` frames on the wire.
11177 ///
11178 /// Runs at most once per gate name per process (the loop gates sweep
11179 /// dozens of attempts and each arm costs a full encode + two decodes).
11180 /// A stream this decoder refuses BY NAME skips the arm -- the arm is
11181 /// about hidden frames, not about that capability gap -- while a pixel
11182 /// mismatch is a hard failure raised inside the compare.
11183 fn hidden_arnr_arm(name: &str, y4m: &[u8], args: &[&str]) -> Option<(usize, usize)> {
11184 static ARMED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
11185 std::sync::OnceLock::new();
11186 if !ARMED
11187 .get_or_init(Default::default)
11188 .lock()
11189 .unwrap()
11190 .insert(name.to_string())
11191 {
11192 return None;
11193 }
11194 let mut arm: Vec<&str> = vec!["--arnr-maxframes=0"];
11195 arm.extend_from_slice(args);
11196 let out = run_with_stdin(Command::new(aomenc_path()).args(&arm), &y4m);
11197 assert!(
11198 out.status.success(),
11199 "{name} HIDDEN-ARM: aomenc refused its own recipe plus --arnr-maxframes=0: {}",
11200 String::from_utf8_lossy(&out.stderr)
11201 );
11202 let stream = out.stdout;
11203 match decode_stream(&stream) {
11204 Err(e) => {
11205 let msg = e.to_string();
11206 assert!(
11207 msg.contains("unsupported"),
11208 "{name} HIDDEN-ARM failed outright: {msg}"
11209 );
11210 eprintln!("{name} HIDDEN-ARM: skipped on a named refusal: {msg}");
11211 None
11212 }
11213 Ok(_) => Some(decode_all_frames_vs_oracle(
11214 &stream,
11215 &format!("{name}-arnr0"),
11216 )),
11217 }
11218 }
11219
11220 /// The repo's first hidden-frame pixel gate. Every other aomenc gate
11221 /// here compares `decode_stream`'s output against `ffmpeg -f obu`, and
11222 /// both sides emit SHOWN frames only -- so an alt-ref frame that is
11223 /// decoded, stored into a reference slot and never displayed was, until
11224 /// this gate, never compared to anything (class
11225 /// gate-blind-to-hidden-frames). His films are aomenc-encoded with the
11226 /// default `--lag-in-frames`, so they are full of exactly these frames.
11227 ///
11228 /// `--auto-alt-ref=1 --lag-in-frames=25` on moving content makes aomenc
11229 /// build alt-refs; `--arnr-maxframes=0` is load-bearing -- with libaom's
11230 /// temporal filter on, this fixture's alt-ref candidates get filtered
11231 /// away and the encoder emits ZERO hidden frames (measured: 0 hidden
11232 /// with the filter on, 3 with it off), which would have made the gate
11233 /// vacuous. The `hidden >= 2` assertion is hard, on both bit depths, so
11234 /// a recipe that stops producing hidden frames fails rather than skips.
11235 #[test]
11236 fn a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact() {
11237 const NAME: &str = "a_real_aomenc_altref_sequence_hidden_frames_decode_pixel_exact";
11238 let _gate_lock = lock_gate_counters();
11239 if !have_ffmpeg() {
11240 eprintln!("SKIP {NAME}: no ffmpeg");
11241 return;
11242 }
11243 if !have_aomenc() {
11244 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11245 return;
11246 }
11247 for bit_depth in [8u32, 10u32] {
11248 let (width, height, frames) = (64usize, 64usize, 40usize);
11249 let duration = frames as f64 / 25.0;
11250 let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25");
11251 let pix_fmt = if bit_depth == 10 {
11252 "yuv420p10le"
11253 } else {
11254 "yuv420p"
11255 };
11256 let y4m = Command::new("ffmpeg")
11257 .args([
11258 "-v",
11259 "error",
11260 "-f",
11261 "lavfi",
11262 "-i",
11263 &source,
11264 "-t",
11265 &duration.to_string(),
11266 "-pix_fmt",
11267 pix_fmt,
11268 "-strict",
11269 "-1",
11270 "-f",
11271 "yuv4mpegpipe",
11272 "-",
11273 ])
11274 .stdin(Stdio::null())
11275 .stdout(Stdio::piped())
11276 .stderr(Stdio::piped())
11277 .output()
11278 .expect("ffmpeg failed to run");
11279 assert!(
11280 y4m.status.success(),
11281 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
11282 String::from_utf8_lossy(&y4m.stderr)
11283 );
11284 let depth_arg = format!("--bit-depth={bit_depth}");
11285 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
11286 let out = run_with_stdin(
11287 Command::new(aomenc_path()).args([
11288 // lane-defon r1: the repo's only gate that decodes hidden
11289 // frames is also the only place a FORWARD KEYFRAME can be
11290 // proven -- a KEY frame with `show_frame == 0`, which is
11291 // exactly the shape this gate already compares in decode
11292 // order. On-values go before the base list (aomenc keeps
11293 // the FIRST occurrence of a repeated flag).
11294 "--enable-fwd-kf=1",
11295 "--fwd-kf-dist=8",
11296 "--codec=av1",
11297 "--passes=1",
11298 "--end-usage=q",
11299 "--cq-level=45",
11300 "--cpu-used=0",
11301 "--threads=1",
11302 "--row-mt=0",
11303 "--kf-max-dist=1000",
11304 "--enable-order-hint=1",
11305 "--auto-alt-ref=1",
11306 "--lag-in-frames=25",
11307 "--arnr-maxframes=0",
11308 &depth_arg,
11309 &input_depth_arg,
11310 // The same tool set every sibling inter gate pins -- the
11311 // open capability gaps (rect/AB partitions, warped/OBMC,
11312 // masked compound, palette, ...) are other lanes' work;
11313 // this gate is about hidden frames, not about them.
11314 "--enable-warped-motion=0",
11315 // OBMC stays off HERE (this gate is about hidden frames);
11316 // the tool's own coverage is the `obmc*` gates and, on a
11317 // 16x8/8x16 leaf, the `--enable-obmc=1` arm of
11318 // `..._with_a_16_level_rect_leaf_...` (lane-inter4 r4).
11319 "--enable-obmc=0",
11320 "--enable-masked-comp=0",
11321 "--enable-interintra-comp=0",
11322 "--enable-onesided-comp=0",
11323 "--enable-interintra-wedge=0",
11324 "--enable-smooth-interintra=0",
11325 "--enable-rect-partitions=0",
11326 "--enable-ab-partitions=0",
11327 "--enable-1to4-partitions=0",
11328 "--enable-filter-intra=0",
11329 "--enable-smooth-intra=0",
11330 "--enable-paeth-intra=0",
11331 "--enable-directional-intra=0",
11332 "--enable-angle-delta=0",
11333 "--enable-tx-size-search=0",
11334 "--enable-cdef=0",
11335 "--enable-restoration=0",
11336 "--max-partition-size=32",
11337 "--min-partition-size=32",
11338 "--enable-palette=0",
11339 "--enable-intrabc=0",
11340 "--enable-cfl-intra=0",
11341 "--enable-ref-frame-mvs=0",
11342 "--obu",
11343 "-o",
11344 "-",
11345 "-",
11346 ]),
11347 &y4m.stdout,
11348 );
11349 assert!(
11350 out.status.success(),
11351 "{NAME}: aomenc refused the {bit_depth}-bit fixture: {}",
11352 String::from_utf8_lossy(&out.stderr)
11353 );
11354 let stream = out.stdout;
11355 let fwd_kf_before = crate::decode::fwd_kf_hits();
11356 let (total, hidden) =
11357 decode_all_frames_vs_oracle(&stream, &format!("altref-hidden-{bit_depth}bit"));
11358 let fwd_kf = crate::decode::fwd_kf_hits() - fwd_kf_before;
11359 assert!(
11360 hidden >= 2,
11361 "{NAME}: the {bit_depth}-bit recipe produced only {hidden} hidden frame(s) of \
11362 {total} decoded -- the gate would be vacuous (class \
11363 gate-blind-to-hidden-frames)"
11364 );
11365 // lane-defon r1: `--enable-fwd-kf=1` is spelled on this recipe, so
11366 // a KEY frame with `show_frame == 0` must actually have been
11367 // decoded -- otherwise the on-value proves nothing.
11368 assert!(
11369 fwd_kf > 0,
11370 "{NAME}: the {bit_depth}-bit recipe decoded {total} frames ({hidden} hidden) but \
11371 zero forward keyframes -- --enable-fwd-kf=1 --fwd-kf-dist=8 never reached the \
11372 bitstream"
11373 );
11374 eprintln!(
11375 "{NAME} {bit_depth}-bit: {total} frames decoded, {hidden} hidden, {fwd_kf} \
11376 forward keyframes, all pixel-exact vs the oracle in decode order"
11377 );
11378 }
11379 }
11380
11381 /// A real `aomenc` filter-intra fixture: every other intra mode disabled
11382 /// (smooth/paeth/directional/angle-delta) and
11383 /// `--max-partition-size=32` (past which `av1_filter_intra_allowed_bsize`'s
11384 /// <=32x32 bound means `use_filter_intra` never reads at all, spec
11385 /// 5.11.14), so the only way this frame codes is `DC_PRED` with filter
11386 /// intra on top -- `--loopfilter-control=0` is required too: this
11387 /// decoder has no in-loop deblocking filter at all, and libaom's default
11388 /// (on) smooths every block-boundary column, which first looked like a
11389 /// filter-intra math bug (mismatches straddling the 32-pixel block
11390 /// seam) until the recipe without it round-tripped byte-exact.
11391 ///
11392 /// lane-av1skipfix: the attempt-loop shape this gate's single recipe
11393 /// lacked. It sweeps (seed, cq) and REQUIRES at least one attempt to both
11394 /// decode and read `use_filter_intra`: a decode error on EVERY attempt is
11395 /// a hard failure carrying the refusal texts, not a printed SKIP, and an
11396 /// attempt that decodes without the symbol firing is still pixel-compared
11397 /// (class `gate-skips-on-its-own-failure`). MEASURED 2026-09-29 on
11398 /// `a21f3680`: seed 42 cq 40 and seed 43 cq 40 read the symbol 3x each,
11399 /// pixel-exact, while seed 44 cq 45 and seed 45 cq 30 decode WITHOUT it --
11400 /// so the one fixed recipe really did carry the whole gate.
11401 ///
11402 /// The per-attempt decode error the old single recipe SKIPped on is
11403 /// `screen_content_tools_determination` (libaom `encoder_utils.c`): a real
11404 /// internal trial-encode/PSNR comparison, not a flag this CLI exposes a
11405 /// knob for -- on this flat gradient fixture it lands on
11406 /// `allow_screen_content_tools=0` most runs but occasionally trips over
11407 /// its 0.9 dB threshold the other way even with palette/intrabc both
11408 /// disabled. That is a genuine separate gap (`decode_stream` never reads
11409 /// `intrabc`/`palette_mode_info`), so it is a NAMED REFUSAL counted per
11410 /// attempt, never a silent skip and never a pass.
11411 #[test]
11412 fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {
11413 const NAME: &str = "a_real_aomenc_filter_intra_stream_decodes_pixel_exact";
11414 let _gate_lock = lock_gate_counters();
11415 if !have_ffmpeg() {
11416 eprintln!("SKIP {NAME}: no ffmpeg");
11417 return;
11418 }
11419 if !have_aomenc() {
11420 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11421 return;
11422 }
11423 let (width, height) = (64usize, 64usize);
11424 // Recipe-search hooks: with the encoder pinned to one thread the stream
11425 // is a deterministic function of (seed, cq), so a firing recipe can be
11426 // searched for without a rebuild. These pin attempt 0 for a bisect; the
11427 // sweep walks the same axes regardless.
11428 let fi_seed: u32 = std::env::var("EC_FI_SEED")
11429 .ok()
11430 .and_then(|v| v.parse().ok())
11431 .unwrap_or(42);
11432 let fi_cq: u32 = std::env::var("EC_FI_CQ")
11433 .ok()
11434 .and_then(|v| v.parse().ok())
11435 .unwrap_or(40);
11436 // Two seeds x three quantisers, so "every attempt refused" and "no
11437 // attempt ever read `use_filter_intra`" are distinguishable failures
11438 // rather than one unlucky recipe.
11439 const CQS: [u32; 3] = [40, 35, 30];
11440 let mut refusals = Vec::new();
11441 let mut counted_exact = 0u32;
11442 let mut uncounted_exact = 0u32;
11443 'attempts: for round in 0..2u32 {
11444 for (i, &walked) in CQS.iter().enumerate() {
11445 let seed = fi_seed + round;
11446 let cq = if round == 0 && i == 0 { fi_cq } else { walked };
11447 let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
11448 let y4m = Command::new("ffmpeg")
11449 .args([
11450 "-v",
11451 "error",
11452 "-f",
11453 "lavfi",
11454 "-i",
11455 &source,
11456 "-pix_fmt",
11457 "yuv420p",
11458 "-f",
11459 "yuv4mpegpipe",
11460 "-",
11461 ])
11462 .stdin(Stdio::null())
11463 .stdout(Stdio::piped())
11464 .stderr(Stdio::piped())
11465 .output()
11466 .expect("ffmpeg failed to run");
11467 assert!(
11468 y4m.status.success(),
11469 "ffmpeg refused to generate the y4m fixture: {}",
11470 String::from_utf8_lossy(&y4m.stderr)
11471 );
11472 let cq_arg = format!("--cq-level={cq}");
11473 let out = run_with_stdin(
11474 Command::new(aomenc_path()).args([
11475 "--codec=av1",
11476 "--passes=1",
11477 "--end-usage=q",
11478 &cq_arg,
11479 "--cpu-used=0",
11480 // Every sibling gate pins these; this one did not, and a
11481 // multi-threaded aomenc is not deterministic, so each run
11482 // encoded a slightly different stream and the gate flaked
11483 // against whichever features that run happened to pick.
11484 // Pinning them makes seed 42 mean one stream (class
11485 // `parallel-flake-is-attempt-selection`).
11486 "--threads=1",
11487 "--row-mt=0",
11488 "--enable-filter-intra=1",
11489 "--enable-smooth-intra=0",
11490 "--enable-paeth-intra=0",
11491 "--enable-directional-intra=0",
11492 "--enable-angle-delta=0",
11493 "--enable-tx-size-search=0",
11494 "--enable-cdef=0",
11495 "--max-partition-size=32",
11496 "--loopfilter-control=0",
11497 "--enable-palette=0",
11498 "--enable-intrabc=0",
11499 "--obu",
11500 "-o",
11501 "-",
11502 "-",
11503 ]),
11504 &y4m.stdout,
11505 );
11506 assert!(
11507 out.status.success(),
11508 "{NAME}: aomenc refused the seed {seed} cq {cq} fixture: {}",
11509 String::from_utf8_lossy(&out.stderr)
11510 );
11511 let stream = out.stdout;
11512 let before = decode::filter_intra_hits();
11513 let frames = match decode_stream(&stream) {
11514 Ok(frames) => frames,
11515 Err(e) => {
11516 refusals.push(format!("seed {seed} cq {cq}: {e}"));
11517 continue;
11518 }
11519 };
11520 // A decode that succeeded is ALWAYS pixel-compared; the hit
11521 // counter only decides whether the attempt counts as firing
11522 // (class `counter-from-refused-stream`).
11523 let counted = decode::filter_intra_hits() != before;
11524 if counted {
11525 counted_exact += 1;
11526 } else {
11527 uncounted_exact += 1;
11528 }
11529 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
11530 assert_eq!(
11531 frames[0].y, ffmpeg_frames[0].y,
11532 "luma vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
11533 );
11534 assert_eq!(
11535 frames[0].u, ffmpeg_frames[0].u,
11536 "U vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
11537 );
11538 assert_eq!(
11539 frames[0].v, ffmpeg_frames[0].v,
11540 "V vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
11541 );
11542 if counted_exact >= 2 {
11543 break 'attempts;
11544 }
11545 }
11546 }
11547 gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
11548 assert!(
11549 counted_exact > 0,
11550 "{NAME}: none of {} attempts decoded a stream that read use_filter_intra -- the \
11551 gate would prove nothing (class gate-blind-to-feature):\n{}",
11552 CQS.len() * 2,
11553 refusals.join("\n")
11554 );
11555 }
11556
11557 /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`
11558 /// (SMPTE colour bars -- a handful of large flat luma regions, exactly
11559 /// the "flat, few-colour, repetitive" content `av1_choose_palette_map`'s
11560 /// RD trial rewards) with `hue=s=0` to flatten chroma to one constant
11561 /// value, so `DC_PRED` already nails every chroma block with zero
11562 /// residual and the encoder's own RD never has a reason to spend bits on
11563 /// a *UV* palette too (a real symbol this decoder still refuses --
11564 /// lane-palette r3's own scope is Y only). `smptebars` has no seed to
11565 /// vary, so the fixture is deterministic by construction; hashed twice
11566 /// below to prove it rather than assert it. `--enable-rect-partitions=0`
11567 /// / `-ab-` / `-1to4-` keep every intra block square, sidestepping the
11568 /// rect-strip screen-content refusal at `read_intra_mode_rect`
11569 /// (decode.rs ~2226) -- that refusal is this lane's own next milestone,
11570 /// not this gate's. `--sb-size=64` and `--threads=1 --row-mt=0` are the
11571 /// sibling-lane facts this charter paid for: a single 64x64 frame is one
11572 /// superblock either way, but pinning them keeps the recipe identical to
11573 /// every other gate in this file. HARD-asserts
11574 /// [`decode::palette_hits`] moved -- a stream that never reads a real
11575 /// palette block would refuse (or not) by construction without proving
11576 /// this milestone at all.
11577 ///
11578 /// lane-palette r4/r6/r7: r3/r4 found that this fixture's reconstructed
11579 /// pixels did not match ffmpeg's decode of the same bytes even though
11580 /// every symbol read by `decode_color_index_map` checked line-for-line
11581 /// against the oracle and matched. r6's range trace (`compare-range-not-tell`)
11582 /// pinned the real cause: `decode_color_index_map` was called from the
11583 /// wrong syntax position -- inline right after the Y colours, instead of
11584 /// after the whole mode-info read (UV palette mode_info + `filter_intra`,
11585 /// `av1_visit_palette`'s real call order). r7 ported the UV palette
11586 /// mode_info read and moved the colour-index-map decode after
11587 /// `filter_intra`; this gate now asserts a real pixel match instead of
11588 /// the old named refusal.
11589 #[test]
11590 fn a_real_aomenc_stream_with_palette_y_decodes_pixel_exact() {
11591 const NAME: &str = "a_real_aomenc_stream_with_palette_y_decodes_pixel_exact";
11592 if !have_ffmpeg() {
11593 eprintln!("SKIP {NAME}: no ffmpeg");
11594 return;
11595 }
11596 if !have_aomenc() {
11597 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11598 return;
11599 }
11600 let source = "smptebars=size=64x64:rate=25";
11601 fn render(source: &str) -> Vec<u8> {
11602 Command::new("ffmpeg")
11603 .args([
11604 "-v",
11605 "error",
11606 "-f",
11607 "lavfi",
11608 "-i",
11609 source,
11610 "-vf",
11611 "hue=s=0",
11612 "-pix_fmt",
11613 "yuv420p",
11614 "-t",
11615 "0.04",
11616 "-f",
11617 "yuv4mpegpipe",
11618 "-",
11619 ])
11620 .stdin(Stdio::null())
11621 .stdout(Stdio::piped())
11622 .stderr(Stdio::piped())
11623 .output()
11624 .expect("ffmpeg failed to run")
11625 .stdout
11626 }
11627 let y4m_a = render(source);
11628 let y4m_b = render(source);
11629 assert_eq!(
11630 y4m_a, y4m_b,
11631 "smptebars must render byte-identical across two runs"
11632 );
11633 let y4m = y4m_a;
11634 let out = run_with_stdin(
11635 Command::new(aomenc_path()).args([
11636 "--codec=av1",
11637 "--passes=1",
11638 "--end-usage=q",
11639 "--cq-level=30",
11640 "--cpu-used=0",
11641 "--threads=1",
11642 "--row-mt=0",
11643 "--sb-size=64",
11644 "--tune-content=screen",
11645 "--enable-palette=1",
11646 "--enable-intrabc=0",
11647 "--enable-rect-partitions=0",
11648 "--enable-ab-partitions=0",
11649 "--enable-1to4-partitions=0",
11650 "--min-partition-size=32",
11651 "--max-partition-size=32",
11652 "--enable-filter-intra=0",
11653 "--enable-smooth-intra=0",
11654 "--enable-paeth-intra=0",
11655 "--enable-directional-intra=0",
11656 "--enable-angle-delta=0",
11657 "--enable-cfl-intra=0",
11658 "--enable-cdef=0",
11659 "--enable-restoration=0",
11660 "--enable-tx-size-search=0",
11661 "--loopfilter-control=0",
11662 "--obu",
11663 "-o",
11664 "-",
11665 "-",
11666 ]),
11667 &y4m,
11668 );
11669 assert!(
11670 out.status.success(),
11671 "aomenc refused the fixture: {}",
11672 String::from_utf8_lossy(&out.stderr)
11673 );
11674 let stream = out.stdout;
11675 let before = decode::palette_hits();
11676 let frames = match decode_stream(&stream) {
11677 Ok(frames) => frames,
11678 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
11679 };
11680 assert!(
11681 decode::palette_hits() > before,
11682 "palette_y_mode never fired decoding this stream -- gate is vacuous"
11683 );
11684 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1);
11685 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
11686 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
11687 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
11688 }
11689
11690 /// lane-kf900 r3: the palette colour reader at BOTH bit depths.
11691 ///
11692 /// `read_palette_colors_y`/`_uv` (decode.rs, mirroring `decodemv.c:478`
11693 /// and `:509`) size every raw literal they read by the sequence's
11694 /// `bit_depth`: the first colour is `bit_depth` bits, `min_bits` is
11695 /// `bit_depth - 3` (Y/U) or `bit_depth - 4` (V), `range` starts at
11696 /// `1 << bit_depth`, and the clamp/wrap bound is `(1 << bit_depth) - 1`.
11697 /// Ours hardcoded 8, so every 10-bit palette block read TWO BITS TOO FEW
11698 /// per transmitted colour and silently decoded the rest of the tile from
11699 /// the wrong bit position.
11700 ///
11701 /// It was silent because raw literals are EQUIPROBABLE: at the ranges
11702 /// this content reaches an equiprobable read maps the msac range onto
11703 /// itself (62728 -> 31364 -> renormalised 62728), so a cross-decoder
11704 /// RANGE ladder stays bit-identical straight through the miscount and
11705 /// only the decoded VALUE moves. Pinned on a 256x192 10-bit
11706 /// `--cq-level=59` stream whose first block is a 32x16 palette: aomdec's
11707 /// `EC_PAL` ladder and ours agreed on every range and disagreed on the
11708 /// very first colour index (0 vs 1); after the fix all 1024 `EC_PAL`
11709 /// lines of that block match aomdec line for line.
11710 ///
11711 /// The recipe is the 8-bit `..._with_palette_y_...` gate's, with the
11712 /// depth as the only variable, so a failure here is the depth and
11713 /// nothing else. HARD-asserts [`decode::palette_hits`] moved on each arm
11714 /// (a stream with no real palette block would prove nothing) and
11715 /// compares all three planes against ffmpeg's decode of the same bytes.
11716 #[test]
11717 fn a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit() {
11718 const NAME: &str = "a_real_aomenc_palette_stream_decodes_pixel_exact_at_8_and_10_bit";
11719 if !have_ffmpeg() {
11720 eprintln!("SKIP {NAME}: no ffmpeg");
11721 return;
11722 }
11723 if !have_aomenc() {
11724 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11725 return;
11726 }
11727 let (width, height) = (64usize, 64usize);
11728 for depth in [8usize, 10] {
11729 let pix_fmt = if depth == 10 {
11730 "yuv420p10le"
11731 } else {
11732 "yuv420p"
11733 };
11734 let render = || {
11735 Command::new("ffmpeg")
11736 .args([
11737 "-v",
11738 "error",
11739 "-f",
11740 "lavfi",
11741 "-i",
11742 "smptebars=size=64x64:rate=25",
11743 "-vf",
11744 "hue=s=0",
11745 "-pix_fmt",
11746 pix_fmt,
11747 "-strict",
11748 "-1",
11749 "-t",
11750 "0.04",
11751 "-f",
11752 "yuv4mpegpipe",
11753 "-",
11754 ])
11755 .stdin(Stdio::null())
11756 .stdout(Stdio::piped())
11757 .stderr(Stdio::piped())
11758 .output()
11759 .expect("ffmpeg failed to run")
11760 .stdout
11761 };
11762 let y4m_a = render();
11763 let y4m_b = render();
11764 assert_eq!(
11765 y4m_a, y4m_b,
11766 "{NAME}: smptebars must render byte-identical across two runs at {depth}-bit"
11767 );
11768 let y4m = y4m_a;
11769 let depth_arg = format!("--bit-depth={depth}");
11770 let input_depth_arg = format!("--input-bit-depth={depth}");
11771 let out = run_with_stdin(
11772 Command::new(aomenc_path())
11773 .args([
11774 "--codec=av1",
11775 "--passes=1",
11776 "--end-usage=q",
11777 "--cq-level=30",
11778 "--cpu-used=0",
11779 "--threads=1",
11780 "--row-mt=0",
11781 "--sb-size=64",
11782 "--tune-content=screen",
11783 "--enable-palette=1",
11784 "--enable-intrabc=0",
11785 "--enable-rect-partitions=0",
11786 "--enable-ab-partitions=0",
11787 "--enable-1to4-partitions=0",
11788 "--min-partition-size=32",
11789 "--max-partition-size=32",
11790 "--enable-filter-intra=0",
11791 "--enable-smooth-intra=0",
11792 "--enable-paeth-intra=0",
11793 "--enable-directional-intra=0",
11794 "--enable-angle-delta=0",
11795 "--enable-cfl-intra=0",
11796 "--enable-cdef=0",
11797 "--enable-restoration=0",
11798 "--enable-tx-size-search=0",
11799 "--loopfilter-control=0",
11800 "--limit=1",
11801 ])
11802 // Per-arm overrides go AFTER the base recipe: aomenc keeps the
11803 // LAST occurrence of a repeated flag.
11804 .args([&depth_arg, &input_depth_arg])
11805 .args(["--obu", "-o", "-", "-"]),
11806 &y4m,
11807 );
11808 assert!(
11809 out.status.success(),
11810 "{NAME}: aomenc refused the {depth}-bit fixture: {}",
11811 String::from_utf8_lossy(&out.stderr)
11812 );
11813 let stream = out.stdout;
11814 let before = decode::palette_hits();
11815 let frames = match decode_stream(&stream) {
11816 Ok(frames) => frames,
11817 Err(e) => panic!("{NAME}: decode_stream refused the {depth}-bit stream: {e}"),
11818 };
11819 assert!(
11820 decode::palette_hits() > before,
11821 "{NAME}: no real palette block at {depth}-bit -- gate is vacuous"
11822 );
11823 let ffmpeg_frames = if depth == 10 {
11824 ffmpeg_decode_sequence_10bit(&stream, width, height, 1)
11825 } else {
11826 ffmpeg_decode_sequence(&stream, width, height, 1)
11827 };
11828 assert_eq!(
11829 frames[0].y, ffmpeg_frames[0].y,
11830 "{NAME}: luma at {depth}-bit"
11831 );
11832 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U at {depth}-bit");
11833 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V at {depth}-bit");
11834 }
11835 }
11836
11837 /// lane-pal8 r1, the gate for a palette on a SQUARE 8x8 LEAF.
11838 ///
11839 /// `read_palette_mode_info` (decodemv.c:567) reads `palette_y_mode` for
11840 /// every `DC_PRED` block whose `av1_get_palette_bsize_ctx`
11841 /// (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`, 0 at 8x8) exists, and
11842 /// `av1_decode_palette_tokens` (decodeframe.c:1135, `av1_visit_palette`)
11843 /// reads the colour-index map after the WHOLE mode-info read. Ours passed
11844 /// `None`/`&[]` from [`decode::decode_leaf8`], reading the mode symbol off
11845 /// CDF row 0 and refusing "a block that actually uses a palette (Y) --
11846 /// reconstruction is out of scope" the moment it fired -- and at 8 bit
11847 /// aomenc palettes SQUARE blocks, so with `--min-partition-size=8` every
11848 /// 8-bit screen-content stream stopped there (lane-kf900 r4's measurement).
11849 ///
11850 /// Sweeps both bit depths x cq 30/40/55 x `--enable-tx-size-search` 0/1 x
11851 /// two lavfi sources (+ a `--tile-columns=1` arm, per the neighbour-map
11852 /// rule: the palette bands are per-mi and tile-guarded). Key frame only
11853 /// (`--limit=1`): the inter frames of these recipes stop on OTHER lanes'
11854 /// open refusals (8x8 inter leaf chroma mode, inter 1:4 partitions).
11855 /// HARD-asserts the 8x8-leaf palette counter moved on the compared arms
11856 /// and that no arm mismatched, in or out of scope.
11857 #[test]
11858 fn a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact() {
11859 const NAME: &str = "a_real_aomenc_palette_stream_with_8x8_leaves_decodes_pixel_exact";
11860 if !have_ffmpeg() {
11861 eprintln!("SKIP {NAME}: no ffmpeg");
11862 return;
11863 }
11864 if !have_aomenc() {
11865 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
11866 return;
11867 }
11868 let (width, height) = (128usize, 128usize);
11869 let (mut leaf8_total, mut fired_arms, mut compared, mut frames_compared) =
11870 (0usize, 0u32, 0u32, 0usize);
11871 let (mut out_of_scope, mut out_of_scope_mismatch, mut refusals) = (0u32, 0u32, 0u32);
11872 let (mut sb_strip_total, mut sb_strip_arms) = (0usize, 0u32);
11873 // lane-t900 r34 LIFTED this shape; the counter stays so the gate
11874 // fails loudly if the refusal ever comes back.
11875 let mut sb_strip_refusals = 0u32;
11876 for src in ["testsrc2", "smptebars"] {
11877 for depth in [8usize, 10usize] {
11878 for cq in [30usize, 40, 55] {
11879 for txs in [0usize, 1] {
11880 for tiles in [0usize, 1] {
11881 let arm = format!("{src}-{depth}bit-cq{cq}-txs{txs}-tc{tiles}");
11882 let pix_fmt = if depth == 10 {
11883 "yuv420p10le"
11884 } else {
11885 "yuv420p"
11886 };
11887 let size = format!("{src}=size={width}x{height}:rate=25");
11888 let render = || {
11889 let out = Command::new("ffmpeg")
11890 .args([
11891 "-v",
11892 "error",
11893 "-f",
11894 "lavfi",
11895 "-i",
11896 &size,
11897 "-t",
11898 "0.04",
11899 "-pix_fmt",
11900 pix_fmt,
11901 "-strict",
11902 "-1",
11903 "-f",
11904 "yuv4mpegpipe",
11905 "-",
11906 ])
11907 .stdin(Stdio::null())
11908 .stdout(Stdio::piped())
11909 .stderr(Stdio::piped())
11910 .output()
11911 .expect("ffmpeg failed to run");
11912 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
11913 out.stdout
11914 };
11915 let y4m_a = render();
11916 let y4m_b = render();
11917 assert_eq!(
11918 y4m_a, y4m_b,
11919 "{NAME}: {arm} must render byte-identical across two runs"
11920 );
11921 let y4m = y4m_a;
11922 let depth_arg = format!("--bit-depth={depth}");
11923 let input_depth_arg = format!("--input-bit-depth={depth}");
11924 let cq_arg = format!("--cq-level={cq}");
11925 let txs_arg = format!("--enable-tx-size-search={txs}");
11926 let tiles_arg = format!("--tile-columns={tiles}");
11927 let out = run_with_stdin(
11928 Command::new(aomenc_path())
11929 .args([
11930 "--codec=av1",
11931 "--passes=1",
11932 "--end-usage=q",
11933 "--cpu-used=0",
11934 "--threads=1",
11935 "--row-mt=0",
11936 "--lag-in-frames=0",
11937 "--limit=1",
11938 "--sb-size=64",
11939 "--tune-content=screen",
11940 "--enable-palette=1",
11941 "--enable-intrabc=0",
11942 "--min-partition-size=8",
11943 "--enable-cdef=0",
11944 "--enable-restoration=0",
11945 "--loopfilter-control=0",
11946 ])
11947 // aomenc keeps the LAST occurrence of a repeated flag,
11948 // so per-arm overrides go after the base recipe.
11949 .args([
11950 &depth_arg,
11951 &input_depth_arg,
11952 &cq_arg,
11953 &txs_arg,
11954 &tiles_arg,
11955 ])
11956 .args(["--obu", "-o", "-", "-"]),
11957 &y4m,
11958 );
11959 assert!(
11960 out.status.success(),
11961 "{NAME}: aomenc refused {arm}: {}",
11962 String::from_utf8_lossy(&out.stderr)
11963 );
11964 let stream = out.stdout;
11965 decode::reset_palette_leaf8_hits();
11966 decode::reset_palette_sb_strip_hits();
11967 let decoded = decode_stream(&stream);
11968 let leaf8 = decode::palette_leaf8_hits();
11969 let sb_strip = decode::palette_sb_strip_hits();
11970 leaf8_total += leaf8;
11971 sb_strip_total += sb_strip;
11972 match decoded {
11973 Ok(frames) => {
11974 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
11975 // The ENCODE's frame count: the per-arm
11976 // render (10417) builds
11977 // `{src}=size=128x128:rate=25` with `-t 0.04`
11978 // (10427) -- one frame -- and the aomenc args
11979 // carry `--limit=1` (10467), so every
11980 // (src, depth, cq, txs, tiles) arm codes
11981 // exactly 1 frame. Asserted ABOVE the oracle
11982 // call.
11983 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
11984 let theirs = if depth == 10 {
11985 ffmpeg_decode_sequence_10bit(
11986 &stream,
11987 width,
11988 height,
11989 frames.len(),
11990 )
11991 } else {
11992 ffmpeg_decode_sequence(&stream, width, height, frames.len())
11993 };
11994 assert_eq!(
11995 frames.len(),
11996 theirs.len(),
11997 "{NAME}: {arm} frame count"
11998 );
11999 let mut same = true;
12000 for (i, (ours, ref_f)) in
12001 frames.iter().zip(theirs.iter()).enumerate()
12002 {
12003 let ok = ours.y == ref_f.y
12004 && ours.u == ref_f.u
12005 && ours.v == ref_f.v;
12006 if !ok {
12007 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
12008 }
12009 same &= ok;
12010 frames_compared += 1;
12011 }
12012 compared += 1;
12013 if sb_strip > 0 {
12014 sb_strip_arms += 1;
12015 assert!(
12016 same,
12017 "{NAME}: {arm} decoded {sb_strip} non-skip palette \
12018 block(s) on a superblock-level strip and did not \
12019 match ffmpeg"
12020 );
12021 }
12022 if leaf8 > 0 || sb_strip > 0 {
12023 fired_arms += 1;
12024 assert!(
12025 same,
12026 "{NAME}: {arm} decoded {leaf8} 8x8-leaf palette \
12027 block(s) and did not match ffmpeg"
12028 );
12029 } else {
12030 out_of_scope += 1;
12031 if !same {
12032 out_of_scope_mismatch += 1;
12033 }
12034 }
12035 eprintln!(
12036 "{NAME}: {arm} {} frame(s), {leaf8} 8x8-leaf palette \
12037 block(s), {sb_strip} superblock-strip palette \
12038 block(s), exact={same}",
12039 frames.len()
12040 );
12041 }
12042 Err(e) => {
12043 let msg = e.to_string();
12044 assert!(
12045 msg.contains("unsupported"),
12046 "{NAME}: {arm} decode failed: {e}"
12047 );
12048 // Named, counted, never turned into a skip.
12049 if msg.contains("superblock-level HORZ/VERT strip") {
12050 sb_strip_refusals += 1;
12051 }
12052 eprintln!("{NAME}: {arm} REFUSED: {e}");
12053 refusals += 1;
12054 }
12055 }
12056 }
12057 }
12058 }
12059 }
12060 }
12061 eprintln!(
12062 "{NAME}: {leaf8_total} 8x8-leaf palette block(s) across {fired_arms} arm(s), \
12063 {compared} arms compared ({frames_compared} frames), {sb_strip_total} \
12064 superblock-strip palette block(s) across {sb_strip_arms} arm(s), \
12065 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
12066 {refusals} refused ({sb_strip_refusals} superblock-strip palette)"
12067 );
12068 assert!(
12069 leaf8_total > 0 && fired_arms > 0,
12070 "{NAME}: gate is vacuous -- no compared arm decoded an 8x8-leaf palette block"
12071 );
12072 assert_eq!(
12073 sb_strip_refusals, 0,
12074 "{NAME}: the superblock-strip palette refusal is back (lane-t900 r34 lifted it)"
12075 );
12076 assert!(
12077 sb_strip_arms > 0 && sb_strip_total > 0,
12078 "{NAME}: no arm decoded a non-skip palette block on a superblock-level strip -- \
12079 the shape r34 lifted is no longer exercised"
12080 );
12081 assert_eq!(
12082 out_of_scope_mismatch, 0,
12083 "{NAME}: an out-of-scope arm mismatched ffmpeg -- a defect, never a skip"
12084 );
12085 assert!(
12086 frames_compared > 0,
12087 "{NAME}: no frame was compared pixel-exact"
12088 );
12089 }
12090
12091 /// lane-av1toolgates: the shared body of the two `enable-rect-tx`
12092 /// coverage gates (8-bit and 10-bit).
12093 ///
12094 /// The aomenc ARGUMENT VECTOR is built by each gate and passed in, never
12095 /// assembled here. That is not tidiness: `gate_coverage`'s `gate_bodies()`
12096 /// splits `stream.rs` on `\n #[` and keeps a segment only if that
12097 /// segment itself contains `--passes=1`, so a flag living in a helper is
12098 /// invisible to the coverage derivation. A helper that owns the recipe
12099 /// would leave this gate counted at whatever depth the helper's own text
12100 /// implies -- which is the blind spot that kept `enable-rect-tx` on the
12101 /// `NEVER_EXERCISED` lists after real streams had exercised it.
12102 ///
12103 /// WHAT THIS GATE IS AND IS NOT. `enable_rect_tx` has no sequence-header
12104 /// bit in AV1 -- aom reads it only in `tx_search.c` (`search_tx_size`'s
12105 /// `!enable_rect_tx && tx_size_wide != tx_size_high` skip and the
12106 /// `tx_size_max_32_square` remap) -- so the flag never reaches a decoder.
12107 /// Spelling `--enable-rect-tx=1` proves the ENCODER was ALLOWED the tool
12108 /// and nothing more. It is CONTEXT here, not the witness: a gate that
12109 /// stopped at the flag would be the `tool-disabled-in-every-gate` defect
12110 /// `NEVER_EXERCISED` exists to prevent, in a new costume.
12111 ///
12112 /// The witness is the PARSED PARTITION SHAPE, the only thing in the
12113 /// bitstream that can carry a rect transform:
12114 /// [`decode::rect_partition_hits`] counts `PARTITION_HORZ`/`PARTITION_VERT`
12115 /// symbols actually read, i.e. a rect partition in the tree this decoder
12116 /// walked, and [`decode::rect_coeff_tu_hits`] counts the rectangular
12117 /// transform units that then coded coefficients through `read_coeffs_rect`
12118 /// (`all_zero == 0`) -- the rect coefficient TABLES being read, not a
12119 /// header bit. Both are asserted above zero over the arms that decoded AND
12120 /// compared, and every frame is pixel-compared against ffmpeg's own decode
12121 /// of the identical bytes.
12122 ///
12123 /// LIMIT, stated because it bounds what this gate can claim: this
12124 /// repository has no INDEPENDENT partition parser to list leaves from --
12125 /// `ec-av1-syntax` parses OBU headers and the sequence header only -- and
12126 /// `ec_av1::census`'s per-frame `blocks`/`tx` shape maps, the one true
12127 /// leaf list, are armed by a process-global `OnceLock` on
12128 /// `EC_AV1_BITCENSUS`, so arming them inside a lib test would switch the
12129 /// accountant on for every other gate in the process. The partition walk is
12130 /// therefore observed through the decoder's own counters, which is weaker
12131 /// than a second opinion but is still a shape fact about the stream rather
12132 /// than a fact about the flag.
12133 ///
12134 /// RED-BEFORE: the COUNTERS, one per assert, both measured.
12135 /// `--enable-rect-tx=0` is deliberately NOT claimed as the mutation: it
12136 /// does NOT zero these counters (39 rect coefficient TUs against 210 on
12137 /// the cq20 arm, because `--enable-rect-partitions=1` already forces
12138 /// non-square transform sizes regardless), and with every partition shape
12139 /// off the flag yields no rect transform at either setting. `=0` does turn
12140 /// the gate red, but through the ORACLE -- its `--enable-tx-size-search=0`
12141 /// arm is a stream ffmpeg cannot decode past frame 6 of 15 -- so the
12142 /// frame-count assert fires first and proves nothing about the tool.
12143 fn rect_tx_tool_gate(name: &str, ten_bit: bool, args: &[String]) -> (usize, usize) {
12144 // A missing tool SKIPs, so the totals the caller sums stay 0 and the
12145 // gate's own witness assert fails loudly instead of passing vacuously
12146 // on a run that decoded nothing.
12147 if !have_ffmpeg() {
12148 eprintln!("SKIP {name}: no ffmpeg");
12149 return (0, 0);
12150 }
12151 if !have_aomenc() {
12152 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
12153 return (0, 0);
12154 }
12155 let (width, height) = (64usize, 64usize);
12156 let y4m = Command::new("ffmpeg")
12157 .args([
12158 "-v",
12159 "error",
12160 "-f",
12161 "lavfi",
12162 "-i",
12163 "mandelbrot=size=64x64:rate=25",
12164 "-pix_fmt",
12165 if ten_bit { "yuv420p10le" } else { "yuv420p" },
12166 // y4m calls 10-bit an unofficial pixel format (no-op at 8).
12167 "-strict",
12168 "-1",
12169 "-t",
12170 "0.60",
12171 "-f",
12172 "yuv4mpegpipe",
12173 "-",
12174 ])
12175 .stdin(Stdio::null())
12176 .stdout(Stdio::piped())
12177 .stderr(Stdio::piped())
12178 .output()
12179 .expect("ffmpeg failed to run");
12180 assert!(
12181 y4m.status.success(),
12182 "{name}: ffmpeg fixture: {}",
12183 String::from_utf8_lossy(&y4m.stderr)
12184 );
12185 let out = run_with_stdin(Command::new(aomenc_path()).args(args), &y4m.stdout);
12186 assert!(
12187 out.status.success(),
12188 "{name}: aomenc refused the fixture: {}",
12189 String::from_utf8_lossy(&out.stderr)
12190 );
12191 let stream = out.stdout;
12192 assert!(!stream.is_empty(), "{name}: aomenc wrote an empty stream");
12193 if ten_bit {
12194 assert_eq!(
12195 parsed_bit_depth(&stream),
12196 10,
12197 "{name}: aomenc did not write a 10-bit sequence header"
12198 );
12199 }
12200 let parts_before = decode::rect_partition_hits();
12201 let tus_before = decode::rect_coeff_tu_hits();
12202 let decoded = match decode_stream(&stream) {
12203 Ok(frames) => frames,
12204 Err(e) => panic!("{name}: decode_stream refused: {e}"),
12205 };
12206 // Sampled after the decode, before the pixel compare, so a mismatch
12207 // report can still say whether the arm fired.
12208 let parts = decode::rect_partition_hits() - parts_before;
12209 let tus = decode::rect_coeff_tu_hits() - tus_before;
12210 // The ENCODE's frame count: the fixture renders `mandelbrot=size=64x64:rate=25`
12211 // with `-t "0.60"` (10677-10691) -- 25 x 0.60 = 15 frames -- and the
12212 // caller's `args` carry no `--limit` (10823-10853), so every arm's stream
12213 // codes all 15. Asserted ABOVE the oracle call, which is the fix for the
12214 // misattribution this gate's own doc comment records: the
12215 // `--enable-tx-size-search=0` arm is a stream ffmpeg cannot decode past
12216 // frame 6 of 15, and with the count taken from our decode the helper's
12217 // byte-length assert fires FIRST and reads as an ffmpeg fault. Naming the
12218 // 15 here makes the shortfall ours to explain.
12219 const ENCODED_FRAMES: usize = 15;
12220 assert_eq!(
12221 decoded.len(),
12222 ENCODED_FRAMES,
12223 "{name}: the encode codes {ENCODED_FRAMES} frames, the decode showed {} (rect \
12224 partitions {parts}, rect coefficient TUs {tus})",
12225 decoded.len()
12226 );
12227 let reference = if ten_bit {
12228 ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len())
12229 } else {
12230 ffmpeg_decode_sequence(&stream, width, height, decoded.len())
12231 };
12232 assert_eq!(
12233 decoded.len(),
12234 reference.len(),
12235 "{name}: shown-frame count vs ffmpeg (rect partitions {parts}, rect coefficient \
12236 TUs {tus})"
12237 );
12238 for (i, (ours, theirs)) in decoded.iter().zip(&reference).enumerate() {
12239 for (plane, (a, b), w) in [
12240 ("Y", (&ours.y, &theirs.y), width),
12241 ("U", (&ours.u, &theirs.u), width / 2),
12242 ("V", (&ours.v, &theirs.v), width / 2),
12243 ] {
12244 assert_eq!(a.len(), b.len(), "{name}: frame {i} {plane} plane length");
12245 if a != b {
12246 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
12247 let _ = std::fs::write(&pin, &stream);
12248 let at = a
12249 .iter()
12250 .zip(b.iter())
12251 .position(|(x, y)| x != y)
12252 .unwrap_or(0);
12253 panic!(
12254 "{name}: frame {i} {plane} mismatch vs ffmpeg at row {}, col {}: {} vs \
12255 {} (rect partitions {parts}, rect coefficient TUs {tus}; stream pinned \
12256 at {})",
12257 at / w,
12258 at % w,
12259 a[at],
12260 b[at],
12261 pin.display()
12262 );
12263 }
12264 }
12265 }
12266 eprintln!(
12267 "{name}: {} bit, pixel-exact vs ffmpeg; parsed rect partitions {parts}, rect \
12268 coefficient TUs {tus}",
12269 if ten_bit { "10" } else { "8" }
12270 );
12271 (parts, tus)
12272 }
12273
12274 /// lane-av1toolgates: the gate-level WITNESS, summed over the arms that
12275 /// decoded AND compared. It cannot be asserted per arm: the cq20 /
12276 /// tx-size-search=1 arm reaches a rect transform through the var-tx
12277 /// search on a SQUARE block (a nonzero rect coefficient count with zero
12278 /// rect partitions read -- the purest form of what `--enable-rect-tx`
12279 /// buys), while the rect PARTITION only shows up on the
12280 /// tx-size-search=0 arm. Either fact alone would let a stream through on
12281 /// which the tool was allowed and unused, which is the defect this
12282 /// coverage entry was written for; together they are the parsed-shape
12283 /// evidence the entry asked for.
12284 #[track_caller]
12285 fn assert_rect_tx_witness(name: &str, parts: usize, tus: usize) {
12286 assert!(
12287 parts > 0,
12288 "{name}: no PARTITION_HORZ/PARTITION_VERT symbol was read on any pixel-exact decode \
12289 -- the parsed partition tree never yielded a rect leaf, so `--enable-rect-tx=1` \
12290 was allowed and unused"
12291 );
12292 assert!(
12293 tus > 0,
12294 "{name}: no rectangular transform unit coded coefficients through read_coeffs_rect \
12295 ({parts} rect partitions read) -- the rect coefficient path was never taken"
12296 );
12297 }
12298
12299 /// lane-av1toolgates: `enable-rect-tx` at 8 BITS. See
12300 /// [`rect_tx_tool_gate`] for what the flag does and does not prove, and
12301 /// why the recipe is spelled here rather than in the helper.
12302 ///
12303 /// The whole recipe is inline: `--passes=1` has to be findable in this
12304 /// segment for the coverage derivation to count the gate at all, and
12305 /// `--enable-rect-tx=1` has to be findable here for it to count the
12306 /// TOOL. The quantiser and the tx-size-search setting are swept as two
12307 /// arms so the witness cannot rest on one RD interaction.
12308 #[test]
12309 fn a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact() {
12310 let mut totals = (0usize, 0usize);
12311 for (cq, tx_search) in [("20", "1"), ("40", "0")] {
12312 let args: Vec<String> = [
12313 "--codec=av1",
12314 "--passes=1",
12315 "--end-usage=q",
12316 "--cpu-used=0",
12317 "--threads=1",
12318 "--row-mt=0",
12319 "--lag-in-frames=0",
12320 "--auto-alt-ref=0",
12321 "--kf-max-dist=1000",
12322 "--error-resilient=1",
12323 "--sb-size=64",
12324 // The tool under test, spelled explicitly. CONTEXT, per
12325 // `rect_tx_tool_gate`: aomenc was ALLOWED rect tx sizes.
12326 "--enable-rect-tx=1",
12327 "--enable-rect-partitions=1",
12328 "--enable-ab-partitions=0",
12329 "--enable-1to4-partitions=0",
12330 "--enable-restoration=0",
12331 "--enable-palette=0",
12332 "--enable-cdef=0",
12333 "--enable-cfl-intra=0",
12334 "--enable-intrabc=0",
12335 "--enable-order-hint=0",
12336 "--min-partition-size=8",
12337 "--max-partition-size=32",
12338 ]
12339 .map(String::from)
12340 .into_iter()
12341 .chain([
12342 format!("--cq-level={cq}"),
12343 format!("--enable-tx-size-search={tx_search}"),
12344 ])
12345 // The output tail comes LAST: aomenc stops reading flags at the
12346 // first bare argument, so a sweep flag appended after `-o - -` is
12347 // silently dropped and the arm encodes a different recipe than the
12348 // one this gate claims to have run.
12349 .chain(["--obu", "-o", "-", "-"].map(String::from))
12350 .collect();
12351 let name = format!(
12352 "a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact[cq{cq}/tx{tx_search}]"
12353 );
12354 let (p, t) = rect_tx_tool_gate(&name, false, &args);
12355 totals.0 += p;
12356 totals.1 += t;
12357 }
12358 assert_rect_tx_witness(
12359 "a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact",
12360 totals.0,
12361 totals.1,
12362 );
12363 eprintln!(
12364 "a_real_aomenc_8bit_stream_with_a_rect_transform_decodes_pixel_exact: 2 arms \
12365 pixel-exact; parsed rect partitions {}, rect coefficient TUs {}",
12366 totals.0, totals.1
12367 );
12368 }
12369
12370 /// lane-av1toolgates: `enable-rect-tx` at 10 BITS -- the same recipe, the
12371 /// same parsed-shape witness, at the depth the 8-bit arm says nothing
12372 /// about (the per-depth rule `NEVER_EXERCISED_10BIT` is built on:
12373 /// lane-hbdinter's two 10-bit-only defects survived because every 10-bit
12374 /// gate pinned the filters off). The depth is spelled in THIS body,
12375 /// which is what files the gate in the 10-bit bucket.
12376 #[test]
12377 fn a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact() {
12378 let mut totals = (0usize, 0usize);
12379 for (cq, tx_search) in [("20", "1"), ("40", "0")] {
12380 let args: Vec<String> = [
12381 "--codec=av1",
12382 "--passes=1",
12383 "--end-usage=q",
12384 "--cpu-used=0",
12385 "--threads=1",
12386 "--row-mt=0",
12387 "--lag-in-frames=0",
12388 "--auto-alt-ref=0",
12389 "--kf-max-dist=1000",
12390 "--error-resilient=1",
12391 "--sb-size=64",
12392 "--input-bit-depth=10",
12393 "--bit-depth=10",
12394 // The tool under test, spelled explicitly. CONTEXT, per
12395 // `rect_tx_tool_gate`: aomenc was ALLOWED rect tx sizes.
12396 "--enable-rect-tx=1",
12397 "--enable-rect-partitions=1",
12398 "--enable-ab-partitions=0",
12399 "--enable-1to4-partitions=0",
12400 "--enable-restoration=0",
12401 "--enable-palette=0",
12402 "--enable-cdef=0",
12403 "--enable-cfl-intra=0",
12404 "--enable-intrabc=0",
12405 "--enable-order-hint=0",
12406 "--min-partition-size=8",
12407 "--max-partition-size=32",
12408 ]
12409 .map(String::from)
12410 .into_iter()
12411 .chain([
12412 format!("--cq-level={cq}"),
12413 format!("--enable-tx-size-search={tx_search}"),
12414 ])
12415 // The output tail comes LAST: aomenc stops reading flags at the
12416 // first bare argument, so a sweep flag appended after `-o - -` is
12417 // silently dropped and the arm encodes a different recipe than the
12418 // one this gate claims to have run.
12419 .chain(["--obu", "-o", "-", "-"].map(String::from))
12420 .collect();
12421 let name = format!(
12422 "a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact[cq{cq}/tx{tx_search}]"
12423 );
12424 let (p, t) = rect_tx_tool_gate(&name, true, &args);
12425 totals.0 += p;
12426 totals.1 += t;
12427 }
12428 assert_rect_tx_witness(
12429 "a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact",
12430 totals.0,
12431 totals.1,
12432 );
12433 eprintln!(
12434 "a_real_aomenc_10bit_stream_with_a_rect_transform_decodes_pixel_exact: 2 arms \
12435 pixel-exact; parsed rect partitions {}, rect coefficient TUs {}",
12436 totals.0, totals.1
12437 );
12438 }
12439
12440 /// lane-kf900 r5, the gate for the rect-strip `use_intrabc` read.
12441 ///
12442 /// `av1_allow_intrabc` is a FRAME-level test (`decodemv.c:892`,
12443 /// `read_intra_frame_mode_info`): on an intra frame whose header set
12444 /// `allow_intrabc`, EVERY intra block reads a `use_intrabc` symbol right
12445 /// after `skip`/`cdef`/`delta_q` and before `mbmi->mode`. There is no
12446 /// block-shape term, so rect strips read it exactly like square leaves --
12447 /// `read_intra_mode_rect` never did, and the arithmetic decoder desynced
12448 /// at the FIRST symbol of the first rect block of every
12449 /// `--tune-content=screen` key frame (measured: `testsrc2` 256x192 cq59
12450 /// 8-bit decoded "OK" with all 49152 luma samples wrong).
12451 ///
12452 /// Arm 0 is that recipe at cq50 without palette: its rect strips really do
12453 /// use intrabc. lane-av1-rect14 reconstructs those strips (2:1 and the
12454 /// 16x4/4x16 pair), so the arm must now decode pixel-exact -- and it must
12455 /// still have read the symbol. The named refusal remains only for a
12456 /// 128-superblock strip (`decode_block_128rect`), which this sb64 recipe
12457 /// does not reach.
12458 /// Arm 1 is the same recipe without palette and without tx-size search --
12459 /// it decodes the whole frame, reading the symbol dozens of times.
12460 /// Arm 2 is a screen-tools key frame whose header does NOT set
12461 /// `allow_intrabc` (cq63): it stays pixel-exact, proving the new read is
12462 /// not taken when libaom does not write it.
12463 ///
12464 /// PIXEL RESIDUE (open, lane-kf900 r5): arm 1's frame is entropy-exact
12465 /// against the instrumented aomdec for 429 mode-ladder elements and then
12466 /// diverges inside the DV read of a SQUARE intrabc block at mi(32,44), so
12467 /// its pixels are not compared here. That is a separate defect in
12468 /// `read_intrabc_dv`, not in the read this gate covers.
12469 #[test]
12470 fn a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips() {
12471 const NAME: &str = "a_real_aomenc_screen_key_frame_reads_use_intrabc_on_rect_strips";
12472 if !have_ffmpeg() {
12473 eprintln!("SKIP {NAME}: no ffmpeg");
12474 return;
12475 }
12476 if !have_aomenc() {
12477 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
12478 return;
12479 }
12480 let (width, height) = (256usize, 192usize);
12481 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
12482 // must_read_use_intrabc)
12483 const TS: &str = "testsrc2=s=256x192:r=25";
12484 const SB: &str = "smptebars=size=256x192:rate=25";
12485 // (arm, source, per-arm overrides AFTER the base recipe, expect_refusal,
12486 // must_read_use_intrabc_on_a_rect_strip)
12487 let arms: [(&str, &str, &[&str], bool, bool); 8] = [
12488 // lane-av1-intrabc (2026-09-20): this arm used to REFUSE here -- the
12489 // 16x8 rect strip it decodes is the first block on main that reaches
12490 // `decode_intrabc_rect`, so the whole arm stopped at a named refusal.
12491 // Reconstruction is ported now, so the arm decodes pixel-exact and
12492 // the `rect_total` assert below keeps it from quietly falling back
12493 // to an ordinary-intra decode of the same block.
12494 (
12495 "testsrc2-cq50-txs0",
12496 TS,
12497 &[
12498 "--cq-level=50",
12499 "--enable-palette=0",
12500 "--enable-tx-size-search=0",
12501 ],
12502 false,
12503 true,
12504 ),
12505 (
12506 "smptebars-cq40-txs0",
12507 SB,
12508 &[
12509 "--cq-level=40",
12510 "--enable-palette=0",
12511 "--enable-tx-size-search=0",
12512 ],
12513 false,
12514 false,
12515 ),
12516 (
12517 "smptebars-cq45-txs0",
12518 SB,
12519 &[
12520 "--cq-level=45",
12521 "--enable-palette=0",
12522 "--enable-tx-size-search=0",
12523 ],
12524 false,
12525 true,
12526 ),
12527 (
12528 "smptebars-cq45-txs1",
12529 SB,
12530 &[
12531 "--cq-level=45",
12532 "--enable-palette=0",
12533 "--enable-tx-size-search=1",
12534 ],
12535 false,
12536 false,
12537 ),
12538 (
12539 "smptebars-cq50-txs1",
12540 SB,
12541 &[
12542 "--cq-level=50",
12543 "--enable-palette=0",
12544 "--enable-tx-size-search=1",
12545 ],
12546 false,
12547 false,
12548 ),
12549 (
12550 "smptebars-cq55-txs0",
12551 SB,
12552 &[
12553 "--cq-level=55",
12554 "--enable-palette=0",
12555 "--enable-tx-size-search=0",
12556 ],
12557 false,
12558 false,
12559 ),
12560 (
12561 "testsrc2-cq63-txs1",
12562 TS,
12563 &[
12564 "--cq-level=63",
12565 "--enable-palette=0",
12566 "--enable-tx-size-search=1",
12567 ],
12568 false,
12569 false,
12570 ),
12571 // lane-kf900 r7: the 8x8-LEAF intrabc arm. Rect and 1:4
12572 // partitions off (so no rect strip refuses first), palette on,
12573 // `TxMode::Largest`: aomenc puts exactly one `use_intrabc` block
12574 // on a `BLOCK_8X8` leaf here, the shape `decode_leaf8` decoded as
12575 // ordinary intra before this round.
12576 (
12577 "testsrc2-cq55-leaf8",
12578 TS,
12579 &[
12580 "--cq-level=55",
12581 "--enable-palette=1",
12582 "--enable-tx-size-search=0",
12583 "--enable-rect-partitions=0",
12584 "--enable-1to4-partitions=0",
12585 ],
12586 false,
12587 false,
12588 ),
12589 ];
12590 let (mut reads_total, mut refused, mut frames_compared) = (0usize, 0u32, 0usize);
12591 let (mut blocks_total, mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) =
12592 (0usize, 0u32, 0u32, 0u32);
12593 let mut leaf8_total = 0usize;
12594 let mut rect_total = 0usize;
12595 for (arm, src, extra, expect_refusal, must_read) in &arms {
12596 let render = || {
12597 let out = Command::new("ffmpeg")
12598 .args([
12599 "-v",
12600 "error",
12601 "-f",
12602 "lavfi",
12603 "-i",
12604 *src,
12605 "-t",
12606 "0.2",
12607 "-pix_fmt",
12608 "yuv420p",
12609 "-strict",
12610 "-1",
12611 "-f",
12612 "yuv4mpegpipe",
12613 "-",
12614 ])
12615 .stdin(Stdio::null())
12616 .stdout(Stdio::piped())
12617 .stderr(Stdio::piped())
12618 .output()
12619 .expect("ffmpeg failed to run");
12620 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
12621 out.stdout
12622 };
12623 let y4m_a = render();
12624 let y4m_b = render();
12625 assert_eq!(
12626 y4m_a, y4m_b,
12627 "{NAME}: {arm} must render byte-identical across two runs"
12628 );
12629 let y4m = y4m_a;
12630 let out = run_with_stdin(
12631 Command::new(aomenc_path())
12632 .args([
12633 "--codec=av1",
12634 "--bit-depth=8",
12635 "--input-bit-depth=8",
12636 "--passes=1",
12637 "--end-usage=q",
12638 "--cpu-used=0",
12639 "--lag-in-frames=0",
12640 "--kf-max-dist=1",
12641 "--limit=1",
12642 "--threads=1",
12643 "--tile-columns=0",
12644 "--enable-rect-partitions=1",
12645 "--enable-1to4-partitions=1",
12646 "--min-partition-size=8",
12647 "--max-partition-size=32",
12648 "--sb-size=64",
12649 // `allow_screen_content_tools` (and with it the frame
12650 // header's `allow_intrabc` bit) comes from here.
12651 "--tune-content=screen",
12652 // Spelled so `gate_coverage` counts the tool as exercised
12653 // rather than defaulted (class `tool-disabled-in-every-gate`).
12654 "--enable-intrabc=1",
12655 ])
12656 // aomenc keeps the LAST occurrence of a repeated flag.
12657 .args(*extra)
12658 .args(["--obu", "-o", "-", "-"]),
12659 &y4m,
12660 );
12661 assert!(
12662 out.status.success(),
12663 "{NAME}: aomenc refused {arm}: {}",
12664 String::from_utf8_lossy(&out.stderr)
12665 );
12666 let stream = out.stdout;
12667 decode::reset_rect_intrabc_reads();
12668 crate::decode::reset_intrabc_hits();
12669 crate::decode::reset_leaf8_intrabc_hits();
12670 crate::decode::reset_intrabc_rect_hits();
12671 let decoded = decode_stream(&stream);
12672 let reads = decode::rect_intrabc_reads();
12673 // Blocks that decoded `use_intrabc == 1` (square path), i.e. that
12674 // read a DV and predicted from the current frame -- distinct from
12675 // `reads`, which counts rect strips that merely READ the flag.
12676 let blocks = crate::decode::intrabc_hits();
12677 reads_total += reads;
12678 blocks_total += blocks;
12679 // The 8x8-leaf shape has its own counter: without it this gate's
12680 // other arms (all rect/32x32 intrabc) would stay green while the
12681 // leaf path decoded an intrabc block as ordinary intra (class
12682 // `gate-blind-to-feature`).
12683 let leaf8 = crate::decode::leaf8_intrabc_hits();
12684 leaf8_total += leaf8;
12685 rect_total += crate::decode::intrabc_rect_hits();
12686 if *arm == "testsrc2-cq55-leaf8" {
12687 assert!(
12688 leaf8 > 0,
12689 "{NAME}: {arm} decoded no intrabc block at an 8x8 leaf -- the arm no longer exercises `decode_leaf8`'s intrabc path"
12690 );
12691 }
12692 if *must_read {
12693 assert!(
12694 reads > 0,
12695 "{NAME}: {arm} read no use_intrabc symbol on a rect strip -- the \
12696 arm no longer exercises the fix (allow_intrabc not set?)"
12697 );
12698 }
12699 match decoded {
12700 Ok(frames) => {
12701 assert!(
12702 !*expect_refusal,
12703 "{NAME}: {arm} decoded a frame whose rect strips use intrabc -- \
12704 reconstruction is not ported, it must refuse by name"
12705 );
12706 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
12707 // The ENCODE's frame count, asserted ABOVE the oracle call:
12708 // the per-arm render (11100) uses `-t 0.2` at TS/SB's
12709 // `rate=25` (10987, 10988) -- 5 input frames -- and the aomenc
12710 // args carry `--limit=1` (11145), so all eight arms code
12711 // exactly 1 frame. The old comment below claimed a count
12712 // assert here would be tautological; that is true of
12713 // `ffmpeg_frames.len() == frames.len()` and false of this:
12714 // `frames.len() == 1` is a fact about the ENCODE, checked
12715 // before `frames.len()` is spent as ffmpeg's frame budget.
12716 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
12717 let ffmpeg_frames =
12718 ffmpeg_decode_sequence(&stream, width, height, frames.len());
12719 // EVERY frame is compared; an arm whose decode never hit an
12720 // intrabc block proves nothing about the DV/prediction path,
12721 // so it is counted OUT OF SCOPE -- but a mismatch there is
12722 // still a failure (`out_of_scope_mismatch == 0`), never a skip.
12723 let mut same = true;
12724 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
12725 let ok = ours.y == theirs.y && ours.u == theirs.u && ours.v == theirs.v;
12726 if !ok {
12727 eprintln!("{NAME}: {arm} MISMATCH at frame {i}");
12728 }
12729 same &= ok;
12730 frames_compared += 1;
12731 }
12732 if blocks > 0 {
12733 fired_arms += 1;
12734 assert!(
12735 same,
12736 "{NAME}: {arm} decoded {blocks} intrabc block(s) and did not match ffmpeg"
12737 );
12738 } else {
12739 out_of_scope += 1;
12740 if !same {
12741 out_of_scope_mismatch += 1;
12742 }
12743 }
12744 eprintln!(
12745 "{NAME}: {arm} {} frame(s), {reads} rect use_intrabc reads, \
12746 {blocks} intrabc block(s), exact={same}",
12747 frames.len()
12748 );
12749 }
12750 Err(e) => {
12751 let msg = e.to_string();
12752 assert!(
12753 msg.contains("unsupported"),
12754 "{NAME}: {arm} decode failed: {e}"
12755 );
12756 assert!(
12757 *expect_refusal,
12758 "{NAME}: {arm} was expected to decode, it refused: {e}"
12759 );
12760 assert!(
12761 msg.contains("intra block copy") || msg.contains("intrabc"),
12762 "{NAME}: {arm} refused for an unrelated reason: {e}"
12763 );
12764 eprintln!("{NAME}: {arm} REFUSED (expected): {e}");
12765 refused += 1;
12766 }
12767 }
12768 }
12769 eprintln!(
12770 "{NAME}: {reads_total} rect-strip use_intrabc symbol(s) read, \
12771 {blocks_total} intrabc block(s) decoded across {fired_arms} arm(s), \
12772 {refused} refused by name, {frames_compared} frames compared, \
12773 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched)"
12774 );
12775 eprintln!(
12776 "{NAME}: {rect_total} intrabc block(s) on a HORZ/VERT rect strip (decode_intrabc_rect)"
12777 );
12778 assert!(
12779 reads_total > 0,
12780 "{NAME}: gate is vacuous -- no arm read the symbol"
12781 );
12782 assert!(
12783 leaf8_total > 0,
12784 "{NAME}: no arm decoded an intrabc block at an 8x8 leaf -- lane-kf900 r7's fix is untested"
12785 );
12786 assert!(
12787 blocks_total > 0 && fired_arms > 0,
12788 "{NAME}: gate is vacuous -- no compared arm actually decoded an intrabc block"
12789 );
12790 assert!(
12791 rect_total > 0,
12792 "{NAME}: no arm decoded an intrabc block on a HORZ/VERT rect strip -- \
12793 `decode_intrabc_rect` is untested"
12794 );
12795 // lane-av1-intrabc: this used to be exactly one -- the 2:1 rect strips
12796 // now reconstruct. The 1:4 pair strips (`decode_rect4_16_strip` et al.)
12797 // still refuse by name, but no arm HERE reaches that shape; it stays
12798 // pinned by `refusal_inventory`'s own gate.
12799 assert_eq!(refused, 0, "{NAME}: an arm still refuses by name");
12800 assert!(
12801 frames_compared > 0,
12802 "{NAME}: no frame was compared pixel-exact"
12803 );
12804 assert_eq!(
12805 out_of_scope_mismatch, 0,
12806 "{NAME}: an arm without an intrabc block still mismatched ffmpeg"
12807 );
12808 }
12809
12810 /// lane-av1-rect14: the 16x4/4x16 intrabc pair. libaom codes the pair's
12811 /// chroma on the odd-mi strip only (`is_chroma_reference`,
12812 /// av1_common_int.h:1454). The witness is the report recipe: testsrc2
12813 /// 640x480 cq60 palette, txs off, which places a 16x4 intrabc strip at
12814 /// mi(76,108). Pre-fix this refused by name. VERT_4 was not produced by
12815 /// any fully-decoded recipe tried here (the allintra stream codes four
12816 /// `PARTITION_VERT_4` at bsize 6 and then stops on the unrelated var-tx
12817 /// mixed-leaf refusal); the VERT arm is the same body with the axes
12818 /// swapped.
12819 #[test]
12820 fn a_16x4_intrabc_pair_strip_decodes_pixel_exact() {
12821 const NAME: &str = "a_16x4_intrabc_pair_strip_decodes_pixel_exact";
12822 if !have_ffmpeg() || !have_aomenc() {
12823 eprintln!("SKIP {NAME}: ffmpeg/aomenc missing");
12824 return;
12825 }
12826 let (width, height) = (640usize, 480usize);
12827 let y4m = Command::new("ffmpeg")
12828 .args([
12829 "-v",
12830 "error",
12831 "-f",
12832 "lavfi",
12833 "-i",
12834 "testsrc2=s=640x480:r=25",
12835 "-frames:v",
12836 "1",
12837 "-pix_fmt",
12838 "yuv420p",
12839 "-strict",
12840 "-1",
12841 "-f",
12842 "yuv4mpegpipe",
12843 "-",
12844 ])
12845 .output()
12846 .expect("ffmpeg")
12847 .stdout;
12848 let out = run_with_stdin(
12849 Command::new(aomenc_path()).args([
12850 "--codec=av1",
12851 "--bit-depth=8",
12852 "--input-bit-depth=8",
12853 "--passes=1",
12854 "--end-usage=q",
12855 "--cpu-used=0",
12856 "--lag-in-frames=0",
12857 "--kf-max-dist=1",
12858 "--limit=1",
12859 "--threads=1",
12860 "--tile-columns=0",
12861 "--enable-rect-partitions=1",
12862 "--enable-1to4-partitions=1",
12863 "--min-partition-size=4",
12864 "--max-partition-size=64",
12865 "--sb-size=64",
12866 "--tune-content=screen",
12867 "--enable-intrabc=1",
12868 "--cq-level=60",
12869 "--enable-palette=1",
12870 "--enable-tx-size-search=0",
12871 "--obu",
12872 "-o",
12873 "-",
12874 "-",
12875 ]),
12876 &y4m,
12877 );
12878 assert!(out.status.success(), "{NAME}: aomenc failed");
12879 crate::decode::reset_rect4_16_pair_hits();
12880 let frames = decode_stream(&out.stdout).unwrap_or_else(|e| panic!("{NAME}: {e}"));
12881 assert!(
12882 crate::decode::rect4_16_intrabc_hits() > 0,
12883 "{NAME}: no 16x4/4x16 intrabc strip -- the pair body was not reached"
12884 );
12885 // The ENCODE's frame count, asserted ABOVE the oracle call: the y4m is
12886 // rendered with `-frames:v 1` (11333) -- a single frame of
12887 // `testsrc2=s=640x480:r=25` -- and aomenc runs with
12888 // `--limit=1 --kf-max-dist=1` (11355, 11356), so the stream codes
12889 // exactly 1 key frame. Below the call this assert could not fire
12890 // first: `ffmpeg_decode_sequence` was already handed `frames.len()`.
12891 assert_eq!(frames.len(), 1, "{NAME}: expected one key frame");
12892 let refs = ffmpeg_decode_sequence(&out.stdout, width, height, frames.len());
12893 assert_eq!(frames[0].y, refs[0].y, "{NAME}: luma");
12894 assert_eq!(frames[0].u, refs[0].u, "{NAME}: u");
12895 assert_eq!(frames[0].v, refs[0].v, "{NAME}: v");
12896 }
12897
12898 /// lane-av1-rect14: lossless 16x4/4x16 chroma is two TX_4X4s, not one
12899 /// TX_8X4. The measured site is luma col 108 of a 320x240 sb128 lossless
12900 /// key frame (lanes/av1lossless128.report.md §6). Rows 0-127 of that
12901 /// frame -- the first superblock row, which contains the site -- must
12902 /// match ffmpeg. A later mismatch is the pre-existing 64x64 square
12903 /// lossless residue (base fails at byte 108; this lane's first remaining
12904 /// mismatch is row 128). The gate fails if that residue moves back into
12905 /// the repaired region.
12906 #[test]
12907 fn a_lossless_16x4_chroma_pair_repairs_the_measured_site() {
12908 const NAME: &str = "a_lossless_16x4_chroma_pair_repairs_the_measured_site";
12909 if !have_ffmpeg() || !have_aomenc() {
12910 eprintln!("SKIP {NAME}: ffmpeg/aomenc missing");
12911 return;
12912 }
12913 let (width, height) = (320usize, 240usize);
12914 let y4m = Command::new("ffmpeg")
12915 .args([
12916 "-v",
12917 "error",
12918 "-f",
12919 "lavfi",
12920 "-i",
12921 "testsrc2=s=320x240:r=25",
12922 "-frames:v",
12923 "1",
12924 "-pix_fmt",
12925 "yuv420p",
12926 "-strict",
12927 "-1",
12928 "-f",
12929 "yuv4mpegpipe",
12930 "-",
12931 ])
12932 .output()
12933 .expect("ffmpeg")
12934 .stdout;
12935 let out = run_with_stdin(
12936 Command::new(aomenc_path()).args([
12937 "--codec=av1",
12938 "--cpu-used=0",
12939 "--lossless=1",
12940 "--sb-size=128",
12941 "--lag-in-frames=0",
12942 "--kf-max-dist=1",
12943 "--limit=1",
12944 "--threads=1",
12945 "--passes=1",
12946 "--enable-1to4-partitions=1",
12947 "--min-partition-size=4",
12948 "--enable-rect-partitions=1",
12949 "--obu",
12950 "-o",
12951 "-",
12952 "-",
12953 ]),
12954 &y4m,
12955 );
12956 assert!(out.status.success(), "{NAME}: aomenc failed");
12957 crate::decode::reset_rect4_16_pair_hits();
12958 let frames = decode_stream(&out.stdout).unwrap_or_else(|e| panic!("{NAME}: {e}"));
12959 assert!(
12960 crate::decode::rect4_16_lossless_chroma_hits() > 0,
12961 "{NAME}: no lossless 16x4/4x16 chroma pair -- the walk was not reached"
12962 );
12963 // The ENCODE's frame count: the y4m is rendered with `-frames:v 1`
12964 // (11414) -- a single frame of `testsrc2=s=320x240:r=25` -- and aomenc
12965 // runs with `--limit=1 --kf-max-dist=1` (11434, 11435), so the stream
12966 // codes exactly 1 lossless key frame. Asserted ABOVE the oracle call:
12967 // this gate then indexes `frames[0]`/`refs[0]`, which a zero-frame
12968 // decode would panic on rather than report.
12969 assert_eq!(frames.len(), 1, "{NAME}: expected one lossless key frame");
12970 let refs = ffmpeg_decode_sequence(&out.stdout, width, height, frames.len());
12971 let repaired = 128 * width;
12972 assert_eq!(
12973 &frames[0].y[..repaired],
12974 &refs[0].y[..repaired],
12975 "{NAME}: luma rows 0-127 (the measured col-108 site) diverged"
12976 );
12977 let chroma_rows = 64 * (width / 2);
12978 assert_eq!(
12979 &frames[0].u[..chroma_rows],
12980 &refs[0].u[..chroma_rows],
12981 "{NAME}: u"
12982 );
12983 assert_eq!(
12984 &frames[0].v[..chroma_rows],
12985 &refs[0].v[..chroma_rows],
12986 "{NAME}: v"
12987 );
12988 // The col-108 byte specifically, so a shift of the old site still fails
12989 // even if some other prefix sample happens to match.
12990 assert_eq!(
12991 frames[0].y[108], refs[0].y[108],
12992 "{NAME}: measured byte 108"
12993 );
12994 }
12995
12996 /// lane-av1tilerows: the 4:4:4 LOSSLESS rect-pair chroma REACH fix --
12997 /// the defect lane `av1formatsweep` filed as **H4** ("4:4:4 lossless +
12998 /// `--tile-rows=1`, frame 3 onward the whole plane goes flat") and this
12999 /// lane's red-before actually measured.
13000 ///
13001 /// **The H4 label was wrong; the defect it points at is real.** Two
13002 /// corrections to the sweep's framing, both measured:
13003 ///
13004 /// 1. `--tile-rows=1` at 256x128 is a **no-op**. aomenc's default
13005 /// superblock is 128px, so 256x128 is 2x1 superblocks -- there is no
13006 /// second superblock ROW to split, and aomenc silently emits a
13007 /// stream BYTE-IDENTICAL to `--tile-columns=0 --tile-rows=0`
13008 /// (verified: both 64828 bytes, `cmp` equal). The sweep's "tiled"
13009 /// fixture contained no tile rows at all. Tile rows at 4:4:4
13010 /// lossless are exact here: measured pixel-exact at 1, 2 and 4 tile
13011 /// rows, both axes (2x2), at 256x128 / 256x256 / 128x256 / 512x128,
13012 /// on a recipe that is exact without tiles.
13013 /// 2. The "frames 0-2 byte-exact, frame 3 onward flat, Y(0,0) 128 vs
13014 /// 81" signature is a **harness frame-order mismatch, not a decode
13015 /// defect**: with altref on, aomdec's `EC_AV1_FINAL_DUMP` writes 7
13016 /// frames in DECODE order while `ffmpeg -f rawvideo` writes 6 in
13017 /// DISPLAY order. Indexing one against the other makes frame 1 differ
13018 /// by 29109 samples (30%) -- and aomdec-vs-ffmpeg ALONE reproduces
13019 /// the identical 29109/24412/20046/19906 counts with no edith
13020 /// decoder in the loop. Our decode-order output is byte-exact against
13021 /// the oracle on all 7.
13022 ///
13023 /// The defect IS real, is in the class the sweep named (a hardcoded
13024 /// 4:2:0-shaped walk at 4:4:4), and is tile-INDEPENDENT: it reproduces
13025 /// on the zero-tile stream. `decode.rs`'s lossless 16x4/4x16 chroma-pair
13026 /// walk passed `tu_reach` a hardcoded 4:2:0 luma footprint
13027 /// (`ox * 2, oy * 2, 8`) for every chroma transform unit. At 4:4:4 a
13028 /// 4x4 chroma unit is 4x4 LUMA, so the footprint is doubled:
13029 /// `Reach::of_tu`'s `col_off + tx_w < bw` test then answers against a
13030 /// block twice its real width and every unit past the midpoint wrongly
13031 /// reports `above_right = false`, so a directional chroma strip predicts
13032 /// from a neighbour libaom never reads.
13033 ///
13034 /// **Measured site (red-before, `git stash` of the fix, same tree):**
13035 /// `testsrc2 256x128 yuv444p`, aomenc `--profile=1 --lossless=1
13036 /// --passes=1 --end-usage=q --threads=1 --row-mt=0 --limit=6
13037 /// --cpu-used=2 --lag-in-frames=0 --kf-max-dist=100` (pinned below).
13038 /// Frame 0 (the KEY frame) and all five inter frames: **63 samples wrong
13039 /// per frame, U 29 + V 34, first at U(110,26) / V(108,26), deltas -10..+13**,
13040 /// region x108..125 y26..29 -- a 16x4 chroma strip at 4:4:4, whose rows
13041 /// are NOT block-aligned (y26), which is the signature of a REACH
13042 /// answer and not of a coefficient or transform error.
13043 ///
13044 /// **Entropy is bit-identical**: `EC_SYMR` on both sides, 351109 reads
13045 /// compared on `(value, range, symbol, post_rng)` with the CDF-row
13046 /// convention reconciled (`32768 - ours_cdf0 == oracle_cdf0`): **zero
13047 /// divergence**. So this is reconstruction arithmetic, not an entropy
13048 /// fork -- which is what separates it from the H1 rect-partition fork
13049 /// (that one forks `EC_SYMR` at `decodetxb.c:158` `txb_skip`).
13050 ///
13051 /// A second, far worse instance of the SAME defect is the 512x128
13052 /// `--cpu-used=2` stream (18779 wrong in the key frame, growing to
13053 /// 130708 by frame 5) -- but that stream ALSO forks entropy
13054 /// (459866 oracle reads vs 369136 ours), so it is not claimed here;
13055 /// it belongs to the H1 rect-partition lane. The pinned fixture below is
13056 /// the entropy-clean, fully-repaired instance.
13057 ///
13058 /// Non-vacuity: the fixture bytes are pinned (length + FNV-1a, like the
13059 /// other `ll444_*` pins), the header must really be `ss (0,0)` at 8-bit
13060 /// with `lossless == 1` (asserted from the parsed sequence header, not
13061 /// assumed), the tiled sweep gates' counter
13062 /// `decode::rect4_16_lossless_chroma_hits()` must FIRE (measured 80
13063 /// units on this fixture -- a 4:2:0 stream of the same content leaves it
13064 /// at 0, because a 4:2:0 lossless 16x4 pair is an 8x4 chroma block and
13065 /// takes the pair-merge, not this walk), and every frame must be
13066 /// byte-exact through BOTH the oracle `aomdec --rawvideo` (decode order,
13067 /// the 7-frame compare that the hidden-frame gates use) and ffmpeg
13068 /// (display order, 4:4:4 full-resolution chroma).
13069 #[test]
13070 fn a_lossless_444_rect16x4_chroma_reach_is_ss_aware() {
13071 const NAME: &str = "a_lossless_444_rect16x4_chroma_reach_is_ss_aware";
13072 const FIXTURE_LEN: usize = 77918;
13073 const FIXTURE_FNV: u64 = 0xe2a2_90ac_f249_4bf7;
13074 const W: usize = 256;
13075 const H: usize = 128;
13076 const FRAMES: usize = 6;
13077 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
13078 .join("fixtures/ll444_rect16x4_chroma_reach.obu");
13079 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
13080 panic!(
13081 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
13082 which is a failure, not a skip",
13083 obu.display()
13084 )
13085 });
13086 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
13087 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
13088
13089 // The header must really be the shape the fix is about: 4:4:4
13090 // (ss 0/0) at 8-bit. A fixture that silently became 4:2:0 would
13091 // take the pair-merge and make every arm below vacuous.
13092 {
13093 let mut p = Av1Parser::new();
13094 let mut pos = 0usize;
13095 let mut seq = None;
13096 while pos < stream.len() {
13097 let Ok(obu) = p.parse_obu(&stream[pos..]) else {
13098 break;
13099 };
13100 pos += obu.total_size;
13101 if matches!(obu.kind, ObuKind::SequenceHeader(_)) {
13102 seq = p.sequence_header();
13103 break;
13104 }
13105 }
13106 let seq = seq.unwrap_or_else(|| panic!("{NAME}: no sequence header parsed"));
13107 assert_eq!(
13108 (
13109 seq.color_config.subsampling_x,
13110 seq.color_config.subsampling_y
13111 ),
13112 (0, 0),
13113 "{NAME}: fixture is not 4:4:4 (ss {}x{})",
13114 seq.color_config.subsampling_x,
13115 seq.color_config.subsampling_y
13116 );
13117 assert_eq!(
13118 seq.color_config.bit_depth, 8,
13119 "{NAME}: fixture bit depth moved"
13120 );
13121 assert_eq!(seq.max_frame_width, W as u32, "{NAME}: fixture width moved");
13122 assert_eq!(
13123 seq.max_frame_height, H as u32,
13124 "{NAME}: fixture height moved"
13125 );
13126 }
13127
13128 let _guard = lock_gate_counters();
13129 crate::decode::reset_rect4_16_pair_hits();
13130 let frames = decode_stream(&stream)
13131 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
13132 let hits = crate::decode::rect4_16_lossless_chroma_hits();
13133 assert!(
13134 hits > 0,
13135 "{NAME}: gate is vacuous -- no lossless 16x4/4x16 chroma-pair unit was \
13136 walked (rect4_16_lossless_chroma_hits = {hits}), so the repaired \
13137 `tu_reach` call site never ran"
13138 );
13139 assert_eq!(frames.len(), FRAMES, "{NAME}: shown frame count");
13140 for f in &frames {
13141 assert_eq!((f.width, f.height), (W, H), "{NAME}: dimensions");
13142 }
13143
13144 // The oracle, DECODE order, every frame including hidden alt-ref
13145 // frames. This is the arm that proves the repair against aomdec's
13146 // own reconstruction, not just ffmpeg's.
13147 if aomdec_available(NAME) {
13148 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, NAME);
13149 assert!(
13150 decoded >= FRAMES,
13151 "{NAME}: oracle decoded {decoded} frames, expected at least {FRAMES}"
13152 );
13153 let _ = hidden;
13154 }
13155
13156 // ffmpeg's decoder: DISPLAY order, full-resolution chroma.
13157 if have_ffmpeg() {
13158 let refs = ffmpeg_decode_sequence_444(&stream, W, H, FRAMES);
13159 for (i, (got, want)) in frames.iter().zip(refs.iter()).enumerate() {
13160 for (p, (g, r)) in [(&got.y, &want.y), (&got.u, &want.u), (&got.v, &want.v)]
13161 .iter()
13162 .enumerate()
13163 {
13164 let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
13165 assert_eq!(
13166 bad, 0,
13167 "{NAME}: ffmpeg frame {i} plane {p}: {bad} samples differ"
13168 );
13169 }
13170 }
13171 } else {
13172 eprintln!("SKIP {NAME} ffmpeg arm: no ffmpeg");
13173 }
13174 }
13175 /// lane-av1-intrabc r4: the reviewer's unblock witness for the rect-strip
13176 /// reconstruction -- a CODED `use_intrabc` block (so its residual reader
13177 /// runs, not just the prediction copy) on a 2:1 strip in BOTH
13178 /// orientations, plus the `TX_MODE_SELECT` (var-tx) shape, every arm
13179 /// byte-exact against ffmpeg.
13180 ///
13181 /// The orientation counters (`intrabc_rect_coded_hits`) are the
13182 /// non-vacuity instrument: [`intrabc_rect_hits`] counts neither the skip
13183 /// flag nor the orientation, so an arm that silently became an all-skip
13184 /// stream (or a stream with only one orientation) would keep the old gate
13185 /// green while the coded residual path went untested
13186 /// (class `gate-blind-to-feature`).
13187 ///
13188 /// # The VERT arm is also the DV-PREDICTOR regression witness
13189 ///
13190 /// The 512x384 arm is the stream that exposed r4's defect: 528 of 294912
13191 /// luma samples were wrong, all inside one `skip == 1` intrabc copy at
13192 /// `mi(84,104)`. Its coded diff was identical to aomdec's and the post-read
13193 /// range matched exactly (`rng=33207` both), so nothing was misread -- the
13194 /// DV PREDICTOR differed. libaom picks `nearestmv` (`-520`) from the
13195 /// `INTRA_FRAME` MV stack; this decoder picked `-512`, one stack entry
13196 /// lower, because the scan that builds that stack walked further than
13197 /// libaom's. The scans step by the candidate BLOCK's own width
13198 /// (`mi_size_wide[bsize]`) over `xd->mi[]`, which holds an entry for every
13199 /// coded block; this decoder's MV grid held only the intrabc blocks, so a
13200 /// non-intrabc neighbour read as uncovered and the scan advanced that cell
13201 /// by one instead of by its real width. See `MiGrid::cover` for the
13202 /// measured walk. A stream that decodes the DV predictor from the wrong
13203 /// stack entry cannot pass this arm's pixel comparison.
13204 #[test]
13205 fn a_coded_rect_intrabc_block_reconstructs_in_both_orientations() {
13206 const NAME: &str = "a_coded_rect_intrabc_block_reconstructs_in_both_orientations";
13207 if !have_ffmpeg() {
13208 eprintln!("SKIP {NAME}: no ffmpeg");
13209 return;
13210 }
13211 if !have_aomenc() {
13212 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13213 return;
13214 }
13215 const TS256: &str = "testsrc2=s=256x192:r=25";
13216 const TS512: &str = "testsrc2=s=512x384:r=25";
13217 // (arm, source, width, height, per-arm overrides, the coded orientation
13218 // this arm must exercise, and whether the frame must code
13219 // `TX_MODE_SELECT` with `allow_intrabc` still set)
13220 let arms: [(&str, &str, usize, usize, &[&str], u8, bool); 3] = [
13221 // HORZ (16x8) coded strip -- the shape the in-gate witness above
13222 // already reconstructs, pinned here with its own orientation counter.
13223 (
13224 "horz-coded-256-cq45-pal0-txs0",
13225 TS256,
13226 256,
13227 192,
13228 &[
13229 "--cq-level=45",
13230 "--enable-palette=0",
13231 "--enable-tx-size-search=0",
13232 ],
13233 0,
13234 false,
13235 ),
13236 // VERT (8x16) coded strip AND the DV-predictor regression stream.
13237 (
13238 "vert-coded-512-cq45-pal1-txs0",
13239 TS512,
13240 512,
13241 384,
13242 &[
13243 "--cq-level=45",
13244 "--enable-palette=1",
13245 "--enable-tx-size-search=0",
13246 ],
13247 1,
13248 false,
13249 ),
13250 // The `TX_MODE_SELECT` (stream A) shape: `--enable-tx-size-search=1`
13251 // makes the frame code `tx_mode == Select`, so the intrabc block's
13252 // transform size comes off the INTER var-tx tree.
13253 (
13254 "txmode-select-256-cq45-pal0-txs1",
13255 TS256,
13256 256,
13257 192,
13258 &[
13259 "--cq-level=45",
13260 "--enable-palette=0",
13261 "--enable-tx-size-search=1",
13262 ],
13263 0,
13264 true,
13265 ),
13266 ];
13267 let mut coded_total = [0usize; 2];
13268 let mut frames_compared = 0usize;
13269 for (arm, src, width, height, extra, want_orient, want_select) in &arms {
13270 let render = || {
13271 let out = Command::new("ffmpeg")
13272 .args([
13273 "-v",
13274 "error",
13275 "-f",
13276 "lavfi",
13277 "-i",
13278 *src,
13279 "-t",
13280 "0.2",
13281 "-pix_fmt",
13282 "yuv420p",
13283 "-strict",
13284 "-1",
13285 "-f",
13286 "yuv4mpegpipe",
13287 "-",
13288 ])
13289 .stdin(Stdio::null())
13290 .stdout(Stdio::piped())
13291 .stderr(Stdio::piped())
13292 .output()
13293 .expect("ffmpeg failed to run");
13294 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
13295 out.stdout
13296 };
13297 let y4m = render();
13298 let out = run_with_stdin(
13299 Command::new(aomenc_path())
13300 .args([
13301 "--codec=av1",
13302 "--bit-depth=8",
13303 "--input-bit-depth=8",
13304 "--passes=1",
13305 "--end-usage=q",
13306 "--cpu-used=0",
13307 "--lag-in-frames=0",
13308 "--kf-max-dist=1",
13309 "--limit=1",
13310 "--threads=1",
13311 "--tile-columns=0",
13312 "--enable-rect-partitions=1",
13313 "--enable-1to4-partitions=1",
13314 "--min-partition-size=8",
13315 "--max-partition-size=32",
13316 "--sb-size=64",
13317 "--tune-content=screen",
13318 "--enable-intrabc=1",
13319 ])
13320 // aomenc keeps the LAST occurrence of a repeated flag.
13321 .args(*extra)
13322 .args(["--obu", "-o", "-", "-"]),
13323 &y4m,
13324 );
13325 assert!(
13326 out.status.success(),
13327 "{NAME}: aomenc refused {arm}: {}",
13328 String::from_utf8_lossy(&out.stderr)
13329 );
13330 let stream = out.stdout;
13331 if *want_select {
13332 let (select, premise) = tx_select_and_intrabc_frames(&stream);
13333 assert!(
13334 select > 0 && premise > 0,
13335 "{NAME}: {arm} no longer codes a frame with both tx_mode == Select and \
13336 allow_intrabc (select={select} premise={premise}), so the TX_MODE_SELECT \
13337 shape is untested here"
13338 );
13339 }
13340 crate::decode::reset_intrabc_rect_hits();
13341 let frames =
13342 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {arm} refused: {e}"));
13343 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
13344 let coded = crate::decode::intrabc_rect_coded_hits();
13345 coded_total[0] += coded[0];
13346 coded_total[1] += coded[1];
13347 assert!(
13348 coded[*want_orient as usize] > 0,
13349 "{NAME}: {arm} reconstructed no CODED ({}) rect intrabc block -- the residual \
13350 reader for this orientation is untested (coded horz/vert = {coded:?})",
13351 if *want_orient == 0 { "HORZ" } else { "VERT" }
13352 );
13353 // The ENCODE's frame count: the per-arm render (11756) uses `-t 0.2`
13354 // at TS256/TS512's `rate=25` (11700, 11701) -- 5 input frames -- and
13355 // the aomenc args carry `--limit=1` (11797), so all three arms code
13356 // exactly 1 frame. Asserted ABOVE the oracle call.
13357 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
13358 let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len());
13359 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
13360 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
13361 assert!(
13362 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
13363 "{NAME}: {arm} frame {i} does not match ffmpeg"
13364 );
13365 frames_compared += 1;
13366 }
13367 eprintln!(
13368 "{NAME}: {arm} {} frame(s) exact, coded rect intrabc horz={} vert={}",
13369 frames.len(),
13370 coded[0],
13371 coded[1]
13372 );
13373 }
13374 assert!(
13375 coded_total[0] > 0 && coded_total[1] > 0,
13376 "{NAME}: gate is vacuous -- coded rect intrabc blocks seen: horz={} vert={}",
13377 coded_total[0],
13378 coded_total[1]
13379 );
13380 assert!(
13381 frames_compared > 0,
13382 "{NAME}: no frame was compared pixel-exact"
13383 );
13384
13385 // lane-av1-intrabc r5: the SKIPPED VERT 2:1 strip -- the arm the
13386 // reviewer's sweep panicked on (a skipped 8x32 strip passed a
13387 // `bw * bh`-sized ZERO_RESIDUAL slice at stride `side`, and
13388 // `reconstruct_mc_rect` indexed `row * side + w` past its end).
13389 // Skip-heavy recipes (low cq, palette off AND on), each decoded
13390 // byte-exact vs ffmpeg on BOTH the default single-threaded path
13391 // (`EC_AV1_RECON_THREADS == 1`, the inline ReconPlanes arm that
13392 // panicked pre-fix) AND the wavefront path. The skipped-orientation
13393 // counter is asserted per arm (`gate-blind-to-feature`): a recipe
13394 // that stops producing a skipped VERT strip fails instead of passing
13395 // vacuously. `lock_gate_counters` because `set_recon_threads` is a
13396 // process-wide knob.
13397 let _par_lock = lock_gate_counters();
13398 let skip_arms: [(&str, &str, usize, usize, &[&str]); 2] = [
13399 (
13400 "vert-skip-512-cq30-pal0-txs0",
13401 TS512,
13402 512,
13403 384,
13404 &[
13405 "--cq-level=30",
13406 "--enable-palette=0",
13407 "--enable-tx-size-search=0",
13408 ],
13409 ),
13410 (
13411 "vert-skip-512-cq30-pal1-txs0",
13412 TS512,
13413 512,
13414 384,
13415 &[
13416 "--cq-level=30",
13417 "--enable-palette=1",
13418 "--enable-tx-size-search=0",
13419 ],
13420 ),
13421 ];
13422 for (arm, src, width, height, extra) in &skip_arms {
13423 let y4m = {
13424 let out = Command::new("ffmpeg")
13425 .args([
13426 "-v",
13427 "error",
13428 "-f",
13429 "lavfi",
13430 "-i",
13431 *src,
13432 "-t",
13433 "0.2",
13434 "-pix_fmt",
13435 "yuv420p",
13436 "-strict",
13437 "-1",
13438 "-f",
13439 "yuv4mpegpipe",
13440 "-",
13441 ])
13442 .stdin(Stdio::null())
13443 .stdout(Stdio::piped())
13444 .stderr(Stdio::piped())
13445 .output()
13446 .expect("ffmpeg failed to run");
13447 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
13448 out.stdout
13449 };
13450 let out = run_with_stdin(
13451 Command::new(aomenc_path())
13452 .args([
13453 "--codec=av1",
13454 "--bit-depth=8",
13455 "--input-bit-depth=8",
13456 "--passes=1",
13457 "--end-usage=q",
13458 "--cpu-used=0",
13459 "--lag-in-frames=0",
13460 "--kf-max-dist=1",
13461 "--limit=1",
13462 "--threads=1",
13463 "--tile-columns=0",
13464 "--enable-rect-partitions=1",
13465 "--enable-1to4-partitions=1",
13466 "--min-partition-size=8",
13467 "--max-partition-size=32",
13468 "--sb-size=64",
13469 "--tune-content=screen",
13470 "--enable-intrabc=1",
13471 ])
13472 // aomenc keeps the LAST occurrence of a repeated flag.
13473 .args(*extra)
13474 .args(["--obu", "-o", "-", "-"]),
13475 &y4m,
13476 );
13477 assert!(
13478 out.status.success(),
13479 "{NAME}: aomenc refused {arm}: {}",
13480 String::from_utf8_lossy(&out.stderr)
13481 );
13482 let stream = out.stdout;
13483 // Default single-threaded path first (the arm that panicked
13484 // pre-fix), then the wavefront path; both must match ffmpeg.
13485 let mut skipped_vert = 0usize;
13486 for threads in [1usize, 4] {
13487 crate::par::set_recon_threads(threads);
13488 crate::decode::reset_intrabc_rect_hits();
13489 let frames = match decode_stream(&stream) {
13490 Ok(frames) => frames,
13491 Err(e) => {
13492 crate::par::set_recon_threads(1);
13493 panic!("{NAME}: {arm} refused at {threads} recon thread(s): {e}")
13494 }
13495 };
13496 let skipped = crate::decode::intrabc_rect_skipped_hits();
13497 assert!(
13498 !frames.is_empty(),
13499 "{NAME}: {arm} decoded no frame at {threads} recon thread(s)"
13500 );
13501 // The ENCODE's frame count: the skip_arms encode (11904) renders
13502 // TS512 with `-t 0.2` at `rate=25` (11907) and its aomenc runs
13503 // with `--limit=1` (11945), so the stream holds 1 coded frame --
13504 // and this loop re-decodes those SAME bytes at each `threads`
13505 // value, so the count is arm-invariant. Asserted ABOVE the call.
13506 assert_eq!(
13507 frames.len(),
13508 1,
13509 "{NAME}: {arm} key frame at {threads} recon thread(s)"
13510 );
13511 let theirs = ffmpeg_decode_sequence(&stream, *width, *height, frames.len());
13512 assert_eq!(
13513 frames.len(),
13514 theirs.len(),
13515 "{NAME}: {arm} frame count at {threads} recon thread(s)"
13516 );
13517 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
13518 assert!(
13519 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
13520 "{NAME}: {arm} frame {i} does not match ffmpeg at {threads} recon thread(s)"
13521 );
13522 }
13523 if threads == 1 {
13524 skipped_vert = skipped[1];
13525 } else {
13526 assert_eq!(
13527 skipped[1], skipped_vert,
13528 "{NAME}: {arm} skipped VERT strip count changed across recon paths"
13529 );
13530 }
13531 eprintln!(
13532 "{NAME}: {arm} {} frame(s) exact at {threads} recon thread(s), skipped rect intrabc horz={} vert={}",
13533 frames.len(),
13534 skipped[0],
13535 skipped[1]
13536 );
13537 }
13538 crate::par::set_recon_threads(1);
13539 assert!(
13540 skipped_vert > 0,
13541 "{NAME}: {arm} reconstructed no SKIPPED VERT rect intrabc strip -- the r5 stride arm is untested"
13542 );
13543 }
13544 }
13545
13546 /// lane-t900 r31: builds one `--tune-content=screen --enable-intrabc=1`
13547 /// key frame, 256x192 8-bit, from a deterministic lavfi source. `tiled`
13548 /// renders a 2x2 tiling of a 128x96 pattern -- exact spatial repetition,
13549 /// the content intra block copy exists for; `square_only` turns the rect
13550 /// and 1:4 partitions off so an intrabc block lands on a SQUARE block
13551 /// instead of stopping on the rect-strip intrabc refusal first.
13552 fn screen_intrabc_stream(
13553 src: &str,
13554 cq: &str,
13555 txs: &str,
13556 tiled: bool,
13557 square_only: bool,
13558 ) -> Vec<u8> {
13559 screen_intrabc_stream_with(src, cq, txs, tiled, square_only, &[])
13560 }
13561
13562 /// [`screen_intrabc_stream`] with per-arm flags appended AFTER the base
13563 /// recipe -- aomenc keeps the LAST occurrence of a repeated flag, so an
13564 /// arm can override `--sb-size` / `--min-partition-size` here.
13565 fn screen_intrabc_stream_with(
13566 src: &str,
13567 cq: &str,
13568 txs: &str,
13569 tiled: bool,
13570 square_only: bool,
13571 extra: &[&str],
13572 ) -> Vec<u8> {
13573 screen_intrabc_stream_at_depth(src, cq, txs, tiled, square_only, 8, extra)
13574 }
13575
13576 /// [`screen_intrabc_stream_with`] at an explicit bit depth (8 or 10): the
13577 /// lavfi source is rendered straight to that depth's yuv4mpegpipe pixel
13578 /// format and aomenc is told to encode at the matching
13579 /// `--bit-depth`/`--input-bit-depth`, so a 10-bit arm produces a genuine
13580 /// high-bit-depth stream rather than an 8-bit one in disguise.
13581 fn screen_intrabc_stream_at_depth(
13582 src: &str,
13583 cq: &str,
13584 txs: &str,
13585 tiled: bool,
13586 square_only: bool,
13587 depth: usize,
13588 extra: &[&str],
13589 ) -> Vec<u8> {
13590 assert!(depth == 8 || depth == 10, "unsupported bit depth {depth}");
13591 let pix_fmt = if depth == 10 {
13592 "yuv420p10le"
13593 } else {
13594 "yuv420p"
13595 };
13596 let mut ff = Command::new("ffmpeg");
13597 ff.args(["-v", "error", "-f", "lavfi", "-i", src, "-t", "0.2"]);
13598 if tiled {
13599 ff.args(["-vf", "tile=2x2"]);
13600 }
13601 let out = ff
13602 .args([
13603 "-pix_fmt",
13604 pix_fmt,
13605 "-strict",
13606 "-1",
13607 "-f",
13608 "yuv4mpegpipe",
13609 "-",
13610 ])
13611 .stdin(Stdio::null())
13612 .stdout(Stdio::piped())
13613 .stderr(Stdio::piped())
13614 .output()
13615 .expect("ffmpeg failed to run");
13616 assert!(out.status.success(), "ffmpeg failed for {src}");
13617 let y4m = out.stdout;
13618 let enc = run_with_stdin(
13619 Command::new(aomenc_path())
13620 .args(["--codec=av1"])
13621 .args([
13622 format!("--bit-depth={depth}"),
13623 format!("--input-bit-depth={depth}"),
13624 ])
13625 .args([
13626 "--passes=1",
13627 "--end-usage=q",
13628 "--cpu-used=0",
13629 "--lag-in-frames=0",
13630 "--kf-max-dist=1",
13631 "--limit=1",
13632 "--threads=1",
13633 "--tile-columns=0",
13634 "--min-partition-size=8",
13635 "--max-partition-size=32",
13636 "--sb-size=64",
13637 "--tune-content=screen",
13638 "--enable-intrabc=1",
13639 "--enable-palette=0",
13640 ])
13641 .args([
13642 format!("--cq-level={cq}"),
13643 format!("--enable-tx-size-search={txs}"),
13644 ])
13645 // aomenc keeps the LAST occurrence of a repeated flag.
13646 .args(if square_only {
13647 &["--enable-rect-partitions=0", "--enable-1to4-partitions=0"][..]
13648 } else {
13649 &[][..]
13650 })
13651 .args(extra)
13652 .args(["--obu", "-o", "-", "-"]),
13653 &y4m,
13654 );
13655 assert!(
13656 enc.status.success(),
13657 "aomenc refused {src} cq={cq}: {}",
13658 String::from_utf8_lossy(&enc.stderr)
13659 );
13660 enc.stdout
13661 }
13662
13663 /// The sequence header's `use_128x128_superblock`, and how many frames of
13664 /// `stream` keep `allow_intrabc` -- the two bits the refusal "intrabc
13665 /// under a 128x128 superblock" is the conjunction of, read out of the
13666 /// headers rather than assumed from the flags handed to the encoder.
13667 fn sb128_and_intrabc_frames(stream: &[u8]) -> (bool, u32) {
13668 let mut parser = Av1Parser::new();
13669 let mut pos = 0usize;
13670 let (mut sb128, mut intrabc) = (false, 0u32);
13671 while pos < stream.len() {
13672 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
13673 break;
13674 };
13675 pos += obu.total_size.max(1);
13676 if let Some(seq) = parser.sequence_header() {
13677 sb128 = seq.use_128x128_superblock;
13678 }
13679 let header = match &obu.kind {
13680 ObuKind::Frame(h, _) => Some(&**h),
13681 ObuKind::FrameHeader(h) => Some(&**h),
13682 _ => None,
13683 };
13684 if header.is_some_and(|h| h.allow_intrabc) {
13685 intrabc += 1;
13686 }
13687 }
13688 (sb128, intrabc)
13689 }
13690
13691 /// lane-t900 r34, the WITNESS (r33 pinned it ignored) that intrabc under
13692 /// a 128x128 superblock decodes pixel-exact.
13693 ///
13694 /// All four arms of r33's census -- `--sb-size=128 --tune-content=screen
13695 /// --enable-intrabc=1` over both `--enable-tx-size-search` settings and
13696 /// two quantisers, on a 2x2 tiling of a 128x96 bar pattern (256x192,
13697 /// 8-bit, `--cpu-used=0 --min-partition-size=8 --max-partition-size=32`,
13698 /// rect and 1:4 off) -- code `use_128x128_superblock && allow_intrabc`.
13699 ///
13700 /// The lift was one constant: `av1_find_ref_dv` (mvref_common.c) takes
13701 /// `mib_size`, the SEQUENCE's superblock size in mi units, so the
13702 /// fallback DV is one 128-px superblock up (or 128 + `INTRABC_DELAY_PIXELS`
13703 /// left on the tile's first superblock row) under a 128 superblock, where
13704 /// [`crate::decode::read_intrabc_dv`] hardcoded 64. Every arm is compared
13705 /// to ffmpeg and the decoded-intrabc-block counter is asserted non-zero,
13706 /// so a stream that stopped using intrabc could not make this vacuous.
13707 ///
13708 /// lane-av1-intrabc (2026-09-17): the four recipes now run at 10 bits as
13709 /// well, and both depths must SHOW the engagement -- `blocks_at_depth`
13710 /// below hard-asserts a decoded intrabc block per depth. The 10-bit
13711 /// coverage the guard records for `enable-intrabc` used to rest on a gate
13712 /// that only SPELLED `--enable-intrabc=1`: measured (same round), all five
13713 /// arms of `a_real_aomenc_rect_strip_palette_decodes_pixel_exact` decode
13714 /// ZERO intrabc blocks at BOTH depths, so the spelling proved nothing and
13715 /// the entry was one encoder-RD change away from being vacuous again
13716 /// (class `tool-disabled-in-every-gate`). An arm here that stops engaging
13717 /// intrabc now fails this gate instead of retiring the entry unproven.
13718 #[test]
13719 fn an_sb128_screen_stream_with_intrabc_decodes_pixel_exact() {
13720 const NAME: &str = "an_sb128_screen_stream_with_intrabc_decodes_pixel_exact";
13721 if !have_ffmpeg() || !have_aomenc() {
13722 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
13723 return;
13724 }
13725 let (width, height) = (256usize, 192usize);
13726 let _guard = lock_gate_counters();
13727 let (mut blocks_total, mut frames_compared) = (0usize, 0u32);
13728 let mut blocks_at_depth = [0usize; 2];
13729 for depth in [8usize, 10] {
13730 for txs in ["0", "1"] {
13731 for cq in ["30", "45"] {
13732 let arm = format!("sb128 {depth}-bit txs={txs} cq={cq}");
13733 let stream = screen_intrabc_stream_at_depth(
13734 "smptebars=size=128x96:rate=25",
13735 cq,
13736 txs,
13737 true,
13738 true,
13739 depth,
13740 &["--sb-size=128"],
13741 );
13742 let (sb128, intrabc_frames) = sb128_and_intrabc_frames(&stream);
13743 assert!(
13744 sb128 && intrabc_frames > 0,
13745 "{NAME}: {arm} no longer codes sb128 + allow_intrabc"
13746 );
13747 crate::decode::reset_intrabc_hits();
13748 let frames =
13749 decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {arm}: {e}"));
13750 let blocks = crate::decode::intrabc_hits();
13751 blocks_total += blocks;
13752 blocks_at_depth[usize::from(depth == 10)] += blocks;
13753 // The ENCODE's frame count:
13754 // `screen_intrabc_stream_at_depth` (12203) renders
13755 // `smptebars=size=128x96:rate=25` with `-t 0.2` and
13756 // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame
13757 // out at 256x192 -- and its aomenc runs with `--limit=1`
13758 // (12101), so all eight (depth, txs, cq) arms code exactly
13759 // 1 frame. Asserted ABOVE the oracle call.
13760 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
13761 let theirs = if depth == 10 {
13762 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
13763 } else {
13764 ffmpeg_decode_sequence(&stream, width, height, frames.len())
13765 };
13766 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
13767 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
13768 assert!(
13769 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
13770 "{NAME}: {arm} frame {i} does not match ffmpeg"
13771 );
13772 frames_compared += 1;
13773 }
13774 eprintln!(
13775 "{NAME}: {arm} intrabc_frames={intrabc_frames} intrabc_blocks={blocks} \
13776 DECODED {} frame(s) exact",
13777 frames.len()
13778 );
13779 }
13780 }
13781 }
13782 assert!(frames_compared > 0, "{NAME}: no frame was compared");
13783 assert!(
13784 blocks_total > 0,
13785 "{NAME}: gate is vacuous -- no arm decoded a single intrabc block"
13786 );
13787 assert!(
13788 blocks_at_depth[0] > 0 && blocks_at_depth[1] > 0,
13789 "{NAME}: 8-bit={} 10-bit={} -- an arm at that depth no longer decodes an intrabc \
13790 block, so `enable-intrabc` coverage there would rest on the flag spelling alone",
13791 blocks_at_depth[0],
13792 blocks_at_depth[1]
13793 );
13794 }
13795
13796 /// lane-av1-ibcrect: `use_intrabc` on a 128-root HORZ/VERT strip
13797 /// (BLOCK_128X64 / BLOCK_64X128) decodes PIXEL-EXACT against the
13798 /// instrumented oracle -- the witness the refusal inventory names after
13799 /// `decode_block_128rect`'s rect-strip intrabc refusal was lifted
13800 /// (`decode_intrabc_128rect`). The square-block twin is
13801 /// [`an_sb128_screen_stream_with_intrabc_decodes_pixel_exact`] above.
13802 ///
13803 /// The recipes are the hunt's proven arms (lanes/ibcrect r1/r2, the same
13804 /// `--sb-size=128 --min-partition-size=64 --enable-rect-partitions=1
13805 /// --enable-ab-partitions=0 --enable-1to4-partitions=0` partition recipe
13806 /// [`a_real_aomenc_sb128_intra_rect_block_decodes_pixel_exact`] uses, plus
13807 /// `--tune-content=screen --enable-intrabc=1` over the DETERMINISTIC geq
13808 /// sinusoid sources -- lavfi `gradients` ignores its seed and re-rolls
13809 /// every run, so a "flake" there was really this):
13810 ///
13811 /// * HORZ arm: 384x320 cq32, 5 all-key frames -- 14 unskipped 128x64
13812 /// intrabc blocks (`skip=false`, real residual reads);
13813 /// * VERT arm: 512x512 cq45, 5 all-key frames -- an unskipped 64x128
13814 /// intrabc block at mi(64,96).
13815 ///
13816 /// Both arms HARD-assert `intrabc_128rect_hits() > 0` and decode-order
13817 /// pixel-exactness of EVERY frame (hidden alt-refs included) against the
13818 /// oracle's own dump, so a stream that stopped engaging the shape fails
13819 /// the gate instead of passing vacuously (class `gate-blind-to-feature`).
13820 ///
13821 /// The 10-bit arm engages the shape. Hunt r2 and the witness re-run both
13822 /// measured `intrabc_128rect_hits` +15 on arm 3, so aomenc does take a
13823 /// 128-root HORZ/VERT strip at 10 bit under this recipe. There is no
13824 /// per-depth coverage gap to print. The gate's hard asserts already
13825 /// cover that arm.
13826 ///
13827 /// The chroma context this shape reads was the r2 defect: per-unit chroma
13828 /// entropy states were stamped inside the mu-chunk loop, then the
13829 /// end-of-block `record_split_luma_rect_mi` re-stamped BOTH planes over
13830 /// the whole 128x64 span with ONE composed state -- level = the SUM of
13831 /// both 64x64 chunks' units, dc = chunk-0's top-left (class
13832 /// `override-slot-on-one-arm`; the inter-128 path fixed the same class
13833 /// with its `mu_chroma_units` replay, decode.rs). The next block then
13834 /// read `txb_skip` off the smeared state.
13835 #[test]
13836 fn an_sb128_rect_strip_with_intrabc_decodes_pixel_exact() {
13837 const NAME: &str = "an_sb128_rect_strip_with_intrabc_decodes_pixel_exact";
13838 let _gate_lock = lock_gate_counters();
13839 if !have_ffmpeg() {
13840 eprintln!("SKIP {NAME}: no ffmpeg");
13841 return;
13842 }
13843 if !have_aomenc() {
13844 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
13845 return;
13846 }
13847 // (tag, width, height, cq, geq luma, 10-bit)
13848 // The geq sources are the hunt's GEO_SMOOTH / GEO_SMOOTH_512,
13849 // byte-identical across runs (see the sb128 intra-rect gate's note).
13850 let arms: [(u32, usize, usize, &str, &str, bool); 3] = [
13851 (
13852 1,
13853 384,
13854 320,
13855 "32",
13856 "128+90*sin((X+2*N)/37)+30*sin(Y/29)",
13857 false,
13858 ),
13859 (
13860 2,
13861 512,
13862 512,
13863 "45",
13864 "128+80*sin((X+3*N)/17)+50*sin(Y/29)+30*sin((X+Y)/13)",
13865 false,
13866 ),
13867 (
13868 3,
13869 384,
13870 320,
13871 "32",
13872 "128+90*sin((X+2*N)/37)+30*sin(Y/29)",
13873 true,
13874 ),
13875 ];
13876 let mut engaged_arms = 0u32;
13877 let mut vert_arms = 0u32;
13878 for (tag, width, height, cq, lum, ten_bit) in arms {
13879 let pix = if ten_bit { "yuv420p10le" } else { "yuv420p" };
13880 let y4m = Command::new("ffmpeg")
13881 .args([
13882 "-v",
13883 "error",
13884 "-f",
13885 "lavfi",
13886 "-i",
13887 &format!(
13888 "nullsrc=size={width}x{height}:rate=25,format=yuv420p,\
13889 geq=lum='{lum}':\
13890 cb='128+30*sin(X/23)':cr='128+30*sin((Y+N)/19)'"
13891 ),
13892 "-pix_fmt",
13893 pix,
13894 "-strict",
13895 "-1",
13896 "-t",
13897 "0.2",
13898 "-f",
13899 "yuv4mpegpipe",
13900 "-",
13901 ])
13902 .stdin(Stdio::null())
13903 .stdout(Stdio::piped())
13904 .stderr(Stdio::piped())
13905 .output()
13906 .expect("ffmpeg failed to run");
13907 assert!(
13908 y4m.status.success(),
13909 "{NAME}: ffmpeg fixture: {}",
13910 String::from_utf8_lossy(&y4m.stderr)
13911 );
13912 let cq_arg = format!("--cq-level={cq}");
13913 let mut args: Vec<&str> = vec![
13914 "--codec=av1",
13915 "--passes=1",
13916 "--end-usage=q",
13917 &cq_arg,
13918 "--cpu-used=0",
13919 "--threads=1",
13920 "--row-mt=0",
13921 "--lag-in-frames=0",
13922 "--kf-max-dist=1",
13923 "--limit=5",
13924 "--tile-columns=0",
13925 "--sb-size=128",
13926 "--min-partition-size=64",
13927 "--enable-rect-partitions=1",
13928 "--enable-ab-partitions=0",
13929 "--enable-1to4-partitions=0",
13930 "--enable-palette=0",
13931 "--tune-content=screen",
13932 "--enable-intrabc=1",
13933 "--deltaq-mode=0",
13934 "--enable-tx-size-search=0",
13935 ];
13936 if ten_bit {
13937 args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
13938 }
13939 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
13940 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
13941 assert!(
13942 out.status.success(),
13943 "{NAME}: aomenc refused the arm {tag} fixture: {}",
13944 String::from_utf8_lossy(&out.stderr)
13945 );
13946 let stream = out.stdout;
13947 let before = crate::decode::intrabc_128rect_hits();
13948 let (frames, hidden) = decode_all_frames_vs_oracle(
13949 &stream,
13950 &format!("ibcrect-strip-{tag}-{width}x{height}"),
13951 );
13952 let hits = crate::decode::intrabc_128rect_hits() - before;
13953 eprintln!(
13954 "{NAME}: arm {tag} {width}x{height} cq={cq} {}bit: {frames} decode-order frames \
13955 pixel-exact ({hidden} hidden), intrabc_128rect_hits=+{hits}",
13956 if ten_bit { 10 } else { 8 },
13957 );
13958 if hits > 0 {
13959 engaged_arms += 1;
13960 // The VERT arm is tag 2; its engagement is what proves the
13961 // 64x128 orientation, not just 128x64.
13962 if tag == 2 {
13963 vert_arms += 1;
13964 }
13965 }
13966 }
13967 assert!(
13968 engaged_arms > 0,
13969 "{NAME}: {engaged_arms} arm(s) decoded pixel-exact but NOT ONE decoded a 128-root \
13970 rect-strip intrabc block -- the shape this gate exists for was never engaged"
13971 );
13972 assert!(
13973 vert_arms > 0,
13974 "{NAME}: the VERT (64x128) orientation was never engaged -- only 128x64 HORZ strips \
13975 proved the lift"
13976 );
13977 }
13978 /// lane-av1intrapred r2, REGRESSION GATE for the two intrabc TX4-split
13979 /// chroma defects this lane fixed.
13980 ///
13981 /// An intrabc 8x8 leaf whose var-tx tree split to TX_4X4 must (a) arm
13982 /// `INTRABC_CHROMA_TX` from the co-located luma TU's coded type -- the
13983 /// chroma units then take that type's class-1 eob row, HORIZ scan and nz
13984 /// contexts (libaom `av1_get_tx_type`'s is_inter branch; intrabc is
13985 /// inter-classified) -- and (b) predict the chroma units from the FRAME
13986 /// COPY at the DV, not intra-from-UV-mode (intrabc's UV mode is DC, so a
13987 /// leaf that loses the override predicts flat DC where libaom copies a
13988 /// busy region).
13989 ///
13990 /// Pre-r2, decode_leaf8's TX4 arm did neither: R5's chroma U txb at
13991 /// mi (36,66) decoded `eob=11` off the 2D row where aomdec decoded
13992 /// `eob=13` off the class-1 row, and the first surviving pixel fork was
13993 /// U(184,4) of mi (2,92) (class `intrabc-chroma-tx-not-armed`, then
13994 /// `intrabc-chroma-predicts-intra`).
13995 ///
13996 /// The fixture is the report's R5 stream pinned into `fixtures/`
13997 /// (aomenc oracle, testsrc2 320x180 tiled 2x2 -> 640x360, sb64 maxp64
13998 /// square-only screen intrabc, cq20, 1 frame; 7173 bytes,
13999 /// sha256 bc699af4a6e7c1c5657f041e8cbdf2d3d899ddb80ec2a549a950b7cebb5b41bd).
14000 /// The gate needs no oracle at run time and cannot be skipped: a missing
14001 /// fixture, a decode error, a zero counter, a moved pixel patch or a
14002 /// changed full-frame fingerprint each fail by name. The fingerprint is
14003 /// FNV-1a (dependency-free, same rationale as the cdf-forwarding gate's).
14004 #[test]
14005 fn an_intrabc_tx4_leaf_chroma_inherits_the_luma_type_and_predicts_from_the_frame_copy() {
14006 const NAME: &str =
14007 "an_intrabc_tx4_leaf_chroma_inherits_the_luma_type_and_predicts_from_the_frame_copy";
14008 const FIXTURE_LEN: usize = 7173;
14009 const FIXTURE_FNV: u64 = 0x3a57_d075_5e4c_fe5b;
14010 const RAW_LEN: usize = 640 * 360 * 3 / 2;
14011 const RAW_FNV: u64 = 0xf271_df27_ce4d_ba66;
14012 // The 4x4 chroma patches at (184,4) -- the first surviving pixel fork
14013 // -- as the oracles (aomdec and ffmpeg agree) reconstruct them.
14014 const U_PATCH: [u16; 16] = [
14015 86, 116, 55, 110, 114, 114, 51, 83, 99, 121, 48, 114, 103, 117, 102, 67,
14016 ];
14017 const V_PATCH: [u16; 16] = [
14018 179, 158, 199, 105, 155, 158, 195, 147, 163, 153, 194, 108, 170, 148, 168, 172,
14019 ];
14020
14021 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14022 .join("fixtures/intrabc_tx4_chroma_kf.obu");
14023 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
14024 panic!(
14025 "{NAME}: pinned fixture {} is missing ({e}) -- the gate cannot run, \
14026 which is a failure, not a skip",
14027 obu.display()
14028 )
14029 });
14030 assert_eq!(stream.len(), FIXTURE_LEN, "{NAME}: fixture length moved");
14031 assert_eq!(fnv1a64(&stream), FIXTURE_FNV, "{NAME}: fixture bytes moved");
14032
14033 let _guard = lock_gate_counters();
14034 crate::decode::reset_leaf8_intrabc_hits();
14035 crate::decode::reset_intrabc_tx4_chroma_copy_hits();
14036 let frames = decode_stream(&stream)
14037 .unwrap_or_else(|e| panic!("{NAME}: the pinned stream no longer decodes cleanly: {e}"));
14038 assert_eq!(frames.len(), 1, "{NAME}: frame count");
14039 let frame = &frames[0];
14040 assert_eq!(
14041 (frame.width, frame.height),
14042 (640, 360),
14043 "{NAME}: dimensions"
14044 );
14045
14046 // Non-vacuity, both halves: the leaf shape must be reached at all,
14047 // and its chroma route must have consulted the ARMED slot (pre-r2
14048 // this counter is 0 -- the arm never armed the slot).
14049 assert!(
14050 crate::decode::leaf8_intrabc_hits() > 0,
14051 "{NAME}: gate is vacuous -- no intrabc 8x8 leaf was decoded"
14052 );
14053 assert!(
14054 crate::decode::intrabc_tx4_chroma_copy_hits() > 0,
14055 "{NAME}: gate is vacuous -- no intrabc TX4-split leaf's chroma read consulted \
14056 the armed slot (class intrabc-chroma-tx-not-armed)"
14057 );
14058
14059 // The first surviving pixel fork: chroma 4x4 at (184,4). The wrong
14060 // wirings put flat intra-DC predictions or the wrong eob class here.
14061 let cw = frame.width / 2;
14062 let u_patch: Vec<u16> = (0..4)
14063 .flat_map(|dy| (0..4).map(move |dx| frame.u[(4 + dy) * cw + 184 + dx]))
14064 .collect();
14065 let v_patch: Vec<u16> = (0..4)
14066 .flat_map(|dy| (0..4).map(move |dx| frame.v[(4 + dy) * cw + 184 + dx]))
14067 .collect();
14068 assert_eq!(u_patch, U_PATCH, "{NAME}: U(184,4) patch moved");
14069 assert_eq!(v_patch, V_PATCH, "{NAME}: V(184,4) patch moved");
14070 // The unit the FRAME-COPY override specifically pins: chroma 4x4 at
14071 // (168,0) is an intrabc TX4-split leaf's chroma whose copy source is
14072 // a busy ramp region; without the `palette_uv_bufs` intrabc wrap the
14073 // read predicts flat intra-DC here (78k chroma bytes drift from this
14074 // unit alone), with it the copy reproduces the oracle exactly.
14075 const U_COPY_PATCH: [u16; 16] = [
14076 91, 91, 91, 91, 120, 120, 120, 120, 120, 120, 120, 120, 73, 102, 116, 116,
14077 ];
14078 const V_COPY_PATCH: [u16; 16] = [
14079 241, 241, 241, 241, 156, 156, 156, 156, 158, 158, 158, 158, 181, 163, 154, 154,
14080 ];
14081 let u_copy: Vec<u16> = (0..4)
14082 .flat_map(|dy| (0..4).map(move |dx| frame.u[dy * cw + 168 + dx]))
14083 .collect();
14084 let v_copy: Vec<u16> = (0..4)
14085 .flat_map(|dy| (0..4).map(move |dx| frame.v[dy * cw + 168 + dx]))
14086 .collect();
14087 assert_eq!(
14088 u_copy, U_COPY_PATCH,
14089 "{NAME}: U(168,0) patch moved -- the intrabc TX4 chroma read no longer \
14090 predicts from the frame copy (class intrabc-chroma-predicts-intra)"
14091 );
14092 assert_eq!(v_copy, V_COPY_PATCH, "{NAME}: V(168,0) patch moved");
14093
14094 // The whole frame, packed as the rawvideo byte stream the oracles
14095 // produce: any remaining byte anywhere in Y/U/V fails the gate.
14096 let mut raw = Vec::with_capacity(RAW_LEN);
14097 for plane in [&frame.y, &frame.u, &frame.v] {
14098 raw.extend(plane.iter().map(|&s| s as u8));
14099 }
14100 assert_eq!(raw.len(), RAW_LEN, "{NAME}: raw size");
14101 assert_eq!(
14102 fnv1a64(&raw),
14103 RAW_FNV,
14104 "{NAME}: full-frame fingerprint moved"
14105 );
14106 }
14107
14108 /// lane-t900 r33, CENSUS for "a sub-8x8 leaf that uses intrabc".
14109 ///
14110 /// The `use_intrabc` symbol IS read at that reader for every sub-8x8 leaf
14111 /// of an `allow_intrabc` frame, so arrival is provable rather than
14112 /// assumed: the arms below force 4x4 leaves (`--min-partition-size=4`) on
14113 /// the exact-repetition screen content that keeps `allow_intrabc`, and the
14114 /// gate requires both counters -- `allow_intrabc` frames and decoded sub-8
14115 /// leaves -- to be non-zero before it reads anything into the refusal
14116 /// firing 0 times (class `gate-blind-to-feature`).
14117 #[test]
14118 fn a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal() {
14119 const NAME: &str =
14120 "a_sub8_leaf_census_over_intrabc_screen_streams_measures_the_sub8_refusal";
14121 if !have_ffmpeg() || !have_aomenc() {
14122 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
14123 return;
14124 }
14125 let (width, height) = (256usize, 192usize);
14126 let _guard = lock_gate_counters();
14127 let (mut premise_arms, mut reached, mut sub8_total, mut frames_compared) =
14128 (0u32, 0u32, 0usize, 0u32);
14129 for cq in ["30", "45"] {
14130 let arm = format!("sub8 cq={cq}");
14131 let stream = screen_intrabc_stream_with(
14132 "smptebars=size=128x96:rate=25",
14133 cq,
14134 "0",
14135 true,
14136 true,
14137 &["--min-partition-size=4"],
14138 );
14139 let (_, intrabc_frames) = sb128_and_intrabc_frames(&stream);
14140 if intrabc_frames > 0 {
14141 premise_arms += 1;
14142 }
14143 // No reset for this counter, so measure the delta (the gate lock
14144 // above keeps another gate's decode out of it).
14145 let sub8_before = crate::decode::sub8_split_hits();
14146 match decode_stream(&stream) {
14147 Ok(frames) => {
14148 let sub8 = crate::decode::sub8_split_hits() - sub8_before;
14149 sub8_total += sub8;
14150 // The ENCODE's frame count: `screen_intrabc_stream_with` (12593)
14151 // renders `smptebars=size=128x96:rate=25` with `-t 0.2` and
14152 // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame
14153 // out -- and its aomenc runs with `--limit=1` (12101), so both
14154 // cq arms code exactly 1 frame. The census is report-only about
14155 // the COUNTS, but its Ok arm asserts pixel-exactness, so the
14156 // budget handed to ffmpeg is pinned here rather than derived
14157 // from the decode under test.
14158 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
14159 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
14160 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
14161 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
14162 assert!(
14163 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
14164 "{NAME}: {arm} frame {i} does not match ffmpeg"
14165 );
14166 frames_compared += 1;
14167 }
14168 eprintln!(
14169 "{NAME}: {arm} intrabc_frames={intrabc_frames} sub8_leaves={sub8} \
14170 DECODED {} frame(s) exact",
14171 frames.len()
14172 );
14173 }
14174 Err(e) => {
14175 let msg = e.to_string();
14176 assert!(
14177 msg.contains("unsupported"),
14178 "{NAME}: {arm} decode failed: {e}"
14179 );
14180 if msg.contains("a sub-8x8 leaf that uses intrabc") {
14181 reached += 1;
14182 }
14183 sub8_total += crate::decode::sub8_split_hits() - sub8_before;
14184 eprintln!("{NAME}: {arm} intrabc_frames={intrabc_frames} REFUSED: {e}");
14185 }
14186 }
14187 }
14188 eprintln!(
14189 "{NAME}: {premise_arms}/2 arm(s) keep allow_intrabc, {sub8_total} sub-8 leaf/leaves \
14190 decoded, {reached} reach the refusal, {frames_compared} frame(s) exact"
14191 );
14192 assert!(
14193 premise_arms > 0,
14194 "{NAME}: census is vacuous -- no arm kept allow_intrabc, so the refusal's own \
14195 premise was never within reach"
14196 );
14197 assert!(
14198 sub8_total > 0,
14199 "{NAME}: census is vacuous -- no sub-8 leaf was decoded at all, so the \
14200 `use_intrabc` symbol this refusal guards was never read"
14201 );
14202 }
14203
14204 /// lane-t900 r33, CENSUS for "an intrabc block whose var-tx tree resolved
14205 /// to mixed leaf transform sizes" -- the residue lane-t900 r32 left when
14206 /// it lifted the intrabc `TX_MODE_SELECT` refusal.
14207 ///
14208 /// The tree is read in full; lane-av1-ibcvtx taught the luma reconstruct
14209 /// to walk the tree's own leaf list, so mixed trees now decode. This
14210 /// census sweeps the quantiser across the exact-repetition recipe that
14211 /// reaches the tree at all and requires the tree to actually be read
14212 /// (`intrabc_vartx_hits`); it stays as the premise witness for the lifted
14213 /// refusal (`reached` is 0 by construction now).
14214 #[test]
14215 fn an_intrabc_vartx_census_measures_the_mixed_leaf_refusal() {
14216 const NAME: &str = "an_intrabc_vartx_census_measures_the_mixed_leaf_refusal";
14217 if !have_ffmpeg() || !have_aomenc() {
14218 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
14219 return;
14220 }
14221 let (width, height) = (256usize, 192usize);
14222 let _guard = lock_gate_counters();
14223 let (mut vartx_total, mut reached, mut frames_compared) = (0usize, 0u32, 0u32);
14224 for cq in ["20", "30", "45", "55"] {
14225 let arm = format!("vartx cq={cq}");
14226 let stream =
14227 screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
14228 let (select, premise) = tx_select_and_intrabc_frames(&stream);
14229 crate::decode::reset_intrabc_vartx_hits();
14230 match decode_stream(&stream) {
14231 Ok(frames) => {
14232 let vartx = crate::decode::intrabc_vartx_hits();
14233 vartx_total += vartx;
14234 // The ENCODE's frame count: `screen_intrabc_stream` (12679)
14235 // renders `smptebars=size=128x96:rate=25` with `-t 0.2` and
14236 // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame
14237 // out -- and its aomenc runs with `--limit=1` (12101), so all
14238 // four cq arms code exactly 1 frame. The census is
14239 // report-only about the COUNTS, but its Ok arm does assert
14240 // pixel-exactness, so the budget it hands ffmpeg is pinned
14241 // here rather than derived from the decode under test.
14242 assert_eq!(frames.len(), 1, "{NAME}: {arm} key frame");
14243 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
14244 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
14245 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
14246 assert!(
14247 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
14248 "{NAME}: {arm} frame {i} does not match ffmpeg"
14249 );
14250 frames_compared += 1;
14251 }
14252 eprintln!(
14253 "{NAME}: {arm} select={select} premise={premise} vartx_blocks={vartx} \
14254 DECODED {} frame(s) exact",
14255 frames.len()
14256 );
14257 }
14258 Err(e) => {
14259 let msg = e.to_string();
14260 assert!(
14261 msg.contains("unsupported"),
14262 "{NAME}: {arm} decode failed: {e}"
14263 );
14264 vartx_total += crate::decode::intrabc_vartx_hits();
14265 if msg.contains("mixed leaf transform sizes") {
14266 reached += 1;
14267 }
14268 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
14269 }
14270 }
14271 }
14272 eprintln!(
14273 "{NAME}: {vartx_total} intrabc block(s) read the var-tx tree, {reached} resolved to \
14274 mixed leaves, {frames_compared} frame(s) exact"
14275 );
14276 assert!(
14277 vartx_total > 0,
14278 "{NAME}: census is vacuous -- no intrabc block read the var-tx tree at all"
14279 );
14280 assert_eq!(
14281 reached, 0,
14282 "{NAME}: an intrabc var-tx tree was REFUSED -- the mixed-leaf refusal \
14283 is lifted (lane-av1-ibcvtx) and must stay gone"
14284 );
14285 }
14286
14287 /// lane-av1-ibcvtx, capability gate for the LIFTED refusal "an intrabc
14288 /// block whose var-tx tree resolved to mixed leaf transform sizes": the
14289 /// t900 r33 census recipe class (screen content, square partitions,
14290 /// tx-size search) reaches mixed trees the moment the canvas carries
14291 /// testsrc2's texture and blocks grow past 32 -- on the PRE-fix tree this
14292 /// exact stream refused by name on its first mixed tree (5 of the 12
14293 /// hunt recipes hit it, `lanes/av1ibcvtx.report.md`).
14294 ///
14295 /// The luma reconstruct walks the tree's own leaf list per leaf (libaom
14296 /// `decode_token_recon_block`), and the block's chroma inherits the
14297 /// co-located luma unit's coded tx type (`av1_get_tx_type`,
14298 /// `blockd.h:1278`) -- the inheritance the uniform multi-TU intrabc path
14299 /// was missing as well: symbol-aligned against an instrumented aomdec,
14300 /// the 640x360 cq20 witness desynced inside the FIRST chroma unit of its
14301 /// first mixed tree until the arm landed, then matched every subsequent
14302 /// read.
14303 ///
14304 /// NOT yet asserted: full pixel-exactness against ffmpeg. A second,
14305 /// PRE-EXISTING defect that is not this refusal -- a NON-intrabc intra
14306 /// block (R5 witness: mi (32,32), 64x64, uniform 4x TX_32X32 tree, every
14307 /// coefficient all_zero, reads symbol-identical to aomdec) mispredicts
14308 /// isolated samples on testsrc2 content (first divergence px (128,296)
14309 /// of the 640x360 cq20 recipe) and cascades over roughly a third of the
14310 /// frame. It is pinned in `lanes/av1ibcvtx.report.md`; when it lands,
14311 /// tighten this gate to a full pixel-exact assert.
14312 #[test]
14313 fn a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal() {
14314 const NAME: &str =
14315 "a_real_aomenc_intrabc_mixed_vartx_tree_decodes_without_the_mixed_leaf_refusal";
14316 if !have_ffmpeg() || !have_aomenc() {
14317 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
14318 return;
14319 }
14320 let (width, height) = (640usize, 360usize);
14321 let _guard = lock_gate_counters();
14322 let stream = screen_intrabc_stream_with(
14323 "testsrc2=size=320x180:rate=25",
14324 "30",
14325 "1",
14326 true,
14327 true,
14328 &["--max-partition-size=64"],
14329 );
14330 let (select, premise) = tx_select_and_intrabc_frames(&stream);
14331 assert!(
14332 premise > 0,
14333 "{NAME}: vacuous -- no frame keeps allow_intrabc under TxMode::Select, \
14334 so the refusal's premise was never within reach (select={select})"
14335 );
14336 crate::decode::reset_intrabc_vartx_hits();
14337 crate::decode::reset_intrabc_vartx_mixed_leaves_hits();
14338 match decode_stream(&stream) {
14339 Ok(frames) => {
14340 let trees = crate::decode::intrabc_vartx_hits();
14341 let mixed = crate::decode::intrabc_vartx_mixed_leaves_hits();
14342 assert!(
14343 trees > 0 && mixed > 0,
14344 "{NAME}: vacuous -- {trees} var-tx tree(s), {mixed} mixed: the \
14345 capability this gate pins was never exercised"
14346 );
14347 // The ENCODE's frame count: `screen_intrabc_stream_with` (12766)
14348 // renders `testsrc2=size=320x180:rate=25` with `-t 0.2` and
14349 // `-vf tile=2x2` (12066, 12069) -- 5 frames in, 1 tiled frame out
14350 // at 640x360 -- and its aomenc runs with `--limit=1` (12101), so
14351 // the stream codes exactly 1 frame. Asserted ABOVE the call.
14352 assert_eq!(frames.len(), 1, "{NAME}: key frame");
14353 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
14354 assert_eq!(frames.len(), theirs.len(), "{NAME}: frame count");
14355 let mut mismatched = 0usize;
14356 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
14357 // A size mismatch makes every number this ladder prints
14358 // meaningless -- the `zip` walks below would truncate to the
14359 // shorter plane and report a clean ladder over what is
14360 // really a plane-shape defect -- so it is LOUD. A PIXEL
14361 // mismatch stays report-only: this gate deliberately
14362 // tolerates the pinned second defect (see the doc comment).
14363 for (plane, a, b) in [
14364 ("Y", &ours.y, &ref_frame.y),
14365 ("U", &ours.u, &ref_frame.u),
14366 ("V", &ours.v, &ref_frame.v),
14367 ] {
14368 assert_eq!(
14369 a.len(),
14370 b.len(),
14371 "{NAME}: frame {i} plane {plane}: ours has {} samples, ffmpeg's has \
14372 {} -- a size mismatch makes this whole diagnostic ladder \
14373 meaningless, so it is loud while a pixel mismatch stays \
14374 report-only",
14375 a.len(),
14376 b.len()
14377 );
14378 }
14379 mismatched += ours
14380 .y
14381 .iter()
14382 .zip(ref_frame.y.iter())
14383 .filter(|(x, y)| x != y)
14384 .count();
14385 mismatched += ours
14386 .u
14387 .iter()
14388 .zip(ref_frame.u.iter())
14389 .filter(|(x, y)| x != y)
14390 .count();
14391 mismatched += ours
14392 .v
14393 .iter()
14394 .zip(ref_frame.v.iter())
14395 .filter(|(x, y)| x != y)
14396 .count();
14397 }
14398 eprintln!(
14399 "{NAME}: select={select} premise={premise} vartx_blocks={trees} \
14400 mixed_trees={mixed}, {mismatched} sample(s) differ from ffmpeg \
14401 (the pinned non-intrabc second defect, see the doc comment)"
14402 );
14403 }
14404 Err(e) => panic!(
14405 "{NAME}: the mixed-leaf refusal is lifted (lane-av1-ibcvtx); the \
14406 witness stream must decode, not stop: {e}"
14407 ),
14408 }
14409 }
14410
14411 /// How many frames of `stream` carry `tx_mode == Select`, and how many of
14412 /// those also keep `allow_intrabc` -- the frame-level premise of the
14413 /// refusal "an intrabc block under TxMode::Select", read out of the
14414 /// headers rather than assumed from the flags handed to the encoder
14415 /// (libaom clears `allow_intrabc` again when no block picked it,
14416 /// encodeframe.c:2336).
14417 fn tx_select_and_intrabc_frames(stream: &[u8]) -> (u32, u32) {
14418 let (mut select, mut premise) = (0u32, 0u32);
14419 let mut p = Av1Parser::new();
14420 let mut pos = 0usize;
14421 while pos < stream.len() {
14422 let obu = p.parse_obu(&stream[pos..]).expect("parse");
14423 pos += obu.total_size;
14424 let header = match &obu.kind {
14425 ObuKind::Frame(h, _) => Some(&**h),
14426 ObuKind::FrameHeader(h) => Some(&**h),
14427 _ => None,
14428 };
14429 if let Some(h) = header {
14430 if h.tx_mode == TxMode::Select {
14431 select += 1;
14432 if h.allow_intrabc {
14433 premise += 1;
14434 }
14435 }
14436 }
14437 }
14438 (select, premise)
14439 }
14440
14441 /// lane-t900 r31, CENSUS for the refusal "an intrabc block under
14442 /// TxMode::Select" -- which this gate DISPROVES as an "no encoder writes
14443 /// one" claim and pins as a real capability gap instead.
14444 ///
14445 /// The premise is reachable by the SPEC: `tx_mode` (5.9.21) is forced to
14446 /// `ONLY_4X4` only under `CodedLossless`, while `allow_intrabc` (5.9.2)
14447 /// needs `allow_screen_content_tools` at unscaled resolution -- two
14448 /// independent conditions. libaom leaves it open too: `select_tx_mode`
14449 /// (encodeframe.c:2355) never consults `allow_intrabc`, and the only
14450 /// downgrade to `TX_MODE_LARGEST` is `txb_split_count == 0`
14451 /// (encodeframe.c:2690).
14452 ///
14453 /// The measurement over 14 real `--tune-content=screen --enable-intrabc=1`
14454 /// recipes:
14455 ///
14456 /// * the 10 non-repeating arms never present the premise at all -- with
14457 /// `--enable-tx-size-search=1` the frame codes `TX_MODE_SELECT` but RD
14458 /// never picks intrabc, so libaom clears `allow_intrabc` again; with
14459 /// `=0` intrabc IS used and the frame is `TX_MODE_LARGEST`. That
14460 /// correlation, not any rule, is why earlier rounds never saw this;
14461 /// * the four EXACT-REPETITION arms (a 2x2 tiling of one 128x96 bar
14462 /// pattern) all code `allow_intrabc && tx_mode == Select`. Two of them
14463 /// stop on the older rect-strip intrabc refusal (the shape that fires
14464 /// first, class `refusal-hides-a-defect`), and the two with rect/1:4
14465 /// partitions off put intrabc on a SQUARE block: `cq=30` reaches THIS
14466 /// refusal by name, `cq=45`'s intrabc blocks are all `skip` and decode
14467 /// pixel-exact against ffmpeg.
14468 ///
14469 /// So the refusal is correct and load-bearing, exactly one arm reaches it,
14470 /// and the lift it names has a waiting witness:
14471 /// [`an_intrabc_block_under_tx_mode_select_decodes_pixel_exact`] (ignored
14472 /// until the intra path reads the inter var-tx tree for an intrabc block).
14473 #[test]
14474 fn an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal() {
14475 const NAME: &str =
14476 "an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal";
14477 if !have_ffmpeg() {
14478 eprintln!("SKIP {NAME}: no ffmpeg");
14479 return;
14480 }
14481 if !have_aomenc() {
14482 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14483 return;
14484 }
14485 const TS: &str = "testsrc2=s=256x192:r=25";
14486 const SB: &str = "smptebars=size=256x192:rate=25";
14487 const PB: &str = "pal75bars=size=256x192:rate=25";
14488 const TILE: &str = "smptebars=size=128x96:rate=25";
14489 let (width, height) = (256usize, 192usize);
14490 // (arm, source, cq, tx-size-search, tiled, square_only)
14491 let arms: [(&str, &str, &str, &str, bool, bool); 14] = [
14492 ("smptebars-cq40-txs1", SB, "40", "1", false, false),
14493 ("smptebars-cq45-txs1", SB, "45", "1", false, false),
14494 ("smptebars-cq55-txs1", SB, "55", "1", false, false),
14495 ("smptebars-cq63-txs1", SB, "63", "1", false, false),
14496 ("pal75bars-cq40-txs1", PB, "40", "1", false, false),
14497 ("pal75bars-cq55-txs1", PB, "55", "1", false, false),
14498 ("testsrc2-cq50-txs1", TS, "50", "1", false, false),
14499 ("testsrc2-cq63-txs1", TS, "63", "1", false, false),
14500 ("smptebars-cq45-txs0", SB, "45", "0", false, false),
14501 ("pal75bars-cq45-txs0", PB, "45", "0", false, false),
14502 ("tiled-cq30-txs1", TILE, "30", "1", true, false),
14503 ("tiled-cq45-txs1", TILE, "45", "1", true, false),
14504 ("tiled-square-cq30-txs1", TILE, "30", "1", true, true),
14505 // lane-t900 r32: both square arms are now ORDINARY census members
14506 // -- cq30 (unskipped intrabc, the inter var-tx tree) and cq45
14507 // (all-skip intrabc, `maxRectTxSize` with no symbol at all) decode
14508 // pixel-exact, so nothing here reaches the lifted refusal.
14509 ("tiled-square-cq45-txs1", TILE, "45", "1", true, true),
14510 ];
14511 let (mut select_arms, mut premise_arms, mut intrabc_arms, mut blocks_total) =
14512 (0u32, 0u32, 0u32, 0usize);
14513 let (mut refused_tx_select, mut frames_compared) = (0u32, 0usize);
14514 for (arm, src, cq, txs, tiled, square_only) in &arms {
14515 let stream = screen_intrabc_stream(src, cq, txs, *tiled, *square_only);
14516 let (select, premise) = tx_select_and_intrabc_frames(&stream);
14517 if select > 0 {
14518 select_arms += 1;
14519 }
14520 if premise > 0 {
14521 premise_arms += 1;
14522 }
14523 crate::decode::reset_intrabc_hits();
14524 let decoded = decode_stream(&stream);
14525 let blocks = crate::decode::intrabc_hits();
14526 blocks_total += blocks;
14527 if blocks > 0 {
14528 intrabc_arms += 1;
14529 }
14530 match decoded {
14531 Ok(frames) => {
14532 assert!(!frames.is_empty(), "{NAME}: {arm} decoded no frame");
14533 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
14534 assert_eq!(frames.len(), theirs.len(), "{NAME}: {arm} frame count");
14535 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
14536 assert!(
14537 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
14538 "{NAME}: {arm} frame {i} does not match ffmpeg"
14539 );
14540 frames_compared += 1;
14541 }
14542 eprintln!(
14543 "{NAME}: {arm} select={select} premise={premise} {blocks} intrabc \
14544 block(s), {} frame(s) exact",
14545 frames.len()
14546 );
14547 }
14548 Err(e) => {
14549 let msg = e.to_string();
14550 assert!(
14551 msg.contains("unsupported"),
14552 "{NAME}: {arm} decode failed: {e}"
14553 );
14554 if msg.contains("an intrabc block under TxMode::Select") {
14555 refused_tx_select += 1;
14556 assert!(
14557 premise > 0,
14558 "{NAME}: {arm} reached the TxMode::Select intrabc refusal in a \
14559 frame that codes no such header"
14560 );
14561 } else {
14562 assert!(
14563 msg.contains("intra block copy"),
14564 "{NAME}: {arm} refused for an unrelated reason: {e}"
14565 );
14566 }
14567 eprintln!("{NAME}: {arm} select={select} premise={premise} REFUSED: {e}");
14568 }
14569 }
14570 }
14571 eprintln!(
14572 "{NAME}: {select_arms}/{n} arm(s) code a TX_MODE_SELECT frame, {premise_arms} of \
14573 those keep allow_intrabc, {intrabc_arms} arm(s) decode an intrabc block \
14574 ({blocks_total} total), {refused_tx_select} reach the refusal, \
14575 {frames_compared} frame(s) compared exact",
14576 n = arms.len()
14577 );
14578 assert!(
14579 intrabc_arms > 0 && blocks_total > 0,
14580 "{NAME}: census is vacuous -- no arm decoded an intrabc block at all"
14581 );
14582 assert!(
14583 premise_arms > 0,
14584 "{NAME}: census is vacuous -- no arm coded a frame with both allow_intrabc and \
14585 tx_mode == Select, so the refusal's own premise was never within reach"
14586 );
14587 assert_eq!(
14588 refused_tx_select, 0,
14589 "{NAME}: lane-t900 r32 lifted this refusal -- an intrabc block now reads the \
14590 INTER tx-size syntax, so no arm may reach it again"
14591 );
14592 assert!(
14593 frames_compared > 0,
14594 "{NAME}: no frame was compared pixel-exact"
14595 );
14596 }
14597
14598 /// lane-t900 r31, the WAITING witness for the capability
14599 /// [`an_intrabc_census_over_screen_key_frames_measures_the_tx_select_refusal`]
14600 /// pins: a real aomenc screen key frame whose intrabc block sits on a
14601 /// square block of a `TX_MODE_SELECT` frame, unskipped. libaom's
14602 /// `parse_decode_block` treats an intrabc block as `inter_block_tx`, so
14603 /// its transform size comes off the inter var-tx partition tree
14604 /// (`read_var_tx_size`), which this decoder reads nowhere on the intra
14605 /// path -- reading the intra `tx_depth` symbol instead desyncs.
14606 ///
14607 /// lane-t900 r32 closed both arms. A SKIPPED intrabc block reads no
14608 /// tx-size symbol at all (`allowSelect = !skip || !is_inter`, false for an
14609 /// intrabc block since libaom's `is_inter_block` counts one); reading the
14610 /// intra `tx_depth` for it consumed a symbol libaom never wrote and
14611 /// desynced the tile a whole block later, at the superblock corner
14612 /// (192,64) (class `equal-range-means-unread`). An UNSKIPPED one reads the
14613 /// inter var-tx tree (`read_var_tx_size`). r31's note that cq=45's blocks
14614 /// are all `skip` was read off that desynced decode: with the tx-size read
14615 /// corrected, cq=45 carries 3 unskipped intrabc blocks of 10 and cq=30
14616 /// carries 1 of 16, so both arms exercise both sides of the split.
14617 #[test]
14618 fn an_intrabc_block_under_tx_mode_select_decodes_pixel_exact() {
14619 const NAME: &str = "an_intrabc_block_under_tx_mode_select_decodes_pixel_exact";
14620 if !have_ffmpeg() || !have_aomenc() {
14621 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
14622 return;
14623 }
14624 let (width, height) = (256usize, 192usize);
14625 for cq in ["30", "45"] {
14626 let stream =
14627 screen_intrabc_stream("smptebars=size=128x96:rate=25", cq, "1", true, true);
14628 let (select, premise) = tx_select_and_intrabc_frames(&stream);
14629 assert!(
14630 select > 0 && premise > 0,
14631 "{NAME}: cq={cq} no longer codes allow_intrabc under TX_MODE_SELECT \
14632 (select={select} premise={premise})"
14633 );
14634 crate::decode::reset_intrabc_hits();
14635 crate::decode::reset_intrabc_vartx_hits();
14636 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: cq={cq}: {e}"));
14637 let (blocks, vartx) = (
14638 crate::decode::intrabc_hits(),
14639 crate::decode::intrabc_vartx_hits(),
14640 );
14641 assert!(
14642 blocks > 0,
14643 "{NAME}: cq={cq} no longer decodes an intrabc block"
14644 );
14645 // r31 recorded cq=45's intrabc blocks as ALL skip; that was read
14646 // off the desynced decode. With the tx-size read corrected both
14647 // arms carry unskipped ones (cq30 1 of 16, cq45 3 of 10), so both
14648 // must reach the var-tx tree or the gate is blind to the lift
14649 // (class `gate-blind-to-feature`).
14650 assert!(
14651 vartx > 0,
14652 "{NAME}: cq={cq} no longer reads the inter var-tx tree for an intrabc block"
14653 );
14654 eprintln!("{NAME}: cq={cq} {blocks} intrabc block(s), {vartx} through var-tx");
14655 // The ENCODE's frame count: `screen_intrabc_stream` (12022) renders
14656 // `smptebars=size=128x96:rate=25` with `-t 0.2` and `-vf tile=2x2`
14657 // (12066, 12069) -- 5 frames in, 1 tiled frame out -- and its aomenc
14658 // runs with `--limit=1` (12101), so both cq arms code exactly 1
14659 // frame. Asserted ABOVE the oracle call.
14660 assert_eq!(frames.len(), 1, "{NAME}: cq={cq} key frame");
14661 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
14662 assert_eq!(frames.len(), theirs.len(), "{NAME}: cq={cq} frame count");
14663 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
14664 assert!(
14665 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
14666 "{NAME}: cq={cq} frame {i} does not match ffmpeg"
14667 );
14668 }
14669 }
14670 }
14671
14672 /// lane-av1txr: a real `aomenc --cdf-update-mode=0` stream (spec 5.9.2
14673 /// `disable_cdf_update`) decodes SAMPLE-EXACT. The read that was missing:
14674 /// `stream.rs` never threaded the header bit, so the tile readers adapted
14675 /// every symbol of a frame the encoder coded against fixed tables -- the
14676 /// stream desynced at its first multi-symbol block and the pixels differed
14677 /// from byte 6 (`EC_PROBE_OUT` vs `ffmpeg -pix_fmt yuv420p`, measured
14678 /// 2026-09-20). The msac unit gate
14679 /// (`a_reader_told_not_to_adapt_matches_a_non_adapting_writer`) pins the
14680 /// mechanism; this one pins the wiring end to end.
14681 #[test]
14682 fn a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact() {
14683 const NAME: &str = "a_real_aomenc_stream_with_cdf_update_disabled_decodes_pixel_exact";
14684 if !have_ffmpeg() || !have_aomenc() {
14685 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
14686 return;
14687 }
14688 let (width, height) = (256usize, 192usize);
14689 let stream = screen_intrabc_stream_with(
14690 "testsrc2=size=256x192:rate=25",
14691 "45",
14692 "1",
14693 false,
14694 true,
14695 &["--cdf-update-mode=0", "--limit=3"],
14696 );
14697 // Non-vacuity: the fixture must really code the bit on every frame.
14698 let mut parser = Av1Parser::new();
14699 let mut pos = 0usize;
14700 let mut headers = 0usize;
14701 while pos < stream.len() {
14702 let Ok(obu) = parser.parse_obu(&stream[pos..]) else {
14703 break;
14704 };
14705 pos += obu.total_size.max(1);
14706 let header = match &obu.kind {
14707 ObuKind::Frame(h, _) | ObuKind::FrameHeader(h) => h,
14708 _ => continue,
14709 };
14710 assert!(
14711 header.disable_cdf_update,
14712 "{NAME}: frame {headers} does not carry disable_cdf_update -- aomenc ignored \
14713 --cdf-update-mode=0"
14714 );
14715 headers += 1;
14716 }
14717 assert!(
14718 headers >= 3,
14719 "{NAME}: only {headers} frame headers in the fixture"
14720 );
14721 let frames = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: {e}"));
14722 // The frame count, and it comes from the WIRE, not from our decode: the
14723 // loop above parsed this stream's own OBU frame headers with
14724 // `Av1Parser` and counted `headers` of them (>= 3, from the arm's
14725 // `--limit=3` at 13127, which overrides the helper's `--limit=1` because
14726 // aomenc keeps the last occurrence of a repeated flag). Asserted ABOVE
14727 // the oracle call, so a decode that showed fewer frames than the bitstream
14728 // codes reds naming the wire instead of asking ffmpeg for the same short
14729 // count. Deriving it from `headers` rather than a literal keeps the pin
14730 // honest if aomenc's frame count ever drifts.
14731 assert_eq!(
14732 frames.len(),
14733 headers,
14734 "{NAME}: the stream codes {headers} frame(s), the decode showed {}",
14735 frames.len()
14736 );
14737 let theirs = ffmpeg_decode_sequence(&stream, width, height, frames.len());
14738 assert_eq!(frames.len(), theirs.len(), "{NAME}: frame count");
14739 for (i, (ours, ref_frame)) in frames.iter().zip(theirs.iter()).enumerate() {
14740 assert!(
14741 ours.y == ref_frame.y && ours.u == ref_frame.u && ours.v == ref_frame.v,
14742 "{NAME}: frame {i} does not match ffmpeg"
14743 );
14744 }
14745 eprintln!("{NAME}: {headers} disable_cdf_update frame headers, all frames sample-exact");
14746 }
14747
14748 /// lane-kf900 r4, the gate for the two lifted palette refusals ("a 1:4
14749 /// rect strip that actually uses a palette (reconstruction is not ported
14750 /// at this shape)" and "a palette block on a HORZ/VERT intra strip below
14751 /// 16x16 (reconstruction not ported)"): real `aomenc` streams that put a
14752 /// palette on a RECT strip, decoded whole-frame pixel-exact against
14753 /// ffmpeg's own decode of the identical bytes, at 8 AND 10 bit.
14754 ///
14755 /// Arm 0 is the stream lane-kf900 r3 pinned and stopped on -- `testsrc2`
14756 /// 256x192, `--cq-level=59 --cpu-used=0 --min-partition-size=8
14757 /// --enable-rect-partitions=1 --enable-tx-size-search=1`, md5
14758 /// `e5f033d8fe34e4418d8cca3ac9d2b595` at 10 bit. Arms 1-2 force the shape
14759 /// on screen-like content with `--tune-content=screen --enable-palette=1
14760 /// --enable-1to4-partitions=1`.
14761 ///
14762 /// An attempt whose decode never hit a rect-strip palette block proves
14763 /// nothing about the lift, so it is counted OUT OF SCOPE rather than
14764 /// silently passing -- but a mismatch on one is still a failure
14765 /// (`out_of_scope_mismatch == 0`), and at least one attempt must fire the
14766 /// counter or the gate is vacuous.
14767 #[test]
14768 fn a_real_aomenc_rect_strip_palette_decodes_pixel_exact() {
14769 const NAME: &str = "a_real_aomenc_rect_strip_palette_decodes_pixel_exact";
14770 if !have_ffmpeg() {
14771 eprintln!("SKIP {NAME}: no ffmpeg");
14772 return;
14773 }
14774 if !have_aomenc() {
14775 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14776 return;
14777 }
14778 let (width, height) = (256usize, 192usize);
14779 let screen: &[&str] = &[
14780 "--tune-content=screen",
14781 "--enable-palette=1",
14782 "--enable-1to4-partitions=1",
14783 "--min-partition-size=8",
14784 ];
14785 // lane-kf900 r6: arms 3-4 are the palette + `--enable-tx-size-search=1`
14786 // shape whose neighbour palette lookup was SUB-granular -- a 16x8 strip
14787 // pair shares one 16px cell, so strip 1 read strip 0's palette size and
14788 // the colour cache came out short. Both were whole-frame wrong before
14789 // the mi-granular fix (`$HOME/.cache/kf900-r6/sweep.log`: smptebars
14790 // cq40/cq55 txs=1 pal=1 = DIFF).
14791 let screen_txs: &[&str] = &[
14792 "--tune-content=screen",
14793 "--enable-palette=1",
14794 "--enable-1to4-partitions=1",
14795 "--min-partition-size=8",
14796 "--max-partition-size=32",
14797 "--sb-size=64",
14798 "--enable-intrabc=1",
14799 "--enable-tx-size-search=1",
14800 ];
14801 let cq40: Vec<&str> = screen_txs
14802 .iter()
14803 .copied()
14804 .chain(["--cq-level=40"])
14805 .collect();
14806 let cq55: Vec<&str> = screen_txs
14807 .iter()
14808 .copied()
14809 .chain(["--cq-level=55"])
14810 .collect();
14811 let arms: [(&str, String, &[&str]); 5] = [
14812 (
14813 "testsrc2-pinned",
14814 "testsrc2=s=256x192:r=25".to_string(),
14815 &[],
14816 ),
14817 (
14818 "testsrc2-screen",
14819 "testsrc2=s=256x192:r=25".to_string(),
14820 screen,
14821 ),
14822 (
14823 "smptebars-screen",
14824 "smptebars=size=256x192:rate=25".to_string(),
14825 screen,
14826 ),
14827 (
14828 "smptebars-screen-txs-cq40",
14829 "smptebars=size=256x192:rate=25".to_string(),
14830 &cq40,
14831 ),
14832 (
14833 "smptebars-screen-txs-cq55",
14834 "smptebars=size=256x192:rate=25".to_string(),
14835 &cq55,
14836 ),
14837 ];
14838 let (mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32, 0u32);
14839 let mut refused = 0u32;
14840 let mut fired_at_depth = [0u32; 2];
14841 let mut frames_compared = 0usize;
14842 for (arm, src, extra) in &arms {
14843 for depth in [8usize, 10] {
14844 let pix_fmt = if depth == 10 {
14845 "yuv420p10le"
14846 } else {
14847 "yuv420p"
14848 };
14849 let render = || {
14850 let out = Command::new("ffmpeg")
14851 .args([
14852 "-v",
14853 "error",
14854 "-f",
14855 "lavfi",
14856 "-i",
14857 src.as_str(),
14858 "-t",
14859 "0.2",
14860 "-pix_fmt",
14861 pix_fmt,
14862 "-strict",
14863 "-1",
14864 "-f",
14865 "yuv4mpegpipe",
14866 "-",
14867 ])
14868 .stdin(Stdio::null())
14869 .stdout(Stdio::piped())
14870 .stderr(Stdio::piped())
14871 .output()
14872 .expect("ffmpeg failed to run");
14873 assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}");
14874 out.stdout
14875 };
14876 let y4m_a = render();
14877 let y4m_b = render();
14878 assert_eq!(
14879 y4m_a, y4m_b,
14880 "{NAME}: {arm} must render byte-identical across two runs at {depth}-bit"
14881 );
14882 let y4m = y4m_a;
14883 let depth_arg = format!("--bit-depth={depth}");
14884 let in_depth_arg = format!("--input-bit-depth={depth}");
14885 let out = run_with_stdin(
14886 Command::new(aomenc_path())
14887 .args(["--codec=av1"])
14888 .args([&depth_arg, &in_depth_arg])
14889 .args([
14890 "--passes=1",
14891 "--end-usage=q",
14892 "--cq-level=59",
14893 "--cpu-used=0",
14894 "--lag-in-frames=0",
14895 "--kf-max-dist=1",
14896 "--limit=1",
14897 "--threads=1",
14898 "--tile-columns=0",
14899 "--enable-tx-size-search=1",
14900 "--min-partition-size=8",
14901 "--enable-rect-partitions=1",
14902 ])
14903 // Per-arm overrides go AFTER the base recipe: aomenc keeps
14904 // the LAST occurrence of a repeated flag.
14905 .args(*extra)
14906 // The 8-bit twin of the pinned recipe picks a 128-root
14907 // HORZ partition, which this decoder still refuses by name
14908 // ("a 128x128 superblock HORZ/VERT or AB partition") --
14909 // an open refusal of another lane, unrelated to palette.
14910 // Pinning the superblock to 64 keeps the 8-bit arm on the
14911 // shape this gate is about; the 10-bit arms are the
14912 // untouched pinned recipe.
14913 .args(if depth == 8 {
14914 &["--sb-size=64"][..]
14915 } else {
14916 &[][..]
14917 })
14918 .args(["--obu", "-o", "-", "-"]),
14919 &y4m,
14920 );
14921 assert!(
14922 out.status.success(),
14923 "{NAME}: aomenc refused {arm} at {depth}-bit: {}",
14924 String::from_utf8_lossy(&out.stderr)
14925 );
14926 let stream = out.stdout;
14927 let before = decode::rect4_palette_hits();
14928 let frames = match decode_stream(&stream) {
14929 Ok(frames) => frames,
14930 // A NAMED refusal is another lane's open shape (here: a
14931 // palette on an 8x8 SQUARE leaf, still out of scope), never
14932 // a pass -- the attempt is counted out of scope and the
14933 // per-depth firing assert below keeps the gate honest.
14934 Err(e) if e.to_string().contains("unsupported") => {
14935 eprintln!("{NAME}: {arm} {depth}-bit REFUSED: {e}");
14936 refused += 1;
14937 continue;
14938 }
14939 Err(e) => panic!("{NAME}: decode failed on {arm} at {depth}-bit: {e}"),
14940 };
14941 let fired = decode::rect4_palette_hits() - before;
14942 // The ENCODE's frame count, asserted ABOVE the oracle call: the
14943 // y4m renders 5 frames (`-t 0.2` at every arm's `rate=25`,
14944 // 13275) but aomenc is given `--limit=1` (13313), so the stream
14945 // codes exactly 1 frame at both depths on every arm. Asserted
14946 // here it is NOT the tautology the old comment below claimed:
14947 // `frames.len() == 1` is a fact about the encode, checked before
14948 // `frames.len()` is spent as ffmpeg's frame budget.
14949 assert_eq!(frames.len(), 1, "{NAME}: {arm} at {depth}-bit key frame");
14950 let ffmpeg_frames = if depth == 10 {
14951 ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len())
14952 } else {
14953 ffmpeg_decode_sequence(&stream, width, height, frames.len())
14954 };
14955 assert!(
14956 !frames.is_empty(),
14957 "{NAME}: {arm} at {depth}-bit decoded no frame"
14958 );
14959 // EVERY decode-order frame, all three planes.
14960 let mut exact = true;
14961 for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() {
14962 if ours.y != theirs.y || ours.u != theirs.u || ours.v != theirs.v {
14963 exact = false;
14964 eprintln!("{NAME}: {arm} {depth}-bit frame {i} differs");
14965 }
14966 frames_compared += 1;
14967 }
14968 if fired > 0 {
14969 fired_arms += 1;
14970 fired_at_depth[usize::from(depth == 10)] += 1;
14971 assert!(
14972 exact,
14973 "{NAME}: {arm} at {depth}-bit has {fired} rect-strip palette block(s) \
14974 and does NOT decode pixel-exact"
14975 );
14976 } else {
14977 out_of_scope += 1;
14978 if !exact {
14979 out_of_scope_mismatch += 1;
14980 }
14981 }
14982 }
14983 }
14984 eprintln!(
14985 "{NAME}: {fired_arms} attempt(s) with a rect-strip palette block, \
14986 {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \
14987 {refused} refused, {frames_compared} frames compared, \
14988 fired 8-bit={} 10-bit={}",
14989 fired_at_depth[0], fired_at_depth[1]
14990 );
14991 // MEASURED 2026-09-02, every 8-bit attempt of these recipes: aomenc
14992 // puts its palettes on SQUARE blocks at 8 bit and every 8-bit stream
14993 // that reaches a rect strip with one lands on a palette shape still
14994 // out of scope (8x8 square leaf, or a 64x32/32x64 superblock strip
14995 // with a real transform). So the 8-bit arms here prove the DECODE
14996 // path, not the lift -- `fired_at_depth[0] == 0` is a known, reported
14997 // coverage gap and not a silent pass: the counter is printed.
14998 assert!(
14999 fired_at_depth[1] > 0,
15000 "{NAME}: no attempt put a palette on a rect strip \
15001 (8-bit={}, 10-bit={}) -- gate is vacuous",
15002 fired_at_depth[0],
15003 fired_at_depth[1]
15004 );
15005 assert!(fired_arms > 0, "{NAME}: gate is vacuous");
15006 assert_eq!(
15007 out_of_scope_mismatch, 0,
15008 "{NAME}: {out_of_scope_mismatch} attempt(s) without a rect-strip palette block \
15009 still mismatched -- an unrelated defect, not a SKIP"
15010 );
15011 }
15012
15013 /// lane-hbd r5: a real `aomenc --bit-depth=10` stream, decoded through
15014 /// this crate's own 10-bit planes (`Picture` widened to `u16` in an
15015 /// earlier round) and checked pixel-exact against ffmpeg's own decode of
15016 /// the identical bytes via [`ffmpeg_decode_sequence_10bit`]. Confirms
15017 /// (hard-asserts, not just trusts) the sequence header this stream
15018 /// actually parses to says `bit_depth == 10` before trusting any pixel
15019 /// match -- a stream that silently fell back to 8-bit would still
15020 /// "match" trivially.
15021 // -------------------------------------------------------------------
15022 // lane-av112bit: the 12-bit gate battery. The blanket refusal is lifted
15023 // for what these gates witness byte-exact against ffmpeg on real
15024 // `aomenc --bit-depth=12 --profile=2` streams: the full intra stack,
15025 // dequant/transforms at the 12-bit dequant tables, deblock, CDEF, loop
15026 // restoration (Wiener AND SGR), and translational subpel motion
15027 // compensation through the bit-depth-parameterised `round_0`/`round_1`
15028 // (libaom `convolve.h:81..86`). Everything else stays refused by name:
15029 // warp and screen content tools (palette/intrabc) at the frame level,
15030 // each with its own real-stream refusal gate below.
15031 // lane-av112bitc: compound joined the witnessed set (refusal gate became
15032 // the six-frame compound witness).
15033 // lane-av112bitg: film grain joined the witnessed set (refusal gate became
15034 // `a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact`).
15035 // -------------------------------------------------------------------
15036
15037 /// The 12-bit witness source, byte-identical to the lane's committed
15038 /// fixture recipe: 160x128 C420p12, a gradient + fine-texture base with a
15039 /// 24x20 box that travels 1.25 px/frame horizontally and 0.75 px/frame
15040 /// vertically with linear edge coverage -- sub-pixel true motion, so an
15041 /// inter frame over it cannot be coded whole-pel-only.
15042 fn y4m_12bit_subpel_source(frames: usize) -> Vec<u8> {
15043 const W: usize = 160;
15044 const H: usize = 128;
15045 let cov = |a: f64, b: f64, i: i64| (b.min(i as f64 + 1.0) - a.max(i as f64)).max(0.0);
15046 let mut y4m = format!("YUV4MPEG2 W{W} H{H} F30:1 Ip A1:1 C420p12\n").into_bytes();
15047 for t in 0..frames {
15048 let (ax, ay) = (12.0 + 1.25 * t as f64, 10.0 + 0.75 * t as f64);
15049 let (bx, by) = (ax + 24.0, ay + 20.0);
15050 y4m.extend_from_slice(b"FRAME\n");
15051 for j in 0..H as i64 {
15052 for i in 0..W as i64 {
15053 let g = (i * 190) / W as i64 + (j * 150) / H as i64;
15054 let mut v = (g * 12
15055 + if (i * 5 + j * 3 + t as i64) % 7 < 3 {
15056 90
15057 } else {
15058 220
15059 }
15060 + if (60..110).contains(&i) && (70..110).contains(&j) {
15061 640
15062 } else {
15063 0
15064 }) as f64;
15065 let c = cov(ax, bx, i) * cov(ay, by, j);
15066 if c > 0.0 {
15067 v = v * (1.0 - c) + 3500.0 * c;
15068 }
15069 y4m.extend_from_slice(&(v.min(4095.0) as u16).to_le_bytes());
15070 }
15071 }
15072 for (base, fx) in [(1900usize, 0usize), (2100, 1)] {
15073 for j in 0..H / 2 {
15074 for i in 0..W / 2 {
15075 let v = if fx == 0 {
15076 base + (((i / 5 + t * 2) % 7) * 120 + (j * 60) / H)
15077 } else {
15078 base + (((j / 4 + t) % 5) * 140 + (i * 40) / W)
15079 };
15080 y4m.extend_from_slice(&(v.min(4095) as u16).to_le_bytes());
15081 }
15082 }
15083 }
15084 }
15085 y4m
15086 }
15087
15088 /// lane-av1gwarp12 fixture: rotating + uniformly zooming mandelbrot as a
15089 /// C420p12 y4m. Rotation composed with a UNIFORM scale is a similarity
15090 /// transform -- exactly the family a 4-parameter ROTZOOM global model
15091 /// expresses (the affine gate needs the anisotropic stretch to force
15092 /// 6 parameters; this lane needs the model vanilla aomenc actually
15093 /// searches, ROTZOOM).
15094 fn y4m_12bit_rotzoom_gm_source(frames: usize) -> Vec<u8> {
15095 const W: usize = 128;
15096 const H: usize = 128;
15097 let source = format!(
15098 "mandelbrot=size=192x192:rate=25,rotate=a=0.12*t:c=black,\
15099 scale=w='ceil(192*(1+0.04*n)/2)*2':h='ceil(192*(1+0.04*n)/2)*2':eval=frame,\
15100 crop={W}:{H}"
15101 );
15102 let duration = (frames as f64 / 25.0).to_string();
15103 let ff_args: Vec<&str> = vec![
15104 "-v",
15105 "error",
15106 "-f",
15107 "lavfi",
15108 "-i",
15109 &source,
15110 "-pix_fmt",
15111 "yuv420p12le",
15112 // y4m has no official 12-bit tag, same as the 10-bit gate.
15113 "-strict",
15114 "-1",
15115 "-t",
15116 &duration,
15117 "-f",
15118 "yuv4mpegpipe",
15119 "-",
15120 ];
15121 let out = Command::new("ffmpeg")
15122 .args(&ff_args)
15123 .stdin(Stdio::null())
15124 .stdout(Stdio::piped())
15125 .stderr(Stdio::piped())
15126 .output()
15127 .expect("ffmpeg failed to run");
15128 assert!(
15129 out.status.success(),
15130 "ffmpeg fixture: {}",
15131 String::from_utf8_lossy(&out.stderr)
15132 );
15133 out.stdout
15134 }
15135
15136 /// The 12-bit coding recipe shared by the witness gates (cpu-used=0 so
15137 /// every search runs; explicit CDEF/restoration ON). Warp/global-motion
15138 /// are deliberately NOT spelled here: this aomenc honours the LAST
15139 /// occurrence of these flags (measured), so a base pin plus an override
15140 /// would silently take the base value -- each gate spells what it needs
15141 /// exactly once.
15142 fn encode_12bit(y4m: &[u8], frames: usize, extra: &[&str]) -> Vec<u8> {
15143 let limit = format!("--limit={frames}");
15144 let mut args: Vec<&str> = vec![
15145 "--codec=av1",
15146 "--profile=2",
15147 "--passes=1",
15148 "--end-usage=q",
15149 "--cq-level=20",
15150 "--cpu-used=0",
15151 "--threads=1",
15152 "--row-mt=0",
15153 "--sb-size=64",
15154 "--lag-in-frames=0",
15155 "--auto-alt-ref=0",
15156 "--kf-max-dist=1000",
15157 "--input-bit-depth=12",
15158 "--bit-depth=12",
15159 "--enable-cdef=1",
15160 "--enable-restoration=1",
15161 "--obu",
15162 "-o",
15163 "-",
15164 "-",
15165 &limit,
15166 ];
15167 // AOMENC FLAG PRECEDENCE (COMMON): aomenc keeps the FIRST occurrence
15168 // of a flag, so the per-arm override goes BEFORE the base list.
15169 args.splice(1..1, extra.iter().copied());
15170 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), y4m);
15171 assert!(
15172 out.status.success(),
15173 "aomenc refused the 12-bit fixture: {}",
15174 String::from_utf8_lossy(&out.stderr)
15175 );
15176 out.stdout
15177 }
15178
15179 /// Asserts the stream's sequence header really says 12-bit before any
15180 /// pixel comparison is trusted.
15181 fn assert_12bit_sequence_header(stream: &[u8], name: &str) {
15182 let mut probe = Av1Parser::new();
15183 let mut pos = 0usize;
15184 while pos < stream.len() && probe.sequence_header().is_none() {
15185 let obu = probe.parse_obu(&stream[pos..]).unwrap();
15186 pos += obu.total_size;
15187 }
15188 let seq = probe
15189 .sequence_header()
15190 .expect("stream has a sequence header OBU");
15191 assert_eq!(
15192 seq.color_config.bit_depth, 12,
15193 "{name}: aomenc did not actually write a 12-bit sequence header"
15194 );
15195 }
15196
15197 fn ffmpeg_decode_sequence_12bit(
15198 stream: &[u8],
15199 width: usize,
15200 height: usize,
15201 frames: usize,
15202 ) -> Vec<Pic> {
15203 let out = run_with_stdin(
15204 Command::new("ffmpeg").args([
15205 "-v",
15206 "error",
15207 "-f",
15208 "obu",
15209 "-i",
15210 "-",
15211 "-f",
15212 "rawvideo",
15213 "-pix_fmt",
15214 "yuv420p12le",
15215 "-",
15216 ]),
15217 stream,
15218 );
15219 assert!(
15220 out.status.success(),
15221 "ffmpeg refused the 12-bit stream: {}",
15222 String::from_utf8_lossy(&out.stderr)
15223 );
15224 let (luma, chroma) = (width * height, width * height / 4);
15225 let frame_bytes = (luma + 2 * chroma) * 2;
15226 assert_eq!(
15227 out.stdout.len(),
15228 frame_bytes * frames,
15229 "expected {frames} 4:2:0 12-bit frames, ffmpeg said: {}",
15230 String::from_utf8_lossy(&out.stderr)
15231 );
15232 fn le16(bytes: &[u8]) -> Vec<u16> {
15233 bytes
15234 .chunks_exact(2)
15235 .map(|c| u16::from_le_bytes([c[0], c[1]]))
15236 .collect()
15237 }
15238 (0..frames)
15239 .map(|i| {
15240 let base = i * frame_bytes;
15241 Pic {
15242 width,
15243 height,
15244 y: le16(&out.stdout[base..base + luma * 2]),
15245 u: le16(&out.stdout[base + luma * 2..base + luma * 2 + chroma * 2]),
15246 v: le16(&out.stdout[base + luma * 2 + chroma * 2..base + frame_bytes]),
15247 }
15248 })
15249 .collect()
15250 }
15251
15252 /// The 12-bit KEY witness: CDEF and loop restoration ON, grain off.
15253 /// Byte-exact against ffmpeg, and the 12-bit-sensitive pixel paths hard-
15254 /// assert fired: a CDEF index literal read (bits > 0) and at least one
15255 /// Wiener or SGR restoration unit. Gauntlet for the parameterised
15256 /// rounding sites: MC/Wiener round pairs, `coeff_shift = bd - 8` CDEF,
15257 /// the 12-bit dequant tables, bd-scaled SGR box sums.
15258 #[test]
15259 fn a_real_aomenc_12bit_stream_decodes_pixel_exact() {
15260 const NAME: &str = "a_real_aomenc_12bit_stream_decodes_pixel_exact";
15261 let _gate_lock = lock_gate_counters();
15262 if !have_ffmpeg() {
15263 eprintln!("SKIP {NAME}: no ffmpeg");
15264 return;
15265 }
15266 if !have_aomenc() {
15267 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15268 return;
15269 }
15270 let y4m = y4m_12bit_subpel_source(1);
15271 let stream = encode_12bit(
15272 &y4m,
15273 1,
15274 &["--enable-warped-motion=0", "--enable-global-motion=0"],
15275 );
15276 assert_12bit_sequence_header(&stream, NAME);
15277 let before_cdef = decode::cdef_idx_hits();
15278 let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
15279 let frames = decode_stream(&stream).unwrap_or_else(|e| {
15280 panic!("{NAME}: decode_stream refused a real 12-bit key frame: {e}")
15281 });
15282 assert_eq!(frames.len(), 1);
15283 assert!(
15284 decode::cdef_idx_hits() > before_cdef,
15285 "{NAME}: no CDEF index literal was read -- CDEF is not exercised"
15286 );
15287 assert!(
15288 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
15289 "{NAME}: no loop restoration unit was decoded -- LR is not exercised"
15290 );
15291 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 1);
15292 assert_eq!(
15293 frames[0].y, ffmpeg_frames[0].y,
15294 "luma vs ffmpeg (12-bit key)"
15295 );
15296 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (12-bit key)");
15297 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (12-bit key)");
15298 }
15299
15300 /// The 12-bit INTER witness: a key frame plus one P frame over sub-pixel
15301 /// true motion. Byte-exact against ffmpeg; hard-asserts the two-pass
15302 /// SUBPEL prediction path ran (`MC_SUBPEL_HITS`), so the frame's own
15303 /// `round_0`/`round_1` -- 5/9 at 12 bits, the whole point of the mc.rs
15304 /// parameterisation -- really executed, and asserts
15305 /// `compound_mode_hits` UNCHANGED (this recipe offers no divergent
15306 /// second reference, so no compound mode symbol is read -- the lane's
15307 /// compound witness is the six-frame gate below).
15308 #[test]
15309 fn a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact() {
15310 const NAME: &str = "a_real_aomenc_12bit_inter_sequence_decodes_pixel_exact";
15311 let _gate_lock = lock_gate_counters();
15312 if !have_ffmpeg() {
15313 eprintln!("SKIP {NAME}: no ffmpeg");
15314 return;
15315 }
15316 if !have_aomenc() {
15317 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15318 return;
15319 }
15320 let y4m = y4m_12bit_subpel_source(2);
15321 let stream = encode_12bit(
15322 &y4m,
15323 2,
15324 &["--enable-warped-motion=0", "--enable-global-motion=0"],
15325 );
15326 assert_12bit_sequence_header(&stream, NAME);
15327 let before_subpel = crate::mc::mc_subpel_hits();
15328 let before_compound = decode::compound_mode_hits();
15329 let frames = decode_stream(&stream).unwrap_or_else(|e| {
15330 panic!("{NAME}: decode_stream refused a real 12-bit inter stream: {e}")
15331 });
15332 assert_eq!(frames.len(), 2);
15333 assert!(
15334 crate::mc::mc_subpel_hits() > before_subpel,
15335 "{NAME}: no subpel inter prediction decoded -- the 12-bit round pair is unexercised"
15336 );
15337 assert_eq!(
15338 decode::compound_mode_hits(),
15339 before_compound,
15340 "{NAME}: a compound mode symbol was read -- the single-reference premise is gone"
15341 );
15342 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2);
15343 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15344 assert_eq!(
15345 ours.y, reference.y,
15346 "frame {i} luma vs ffmpeg (12-bit inter)"
15347 );
15348 assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit inter)");
15349 assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit inter)");
15350 }
15351 }
15352
15353 /// The 12-bit WARP witness (lane-av112bitw): the same source and recipe
15354 /// with the warp tools ON -- aomenc picks warp models on this content
15355 /// (measured pre-lift: the warp model fires at the third frame, and the
15356 /// decode refused by name at exactly that block) -- now decodes
15357 /// BYTE-EXACT against ffmpeg. The warp filter's shifts are the bumped
15358 /// `conv_params->round_0` (`warp::warp_round_0`, 5 at 12 bits, feeding
15359 /// `reduce_bits_horiz`, the derived non-compound
15360 /// `reduce_bits_vert = 2*FILTER_BITS - round_0` and both `offset_bits`),
15361 /// the whole libaom `get_conv_params_no_round` 12-bit bump.
15362 ///
15363 /// Non-vacuous: the same recipe refused by name before the lift, the
15364 /// gate hard-asserts a warp predictor was really resolved (a warpless
15365 /// stream would pass the pixel compare and prove nothing), and every
15366 /// plane of every frame compares against ffmpeg's decode.
15367 #[test]
15368 fn a_12bit_warped_motion_stream_decodes_pixel_exact() {
15369 const NAME: &str = "a_12bit_warped_motion_stream_decodes_pixel_exact";
15370 let _gate_lock = lock_gate_counters();
15371 if !have_ffmpeg() {
15372 eprintln!("SKIP {NAME}: no ffmpeg");
15373 return;
15374 }
15375 if !have_aomenc() {
15376 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15377 return;
15378 }
15379 let y4m = y4m_12bit_subpel_source(6);
15380 // Exactly the recipe measured to refuse at warp pre-lift: warp ON,
15381 // global motion NOT spelled (spelling it ON drives a GLOBAL_GLOBALMV
15382 // compound block into the compound-warp arm -- see the compound gate
15383 // below), six frames -- the warp model fires at the third frame.
15384 let stream = encode_12bit(&y4m, 6, &["--enable-warped-motion=1"]);
15385 assert_12bit_sequence_header(&stream, NAME);
15386 let (before_selected, before_warp8, before_affine) = (
15387 decode::warp_selected_hits(),
15388 decode::warp_hits_8(),
15389 decode::affine_gm_hits(),
15390 );
15391 let frames = decode_stream(&stream).unwrap_or_else(|e| {
15392 panic!("{NAME}: decode_stream refused a real 12-bit warp stream: {e}")
15393 });
15394 assert_eq!(frames.len(), 6);
15395 let (delta_selected, delta_warp8, delta_affine) = (
15396 decode::warp_selected_hits() - before_selected,
15397 decode::warp_hits_8() - before_warp8,
15398 decode::affine_gm_hits() - before_affine,
15399 );
15400 eprintln!(
15401 "{NAME}: warp_engagement selected(16x16+ symbol)={delta_selected} \
15402 warped8(usable 8x8 model)={delta_warp8} affine_gm(6-param model)={delta_affine}"
15403 );
15404 assert!(
15405 delta_selected + delta_warp8 + delta_affine > 0,
15406 "{NAME}: no warp predictor was resolved -- the stream carries no \
15407 warp model and the pixel compare would prove nothing"
15408 );
15409 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6);
15410 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15411 assert_eq!(
15412 ours.y, reference.y,
15413 "frame {i} luma vs ffmpeg (12-bit warp)"
15414 );
15415 assert_eq!(ours.u, reference.u, "frame {i} U vs ffmpeg (12-bit warp)");
15416 assert_eq!(ours.v, reference.v, "frame {i} V vs ffmpeg (12-bit warp)");
15417 }
15418 }
15419
15420 /// The 12-bit COMPOUND witness (lane-av112bitc): the parent's source
15421 /// and recipe with warp pinned OFF -- with six frames LAST diverges
15422 /// from GOLDEN from frame 2 on and aomenc codes compound inter blocks
15423 /// (pre-lift measurement: the decode refused at the compound mode
15424 /// read). Two arms: the default recipe (dist-weighted average
15425 /// combines live) and `--enable-dist-wtd-comp=0` (pushes compound AND
15426 /// the masked choice harder: 6 diffwtd blends). Both byte-exact
15427 /// against ffmpeg; each hard-asserts compound mode symbols and
15428 /// masked-diffwtd blends really ran, so the parameterised combine
15429 /// rounds (`INTER_POST_ROUND - delta`, diffwtd `+ (bd-8) - delta` at
15430 /// 12 bits) and the ffmpeg-pinned pixel path genuinely executed.
15431 #[test]
15432 fn a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact() {
15433 const NAME: &str = "a_real_aomenc_12bit_compound_inter_sequence_decodes_pixel_exact";
15434 let _gate_lock = lock_gate_counters();
15435 if !have_ffmpeg() {
15436 eprintln!("SKIP {NAME}: no ffmpeg");
15437 return;
15438 }
15439 if !have_aomenc() {
15440 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15441 return;
15442 }
15443 let y4m = y4m_12bit_subpel_source(6);
15444 for (arm, extra) in [
15445 ("dist-wtd", &["--enable-warped-motion=0"][..]),
15446 (
15447 "plain-masked",
15448 &["--enable-warped-motion=0", "--enable-dist-wtd-comp=0"][..],
15449 ),
15450 ] {
15451 let stream = encode_12bit(&y4m, 6, &extra);
15452 assert_12bit_sequence_header(&stream, NAME);
15453 let before_compound = decode::compound_mode_hits();
15454 let before_masked = decode::masked_compound_hits();
15455 let before_diffwtd = decode::diffwtd_hits();
15456 let before_wedge = decode::wedge_hits();
15457 let frames = decode_stream(&stream).unwrap_or_else(|e| {
15458 panic!("{NAME} [{arm}]: decode_stream refused a real 12-bit compound stream: {e}")
15459 });
15460 assert_eq!(frames.len(), 6, "{NAME} [{arm}]: frame count");
15461 let (comp, masked, diffwtd, wedge) = (
15462 decode::compound_mode_hits() - before_compound,
15463 decode::masked_compound_hits() - before_masked,
15464 decode::diffwtd_hits() - before_diffwtd,
15465 decode::wedge_hits() - before_wedge,
15466 );
15467 eprintln!(
15468 "{NAME} [{arm}]: compound blocks={comp} masked={masked} diffwtd={diffwtd} wedge={wedge}"
15469 );
15470 assert!(
15471 comp > 0,
15472 "{NAME} [{arm}]: no compound mode symbol was read -- the compound path is unexercised"
15473 );
15474 assert!(
15475 masked > 0,
15476 "{NAME} [{arm}]: no masked compound block ran -- the masked combine is unexercised"
15477 );
15478 assert!(
15479 diffwtd > 0,
15480 "{NAME} [{arm}]: no diffwtd blend ran -- the diffwtd combine is unexercised"
15481 );
15482 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 6);
15483 for (i, (ours, reference)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15484 assert_eq!(
15485 ours.y, reference.y,
15486 "{NAME} [{arm}] frame {i} luma vs ffmpeg"
15487 );
15488 assert_eq!(ours.u, reference.u, "{NAME} [{arm}] frame {i} U vs ffmpeg");
15489 assert_eq!(ours.v, reference.v, "{NAME} [{arm}] frame {i} V vs ffmpeg");
15490 }
15491 }
15492 }
15493
15494 /// lane-av112bitg: the 12-bit film grain witness. A real
15495 /// `aomenc --bit-depth=12 --profile=2 --film-grain-test=5` stream -- grain
15496 /// params present AND applied (2 luma + 9 cb + 9 cr scaling points,
15497 /// overlap blending on, clip-to-restricted-range on; the second frame is
15498 /// an INTER frame that inherits the params via `update_grain = 0`) --
15499 /// decoded byte-exact against ffmpeg's own 12-bit decode of the identical
15500 /// bytes (ffmpeg synthesizes grain by default; no grain-disable flag is
15501 /// passed anywhere in this file). Proves the bit-depth-generic grain path
15502 /// at 12 bits: `grain_range`'s ±(128 << 4) AR clamp and overlap-blend
15503 /// clamp, the `gauss_sec_shift = 12 - bd` Gaussian shift, the 4096-entry
15504 /// expanded scaling-LUT interpolation, and the `<< (bit_depth - 8)`
15505 /// chroma offsets and legal-range clamps. HARD-asserts the parsed headers
15506 /// really carry that coverage and `film_grain::grain_hits()` fired, so
15507 /// neither a params-without-apply stream nor a silently-skipped synthesis
15508 /// can pass vacuously.
15509 #[test]
15510 fn a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact() {
15511 const NAME: &str = "a_real_aomenc_12bit_film_grain_stream_decodes_pixel_exact";
15512 let _gate_lock = lock_gate_counters();
15513 if !have_ffmpeg() {
15514 eprintln!("SKIP {NAME}: no ffmpeg");
15515 return;
15516 }
15517 if !have_aomenc() {
15518 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15519 return;
15520 }
15521 let y4m = y4m_12bit_subpel_source(2);
15522 // Warp stays refused at 12 bits (lane-av112bitg lifts GRAIN only), so
15523 // the arm pins both motion tools off exactly once each -- aomenc
15524 // otherwise picks warped motion on this fixture's sub-pel motion.
15525 let stream = encode_12bit(
15526 &y4m,
15527 2,
15528 &[
15529 "--film-grain-test=5",
15530 "--enable-warped-motion=0",
15531 "--enable-global-motion=0",
15532 ],
15533 );
15534 assert_12bit_sequence_header(&stream, NAME);
15535 // The arm is only honest if the stream itself carries the coverage:
15536 // grain applied on every frame, scaling points on all three planes,
15537 // overlap blending and restricted-range clipping on.
15538 let mut probe = Av1Parser::new();
15539 let mut pos = 0usize;
15540 let mut grain_frames = 0usize;
15541 while pos < stream.len() {
15542 let obu = probe.parse_obu(&stream[pos..]).unwrap();
15543 pos += obu.total_size;
15544 if let ObuKind::Frame(header, _) = obu.kind {
15545 let fg = &header.film_grain;
15546 assert!(
15547 fg.apply_grain,
15548 "{NAME}: frame without apply_grain -- aomenc emitted params it does not apply"
15549 );
15550 assert!(
15551 fg.num_y_points > 0 && fg.num_cb_points > 0 && fg.num_cr_points > 0,
15552 "{NAME}: grain without all three planes' scaling points -- the bit-depth \
15553 LUT math would not be exercised"
15554 );
15555 assert!(
15556 fg.overlap_flag,
15557 "{NAME}: overlap off -- the grain_min/grain_max blend clamp is not exercised"
15558 );
15559 assert!(
15560 fg.clip_to_restricted_range,
15561 "{NAME}: clip_to_restricted_range off -- the << (bd - 8) legal-range clamps \
15562 are not exercised"
15563 );
15564 grain_frames += 1;
15565 }
15566 }
15567 assert_eq!(grain_frames, 2, "{NAME}: expected grain on both frames");
15568 let before = crate::film_grain::grain_hits();
15569 let frames = decode_stream(&stream).unwrap_or_else(|e| {
15570 panic!("{NAME}: decode_stream refused a real 12-bit grain stream: {e}")
15571 });
15572 assert_eq!(frames.len(), 2);
15573 assert!(
15574 crate::film_grain::grain_hits() > before,
15575 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
15576 );
15577 let ffmpeg_frames = ffmpeg_decode_sequence_12bit(&stream, 160, 128, 2);
15578 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15579 assert_eq!(
15580 ours.y, theirs.y,
15581 "{NAME}: luma vs ffmpeg (12-bit grain, frame {i})"
15582 );
15583 assert_eq!(
15584 ours.u, theirs.u,
15585 "{NAME}: U vs ffmpeg (12-bit grain, frame {i})"
15586 );
15587 assert_eq!(
15588 ours.v, theirs.v,
15589 "{NAME}: V vs ffmpeg (12-bit grain, frame {i})"
15590 );
15591 }
15592 eprintln!(
15593 "{NAME}: byte-exact, grain_hits={}",
15594 crate::film_grain::grain_hits()
15595 );
15596 }
15597
15598 /// The 12-bit screen-content refusal: a real `--tune-content=screen
15599 /// --enable-palette=1 --enable-intrabc=1` frame carries
15600 /// `allow_screen_content_tools = 1` and is refused by name at the frame
15601 /// gate -- palette and intrabc have no 12-bit witness.
15602 #[test]
15603 fn a_12bit_screen_content_stream_is_refused_by_name() {
15604 const NAME: &str = "a_12bit_screen_content_stream_is_refused_by_name";
15605 let _gate_lock = lock_gate_counters();
15606 if !have_ffmpeg() {
15607 eprintln!("SKIP {NAME}: no ffmpeg");
15608 return;
15609 }
15610 if !have_aomenc() {
15611 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15612 return;
15613 }
15614 let y4m = Command::new("ffmpeg")
15615 .args([
15616 "-v",
15617 "error",
15618 "-f",
15619 "lavfi",
15620 "-i",
15621 "smptebars=s=128x128:r=25",
15622 "-pix_fmt",
15623 "yuv420p12le",
15624 "-strict",
15625 "-1",
15626 "-frames:v",
15627 "2",
15628 "-f",
15629 "yuv4mpegpipe",
15630 "-",
15631 ])
15632 .stdin(Stdio::null())
15633 .stdout(Stdio::piped())
15634 .stderr(Stdio::piped())
15635 .output()
15636 .expect("ffmpeg failed to run");
15637 assert!(
15638 y4m.status.success(),
15639 "ffmpeg failed to render the 12-bit screen fixture: {}",
15640 String::from_utf8_lossy(&y4m.stderr)
15641 );
15642 let stream = encode_12bit(
15643 &y4m.stdout,
15644 1,
15645 &[
15646 "--tune-content=screen",
15647 "--enable-palette=1",
15648 "--enable-intrabc=1",
15649 ],
15650 );
15651 let err = decode_stream(&stream).unwrap_err().to_string();
15652 assert!(
15653 err.contains(
15654 "a 12-bit frame with screen content tools (allow_screen_content_tools=1: neither palette nor intrabc has a 12-bit witness)"
15655 ),
15656 "{NAME}: expected the 12-bit screen content refusal, got: {err}"
15657 );
15658 }
15659
15660 #[test]
15661 fn a_real_aomenc_10bit_stream_decodes_pixel_exact() {
15662 const NAME: &str = "a_real_aomenc_10bit_stream_decodes_pixel_exact";
15663 if !have_ffmpeg() {
15664 eprintln!("SKIP {NAME}: no ffmpeg");
15665 return;
15666 }
15667 if !have_aomenc() {
15668 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15669 return;
15670 }
15671 let (width, height) = (64usize, 64usize);
15672 let y4m = Command::new("ffmpeg")
15673 .args([
15674 "-v",
15675 "error",
15676 "-f",
15677 "lavfi",
15678 "-i",
15679 &gradients_source(42, width, height, "duration=0.04:rate=25"),
15680 "-pix_fmt",
15681 "yuv420p10le",
15682 "-strict",
15683 "-1",
15684 "-t",
15685 "0.04",
15686 "-f",
15687 "yuv4mpegpipe",
15688 "-",
15689 ])
15690 .stdin(Stdio::null())
15691 .stdout(Stdio::piped())
15692 .stderr(Stdio::piped())
15693 .output()
15694 .expect("ffmpeg failed to run");
15695 assert!(
15696 y4m.status.success(),
15697 "ffmpeg failed to render the 10-bit fixture: {}",
15698 String::from_utf8_lossy(&y4m.stderr)
15699 );
15700 let out = run_with_stdin(
15701 Command::new(aomenc_path()).args([
15702 "--codec=av1",
15703 "--passes=1",
15704 "--end-usage=q",
15705 "--cq-level=30",
15706 "--cpu-used=0",
15707 "--threads=1",
15708 "--row-mt=0",
15709 "--sb-size=64",
15710 "--input-bit-depth=10",
15711 "--bit-depth=10",
15712 "--limit=1",
15713 "--obu",
15714 "-o",
15715 "-",
15716 "-",
15717 ]),
15718 &y4m.stdout,
15719 );
15720 assert!(
15721 out.status.success(),
15722 "aomenc refused the 10-bit fixture: {}",
15723 String::from_utf8_lossy(&out.stderr)
15724 );
15725 let stream = out.stdout;
15726 // Confirm the sequence header this stream actually parses to before
15727 // trusting any pixel comparison below.
15728 let mut probe = Av1Parser::new();
15729 let mut pos = 0usize;
15730 while pos < stream.len() && probe.sequence_header().is_none() {
15731 let obu = probe.parse_obu(&stream[pos..]).unwrap();
15732 pos += obu.total_size;
15733 }
15734 let seq = probe
15735 .sequence_header()
15736 .expect("stream has a sequence header OBU");
15737 assert_eq!(
15738 seq.color_config.bit_depth, 10,
15739 "{NAME}: aomenc did not actually write a 10-bit sequence header"
15740 );
15741 let frames = match decode_stream(&stream) {
15742 Ok(frames) => frames,
15743 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit stream: {e}"),
15744 };
15745 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
15746 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (10-bit)");
15747 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (10-bit)");
15748 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (10-bit)");
15749 }
15750
15751 /// The 10-bit *inter* counterpart of the gate above: a real `aomenc`
15752 /// `yuv420p10le` sequence whose non-key frames are plain forward
15753 /// single-`LAST_FRAME` P frames (same `--lag-in-frames=0
15754 /// --auto-alt-ref=0 --error-resilient=1` shape as the 8-bit inter gate),
15755 /// decoded pixel-exact on every frame. 10-bit intra was proven exact by
15756 /// lane-hbd; inter reconstruction at `bit_depth == 10` was never gated.
15757 #[test]
15758 fn a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact() {
15759 const NAME: &str = "a_real_aomenc_10bit_inter_sequence_decodes_pixel_exact";
15760 let _gate_lock = lock_gate_counters();
15761 if !have_ffmpeg() {
15762 eprintln!("SKIP {NAME}: no ffmpeg");
15763 return;
15764 }
15765 if !have_aomenc() {
15766 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15767 return;
15768 }
15769 let (width, height, frame_count) = (128usize, 64usize, 16usize);
15770 let y4m = Command::new("ffmpeg")
15771 .args([
15772 "-v",
15773 "error",
15774 "-f",
15775 "lavfi",
15776 "-i",
15777 &gradients_source(42, width, height, "duration=0.64:rate=25"),
15778 "-pix_fmt",
15779 "yuv420p10le",
15780 "-strict",
15781 "-1",
15782 "-t",
15783 "0.64",
15784 "-f",
15785 "yuv4mpegpipe",
15786 "-",
15787 ])
15788 .stdin(Stdio::null())
15789 .stdout(Stdio::piped())
15790 .stderr(Stdio::piped())
15791 .output()
15792 .expect("ffmpeg failed to run");
15793 assert!(
15794 y4m.status.success(),
15795 "ffmpeg failed to render the 10-bit fixture: {}",
15796 String::from_utf8_lossy(&y4m.stderr)
15797 );
15798 let out = run_with_stdin(
15799 Command::new(aomenc_path()).args([
15800 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
15801 // occurrence, so overrides go before the base list).
15802 "--loopfilter-control=1",
15803 "--codec=av1",
15804 "--passes=1",
15805 "--end-usage=q",
15806 "--cq-level=15",
15807 "--cpu-used=0",
15808 "--threads=1",
15809 "--row-mt=0",
15810 "--sb-size=64",
15811 "--input-bit-depth=10",
15812 "--bit-depth=10",
15813 "--lag-in-frames=0",
15814 "--auto-alt-ref=0",
15815 "--kf-max-dist=1000",
15816 "--error-resilient=1",
15817 "--aq-mode=0",
15818 "--deltaq-mode=0",
15819 "--enable-cdef=0",
15820 "--enable-rect-partitions=0",
15821 "--enable-ab-partitions=0",
15822 "--enable-1to4-partitions=0",
15823 "--enable-filter-intra=0",
15824 "--enable-smooth-intra=0",
15825 "--enable-paeth-intra=0",
15826 "--enable-directional-intra=0",
15827 "--enable-angle-delta=0",
15828 "--enable-tx-size-search=0",
15829 "--enable-cdef=1",
15830 "--enable-restoration=1",
15831 "--min-partition-size=16",
15832 "--max-partition-size=32",
15833 "--enable-palette=0",
15834 "--enable-intrabc=0",
15835 "--enable-cfl-intra=0",
15836 "--enable-ref-frame-mvs=0",
15837 "--obu",
15838 "-o",
15839 "-",
15840 "-",
15841 ]),
15842 &y4m.stdout,
15843 );
15844 assert!(
15845 out.status.success(),
15846 "aomenc refused the 10-bit fixture: {}",
15847 String::from_utf8_lossy(&out.stderr)
15848 );
15849 let stream = out.stdout;
15850 if let Ok(dump) = std::env::var("EC_AV1_GATE_DUMP") {
15851 std::fs::write(dump, &stream).expect("dump stream");
15852 }
15853 let mut probe = Av1Parser::new();
15854 let mut pos = 0usize;
15855 while pos < stream.len() && probe.sequence_header().is_none() {
15856 let obu = probe.parse_obu(&stream[pos..]).unwrap();
15857 pos += obu.total_size;
15858 }
15859 assert_eq!(
15860 probe
15861 .sequence_header()
15862 .expect("stream has a sequence header OBU")
15863 .color_config
15864 .bit_depth,
15865 10,
15866 "{NAME}: aomenc did not actually write a 10-bit sequence header"
15867 );
15868 let before_deblock = decode::deblock_hits();
15869 let before_inter = decode::inter_pred_hits();
15870 let before_lr = crate::restoration::wiener_hits()
15871 + crate::restoration::sgrproj_hits()
15872 + crate::restoration::switchable_hits();
15873 let frames = match decode_stream(&stream) {
15874 Ok(frames) => frames,
15875 Err(e) => panic!("{NAME}: decode_stream refused a real 10-bit inter stream: {e}"),
15876 };
15877 assert!(
15878 decode::inter_pred_hits() > before_inter,
15879 "{NAME}: no inter-predicted block decoded -- the gate proves nothing"
15880 );
15881 assert!(
15882 decode::deblock_hits() > before_deblock,
15883 "{NAME}: no deblocking edge fired -- raise cq-level"
15884 );
15885 // Loop restoration is where the 10-bit inter/intra defect lived
15886 // (lane-hbdinter r1: the self-guided box sums were never brought back
15887 // to the 8-bit scale, `restoration.c:660`); a recipe whose RD happened
15888 // to pick RESTORE_NONE would pass while proving nothing.
15889 assert!(
15890 crate::restoration::wiener_hits()
15891 + crate::restoration::sgrproj_hits()
15892 + crate::restoration::switchable_hits()
15893 > before_lr,
15894 "{NAME}: no loop-restoration unit decoded a real filter -- lower cq-level"
15895 );
15896 eprintln!(
15897 "{NAME}: inter_pred {} deblock {} cdef_idx {} wiener {} sgrproj {}",
15898 decode::inter_pred_hits() - before_inter,
15899 decode::deblock_hits() - before_deblock,
15900 decode::cdef_idx_hits(),
15901 crate::restoration::wiener_hits(),
15902 crate::restoration::sgrproj_hits(),
15903 );
15904 assert_eq!(frames.len(), frame_count);
15905 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count);
15906 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
15907 if got.y != want.y || got.u != want.u || got.v != want.v {
15908 let pin = std::env::temp_dir().join("ec-av1-10bit-inter-gate-fail.obu");
15909 let _ = std::fs::write(&pin, &stream);
15910 let first = |a: &Vec<u16>, b: &Vec<u16>| {
15911 a.iter()
15912 .zip(b)
15913 .enumerate()
15914 .find(|(_, (x, y))| x != y)
15915 .map(|(k, (x, y))| (k, *x, *y))
15916 };
15917 panic!(
15918 "{NAME}: frame {i} mismatch vs ffmpeg -- Y {:?} U {:?} V {:?}; stream pinned at {}",
15919 first(&got.y, &want.y),
15920 first(&got.u, &want.u),
15921 first(&got.v, &want.v),
15922 pin.display()
15923 );
15924 }
15925 }
15926 }
15927
15928 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --film-grain-test=1`
15929 /// stream, decoded pixel-exact against ffmpeg's own 10-bit decode of the
15930 /// identical bytes (ffmpeg synthesizes grain by default -- no
15931 /// grain-disable flag is passed anywhere in this file). Proves the
15932 /// bit-depth-generic grain path (`film_grain.rs`'s `grain_range`,
15933 /// `scale_lut`, the `<< (bit_depth - 8)` offsets/legal ranges) rather
15934 /// than the old `bit_depth != 8` refusal. HARD-asserts both the parsed
15935 /// `bit_depth == 10` and `film_grain::grain_hits() > 0`, so neither a
15936 /// silent 8-bit fallback nor a stream aomenc emitted without
15937 /// `apply_grain` can make it pass vacuously.
15938 #[test]
15939 fn a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact() {
15940 const NAME: &str = "a_real_aomenc_10bit_film_grain_stream_decodes_pixel_exact";
15941 if !have_ffmpeg() {
15942 eprintln!("SKIP {NAME}: no ffmpeg");
15943 return;
15944 }
15945 if !have_aomenc() {
15946 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
15947 return;
15948 }
15949 let (width, height) = (64usize, 64usize);
15950 let stream = encode_10bit_gradients(
15951 NAME,
15952 width,
15953 height,
15954 1,
15955 &["--film-grain-test=1", "--limit=1"],
15956 );
15957 assert_eq!(
15958 parsed_bit_depth(&stream),
15959 10,
15960 "{NAME}: aomenc did not actually write a 10-bit sequence header"
15961 );
15962 let mut probe = Av1Parser::new();
15963 let mut pos = 0usize;
15964 let mut saw_grain = false;
15965 while pos < stream.len() {
15966 let obu = probe.parse_obu(&stream[pos..]).unwrap();
15967 pos += obu.total_size;
15968 if let ObuKind::Frame(header, _) = obu.kind
15969 && header.film_grain.apply_grain
15970 {
15971 // A grain block whose scaling LUT is empty would blend a
15972 // zero delta into every pixel and let this gate pass without
15973 // the bit-depth math mattering at all.
15974 assert!(
15975 header.film_grain.num_y_points > 0,
15976 "{NAME}: apply_grain with no luma scaling points -- grain would be a no-op"
15977 );
15978 saw_grain = true;
15979 }
15980 }
15981 assert!(saw_grain, "{NAME}: aomenc did not turn on apply_grain");
15982 let before = crate::film_grain::grain_hits();
15983 let frames = match decode_stream(&stream) {
15984 Ok(frames) => frames,
15985 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
15986 };
15987 assert!(
15988 crate::film_grain::grain_hits() > before,
15989 "{NAME}: matched but zero grain_hits -- grain synthesis never ran"
15990 );
15991 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
15992 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
15993 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
15994 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
15995 eprintln!(
15996 "{NAME}: pixel-exact, grain_hits={}",
15997 crate::film_grain::grain_hits()
15998 );
15999 }
16000
16001 /// lane-t900 r29: `fixtures/superres_kf_cdef_lr_64x64.obu` is a real
16002 /// aomenc key frame (64x64 upscaled from a coded 43x64,
16003 /// `--superres-mode=1 --superres-denominator=12 --cpu-used=0 --sb-size=64
16004 /// --enable-cdef=1 --enable-restoration=1 --cq-level=32`) -- the first
16005 /// stream in this repo that runs BOTH in-loop filters under superres.
16006 ///
16007 /// The defect it pins: spec 7.16's upscale runs between CDEF and loop
16008 /// restoration (libaom `superres_post_decode`, `decodeframe.c`, called
16009 /// between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`),
16010 /// but this decoder ran the whole filter chain on the DOWNSCALED frame
16011 /// and upscaled last, in `stream.rs`. Loop restoration therefore filtered
16012 /// downscaled pixels with a unit grid sized from the downscaled width
16013 /// (1873 wrong samples, max 7, on this very stream). Class
16014 /// `wrong-stage-width`: every plane width in the filter chain is either
16015 /// the downscaled one (deblock, CDEF, and the mi grid all three walk) or
16016 /// the upscaled one (loop restoration's `av1_get_upsampled_plane_size`
16017 /// unit grid, `av1_loop_restoration_corners_in_sb`'s `mi_to_num_x`
16018 /// superres arm, and the pixel filters themselves); the sweep is every
16019 /// caller of `apply_deblock`/`apply_cdef`/`apply_loop_restoration` plus
16020 /// `RestorationGrid::new` and `read_lr`.
16021 #[test]
16022 fn a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact() {
16023 const NAME: &str =
16024 "a_superres_key_frame_with_cdef_and_loop_restoration_decodes_pixel_exact";
16025 let _gate_lock = lock_gate_counters();
16026 if !have_ffmpeg() {
16027 eprintln!("SKIP {NAME}: no ffmpeg");
16028 return;
16029 }
16030 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16031 .join("fixtures/superres_kf_cdef_lr_64x64.obu");
16032 let stream = std::fs::read(&path)
16033 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
16034 let (width, height) = (64usize, 64usize);
16035 let before_lr = crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits();
16036 let frames = match decode_stream(&stream) {
16037 Ok(frames) => frames,
16038 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
16039 };
16040 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
16041 assert_eq!((frames[0].width, frames[0].height), (width, height));
16042 // class `gate-blind-to-feature`: the stream must actually upscale and
16043 // actually run a real restoration filter, or this gate proves nothing.
16044 assert!(
16045 crate::superres::superres_hits() > 0,
16046 "{NAME}: zero superres_hits -- the frame was never upscaled"
16047 );
16048 assert!(
16049 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits() > before_lr,
16050 "{NAME}: zero restoration units fired -- LR never ran under superres"
16051 );
16052 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
16053 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
16054 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
16055 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
16056 }
16057
16058 /// Shared body for the lane-av1superhbd HIGH-BIT-DEPTH 4:4:4 superres
16059 /// arms: 10-bit and 12-bit, `--superres-mode=1` at a fixed denominator
16060 /// and `--superres-mode=2` (a per-frame denominator libaom picks itself).
16061 ///
16062 /// Everything the 8-bit 4:4:4 superres cell is non-vacuous by, repeated
16063 /// here, plus the one thing that only matters above 8 bits: the gate
16064 /// asserts the PARSED `bit_depth` equals the depth it names, because a
16065 /// 10-bit recipe whose flags were mistyped still decodes -- it just
16066 /// decodes a DIFFERENT cell than the gate claims, which is the same
16067 /// "phantom cell" trap lane-av1444edge r3 recorded for
16068 /// `use_superres=false`.
16069 ///
16070 /// The per-frame table is `(denominator, coded_width)` in DECODE order.
16071 /// The coded width is re-derived as `(UpscaledWidth*8 + denom/2)/denom`
16072 /// from that frame's OWN parsed denominator rather than only compared to
16073 /// a literal, so a re-pinned fixture cannot satisfy the literals while
16074 /// the scaled-size arithmetic moves under them. `superres_hits` and
16075 /// `predict_scaled_hits` are asserted as DELTAS (both are process-wide
16076 /// counters with no reset).
16077 #[allow(clippy::too_many_arguments)]
16078 fn a_444_hbd_superres_arm(
16079 name: &str,
16080 fixture: &str,
16081 fixture_len: usize,
16082 fixture_fnv: u64,
16083 fixture_sha: &str,
16084 bit_depth: u8,
16085 upscaled: (usize, usize),
16086 per_frame: &[(u8, usize)],
16087 ) -> Vec<FrameHeader> {
16088 let obu = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(fixture);
16089 let stream = std::fs::read(&obu).unwrap_or_else(|e| {
16090 panic!(
16091 "{name}: pinned fixture {fixture} is missing ({e}) -- the gate cannot run, \
16092 which is a failure, not a skip"
16093 )
16094 });
16095 assert_eq!(stream.len(), fixture_len, "{name}: fixture length moved");
16096 assert_eq!(fnv1a64(&stream), fixture_fnv, "{name}: fixture bytes moved");
16097
16098 // --- the header facts the CELL depends on, parsed not assumed ------
16099 let mut parser = Av1Parser::new();
16100 let mut pos = 0usize;
16101 let mut seq = None;
16102 let mut heads: Vec<FrameHeader> = Vec::new();
16103 while pos < stream.len() {
16104 let parsed = parser
16105 .parse_obu(&stream[pos..])
16106 .unwrap_or_else(|e| panic!("{name}: aomenc OBU does not parse: {e:?}"));
16107 if parsed.total_size == 0 {
16108 break;
16109 }
16110 pos += parsed.total_size;
16111 match parsed.kind {
16112 ObuKind::SequenceHeader(s) => seq = Some(s),
16113 ObuKind::FrameHeader(h) => heads.push(*h),
16114 ObuKind::Frame(h, _) => heads.push(*h),
16115 _ => {}
16116 }
16117 }
16118 let seq = seq.unwrap_or_else(|| panic!("{name}: the stream carries no sequence header"));
16119 assert_eq!(
16120 (
16121 seq.color_config.subsampling_x,
16122 seq.color_config.subsampling_y
16123 ),
16124 (0, 0),
16125 "{name}: the stream is not 4:4:4 (ss = ({}, {}))",
16126 seq.color_config.subsampling_x,
16127 seq.color_config.subsampling_y
16128 );
16129 // The high-bit-depth claim itself. A `--bit-depth` flag that silently
16130 // did not take effect still produces a decodable 4:4:4 superres
16131 // stream -- at 8 bits -- and every other assertion below would pass.
16132 assert_eq!(
16133 seq.color_config.bit_depth, bit_depth,
16134 "{name}: the sequence header parses bit_depth {}, not the {bit_depth} this gate \
16135 names -- the encoder flags did not take effect and this is a different cell",
16136 seq.color_config.bit_depth
16137 );
16138 assert!(
16139 seq.enable_superres,
16140 "{name}: the sequence header does not enable superres at all"
16141 );
16142 assert_eq!(
16143 heads.len(),
16144 per_frame.len(),
16145 "{name}: {} frame headers, expected {}",
16146 heads.len(),
16147 per_frame.len()
16148 );
16149 for (i, (h, (denom, coded))) in heads.iter().zip(per_frame).enumerate() {
16150 assert!(
16151 h.use_superres,
16152 "{name}: frame {i} has use_superres = false -- this is an UNSCALED stream and \
16153 the gate would measure something other than the cell it names (class \
16154 gate-blind-to-feature)"
16155 );
16156 assert_eq!(
16157 h.superres_denom, *denom,
16158 "{name}: frame {i} PARSED denominator moved from {denom} -- read the header, \
16159 never the encoder flag (mode 2 chooses its own)"
16160 );
16161 assert_eq!(
16162 (h.upscaled_width as usize, h.frame_height as usize),
16163 upscaled,
16164 "{name}: frame {i} upscaled size moved"
16165 );
16166 assert_eq!(
16167 (h.frame_width as usize, h.frame_height as usize),
16168 (*coded, upscaled.1),
16169 "{name}: frame {i} CODED size moved -- this is the scaled half of the cell and \
16170 the part an unsized stream gets wrong"
16171 );
16172 let d = u32::from(*denom);
16173 assert_eq!(
16174 (h.upscaled_width * 8 + d / 2) / d,
16175 h.frame_width,
16176 "{name}: frame {i}: FrameWidth is not (UpscaledWidth*8 + denom/2)/denom -- the \
16177 scaled size the cell rests on is not the spec's"
16178 );
16179 }
16180
16181 // --- the pixels -----------------------------------------------------
16182 let _guard = lock_gate_counters();
16183 let before_sr = crate::superres::superres_hits();
16184 let before_scaled = crate::mc::predict_scaled_hits();
16185 let frames = decode_stream(&stream).unwrap_or_else(|e| {
16186 panic!("{name}: the pinned {bit_depth}-bit 4:4:4 superres stream was refused: {e}")
16187 });
16188 let scaled_up = crate::superres::superres_hits() - before_sr;
16189 let scaled_mc = crate::mc::predict_scaled_hits() - before_scaled;
16190 assert!(
16191 scaled_up > 0,
16192 "{name}: zero superres_hits -- the upscaler never ran (class gate-blind-to-feature)"
16193 );
16194 assert!(
16195 scaled_mc > 0,
16196 "{name}: zero predict_scaled_hits -- no inter block read a scaled reference, so the \
16197 scaled-PREDICTION half of the cell is unexercised (class gate-blind-to-feature)"
16198 );
16199 assert_eq!(frames.len(), per_frame.len(), "{name}: decoded frame count");
16200 let max = (1u32 << bit_depth) - 1;
16201 for (i, f) in frames.iter().enumerate() {
16202 assert_eq!(
16203 (f.width, f.height),
16204 upscaled,
16205 "{name}: frame {i} came back {}x{}, not the UPSCALED {}x{}",
16206 f.width,
16207 f.height,
16208 upscaled.0,
16209 upscaled.1
16210 );
16211 for (plane, samples) in [("Y", &f.y), ("U", &f.u), ("V", &f.v)] {
16212 assert_eq!(
16213 samples.len(),
16214 upscaled.0 * upscaled.1,
16215 "{name}: frame {i} {plane} plane is {} samples; at 4:4:4 upscaled it must be \
16216 full resolution ({}x{})",
16217 samples.len(),
16218 upscaled.0,
16219 upscaled.1
16220 );
16221 // The depth claim, on the pixels: a decoder that lost the
16222 // high bits (or produced 8-bit values padded into a u16
16223 // plane) would satisfy every length and geometry assert above
16224 // and only be caught here.
16225 assert!(
16226 samples.iter().all(|&s| u32::from(s) <= max),
16227 "{name}: frame {i} {plane} carries a sample above the {bit_depth}-bit \
16228 maximum {max} -- the bit depth of the OUTPUT does not match the header"
16229 );
16230 }
16231 }
16232 if aomdec_available(name) {
16233 let (decoded, hidden) = decode_all_frames_vs_oracle(&stream, name);
16234 eprintln!(
16235 "{name}: {decoded} decode-order frame(s) ({hidden} hidden) byte-exact vs aomdec \
16236 at {bit_depth}-bit {upscaled:?} upscaled from {per_frame:?} (denominator, coded \
16237 width) per frame, {scaled_up} upscale(s), {scaled_mc} scaled MC block(s); \
16238 fixture sha256 {fixture_sha}"
16239 );
16240 }
16241 heads
16242 }
16243
16244 /// lane-av1superhbd (1): 4:4:4 superres at **10 bits**, `--superres-mode=1
16245 /// --superres-denominator=12` on all four frames -- coded 171x128 upscaled
16246 /// to 256x128 at `denom = 12`.
16247 ///
16248 /// **What it closes.** Every superres fixture the crate carried parsed
16249 /// `bit_depth = 8` (4:2:0 `superres_kf_cdef_lr_64x64.obu`) or was 4:2:0
16250 /// (`superres_alltools_sb128_320x180.obu`), and the 4:4:4 superres cells
16251 /// were 8-bit. The chroma-format sweep's not-measured list kept "4:4:4
16252 /// superres at 10/12 bits" open on that basis. This arm is the 10-bit
16253 /// measurement: a 4:4:4 chroma plane upscaled at FULL resolution, where
16254 /// the upscaler and the scaled inter predictor both run with a
16255 /// 10-bit sample width and the 4:4:4 chroma gather has no subsampling
16256 /// halving to hide behind.
16257 ///
16258 /// **The recipe** (sha256
16259 /// `95b49d7aa81843399ee3aa64bdadfec8f4037bcc3f861923c9b2da3bc868b223`,
16260 /// 15803 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p10le):
16261 /// ```text
16262 /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \
16263 /// -pix_fmt yuv444p10le -strict -1 -f yuv4mpegpipe - | \
16264 /// aomenc --codec=av1 --profile=1 --bit-depth=10 --input-bit-depth=10 \
16265 /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \
16266 /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \
16267 /// --superres-mode=1 --superres-denominator=12 \
16268 /// --superres-kf-denominator=12 --obu -o - -
16269 /// ```
16270 /// `-strict -1` is load-bearing: without it ffmpeg refuses to write
16271 /// `yuv444p10le` into a y4m pipe at all (zero bytes out).
16272 #[test]
16273 fn a_444_lossy_superres_10bit_d12_stream_decodes_pixel_exact() {
16274 a_444_hbd_superres_arm(
16275 "a_444_lossy_superres_10bit_d12_stream_decodes_pixel_exact",
16276 "fixtures/444_lossy_superres_256x128_d12_10bit.obu",
16277 15803,
16278 0x9fad_3227_6e91_792c,
16279 "95b49d7aa81843399ee3aa64bdadfec8f4037bcc3f861923c9b2da3bc868b223",
16280 10,
16281 (256, 128),
16282 &[(12, 171); 4],
16283 );
16284 }
16285
16286 /// lane-av1superhbd (2): 4:4:4 superres at **12 bits**,
16287 /// `--superres-mode=1 --superres-denominator=12`, coded 171x128 upscaled
16288 /// to 256x128.
16289 ///
16290 /// **Why the source is `mandelbrot` and not `testsrc2`.** The 12-bit
16291 /// frame gate refuses a frame carrying `allow_screen_content_tools = 1`
16292 /// by name (palette and intrabc have no 12-bit witness). libaom sets
16293 /// that bit from its own content detection
16294 /// (`av1_set_screen_content_options` -> `encoder_utils.c:1153`, keyed on
16295 /// the palette-pixel ratio of the FIRST pass), and `testsrc2` -- flat
16296 /// colour bars and hard edges -- trips it at 12 bits while the very same
16297 /// recipe at 10 bits does not. `--enable-palette=0 --enable-intrabc=0`
16298 /// and `--tune-content=film` do NOT suppress it (measured: all four
16299 /// still parse `allow_screen_content_tools = true`), because the
16300 /// detection is a property of the CONTENT, not of those flags. A
16301 /// photographic source (`mandelbrot`, same geometry and frame count)
16302 /// parses `allow_screen_content_tools = false` and decodes. This is a
16303 /// source choice, stated so the next lane does not re-derive it.
16304 ///
16305 /// **The recipe** (sha256
16306 /// `973bf374c0185c4e6301509ce834cef01318e6cdb9488fd258118d7ec89bdd04`,
16307 /// 11023 bytes, 4 frames, `mandelbrot 256x128 rate=25` yuv444p12le):
16308 /// ```text
16309 /// ffmpeg -f lavfi -i "mandelbrot=size=256x128:rate=25" -frames:v 4 \
16310 /// -pix_fmt yuv444p12le -strict -1 -f yuv4mpegpipe - | \
16311 /// aomenc --codec=av1 --profile=1 --bit-depth=12 --input-bit-depth=12 \
16312 /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \
16313 /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \
16314 /// --superres-mode=1 --superres-denominator=12 \
16315 /// --superres-kf-denominator=12 --obu -o - -
16316 /// ```
16317 /// Byte-reproducible: two independent encodes produced the same 11023
16318 /// bytes.
16319 #[test]
16320 fn a_444_lossy_superres_12bit_d12_stream_decodes_pixel_exact() {
16321 a_444_hbd_superres_arm(
16322 "a_444_lossy_superres_12bit_d12_stream_decodes_pixel_exact",
16323 "fixtures/444_lossy_superres_256x128_d12_12bit.obu",
16324 11023,
16325 0xd6cf_bb83_2b42_8e2d,
16326 "973bf374c0185c4e6301509ce834cef01318e6cdb9488fd258118d7ec89bdd04",
16327 12,
16328 (256, 128),
16329 &[(12, 171); 4],
16330 );
16331 }
16332
16333 /// lane-av1superhbd (3): 4:4:4 superres at **12 bits** at the WIDEST
16334 /// denominator this geometry allows, `--superres-denominator=9` -- coded
16335 /// 228x128 upscaled to 256x128, so 28 of the 256 columns are the frame's
16336 /// right-edge upscale margin, against 12's 85.
16337 ///
16338 /// It is a separate gate from the den=12 arm because the margin is
16339 /// where a round-trip is most likely to read past the coded picture: a
16340 /// decoder that sized the upscale source from `UpscaledWidth` instead of
16341 /// `FrameWidth` is exact at den=12 on this content and wrong here. Its
16342 /// recipe is the 12-bit one above with `--superres-denominator=9
16343 /// --superres-kf-denominator=9` (sha256
16344 /// `898c775108495b998cb5ec9b08e194d4656ed0140aa8e7e7236892d468bbad99`,
16345 /// 13015 bytes).
16346 #[test]
16347 fn a_444_lossy_superres_12bit_d9_stream_decodes_pixel_exact() {
16348 a_444_hbd_superres_arm(
16349 "a_444_lossy_superres_12bit_d9_stream_decodes_pixel_exact",
16350 "fixtures/444_lossy_superres_256x128_d9_12bit.obu",
16351 13015,
16352 0x4110_ce7b_cd85_901b,
16353 "898c775108495b998cb5ec9b08e194d4656ed0140aa8e7e7236892d468bbad99",
16354 12,
16355 (256, 128),
16356 &[(9, 228); 4],
16357 );
16358 }
16359
16360 /// lane-av1superhbd (4): 4:4:4 superres at **10 bits** under
16361 /// `--superres-mode=2` -- the random-denominator arm, where libaom picks
16362 /// a DIFFERENT denominator for every frame and IGNORES
16363 /// `--superres-denominator` entirely.
16364 ///
16365 /// This is what keeps the high-bit-depth superres cell from silently
16366 /// degenerating into a single-denominator cell: the per-frame parsed
16367 /// denominators are 11, 14, 15, 9 -- three of them values no flag on the
16368 /// command line ever named -- so a gate that read the flag instead of
16369 /// the header would be wrong on three of four frames. The assertion
16370 /// below makes that structural rather than incidental, and it is the
16371 /// assertion that fails if a future libaom starts honouring the flag
16372 /// under mode 2.
16373 ///
16374 /// **The recipe** (sha256
16375 /// `699398aba58fb53b80e05d3d214eb746a3c91945e01da6b47488513f20b55668`,
16376 /// 17776 bytes, 4 frames, `testsrc2 256x128 rate=25` yuv444p10le):
16377 /// ```text
16378 /// ffmpeg -f lavfi -i "testsrc2=size=256x128:rate=25" -frames:v 4 \
16379 /// -pix_fmt yuv444p10le -strict -1 -f yuv4mpegpipe - | \
16380 /// aomenc --codec=av1 --profile=1 --bit-depth=10 --input-bit-depth=10 \
16381 /// --passes=1 --end-usage=q --cq-level=20 --cpu-used=2 --threads=1 \
16382 /// --row-mt=0 --lag-in-frames=0 --kf-max-dist=100 --limit=4 \
16383 /// --superres-mode=2 --obu -o - -
16384 /// ```
16385 #[test]
16386 fn a_444_lossy_superres_10bit_mode2_random_denom_stream_decodes_pixel_exact() {
16387 const NAME: &str =
16388 "a_444_lossy_superres_10bit_mode2_random_denom_stream_decodes_pixel_exact";
16389 let heads = a_444_hbd_superres_arm(
16390 NAME,
16391 "fixtures/444_lossy_superres_mode2_256x128_10bit.obu",
16392 17776,
16393 0x164f_4099_7576_7ae4,
16394 "699398aba58fb53b80e05d3d214eb746a3c91945e01da6b47488513f20b55668",
16395 10,
16396 (256, 128),
16397 &[(11, 186), (14, 146), (15, 137), (9, 228)],
16398 );
16399 // Distinct-denominator assert: the cell must stay a MULTI-denominator
16400 // one. A libaom that collapsed mode 2 onto a single denominator (or
16401 // stopped scaling) would still decode, and the gate above would still
16402 // hold only because the literals would have been re-pinned with it --
16403 // so the property is asserted from the parsed headers directly.
16404 let denoms: Vec<u8> = heads.iter().map(|h| h.superres_denom).collect();
16405 let mut distinct = denoms.clone();
16406 distinct.sort_unstable();
16407 distinct.dedup();
16408 assert!(
16409 distinct.len() >= 3,
16410 "{NAME}: the stream carries denominators {denoms:?} -- fewer than three distinct \
16411 values, so this is no longer the per-frame-denominator cell and the pin has to be \
16412 re-derived from the stream"
16413 );
16414 let flagged = [9u8, 12, 16];
16415 assert!(
16416 denoms.iter().any(|d| !flagged.contains(d)),
16417 "{NAME}: every parsed denominator is one of the flag values {flagged:?} -- mode 2 now \
16418 appears to honour --superres-denominator, and this cell stops being the \
16419 flag-ignoring one"
16420 );
16421 }
16422
16423 /// lane-av1superhbd (5): 4:4:4 superres at **12 bits** under
16424 /// `--superres-mode=2` -- the high-bit-depth random-denominator arm, the
16425 /// 12-bit twin of the arm above (sha256
16426 /// `18aa8b3124ab10672f22577a8eea81e44141a3d0bb506104aee2f950254a2e9f`,
16427 /// 14656 bytes, same `mandelbrot` source as the 12-bit fixed-denominator
16428 /// arms). Its parsed denominators are again 11/14/15/9 at coded widths
16429 /// 186/146/137/228, so the upscaler is handed FOUR coded-to-upscaled
16430 /// ratios in one 12-bit decode -- the case a single-denominator gate
16431 /// cannot reach at any bit depth.
16432 #[test]
16433 fn a_444_lossy_superres_12bit_mode2_random_denom_stream_decodes_pixel_exact() {
16434 const NAME: &str =
16435 "a_444_lossy_superres_12bit_mode2_random_denom_stream_decodes_pixel_exact";
16436 let heads = a_444_hbd_superres_arm(
16437 NAME,
16438 "fixtures/444_lossy_superres_mode2_256x128_12bit.obu",
16439 14656,
16440 0xef38_3fb7_b284_2166,
16441 "18aa8b3124ab10672f22577a8eea81e44141a3d0bb506104aee2f950254a2e9f",
16442 12,
16443 (256, 128),
16444 &[(11, 186), (14, 146), (15, 137), (9, 228)],
16445 );
16446 let denoms: Vec<u8> = heads.iter().map(|h| h.superres_denom).collect();
16447 let mut distinct = denoms.clone();
16448 distinct.sort_unstable();
16449 distinct.dedup();
16450 assert!(
16451 distinct.len() >= 3,
16452 "{NAME}: the stream carries denominators {denoms:?} -- fewer than three distinct \
16453 values, so this is no longer the per-frame-denominator cell and the pin has to be \
16454 re-derived from the stream"
16455 );
16456 let flagged = [9u8, 12, 16];
16457 assert!(
16458 denoms.iter().any(|d| !flagged.contains(d)),
16459 "{NAME}: every parsed denominator is one of the flag values {flagged:?} -- mode 2 now \
16460 appears to honour --superres-denominator, and this cell stops being the \
16461 flag-ignoring one"
16462 );
16463 }
16464
16465 /// lane-filt1: `EC_AV1_FILTER_THREADS` splits every in-frame filter stage
16466 /// -- deblock (row bands for the vertical-edge pass, column bands for the
16467 /// horizontal one), CDEF (mi row bands), loop restoration (RU row bands)
16468 /// and film grain (32-pixel block rows) -- across scoped worker threads.
16469 /// A split is only legal if it is BYTE-EXACT, so this gate decodes two
16470 /// real aomenc streams at 1 and at 4 filter threads and compares every
16471 /// output frame's three planes.
16472 ///
16473 /// Between them the fixtures fire all four stages, and the firing
16474 /// counters are asserted rather than assumed (class `gate-blind-to-feature`):
16475 /// `superres_alltools_sb128_320x180.obu` is the 10-bit CDEF + loop
16476 /// restoration stream, `grain_cdef_lr_128x128.obu` a 128x128
16477 /// `--denoise-noise-level=25` stream whose frames carry film grain
16478 /// parameters (small enough that 4 bands is one block row each, which is
16479 /// what exercises the grain band's one-row `prelude` replay).
16480 /// lane-wave1 step (ii): the superblock-row wavefront
16481 /// (`EC_AV1_RECON_THREADS`) reconstructs every output frame byte for
16482 /// byte as the inline path does, on a hidden-ARF 10-bit stream (no-show
16483 /// frames, CfL, 128 superblocks) and on the two screen-content streams
16484 /// whose palette/intrabc blocks READ the current frame's pixels while
16485 /// parsing -- the sites that make the workers barrier.
16486 #[test]
16487 fn a_real_stream_reconstructs_identically_with_one_and_four_recon_threads() {
16488 const NAME: &str = "a_real_stream_reconstructs_identically_with_one_and_four_recon_threads";
16489 let _gate_lock = lock_gate_counters();
16490 for fixture in [
16491 "reelb_arf_witness.obu",
16492 "palette_screen_witness.obu",
16493 "palette_screen_witness_10bit.obu",
16494 // lane-av1wavefront: the 4:4:4 inter witness. The wavefront's
16495 // replay-side chroma (`mv_to_q4(.., ss_x(fctx))` in the deferred
16496 // builds, `exec_intra`'s CfL AC) used to read the worker's fresh
16497 // `FrameCtx` 4:2:0 DEFAULT instead of the frame's subsampling --
16498 // invisible on the three 4:2:0 streams above, chroma-only loss on
16499 // this one (f1 U 17504 / V 3, f2 U 25472 / V 1472 at PREFILT).
16500 "444_sb128rect_lr_witness.obu",
16501 ] {
16502 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16503 .join("fixtures")
16504 .join(fixture);
16505 let stream = std::fs::read(&path)
16506 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
16507 crate::par::set_recon_threads(1);
16508 let one = match decode_stream(&stream) {
16509 Ok(frames) => frames,
16510 Err(e) => panic!("{NAME}: {fixture} refused at 1 recon thread: {e}"),
16511 };
16512 crate::par::set_recon_threads(4);
16513 let four = match decode_stream(&stream) {
16514 Ok(frames) => frames,
16515 Err(e) => {
16516 crate::par::set_recon_threads(1);
16517 panic!("{NAME}: {fixture} refused at 4 recon threads: {e}")
16518 }
16519 };
16520 crate::par::set_recon_threads(1);
16521 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
16522 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
16523 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
16524 assert_eq!(
16525 a.y, b.y,
16526 "{NAME}: {fixture} frame {i} luma differs at 4 recon threads"
16527 );
16528 assert_eq!(
16529 a.u, b.u,
16530 "{NAME}: {fixture} frame {i} U differs at 4 recon threads"
16531 );
16532 assert_eq!(
16533 a.v, b.v,
16534 "{NAME}: {fixture} frame {i} V differs at 4 recon threads"
16535 );
16536 }
16537 }
16538 }
16539
16540 /// lane-memfix: the pool grows to the peak of `busy + queued` over the
16541 /// job tree and stops there. Before, a job running on a pool worker
16542 /// opened a SECOND pool on that worker's own thread-local -- one level
16543 /// per pipeline stage, none of them ever shrinking -- which is how a 4K
16544 /// decode at `(16, 4, 2)` reached 1038 live threads. Two decodes of the
16545 /// same stream: the count stays inside the composed setting and the
16546 /// second decode adds nothing (the ratchet is what cost the memory).
16547 #[test]
16548 fn the_worker_pool_stays_bounded_across_repeated_threaded_decodes() {
16549 const NAME: &str = "the_worker_pool_stays_bounded_across_repeated_threaded_decodes";
16550 let _gate_lock = lock_gate_counters();
16551 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16552 .join("fixtures")
16553 .join("superres_alltools_sb128_320x180.obu");
16554 let stream = std::fs::read(&path)
16555 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
16556 crate::par::set_filter_threads(4);
16557 crate::par::set_recon_threads(2);
16558 let mut counts = [0usize; 2];
16559 let mut frames = [0usize; 2];
16560 for (i, slot) in counts.iter_mut().enumerate() {
16561 let mut n = 0usize;
16562 let r = decode_stream_with_threads(&stream, 4, |_, _, _| {
16563 n += 1;
16564 Ok(())
16565 });
16566 if let Err(e) = r {
16567 crate::par::set_filter_threads(1);
16568 crate::par::set_recon_threads(1);
16569 panic!("{NAME}: refused on decode {i}: {e}");
16570 }
16571 frames[i] = n;
16572 *slot = crate::par::pool_threads();
16573 }
16574 crate::par::set_filter_threads(1);
16575 crate::par::set_recon_threads(1);
16576 assert!(
16577 frames[0] > 1,
16578 "{NAME}: the fixture decoded {} frames, so nothing was threaded",
16579 frames[0]
16580 );
16581 // 4 frame workers x (recon 2 + filter 4) plus the two in-flight
16582 // slots `stream.rs` allows over the thread count, with room for the
16583 // show jobs -- 1038 was three orders past this.
16584 assert!(
16585 counts[1] <= 4 * (2 + 4) + 2 * 4,
16586 "{NAME}: the pool grew to {} threads at 4 frame / 4 filter / 2 recon",
16587 counts[1]
16588 );
16589 // The pool grows to `busy + queued`, so a loaded box can queue one
16590 // more job than an idle one did (seen: 9 -> 10 at load 62). The
16591 // bound above is the structural claim; here only a runaway counts.
16592 assert!(
16593 counts[1] <= counts[0] + 4,
16594 "{NAME}: a second decode of the same stream grew the pool from {} to {} threads",
16595 counts[0],
16596 counts[1]
16597 );
16598 }
16599
16600 #[test]
16601 fn a_real_stream_filters_identically_with_one_and_four_filter_threads() {
16602 const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads";
16603 let _gate_lock = lock_gate_counters();
16604 for (fixture, wants_lr, wants_grain) in [
16605 ("superres_alltools_sb128_320x180.obu", true, false),
16606 ("grain_cdef_lr_128x128.obu", false, true),
16607 ] {
16608 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16609 .join("fixtures")
16610 .join(fixture);
16611 let stream = std::fs::read(&path)
16612 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
16613 let before = (
16614 crate::decode::deblock_hits(),
16615 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
16616 crate::film_grain::grain_hits(),
16617 );
16618 crate::par::set_filter_threads(1);
16619 let one = match decode_stream(&stream) {
16620 Ok(frames) => frames,
16621 Err(e) => panic!("{NAME}: {fixture} refused at 1 filter thread: {e}"),
16622 };
16623 let after = (
16624 crate::decode::deblock_hits(),
16625 crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(),
16626 crate::film_grain::grain_hits(),
16627 );
16628 crate::par::set_filter_threads(4);
16629 let four = match decode_stream(&stream) {
16630 Ok(frames) => frames,
16631 Err(e) => {
16632 crate::par::set_filter_threads(1);
16633 panic!("{NAME}: {fixture} refused at 4 filter threads: {e}")
16634 }
16635 };
16636 crate::par::set_filter_threads(1);
16637 assert!(
16638 after.0 > before.0,
16639 "{NAME}: {fixture} deblocked no edge at all"
16640 );
16641 if wants_lr {
16642 assert!(
16643 after.1 > before.1,
16644 "{NAME}: {fixture} ran no restoration unit"
16645 );
16646 }
16647 if wants_grain {
16648 assert!(
16649 after.2 > before.2,
16650 "{NAME}: {fixture} applied no film grain"
16651 );
16652 }
16653 assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count");
16654 assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing");
16655 for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() {
16656 assert_eq!(
16657 a.y, b.y,
16658 "{NAME}: {fixture} frame {i} luma differs at 4 filter threads"
16659 );
16660 assert_eq!(
16661 a.u, b.u,
16662 "{NAME}: {fixture} frame {i} U differs at 4 filter threads"
16663 );
16664 assert_eq!(
16665 a.v, b.v,
16666 "{NAME}: {fixture} frame {i} V differs at 4 filter threads"
16667 );
16668 }
16669 }
16670 }
16671
16672 /// lane-t900 r30b: `fixtures/superres_alltools_sb128_320x180.obu` is 10
16673 /// frames of `--cpu-used=4 --sb-size=128 --superres-mode=1
16674 /// --superres-denominator=12 --cq-level=32` with every tool aomenc turns
16675 /// on by default (CDEF, loop restoration, OBMC, compound, warp) -- the
16676 /// first stream here that deblocks CHROMA across a group of 4x4 luma
16677 /// blocks.
16678 ///
16679 /// The defect it pins (fixed at this commit, `decode.rs`'s
16680 /// `plane_to_mi`/`edge_params`): `set_lpf_parameters`
16681 /// (`av1_loopfilter.c:245`) indexes the mi grid for a CHROMA edge at
16682 /// `scale | ((coord << scale) >> MI_SIZE_LOG2)` -- the BOTTOM/RIGHT mi of
16683 /// the co-located 8x8 luma group, the same cell that donates the group's
16684 /// chroma prediction. This decoder dropped that `| 1` and read the
16685 /// group's top-left mi, stepped to the previous cell by one mi instead of
16686 /// `1 << ss`, and priced `pu_edge` by comparing mi origins rather than
16687 /// the edge coordinate against the block size in the FILTERED plane's own
16688 /// pixels (chroma bottoms out at 4). All three are invisible while every
16689 /// block is 8x8 or larger (all four mi of a group carry the same tx size,
16690 /// ref frame, skip flag and delta_lf) and wrong the moment cpu-used=4
16691 /// splits a group into 4x4 blocks: on this stream one U sample of frame 2
16692 /// took a filter level of 12 where libaom's neighbouring 4x4 block gives
16693 /// 8, and the error compounded through the reference chain to 280 U + 331
16694 /// V samples (max 9) by frame 9. Class `context-read-from-one-cell`.
16695 ///
16696 /// Post-deblock, this stream is now byte-exact against the instrumented
16697 /// libaom (`EC_AV1_POSTDEBLOCK_DUMP`) in all 10 frames, and the final
16698 /// output matches ffmpeg's.
16699 #[test]
16700 fn a_superres_all_tools_sb128_stream_decodes_pixel_exact() {
16701 const NAME: &str = "a_superres_all_tools_sb128_stream_decodes_pixel_exact";
16702 let _gate_lock = lock_gate_counters();
16703 if !have_ffmpeg() {
16704 eprintln!("SKIP {NAME}: no ffmpeg");
16705 return;
16706 }
16707 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16708 .join("fixtures/superres_alltools_sb128_320x180.obu");
16709 let stream = std::fs::read(&path)
16710 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
16711 let (width, height, count) = (320usize, 180usize, 10usize);
16712 let frames = match decode_stream(&stream) {
16713 Ok(frames) => frames,
16714 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
16715 };
16716 assert_eq!(frames.len(), count, "{NAME}: frame count");
16717 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, count);
16718 for (i, (ours, theirs)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
16719 assert_eq!(ours.y, theirs.y, "{NAME}: frame {i} luma vs ffmpeg");
16720 assert_eq!(ours.u, theirs.u, "{NAME}: frame {i} U vs ffmpeg");
16721 assert_eq!(ours.v, theirs.v, "{NAME}: frame {i} V vs ffmpeg");
16722 }
16723 }
16724
16725 /// lane-golomb r1: THE FILM ITSELF. `crates/ec-av1/fixtures/reelb_head_key_frame.obu`
16726 /// is the first frame of the user's ReelB AV1 release (3840x1608
16727 /// yuv420p10le, `ffmpeg -i <mkv> -c copy -frames:v 1 -f obu`, 147 bytes) --
16728 /// a real 10-bit key frame whose height is NOT a multiple of the 64-pixel
16729 /// superblock, so its last superblock row (mi_row=400 of 402) carries the
16730 /// edge partition symbol this lane fixed: libaom's `ec_read_partition_impl`
16731 /// returns `PARTITION_HORZ` when the gathered `split_or_horz` bit is 0, and
16732 /// this decoder used to READ that bit and throw it away, forcing SPLIT
16733 /// (class `parsed-then-discarded`). The desync surfaced two rows later as
16734 /// "a Golomb tail longer than this decoder reads" -- a refusal naming the
16735 /// symptom, never the cause.
16736 #[test]
16737 fn the_reelb_head_key_frame_decodes_pixel_exact() {
16738 const NAME: &str = "the_reelb_head_key_frame_decodes_pixel_exact";
16739 if !have_ffmpeg() {
16740 eprintln!("SKIP {NAME}: no ffmpeg");
16741 return;
16742 }
16743 let path =
16744 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_head_key_frame.obu");
16745 let stream = std::fs::read(&path)
16746 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
16747 let (width, height) = (3840usize, 1608usize);
16748 let frames = match decode_stream(&stream) {
16749 Ok(frames) => frames,
16750 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
16751 };
16752 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
16753 assert_eq!((frames[0].width, frames[0].height), (width, height));
16754 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
16755 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
16756 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
16757 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
16758 }
16759 /// lane-reelckf r2: `crates/ec-av1/fixtures/reelc_kf2700.obu` is a 1920x792
16760 /// 10-bit AV1 key frame taken out of one of the user's own films
16761 /// (`ffmpeg -ss 2700 -c:v copy -f obu`, then truncated to its first temporal
16762 /// unit, 36 kB) -- the ONLY stream in this repo that contains a SKIPPED
16763 /// `UV_CFL_PRED` block. 30 aomenc recipes (r1's 20 plus r2's chroma-correlated
16764 /// `geq` sweep, cq 40..63, cpu-used 0..2, min/max-partition 4..64, 8 and
16765 /// 10 bit) never made the encoder pick one, so the counter can only be
16766 /// hard-asserted against a real film frame. The instrumented oracle agrees:
16767 /// `EC_TRACE_MODE=1 aomdec` prints 5 `EC_IMODE_VAL ... uv_mode=13 skip=1`
16768 /// lines for this frame.
16769 ///
16770 /// The defect it pins (fixed at 29cd53f, `decode.rs:7719`/`:10528`/`:10891`):
16771 /// a skipped intra block must still PREDICT with CfL -- libaom's
16772 /// `predict_and_reconstruct_intra_block` predicts every plane and guards only
16773 /// the residual on `skip_txfm`. Before the fix this frame had 499 wrong
16774 /// chroma samples (U rows 48..79 cols 464..492); after it, zero.
16775 ///
16776 /// The ffmpeg reference is `ffmpeg -f obu -i <fixture> -f rawvideo
16777 /// -pix_fmt yuv420p10le -` (what `ffmpeg_decode_sequence_10bit` runs).
16778 #[test]
16779 fn a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact() {
16780 const NAME: &str = "a_real_film_key_frame_with_a_skipped_cfl_block_decodes_pixel_exact";
16781 let path =
16782 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelc_kf2700.obu");
16783 let stream = std::fs::read(&path)
16784 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
16785 let (width, height) = (1920usize, 792usize);
16786 let before = crate::decode::reelc_chroma_counters();
16787 let frames = match decode_stream(&stream) {
16788 Ok(frames) => frames,
16789 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
16790 };
16791 let after = crate::decode::reelc_chroma_counters();
16792 let skip_cfl = after.0 - before.0;
16793 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
16794 assert_eq!((frames[0].width, frames[0].height), (width, height));
16795 // Asserted before the ffmpeg compare so an absent ffmpeg cannot make the
16796 // gate vacuous: the skipped-CfL path is exercised on every run.
16797 assert!(
16798 skip_cfl > 0,
16799 "{NAME}: zero skipped-CfL blocks -- the fixture no longer exercises defect 1"
16800 );
16801 if !have_ffmpeg() {
16802 eprintln!("SKIP {NAME} pixel compare: no ffmpeg (skipped_cfl={skip_cfl})");
16803 return;
16804 }
16805 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
16806 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
16807 assert_eq!(
16808 frames[0].u, ffmpeg_frames[0].u,
16809 "{NAME}: U vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
16810 );
16811 assert_eq!(
16812 frames[0].v, ffmpeg_frames[0].v,
16813 "{NAME}: V vs ffmpeg ({skip_cfl} skipped-CfL blocks)"
16814 );
16815 eprintln!("{NAME}: pixel-exact, skipped_cfl={skip_cfl}");
16816 }
16817
16818 /// lane-kf1200 r2: the same film's `-ss 300` key frame, pinned because no
16819 /// aomenc recipe reaches its shape -- a SKIPPED sub-8x8 chroma block whose
16820 /// `uv_mode` is `UV_CFL_PRED`. (lane-reelckf r1 burned 20 recipes across cq
16821 /// 40..63 and nine lavfi sources hunting exactly this block and never got
16822 /// one; ledger dead-end "never produced a SKIPPED 1:4 or sub-8x8 CfL
16823 /// block".) Before the fix the two sub-8x8 skip arms passed `None` for the
16824 /// CfL argument, so the block reconstructed as flat DC and 463 bytes of
16825 /// this frame's chroma were wrong. HARD-asserts `skip_cfl_hits` moved, so
16826 /// the fixture cannot silently stop exercising the arm.
16827 #[test]
16828 fn the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact() {
16829 const NAME: &str = "the_reelb_ss300_key_frame_skipped_cfl_decodes_pixel_exact";
16830 if !have_ffmpeg() {
16831 eprintln!("SKIP {NAME}: no ffmpeg");
16832 return;
16833 }
16834 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16835 .join("fixtures/reelb_ss300_key_frame.obu");
16836 let stream = std::fs::read(&path)
16837 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
16838 let (width, height) = (3840usize, 1608usize);
16839 let before = crate::decode::skip_cfl_hits();
16840 let frames = match decode_stream(&stream) {
16841 Ok(frames) => frames,
16842 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
16843 };
16844 let skipped_cfl = crate::decode::skip_cfl_hits() - before;
16845 assert!(
16846 skipped_cfl > 0,
16847 "{NAME}: zero skipped sub-8x8 CfL blocks -- the fixture no longer \
16848 exercises the arm this test exists for"
16849 );
16850 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
16851 assert_eq!((frames[0].width, frames[0].height), (width, height));
16852 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
16853 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
16854 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
16855 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
16856 eprintln!("{NAME}: {skipped_cfl} skipped sub-8x8 CfL chroma blocks, frame pixel-exact");
16857 }
16858
16859 /// lane-kf900 r2: the film's key frame at -ss 900, one frame
16860 /// (`crates/ec-av1/fixtures/reelb_kf900.obu`, 484640 bytes, sha256
16861 /// `a273ae99328388be14a1ff8fa1c5a6d391a9948159eaef120e1b50e02015eb83`,
16862 /// extracted twice from independent
16863 /// `ffmpeg -ss 900 -t 2 -i <2160p AV1 HDR10 mkv> -c:v copy -f obu` runs and
16864 /// truncated to the first frame; both extracts hashed identically).
16865 ///
16866 /// This is the ONLY stream that reaches the r1 defect: a SKIPPED 8x8 intra
16867 /// leaf whose `tx_depth` symbol resolved to `TX_4X4` still publishes 4 --
16868 /// not its 8-pixel block side -- to the next block's `get_tx_size_context`
16869 /// (`set_txfm_ctxs(mbmi->tx_size, bw, bh, skip_txfm && is_inter_block(...))`,
16870 /// `decodemv.c`; the skip term is 0 for intra). It fires 15 times here and
16871 /// zero times across 108 measured aomenc recipes, so the counter is
16872 /// asserted against the film rather than against a synthesised stream.
16873 ///
16874 /// LUMA only. U/V still differ (open residue, lane-kf900 r2: 221 U and
16875 /// 47912 V samples, max |d| 23/2, first at chroma (195, 640) -- chroma
16876 /// RESIDUAL, the prediction there is bit-exact against aomdec's
16877 /// `EC_PREDOUT`), so this gate pins what is proven and no more.
16878 #[test]
16879 fn a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact()
16880 {
16881 const NAME: &str = "a_10bit_key_frame_with_skipped_8x8_intra_leaves_that_split_their_transform_decodes_luma_exact";
16882 if !have_ffmpeg() {
16883 eprintln!("SKIP {NAME}: no ffmpeg");
16884 return;
16885 }
16886 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/reelb_kf900.obu");
16887 let stream = std::fs::read(&path)
16888 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
16889 let (width, height) = (3840usize, 1608usize);
16890 crate::decode::reset_skip_split_tx_hits();
16891 let frames = match decode_stream(&stream) {
16892 Ok(frames) => frames,
16893 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
16894 };
16895 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
16896 assert_eq!((frames[0].width, frames[0].height), (width, height));
16897 assert!(
16898 crate::decode::skip_split_tx_hits() >= 15,
16899 "{NAME}: skip_split_tx_hits() == {} -- the stream that carries the tx-context \
16900 defect stopped carrying it, so this gate proves nothing",
16901 crate::decode::skip_split_tx_hits()
16902 );
16903 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
16904 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
16905 }
16906
16907 /// lane-kf1200 r3: the same film's `-ss 600` key frame (3840x1608, one
16908 /// 8-px partial bottom superblock row), pinned because no aomenc recipe
16909 /// reaches its shape -- a SKIPPED 8x8 intra leaf whose `tx_depth` resolved
16910 /// to TX_4X4. (80 recipes swept this round: 4 frame shapes x 2 sources x
16911 /// cq 32..63 x cpu-used 0/3 x 8/10-bit, all with
16912 /// `--enable-tx-size-search=1 --enable-filter-intra=1`; every one came
16913 /// back with `skip_split_tx_hits == 0`, `lanes/kf1200-r3.report.md`.)
16914 /// An intra block reads `tx_depth` whether or not it is skipped, so the
16915 /// leaf must record its resolved 4 -- not its 8x8 side -- in the txfm
16916 /// context; recording 8 gave the NEXT block's `tx_depth` symbol the wrong
16917 /// `tx_size_cdf` row (ctx 2 where libaom reads 1) and desynced the
16918 /// entropy stream at mi (400,46). HARD-asserts `skip_split_tx_hits` moved.
16919 #[test]
16920 fn the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact() {
16921 const NAME: &str = "the_reelb_ss600_key_frame_skipped_split_tx_decodes_pixel_exact";
16922 if !have_ffmpeg() {
16923 eprintln!("SKIP {NAME}: no ffmpeg");
16924 return;
16925 }
16926 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16927 .join("fixtures/reelb_ss600_key_frame.obu");
16928 let stream = std::fs::read(&path)
16929 .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display()));
16930 let (width, height) = (3840usize, 1608usize);
16931 crate::decode::reset_skip_split_tx_hits();
16932 let frames = match decode_stream(&stream) {
16933 Ok(frames) => frames,
16934 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
16935 };
16936 let skipped_split_tx = crate::decode::skip_split_tx_hits();
16937 assert!(
16938 skipped_split_tx > 0,
16939 "{NAME}: zero skipped 8x8 leaves with a split transform -- the fixture no longer \
16940 exercises the arm this test exists for"
16941 );
16942 assert_eq!(frames.len(), 1, "{NAME}: one key frame");
16943 assert_eq!((frames[0].width, frames[0].height), (width, height));
16944 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
16945 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
16946 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
16947 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
16948 eprintln!("{NAME}: {skipped_split_tx} skipped 8x8 TX_4X4 leaves, frame pixel-exact");
16949 }
16950
16951 /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1
16952 /// --superres-denominator=12` key frame, decoded pixel-exact against
16953 /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s
16954 /// `clip_pixel_highbd` clamp (`(1 << bit_depth) - 1`) on real 10-bit
16955 /// planes rather than the old `bit_depth != 8` refusal. HARD-asserts
16956 /// `bit_depth == 10` and `superres_hits > 0`.
16957 #[test]
16958 fn a_real_aomenc_10bit_superres_stream_decodes_pixel_exact() {
16959 const NAME: &str = "a_real_aomenc_10bit_superres_stream_decodes_pixel_exact";
16960 if !have_ffmpeg() {
16961 eprintln!("SKIP {NAME}: no ffmpeg");
16962 return;
16963 }
16964 if !have_aomenc() {
16965 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
16966 return;
16967 }
16968 let (width, height) = (64usize, 64usize);
16969 let stream = encode_10bit_gradients(
16970 NAME,
16971 width,
16972 height,
16973 1,
16974 &[
16975 "--limit=1",
16976 "--kf-max-dist=0",
16977 "--superres-mode=1",
16978 "--superres-denominator=12",
16979 "--superres-kf-denominator=12",
16980 "--enable-rect-partitions=0",
16981 "--enable-ab-partitions=0",
16982 "--enable-1to4-partitions=0",
16983 "--enable-filter-intra=0",
16984 "--enable-smooth-intra=0",
16985 "--enable-paeth-intra=0",
16986 "--enable-directional-intra=0",
16987 "--enable-angle-delta=0",
16988 "--enable-tx-size-search=0",
16989 "--enable-cdef=0",
16990 "--enable-restoration=0",
16991 "--max-partition-size=32",
16992 "--min-partition-size=32",
16993 "--enable-palette=0",
16994 "--enable-intrabc=0",
16995 "--enable-cfl-intra=0",
16996 ],
16997 );
16998 assert_eq!(
16999 parsed_bit_depth(&stream),
17000 10,
17001 "{NAME}: aomenc did not actually write a 10-bit sequence header"
17002 );
17003 let before = crate::superres::superres_hits();
17004 let frames = match decode_stream(&stream) {
17005 Ok(frames) => frames,
17006 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
17007 };
17008 assert!(
17009 crate::superres::superres_hits() > before,
17010 "{NAME}: matched but zero superres_hits -- the upscaler never ran"
17011 );
17012 let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1);
17013 assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg");
17014 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg");
17015 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg");
17016 eprintln!(
17017 "{NAME}: pixel-exact, superres_hits={}",
17018 crate::superres::superres_hits()
17019 );
17020 }
17021
17022 /// lane-hbdgates r1: drive one 10-bit aomenc recipe over `seeds`, decode
17023 /// every attempt and pixel-compare every SHOWN frame against ffmpeg's own
17024 /// 10-bit decode of the identical bytes. Per-tool firing counters are
17025 /// sampled PER ATTEMPT and summed only over attempts that decoded *and*
17026 /// compared -- a stream that hit a named refusal contributes nothing
17027 /// (class `counter-from-refused-stream`). Named refusals are tolerated
17028 /// and reported; a pixel mismatch is a hard failure, never a SKIP.
17029 fn ten_bit_tool_gate(
17030 name: &str,
17031 width: usize,
17032 height: usize,
17033 frames: usize,
17034 extra: &[&str],
17035 seeds: &[u32],
17036 counters: &[(&str, fn() -> usize)],
17037 ) {
17038 fn first_diff(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
17039 ours.iter()
17040 .zip(theirs.iter())
17041 .position(|(a, b)| a != b)
17042 .map(|i| {
17043 format!(
17044 "first diff at index {i} (row {}, col {}): ours {} vs ffmpeg {}",
17045 i / width,
17046 i % width,
17047 ours[i],
17048 theirs[i]
17049 )
17050 })
17051 }
17052 let mut totals = vec![0usize; counters.len()];
17053 let mut refusals: Vec<String> = Vec::new();
17054 let mut compared = 0usize;
17055 for &seed in seeds {
17056 let stream = encode_10bit_gradients_seed(name, seed, width, height, frames, extra);
17057 assert_eq!(
17058 parsed_bit_depth(&stream),
17059 10,
17060 "{name}: aomenc did not write a 10-bit sequence header (seed {seed})"
17061 );
17062 let before: Vec<usize> = counters.iter().map(|(_, f)| f()).collect();
17063 let decoded = match decode_stream(&stream) {
17064 Ok(frames) => frames,
17065 Err(e) => {
17066 refusals.push(format!("seed {seed}: {e}"));
17067 continue;
17068 }
17069 };
17070 // Deltas are read BEFORE the pixel compare so a mismatch report
17071 // says whether the tool under test actually fired on the failing
17072 // stream (a mismatch with a zero delta is some other defect).
17073 let deltas: Vec<usize> = counters
17074 .iter()
17075 .zip(before.iter())
17076 .map(|((_, f), b)| f() - b)
17077 .collect();
17078 let fired: Vec<String> = counters
17079 .iter()
17080 .zip(deltas.iter())
17081 .map(|((label, _), d)| format!("{label}={d}"))
17082 .collect();
17083 let fired = fired.join(" ");
17084 // The ENCODE's frame count, and it is this helper's `frames` PARAMETER
17085 // (15446) -- not our decode's length. It is the same value handed to
17086 // `encode_10bit_gradients_seed` (15469), which renders
17087 // `frames / 25.0` seconds at `rate=25` (15928, 15940) and runs
17088 // aomenc with no `--limit` of its own, so the stream codes exactly
17089 // `frames` frames: 1 for the single-key-frame callers, 24 for the
17090 // `--lag-in-frames=16` inter callers. Asserted ABOVE the oracle call,
17091 // so a decode that showed fewer reds naming the encode rather than
17092 // handing ffmpeg the same short count.
17093 assert_eq!(
17094 decoded.len(),
17095 frames,
17096 "{name}: seed {seed}: the encode codes {frames} frame(s), the decode showed {}",
17097 decoded.len()
17098 );
17099 let reference = ffmpeg_decode_sequence_10bit(&stream, width, height, decoded.len());
17100 assert_eq!(
17101 decoded.len(),
17102 reference.len(),
17103 "{name}: seed {seed}: shown-frame count vs ffmpeg"
17104 );
17105 for (i, (ours, theirs)) in decoded.iter().zip(reference.iter()).enumerate() {
17106 for (plane, (a, b), w) in [
17107 ("Y", (&ours.y, &theirs.y), width),
17108 ("U", (&ours.u, &theirs.u), width / 2),
17109 ("V", (&ours.v, &theirs.v), width / 2),
17110 ] {
17111 if let Some(d) = first_diff(a, b, w) {
17112 panic!("{name}: seed {seed} frame {i} plane {plane}: {d} [{fired}]");
17113 }
17114 assert_eq!(
17115 a.len(),
17116 b.len(),
17117 "{name}: seed {seed} frame {i} plane {plane}: ours has {} samples, \
17118 ffmpeg's has {} -- a short plane would zip-truncate the walk above \
17119 and hide a chroma-span defect",
17120 a.len(),
17121 b.len()
17122 );
17123 }
17124 }
17125 compared += 1;
17126 for (i, d) in deltas.iter().enumerate() {
17127 totals[i] += d;
17128 }
17129 }
17130 assert!(
17131 compared > 0,
17132 "{name}: every attempt hit a named refusal:\n{}",
17133 refusals.join("\n")
17134 );
17135 for (i, (label, _)) in counters.iter().enumerate() {
17136 assert!(
17137 totals[i] > 0,
17138 "{name}: {compared} attempt(s) decoded pixel-exact but {label} never fired -- \
17139 the gate would prove nothing about that tool. refusals:\n{}",
17140 refusals.join("\n")
17141 );
17142 }
17143 let summary: Vec<String> = counters
17144 .iter()
17145 .zip(totals.iter())
17146 .map(|((label, _), t)| format!("{label}={t}"))
17147 .collect();
17148 eprintln!(
17149 "{name}: {compared}/{} attempts pixel-exact, {}",
17150 seeds.len(),
17151 summary.join(" ")
17152 );
17153 }
17154
17155 /// lane-hbdgates r1: the four intra tools that had an 8-bit gate and no
17156 /// 10-bit one (`filter-intra`, `smooth-intra`, `paeth-intra`,
17157 /// `intra-edge-filter`) on ONE real 10-bit `aomenc` key frame, each with
17158 /// its own hard-asserted counter. His two films are yuv420p10le, so an
17159 /// 8-bit-only gate for these tools proves nothing about the streams that
17160 /// matter (lane-covbd r1).
17161 #[test]
17162 fn a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact() {
17163 const NAME: &str = "a_real_aomenc_10bit_intra_tools_stream_decodes_pixel_exact";
17164 if !have_ffmpeg() {
17165 eprintln!("SKIP {NAME}: no ffmpeg");
17166 return;
17167 }
17168 if !have_aomenc() {
17169 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17170 return;
17171 }
17172 ten_bit_tool_gate(
17173 NAME,
17174 64,
17175 64,
17176 1,
17177 &[
17178 "--limit=1",
17179 "--kf-max-dist=0",
17180 "--enable-filter-intra=1",
17181 "--enable-smooth-intra=1",
17182 "--enable-paeth-intra=1",
17183 "--enable-intra-edge-filter=1",
17184 "--enable-directional-intra=1",
17185 "--enable-angle-delta=0",
17186 "--enable-rect-partitions=0",
17187 "--enable-ab-partitions=0",
17188 "--enable-1to4-partitions=0",
17189 "--enable-tx-size-search=0",
17190 "--enable-cdef=0",
17191 "--enable-restoration=0",
17192 "--max-partition-size=32",
17193 "--min-partition-size=16",
17194 "--enable-palette=0",
17195 "--enable-intrabc=0",
17196 "--enable-cfl-intra=0",
17197 "--enable-ref-frame-mvs=0",
17198 ],
17199 &[42, 7, 11, 23, 31, 57],
17200 &[
17201 ("filter_intra_hits", decode::filter_intra_hits),
17202 ("smooth_pred_hits", crate::intra::smooth_pred_hits),
17203 ("paeth_pred_hits", crate::intra::paeth_pred_hits),
17204 (
17205 "intra_edge_filter_hits",
17206 crate::intra::intra_edge_filter_hits,
17207 ),
17208 ],
17209 );
17210 }
17211
17212 /// lane-hbdgates r1: `--enable-restoration=1` at 10 bits. Every earlier
17213 /// bit-depth gate ran `--enable-restoration=0`, which is exactly why two
17214 /// high-bit-depth loop-restoration defects survived to 2026-09-01
17215 /// (SGR box sums unscaled, Wiener clamp at the 8-bit bound). Same recipe
17216 /// as the 8-bit LR gate, at 10 bits.
17217 // Written `#[ignore]`d on lane-hbdgates (the branch lacked lane-hbdinter's
17218 // 10-bit LR fix and failed at seed 42, frame 0, Y index 122: ours 351 vs
17219 // ffmpeg 350). Un-ignored on the merge into main 2026-09-01, where the
17220 // SGR box-sum scaling and the Wiener clamp are fixed: 16/16 attempts
17221 // pixel-exact, lr_hits=28.
17222 #[test]
17223 fn a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact() {
17224 const NAME: &str = "a_real_aomenc_10bit_restoration_stream_decodes_pixel_exact";
17225 if !have_ffmpeg() {
17226 eprintln!("SKIP {NAME}: no ffmpeg");
17227 return;
17228 }
17229 if !have_aomenc() {
17230 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17231 return;
17232 }
17233 // 192x128 = 3x2 superblocks, so `read_lr` is re-entered per SB
17234 // (the 8-bit LR gate's own trap warning); cq-level=15 because
17235 // aomenc's RD only picks a non-RESTORE_NONE frame type at low cq.
17236 ten_bit_tool_gate(
17237 NAME,
17238 192,
17239 128,
17240 1,
17241 &[
17242 "--limit=1",
17243 "--kf-max-dist=0",
17244 "--cq-level=15",
17245 "--enable-restoration=1",
17246 "--enable-cdef=0",
17247 "--enable-rect-partitions=0",
17248 "--enable-ab-partitions=0",
17249 "--enable-1to4-partitions=0",
17250 "--enable-filter-intra=0",
17251 "--enable-smooth-intra=0",
17252 "--enable-paeth-intra=0",
17253 "--enable-tx-size-search=0",
17254 "--max-partition-size=32",
17255 "--min-partition-size=16",
17256 "--enable-palette=0",
17257 "--enable-intrabc=0",
17258 "--enable-cfl-intra=0",
17259 "--enable-ref-frame-mvs=0",
17260 ],
17261 &LR_SEEDS,
17262 &[("lr_hits", ten_bit_lr_hits)],
17263 );
17264 }
17265
17266 /// Seeds swept by the 10-bit LR gate (the 8-bit gate needs ~40 attempts
17267 /// to land a non-RESTORE_NONE frame; every attempt here still has to
17268 /// decode pixel-exact).
17269 /// lane-obmcrec r1: the `LR_SEEDS` members whose 1:4-partition stream both
17270 /// fires `obmc_pair_filter_hits` and decodes every frame pixel-exact.
17271 /// Measured over seeds 42..=73 (32 encodes): 43/46/47/65/66 fire and are
17272 /// exact; 70 and 73 fire and mismatch, but mismatch IDENTICALLY with
17273 /// `--enable-obmc=0` (seed 73 frame 1 luma, seed 70 frame 16), so their
17274 /// defect is in the `--min-partition-size=4` recipe, not in OBMC -- kept
17275 /// out of this gate rather than papered over, and reported as open.
17276 const OBMC_PAIR_SEEDS: [u32; 5] = [43, 46, 47, 65, 66];
17277
17278 const LR_SEEDS: [u32; 16] = [
17279 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
17280 ];
17281
17282 /// Wiener + SGR + switchable loop-restoration firings, summed.
17283 fn ten_bit_lr_hits() -> usize {
17284 crate::restoration::wiener_hits()
17285 + crate::restoration::sgrproj_hits()
17286 + crate::restoration::switchable_hits()
17287 }
17288
17289 /// lane-reelckf2 r1: loop restoration on frame sizes whose LAST stripe is
17290 /// partial, with 128-sample superblocks -- the two stripe shapes whose
17291 /// boundary substitution is special (`filter_restoration_unit`: the first
17292 /// stripe is 8 rows short and takes its above boundary from the frame's
17293 /// own top rows, the last one is truncated and takes its below boundary
17294 /// from the frame's own bottom row) had no gate at all: every earlier LR
17295 /// size (192x128, 160x96) is a whole multiple of 64 rows and ran at
17296 /// `--sb-size=64`. 152 = 2*64+24 and 216 = 3*64+24 both leave a 32-row
17297 /// tail stripe, mirroring the 792-row 10-bit film that made this lane.
17298 /// `lr_stripe0_hits`/`lr_last_stripe_hits` are hard-asserted per attempt
17299 /// by [`ten_bit_tool_gate`], so an RD that picked RESTORE_NONE on either
17300 /// stripe cannot pass.
17301 #[test]
17302 fn a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact() {
17303 const NAME: &str =
17304 "a_real_aomenc_10bit_partial_bottom_stripe_restoration_decodes_pixel_exact";
17305 if !have_ffmpeg() {
17306 eprintln!("SKIP {NAME}: no ffmpeg");
17307 return;
17308 }
17309 if !have_aomenc() {
17310 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17311 return;
17312 }
17313 // `--sb-size=128` goes in `extra`, which the helper appends AFTER its
17314 // own `--sb-size=64` (aomenc keeps the LAST occurrence of a repeated
17315 // flag, measured 2026-09-02); `--max-partition-size=32` keeps the 128
17316 // root on SPLIT, the only 128-root partition decoded today.
17317 for (width, height, cq) in [
17318 (256usize, 152usize, "15"),
17319 (384, 216, "15"),
17320 (256, 152, "25"),
17321 ] {
17322 ten_bit_tool_gate(
17323 &format!("{NAME} {width}x{height} cq{cq}"),
17324 width,
17325 height,
17326 1,
17327 &[
17328 "--limit=1",
17329 "--kf-max-dist=0",
17330 &format!("--cq-level={cq}"),
17331 "--sb-size=128",
17332 "--enable-restoration=1",
17333 "--enable-cdef=0",
17334 "--enable-rect-partitions=0",
17335 "--enable-ab-partitions=0",
17336 "--enable-1to4-partitions=0",
17337 "--enable-filter-intra=0",
17338 "--enable-smooth-intra=0",
17339 "--enable-paeth-intra=0",
17340 "--enable-tx-size-search=0",
17341 "--max-partition-size=32",
17342 "--min-partition-size=16",
17343 "--enable-palette=0",
17344 "--enable-intrabc=0",
17345 "--enable-cfl-intra=0",
17346 "--enable-ref-frame-mvs=0",
17347 ],
17348 &LR_SEEDS,
17349 &[
17350 ("lr_hits", ten_bit_lr_hits),
17351 ("lr_stripe0_hits", crate::restoration::lr_stripe0_hits),
17352 (
17353 "lr_last_stripe_hits",
17354 crate::restoration::lr_last_stripe_hits,
17355 ),
17356 ],
17357 );
17358 }
17359 }
17360
17361 /// lane-hbdgates r1: `--enable-rect-partitions=1 --enable-ab-partitions=1`
17362 /// at 10 bits, one intra stream, one counter per tool
17363 /// (`rect_partition_hits`, `partab_hits`) so a stream that only fired the
17364 /// rect arms cannot stand in for AB.
17365 #[test]
17366 fn a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact() {
17367 const NAME: &str = "a_real_aomenc_10bit_rect_and_ab_partitions_decode_pixel_exact";
17368 if !have_ffmpeg() {
17369 eprintln!("SKIP {NAME}: no ffmpeg");
17370 return;
17371 }
17372 if !have_aomenc() {
17373 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17374 return;
17375 }
17376 // The 8-bit free-partition/AB recipe, verbatim, at 10 bits: AB
17377 // splits are an INTER dispatch here (intra-frame AB is still a named
17378 // refusal), so the stream needs alt-refs and 24 frames, not one key
17379 // frame.
17380 ten_bit_tool_gate(
17381 NAME,
17382 64,
17383 64,
17384 24,
17385 &[
17386 "--cq-level=45",
17387 "--kf-max-dist=1000",
17388 "--auto-alt-ref=1",
17389 "--lag-in-frames=16",
17390 "--enable-fwd-kf=0",
17391 "--enable-order-hint=1",
17392 "--enable-warped-motion=1",
17393 "--enable-obmc=1",
17394 "--tune-content=default",
17395 "--enable-masked-comp=0",
17396 "--enable-interintra-comp=0",
17397 "--enable-onesided-comp=0",
17398 "--enable-interintra-wedge=0",
17399 "--enable-smooth-interintra=0",
17400 "--enable-rect-partitions=1",
17401 "--enable-ab-partitions=1",
17402 "--enable-1to4-partitions=0",
17403 "--enable-filter-intra=0",
17404 "--enable-smooth-intra=0",
17405 "--enable-paeth-intra=0",
17406 "--enable-directional-intra=0",
17407 "--enable-angle-delta=0",
17408 "--enable-tx-size-search=0",
17409 "--enable-cdef=0",
17410 "--enable-restoration=0",
17411 "--max-partition-size=32",
17412 "--min-partition-size=16",
17413 "--enable-palette=0",
17414 "--enable-intrabc=0",
17415 "--enable-cfl-intra=0",
17416 "--enable-ref-frame-mvs=0",
17417 ],
17418 &LR_SEEDS,
17419 &[
17420 ("rect_partition_hits", decode::rect_partition_hits),
17421 ("partab_hits", decode::partab_hits),
17422 ],
17423 );
17424 }
17425
17426 /// lane-obmcrec r1: OBMC whose above/left neighbour is a 4-wide/4-tall
17427 /// 1:4-partition strip -- the shape the three 1080p 10-bit film cuts
17428 /// refused on ("an OBMC neighbour whose switchable interp filter was never
17429 /// recorded"). `overlappable_above`/`_left` snap such a neighbour to the
17430 /// chroma pair's SECOND mi but used to read its interp filter from the
17431 /// FIRST one, a different block whose filter record is the intra
17432 /// `[3, 3]` sentinel whenever that half is intra. `obmc_pair_filter_hits`
17433 /// counts exactly that neighbour shape, so a stream without 1:4 strips
17434 /// next to an OBMC block cannot stand in for it.
17435 #[test]
17436 fn a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact() {
17437 const NAME: &str =
17438 "a_real_aomenc_10bit_obmc_over_1to4_strip_neighbours_decodes_pixel_exact";
17439 if !have_ffmpeg() {
17440 eprintln!("SKIP {NAME}: no ffmpeg");
17441 return;
17442 }
17443 if !have_aomenc() {
17444 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17445 return;
17446 }
17447 ten_bit_tool_gate(
17448 NAME,
17449 128,
17450 128,
17451 24,
17452 &[
17453 "--ec-fixture-noise",
17454 "--cq-level=45",
17455 "--kf-max-dist=1000",
17456 "--auto-alt-ref=1",
17457 "--lag-in-frames=16",
17458 "--enable-fwd-kf=0",
17459 "--enable-order-hint=1",
17460 "--enable-warped-motion=0",
17461 "--enable-obmc=1",
17462 "--tune-content=default",
17463 "--enable-masked-comp=0",
17464 "--enable-interintra-comp=0",
17465 "--enable-onesided-comp=0",
17466 "--enable-interintra-wedge=0",
17467 "--enable-smooth-interintra=0",
17468 "--enable-rect-partitions=1",
17469 "--enable-ab-partitions=0",
17470 "--enable-1to4-partitions=1",
17471 "--enable-filter-intra=0",
17472 "--enable-smooth-intra=0",
17473 "--enable-paeth-intra=0",
17474 "--enable-directional-intra=0",
17475 "--enable-angle-delta=0",
17476 "--enable-tx-size-search=0",
17477 "--enable-cdef=0",
17478 "--enable-restoration=0",
17479 "--max-partition-size=32",
17480 "--min-partition-size=4",
17481 "--enable-palette=0",
17482 "--enable-intrabc=0",
17483 "--enable-cfl-intra=0",
17484 "--enable-ref-frame-mvs=0",
17485 ],
17486 &OBMC_PAIR_SEEDS,
17487 &[("obmc_pair_filter_hits", decode::obmc_pair_filter_hits)],
17488 );
17489 }
17490
17491 /// `bit_depth` of the first sequence header in `stream`.
17492 fn parsed_bit_depth(stream: &[u8]) -> u8 {
17493 let mut probe = Av1Parser::new();
17494 let mut pos = 0usize;
17495 while pos < stream.len() && probe.sequence_header().is_none() {
17496 let obu = probe.parse_obu(&stream[pos..]).unwrap();
17497 pos += obu.total_size;
17498 }
17499 probe
17500 .sequence_header()
17501 .expect("stream has a sequence header OBU")
17502 .color_config
17503 .bit_depth
17504 }
17505
17506 /// Render `frames` of the shared `gradients_source` as `yuv420p10le` and
17507 /// encode it with a real 10-bit `aomenc`, returning the OBU stream.
17508 /// `extra` carries the tool flags under test.
17509 fn encode_10bit_gradients(
17510 name: &str,
17511 width: usize,
17512 height: usize,
17513 frames: usize,
17514 extra: &[&str],
17515 ) -> Vec<u8> {
17516 encode_10bit_gradients_seed(name, 42, width, height, frames, extra)
17517 }
17518
17519 /// As [`encode_10bit_gradients`], but with the fixture seed exposed --
17520 /// lane-hbdgates r1 sweeps seeds so a tool that aomenc's RD declines on
17521 /// one fixture still gets a firing stream.
17522 fn encode_10bit_gradients_seed(
17523 name: &str,
17524 seed: u32,
17525 width: usize,
17526 height: usize,
17527 frames: usize,
17528 extra: &[&str],
17529 ) -> Vec<u8> {
17530 let duration = frames as f64 / 25.0;
17531 // lane-ab32 r1: `--ec-fixture-noise` is not an aomenc flag -- it is a
17532 // fixture request, consumed (and stripped) here: the smooth gradients
17533 // source codes as PARTITION_NONE everywhere, so a partition gate needs
17534 // seeded noise on top of it to give the RD a reason to split.
17535 let noisy = extra.contains(&"--ec-fixture-noise");
17536 let stripped: Vec<&str> = extra
17537 .iter()
17538 .copied()
17539 .filter(|a| *a != "--ec-fixture-noise")
17540 .collect();
17541 let extra: &[&str] = &stripped;
17542 let base = gradients_source(seed, width, height, &format!("duration={duration}:rate=25"));
17543 let source = if noisy {
17544 format!("{base},noise=alls=40:all_seed={seed}")
17545 } else {
17546 base
17547 };
17548 let y4m = Command::new("ffmpeg")
17549 .args([
17550 "-v",
17551 "error",
17552 "-f",
17553 "lavfi",
17554 "-i",
17555 &source,
17556 "-pix_fmt",
17557 "yuv420p10le",
17558 "-strict",
17559 "-1",
17560 "-t",
17561 &format!("{duration}"),
17562 "-f",
17563 "yuv4mpegpipe",
17564 "-",
17565 ])
17566 .stdin(Stdio::null())
17567 .stdout(Stdio::piped())
17568 .stderr(Stdio::piped())
17569 .output()
17570 .expect("ffmpeg failed to run");
17571 assert!(
17572 y4m.status.success(),
17573 "{name}: ffmpeg failed to render the 10-bit fixture: {}",
17574 String::from_utf8_lossy(&y4m.stderr)
17575 );
17576 let mut args: Vec<&str> = vec!["--codec=av1", "--passes=1", "--end-usage=q"];
17577 // lane-hbdgates r1: a caller-supplied `--cq-level` REPLACES the
17578 // default rather than being appended after it -- two `--cq-level`
17579 // flags on one aomenc line is a coin flip on which one lands.
17580 if !extra.iter().any(|a| a.starts_with("--cq-level=")) {
17581 args.push("--cq-level=30");
17582 }
17583 args.extend_from_slice(&[
17584 "--cpu-used=0",
17585 "--threads=1",
17586 "--row-mt=0",
17587 "--sb-size=64",
17588 "--input-bit-depth=10",
17589 "--bit-depth=10",
17590 ]);
17591 args.extend_from_slice(extra);
17592 args.extend_from_slice(&["--obu", "-o", "-", "-"]);
17593 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
17594 assert!(
17595 out.status.success(),
17596 "{name}: aomenc refused the 10-bit fixture: {}",
17597 String::from_utf8_lossy(&out.stderr)
17598 );
17599 out.stdout
17600 }
17601
17602 /// A real `aomenc` palette-**UV** fixture (lane-palette2 r2): `testsrc2`
17603 /// (the multicoloured AV1 test pattern -- flat, few-colour, repetitive
17604 /// per-region colour *and* chroma, unlike `smptebars=hue=s=0` above,
17605 /// which flattened chroma to a single value specifically to avoid
17606 /// exercising this path). Same square-only recipe as the palette-Y gate
17607 /// (`--enable-rect-partitions=0`/`-ab-`/`-1to4-`, fixed 32x32 partition)
17608 /// so a UV palette block never lands inside the still-refused HORZ/VERT
17609 /// screen-content strip. HARD-asserts [`decode::palette_uv_hits`] moved
17610 /// -- a stream that never reads a real UV palette block would decode (or
17611 /// not) by construction without proving this milestone at all
17612 /// ([[gate-blind-to-feature]]).
17613 #[test]
17614 fn a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact() {
17615 const NAME: &str = "a_real_aomenc_stream_with_palette_uv_decodes_pixel_exact";
17616 if !have_ffmpeg() {
17617 eprintln!("SKIP {NAME}: no ffmpeg");
17618 return;
17619 }
17620 if !have_aomenc() {
17621 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17622 return;
17623 }
17624 let source = "testsrc2=size=64x64:rate=25";
17625 fn render(source: &str) -> Vec<u8> {
17626 Command::new("ffmpeg")
17627 .args([
17628 "-v",
17629 "error",
17630 "-f",
17631 "lavfi",
17632 "-i",
17633 source,
17634 "-pix_fmt",
17635 "yuv420p",
17636 "-t",
17637 "0.16",
17638 "-f",
17639 "yuv4mpegpipe",
17640 "-",
17641 ])
17642 .stdin(Stdio::null())
17643 .stdout(Stdio::piped())
17644 .stderr(Stdio::piped())
17645 .output()
17646 .expect("ffmpeg failed to run")
17647 .stdout
17648 }
17649 let y4m_a = render(source);
17650 let y4m_b = render(source);
17651 assert_eq!(
17652 y4m_a, y4m_b,
17653 "testsrc2 must render byte-identical across two runs"
17654 );
17655 let y4m = y4m_a;
17656 let out = run_with_stdin(
17657 Command::new(aomenc_path()).args([
17658 "--codec=av1",
17659 "--passes=1",
17660 "--end-usage=q",
17661 "--cq-level=30",
17662 "--cpu-used=0",
17663 "--threads=1",
17664 "--row-mt=0",
17665 "--sb-size=64",
17666 "--tune-content=screen",
17667 "--enable-palette=1",
17668 "--enable-intrabc=0",
17669 "--enable-rect-partitions=0",
17670 "--enable-ab-partitions=0",
17671 "--enable-1to4-partitions=0",
17672 "--min-partition-size=32",
17673 "--max-partition-size=32",
17674 "--enable-filter-intra=0",
17675 "--enable-cdef=0",
17676 "--enable-restoration=0",
17677 "--enable-tx-size-search=0",
17678 "--loopfilter-control=0",
17679 "--obu",
17680 "-o",
17681 "-",
17682 "-",
17683 ]),
17684 &y4m,
17685 );
17686 assert!(
17687 out.status.success(),
17688 "aomenc refused the fixture: {}",
17689 String::from_utf8_lossy(&out.stderr)
17690 );
17691 let stream = out.stdout;
17692 let before = decode::palette_uv_hits();
17693 let frames = match decode_stream(&stream) {
17694 Ok(frames) => frames,
17695 Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
17696 };
17697 assert!(
17698 decode::palette_uv_hits() > before,
17699 "palette_uv_mode never fired decoding this stream -- gate is vacuous"
17700 );
17701 let frame_count = frames.len();
17702 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, frame_count);
17703 for i in 0..frame_count {
17704 assert_eq!(frames[i].y, ffmpeg_frames[i].y, "luma vs ffmpeg, frame {i}");
17705 assert_eq!(frames[i].u, ffmpeg_frames[i].u, "U vs ffmpeg, frame {i}");
17706 assert_eq!(frames[i].v, ffmpeg_frames[i].v, "V vs ffmpeg, frame {i}");
17707 }
17708 }
17709
17710 /// A real `aomenc` fixture that lands palette syntax on a HORZ/VERT
17711 /// intra strip (lane-palette2 r5, gating r4's `read_intra_mode_rect`
17712 /// wiring). `smptebars`/`rgbtestsrc` at plain default settings both hit a
17713 /// SQUARE palette refusal or an unrelated 32x32 `HORZ_A`/`VERT_A`/etc
17714 /// partition FIRST on every size/cq combo probed -- `--enable-ab-
17715 /// partitions=0` measurably does not stop aomenc choosing one at this
17716 /// screen-content tune (byte-identical output with `=0` vs `=1`, same
17717 /// aomenc quirk as `[[lane-sbpart-r2]]`'s SB-level AB). Forcing
17718 /// `--min/max-partition-size=64` sidesteps that whole 32x32-level code
17719 /// path: the only choices left at the (single, key-frame) superblock are
17720 /// NONE/SPLIT/HORZ/VERT/AB/1to4 straight from [`decode_block_rect64`],
17721 /// and a size/cq sweep (measured live this round) reliably lands
17722 /// PARTITION_HORZ/VERT with a real (non-split-tx) palette block on both
17723 /// sources. Drives `decode_stream` directly (below any refusal) and
17724 /// HARD-asserts [`decode::palette_rect_hits`] moved on every attempt that
17725 /// didn't refuse, before comparing pixels ([[gate-blind-to-feature]]) --
17726 /// a decode that never lands a rect palette block is not a match.
17727 #[test]
17728 fn a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact() {
17729 const NAME: &str = "a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact";
17730 let _gate_lock = lock_gate_counters();
17731 if !have_ffmpeg() {
17732 eprintln!("SKIP {NAME}: no ffmpeg");
17733 return;
17734 }
17735 if !have_aomenc() {
17736 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17737 return;
17738 }
17739 let mut matched = 0u32;
17740 let mut uncounted_exact = 0u32;
17741 let mut named_refusals = 0u32;
17742 let mut attempts = 0u32;
17743 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
17744 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
17745 for src_name in ["smptebars", "rgbtestsrc"] {
17746 for (width, height) in sizes {
17747 for cq in cqs {
17748 attempts += 1;
17749 let source = format!("{src_name}=size={width}x{height}:rate=25");
17750 let y4m = Command::new("ffmpeg")
17751 .args([
17752 "-v",
17753 "error",
17754 "-f",
17755 "lavfi",
17756 "-i",
17757 &source,
17758 "-pix_fmt",
17759 "yuv420p",
17760 "-t",
17761 "0.04",
17762 "-f",
17763 "yuv4mpegpipe",
17764 "-",
17765 ])
17766 .stdin(Stdio::null())
17767 .stdout(Stdio::piped())
17768 .stderr(Stdio::piped())
17769 .output()
17770 .expect("ffmpeg failed to run");
17771 assert!(
17772 y4m.status.success(),
17773 "ffmpeg fixture: {}",
17774 String::from_utf8_lossy(&y4m.stderr)
17775 );
17776 let cq_arg = format!("--cq-level={cq}");
17777 let out = run_with_stdin(
17778 Command::new(aomenc_path()).args([
17779 "--codec=av1",
17780 "--passes=1",
17781 "--end-usage=q",
17782 &cq_arg,
17783 "--cpu-used=4",
17784 "--threads=1",
17785 "--row-mt=0",
17786 "--sb-size=64",
17787 "--enable-palette=1",
17788 "--min-partition-size=16",
17789 "--max-partition-size=64",
17790 "--obu",
17791 "-o",
17792 "-",
17793 "-",
17794 ]),
17795 &y4m.stdout,
17796 );
17797 assert!(
17798 out.status.success(),
17799 "aomenc refused the fixture ({source} cq={cq}): {}",
17800 String::from_utf8_lossy(&out.stderr)
17801 );
17802 let stream = out.stdout;
17803 let before = crate::decode::palette_rect_hits();
17804 let frames = match decode_stream(&stream) {
17805 Err(e) => {
17806 let msg = e.to_string();
17807 assert!(
17808 msg.contains("unsupported"),
17809 "{NAME} failed outright, not a named refusal \
17810 ({source} cq={cq}): {msg}"
17811 );
17812 named_refusals += 1;
17813 eprintln!("{source} cq={cq}: refusal: {msg}");
17814 continue;
17815 }
17816 Ok(frames) => frames,
17817 };
17818 // A successful decode is ALWAYS pixel-compared; the hit
17819 // counter only decides whether the attempt counts toward
17820 // the hit-asserting total (class
17821 // [[gate-skips-on-its-own-failure]]: the old `continue`
17822 // here let 16/70 decoded attempts past without any pixel
17823 // check at all).
17824 let counted = crate::decode::palette_rect_hits() != before;
17825 if !counted {
17826 eprintln!(
17827 "{NAME}: {source} cq={cq} decoded without ever landing a rect \
17828 palette block (palette_rect_hits unchanged) -- pixel-compared, \
17829 not counted toward the hit assertion"
17830 );
17831 }
17832 let frame_count = frames.len();
17833 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
17834 if frames
17835 .iter()
17836 .zip(&ffmpeg_frames)
17837 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v)
17838 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
17839 {
17840 std::fs::write(&path, &stream).expect("writing pinned stream");
17841 eprintln!(
17842 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
17843 );
17844 }
17845 for i in 0..frame_count {
17846 assert_eq!(
17847 frames[i].y, ffmpeg_frames[i].y,
17848 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
17849 );
17850 assert_eq!(
17851 frames[i].u, ffmpeg_frames[i].u,
17852 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
17853 );
17854 assert_eq!(
17855 frames[i].v, ffmpeg_frames[i].v,
17856 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
17857 );
17858 }
17859 if counted {
17860 matched += 1;
17861 } else {
17862 uncounted_exact += 1;
17863 }
17864 }
17865 }
17866 }
17867 assert!(
17868 matched > 0,
17869 "{NAME}: no attempt out of {attempts} ever landed a matching rect palette \
17870 block ({named_refusals} named refusals) -- palette_rect_hits never proven \
17871 pixel-exact"
17872 );
17873 eprintln!(
17874 "{NAME}: {matched}/{attempts} attempts matched pixel-exact, \
17875 {uncounted_exact} decoded-and-pixel-exact but uncounted, {named_refusals} \
17876 named refusals, palette_rect_hits={}",
17877 crate::decode::palette_rect_hits()
17878 );
17879 }
17880
17881 /// The BROAD case (lane-palette2 r6, per its charter): a HORZ/VERT intra
17882 /// strip in a screen-content-tools frame that does NOT necessarily use a
17883 /// palette. This is what the refusal r4 removed actually guarded --
17884 /// [`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`] above
17885 /// gates the rarer "and picks a palette" case, which r5 measured RD
17886 /// almost never chooses -- 39/70 of that same sweep DID land here (a
17887 /// clean rect-strip decode with `palette_rect_hits` unchanged), just
17888 /// uncounted by r5's narrower assertion. Same `--min/max-partition-size=64`
17889 /// recipe r5 measured live to dodge the 32x32-level AB-partition quirk
17890 /// ([[lane-sbpart-r2]]), single key frame, size/cq sweep. HARD-asserts
17891 /// [`decode::rect_screen_content_hits`] moved -- proof this stream
17892 /// actually ran [`read_intra_mode_rect`]'s screen-content-tools branch --
17893 /// before comparing pixels.
17894 #[test]
17895 fn a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact() {
17896 const NAME: &str = "a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact";
17897 let _gate_lock = lock_gate_counters();
17898 if !have_ffmpeg() {
17899 eprintln!("SKIP {NAME}: no ffmpeg");
17900 return;
17901 }
17902 if !have_aomenc() {
17903 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
17904 return;
17905 }
17906 let mut matched = 0u32;
17907 // Blocks that reconstructed a palette-Y prediction through a SPLIT
17908 // luma transform (lane-palette2 r7's lifted refusal): the same
17909 // screen-content streams exercise it, so this gate proves both.
17910 let mut split_palette_matched = 0u32;
17911 let mut uncounted_exact = 0u32;
17912 let mut named_refusals = 0u32;
17913 let mut attempts = 0u32;
17914 let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
17915 let cqs = [5u32, 15, 25, 35, 45, 55, 63];
17916 for src_name in ["smptebars", "rgbtestsrc"] {
17917 for (width, height) in sizes {
17918 for cq in cqs {
17919 attempts += 1;
17920 let source = format!("{src_name}=size={width}x{height}:rate=25");
17921 let y4m = Command::new("ffmpeg")
17922 .args([
17923 "-v",
17924 "error",
17925 "-f",
17926 "lavfi",
17927 "-i",
17928 &source,
17929 "-pix_fmt",
17930 "yuv420p",
17931 "-t",
17932 "0.04",
17933 "-f",
17934 "yuv4mpegpipe",
17935 "-",
17936 ])
17937 .stdin(Stdio::null())
17938 .stdout(Stdio::piped())
17939 .stderr(Stdio::piped())
17940 .output()
17941 .expect("ffmpeg failed to run");
17942 assert!(
17943 y4m.status.success(),
17944 "ffmpeg fixture: {}",
17945 String::from_utf8_lossy(&y4m.stderr)
17946 );
17947 let cq_arg = format!("--cq-level={cq}");
17948 let out = run_with_stdin(
17949 Command::new(aomenc_path()).args([
17950 "--codec=av1",
17951 "--passes=1",
17952 "--end-usage=q",
17953 &cq_arg,
17954 "--cpu-used=4",
17955 "--threads=1",
17956 "--row-mt=0",
17957 "--sb-size=64",
17958 "--enable-palette=1",
17959 "--min-partition-size=16",
17960 "--max-partition-size=64",
17961 "--obu",
17962 "-o",
17963 "-",
17964 "-",
17965 ]),
17966 &y4m.stdout,
17967 );
17968 assert!(
17969 out.status.success(),
17970 "aomenc refused the fixture ({source} cq={cq}): {}",
17971 String::from_utf8_lossy(&out.stderr)
17972 );
17973 let stream = out.stdout;
17974 let before = crate::decode::rect_screen_content_hits();
17975 let split_before = crate::decode::palette_split_tx_hits();
17976 let frames = match decode_stream(&stream) {
17977 Err(e) => {
17978 let msg = e.to_string();
17979 assert!(
17980 msg.contains("unsupported"),
17981 "{NAME} failed outright, not a named refusal \
17982 ({source} cq={cq}): {msg}"
17983 );
17984 named_refusals += 1;
17985 eprintln!("{source} cq={cq}: refusal: {msg}");
17986 continue;
17987 }
17988 Ok(frames) => frames,
17989 };
17990 // Same integrity rule as the palette gate above: decoded
17991 // means pixel-compared, counter or no counter.
17992 let counted = crate::decode::rect_screen_content_hits() != before;
17993 if !counted {
17994 eprintln!(
17995 "{NAME}: {source} cq={cq} decoded without ever running the rect \
17996 screen-content path (rect_screen_content_hits unchanged) -- \
17997 pixel-compared, not counted toward the hit assertion"
17998 );
17999 }
18000 let frame_count = frames.len();
18001 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
18002 if frames
18003 .iter()
18004 .zip(&ffmpeg_frames)
18005 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v)
18006 && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
18007 {
18008 std::fs::write(&path, &stream).expect("writing pinned stream");
18009 eprintln!(
18010 "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
18011 );
18012 }
18013 for i in 0..frame_count {
18014 assert_eq!(
18015 frames[i].y, ffmpeg_frames[i].y,
18016 "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
18017 );
18018 assert_eq!(
18019 frames[i].u, ffmpeg_frames[i].u,
18020 "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
18021 );
18022 assert_eq!(
18023 frames[i].v, ffmpeg_frames[i].v,
18024 "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
18025 );
18026 }
18027 if counted {
18028 matched += 1;
18029 } else {
18030 uncounted_exact += 1;
18031 }
18032 if counted && crate::decode::palette_split_tx_hits() > split_before {
18033 split_palette_matched += 1;
18034 }
18035 }
18036 }
18037 }
18038 assert!(
18039 split_palette_matched > 0,
18040 "{NAME}: no pixel-exact attempt ever reconstructed a palette block with a \
18041 split luma transform -- the lifted refusal is ungated"
18042 );
18043 assert!(
18044 matched > 0,
18045 "{NAME}: no attempt out of {attempts} ever landed a matching rect \
18046 screen-content block ({named_refusals} named refusals) -- \
18047 rect_screen_content_hits never proven pixel-exact"
18048 );
18049 eprintln!(
18050 "{NAME}: {matched}/{attempts} attempts matched pixel-exact \
18051 ({split_palette_matched} of them through a split-transform palette block), \
18052 {uncounted_exact} decoded-and-pixel-exact but uncounted, \
18053 {named_refusals} named refusals, rect_screen_content_hits={}, \
18054 palette_split_tx_hits={}",
18055 crate::decode::rect_screen_content_hits(),
18056 crate::decode::palette_split_tx_hits()
18057 );
18058 }
18059
18060 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s
18061 /// harness, but with the deblocking filter left *on* (no
18062 /// `--loopfilter-control=0`) at a crf high enough that libaom actually
18063 /// picks a nonzero level -- proves `apply_deblock` itself, not just that
18064 /// this decoder still works when every edge lands on level 0. CDEF
18065 /// stays off so a pixel mismatch can only come from the loop filter.
18066 ///
18067 /// lane-av1skipfix: the attempt-loop shape. The sweep walks cq (which is
18068 /// what decides whether libaom picks a nonzero deblocking level at all)
18069 /// and seed, REQUIRES at least one attempt to decode, and hard-asserts
18070 /// `decode::deblock_hits` on a pixel-compared attempt -- a decode error on
18071 /// every attempt is a hard failure carrying the refusal texts, never a
18072 /// printed SKIP (class `gate-skips-on-its-own-failure`). MEASURED
18073 /// 2026-09-29 on `a21f3680`: cq 55/45/35/63 all decode pixel-exact with
18074 /// 48/64/64/64 deblock edges, so the old single recipe was one lucky
18075 /// point of a cq range that needed no fallback.
18076 #[test]
18077 fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() {
18078 const NAME: &str = "a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact";
18079 let _gate_lock = lock_gate_counters();
18080 if !have_ffmpeg() {
18081 eprintln!("SKIP {NAME}: no ffmpeg");
18082 return;
18083 }
18084 if !have_aomenc() {
18085 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18086 return;
18087 }
18088 let (width, height) = (64usize, 64usize);
18089 // Two seeds x four quantisers.
18090 const CQS: [u32; 4] = [55, 45, 35, 63];
18091 let mut refusals = Vec::new();
18092 let mut counted_exact = 0u32;
18093 let mut uncounted_exact = 0u32;
18094 'attempts: for round in 0..2u32 {
18095 for cq in CQS {
18096 let source = gradients_source(42 + round, width, height, "duration=0.04:rate=25");
18097 let y4m = Command::new("ffmpeg")
18098 .args(["-v", "error", "-f", "lavfi", "-i"])
18099 .arg(&source)
18100 .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
18101 .stdin(Stdio::null())
18102 .stdout(Stdio::piped())
18103 .stderr(Stdio::piped())
18104 .output()
18105 .expect("ffmpeg failed to run");
18106 assert!(
18107 y4m.status.success(),
18108 "{NAME}: ffmpeg fixture (seed {} cq {cq}): {}",
18109 42 + round,
18110 String::from_utf8_lossy(&y4m.stderr)
18111 );
18112 let cq_arg = format!("--cq-level={cq}");
18113 let out = run_with_stdin(
18114 Command::new(aomenc_path()).args([
18115 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
18116 // occurrence, so overrides go before the base list).
18117 "--loopfilter-control=1",
18118 "--codec=av1",
18119 "--passes=1",
18120 "--end-usage=q",
18121 &cq_arg,
18122 "--cpu-used=0",
18123 "--enable-filter-intra=0",
18124 "--enable-smooth-intra=0",
18125 "--enable-paeth-intra=0",
18126 "--enable-directional-intra=0",
18127 "--enable-angle-delta=0",
18128 "--enable-tx-size-search=0",
18129 "--enable-cdef=0",
18130 // Loop restoration is a named refusal (aomenc's RD picks
18131 // Sgrproj on this kind of content) -- off in every recipe
18132 // whose test targets a different surface.
18133 "--enable-restoration=0",
18134 "--max-partition-size=32",
18135 "--enable-palette=0",
18136 "--enable-intrabc=0",
18137 "--enable-cfl-intra=0",
18138 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
18139 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
18140 "--enable-ref-frame-mvs=0",
18141 "--obu",
18142 "-o",
18143 "-",
18144 "-",
18145 ]),
18146 &y4m.stdout,
18147 );
18148 assert!(
18149 out.status.success(),
18150 "{NAME}: aomenc refused the seed {} cq {cq} fixture: {}",
18151 42 + round,
18152 String::from_utf8_lossy(&out.stderr)
18153 );
18154 let stream = out.stdout;
18155 let before = decode::deblock_hits();
18156 let frames = match decode_stream(&stream) {
18157 Ok(frames) => frames,
18158 Err(e) => {
18159 refusals.push(format!("seed {} cq {cq}: {e}", 42 + round));
18160 continue;
18161 }
18162 };
18163 // A decode that succeeded is ALWAYS pixel-compared; the hit
18164 // counter only decides whether the attempt counts as firing
18165 // (class `counter-from-refused-stream`).
18166 let counted = decode::deblock_hits() != before;
18167 if counted {
18168 counted_exact += 1;
18169 } else {
18170 uncounted_exact += 1;
18171 }
18172 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
18173 assert_eq!(
18174 frames[0].y,
18175 ffmpeg_frames[0].y,
18176 "luma vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})",
18177 42 + round
18178 );
18179 assert_eq!(
18180 frames[0].u,
18181 ffmpeg_frames[0].u,
18182 "U vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})",
18183 42 + round
18184 );
18185 assert_eq!(
18186 frames[0].v,
18187 ffmpeg_frames[0].v,
18188 "V vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})",
18189 42 + round
18190 );
18191 if counted_exact >= 2 {
18192 break 'attempts;
18193 }
18194 }
18195 }
18196 gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
18197 assert!(
18198 counted_exact > 0,
18199 "{NAME}: none of {} attempts decoded a stream with a deblocking edge -- \
18200 apply_deblock is unproven (class gate-blind-to-feature):\n{}",
18201 CQS.len() * 2,
18202 refusals.join("\n")
18203 );
18204 }
18205
18206 /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`],
18207 /// but WITHOUT `--enable-tx-size-search=0` -- the one flag every other
18208 /// recipe in this file pins off specifically to keep the stream on
18209 /// `TxMode::Largest`. Dropped, aomenc's RD is free to pick
18210 /// `TxMode::Select` and split some blocks' luma transform below their own
18211 /// side (spec 5.11.16), which is what this test's `tx_depth_hits()`
18212 /// counter proves actually happened -- a stream that resolves every
18213 /// `tx_depth` to 0 would pixel-match by construction (identical to
18214 /// `TxMode::Largest`) without exercising the new split-TU decode path at
18215 /// all. Same multi-seed retry shape as
18216 /// [`a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact`]:
18217 /// aomenc's own RD is free (with tx-size search on) to also occasionally
18218 /// pick `allow_screen_content_tools` on this content, a separate,
18219 /// already-named refusal -- try several seeds, and the first stream that
18220 /// both decodes AND actually split a transform must be pixel-exact.
18221 #[test]
18222 fn a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact() {
18223 if !have_ffmpeg() {
18224 eprintln!(
18225 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no ffmpeg"
18226 );
18227 return;
18228 }
18229 if !have_aomenc() {
18230 eprintln!(
18231 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: no aomenc at {}",
18232 aomenc_path().display()
18233 );
18234 return;
18235 }
18236 let (width, height) = (64usize, 64usize);
18237 let mut refusals = Vec::new();
18238 let mut uncounted_exact = 0u32;
18239 for attempt in 0..40u32 {
18240 let seed = 42 + attempt;
18241 // A flat gradient never has enough local detail for the RD
18242 // search to prefer a split transform over the block's own full
18243 // size -- `mandelbrot`'s fractal boundary gives every attempt
18244 // (a different `start_scale`) sharp, varied-frequency edges.
18245 // start_scale 5.0 is the proven first try (decodes pixel-exact
18246 // AND reads the seven-symbol set-1 tx_type rows on TX8 TUs);
18247 // later attempts walk down for variety when aomenc's RD flips
18248 // elsewhere.
18249 let source = format!(
18250 "mandelbrot=size=64x64:start_scale={}:rate=25",
18251 5.0 - f64::from(attempt) * 0.06
18252 );
18253 let y4m = Command::new("ffmpeg")
18254 .args([
18255 "-v",
18256 "error",
18257 "-f",
18258 "lavfi",
18259 "-i",
18260 &source,
18261 // Desaturated: chroma stays flat (constant 128) so
18262 // `uv_mode` always resolves to `DC_PRED` and this
18263 // decoder's still-unsupported directional-chroma round-2
18264 // gap never fires, leaving the luma detail alone to
18265 // drive whether `TxMode::Select`'s RD splits a block.
18266 "-vf",
18267 "hue=s=0",
18268 "-pix_fmt",
18269 "yuv420p",
18270 "-t",
18271 "0.04",
18272 "-f",
18273 "yuv4mpegpipe",
18274 "-",
18275 ])
18276 .stdin(Stdio::null())
18277 .stdout(Stdio::piped())
18278 .stderr(Stdio::piped())
18279 .output()
18280 .expect("ffmpeg failed to run");
18281 assert!(
18282 y4m.status.success(),
18283 "ffmpeg fixture: {}",
18284 String::from_utf8_lossy(&y4m.stderr)
18285 );
18286 let out = run_with_stdin(
18287 Command::new(aomenc_path()).args([
18288 "--codec=av1",
18289 "--passes=1",
18290 "--end-usage=q",
18291 "--cq-level=45",
18292 "--cpu-used=0",
18293 "--enable-rect-partitions=0",
18294 "--enable-ab-partitions=0",
18295 "--enable-1to4-partitions=0",
18296 "--enable-filter-intra=0",
18297 // Every non-DC intra tool off: directional chroma and
18298 // angle deltas are separate round-2 gaps, and DC-only
18299 // residual is exactly what gives the RD search a reason
18300 // to split a transform.
18301 "--enable-smooth-intra=0",
18302 "--enable-paeth-intra=0",
18303 "--enable-directional-intra=0",
18304 "--enable-angle-delta=0",
18305 "--enable-cdef=0",
18306 // Loop restoration is a named refusal (aomenc's RD picks
18307 // Sgrproj on this kind of content) -- off in every recipe
18308 // whose test targets a different surface.
18309 "--enable-restoration=0",
18310 "--max-partition-size=32",
18311 // 16x16 blocks are what split into the TX8 TUs whose
18312 // set-1 tx_type rows this gate exists to prove; some
18313 // scales resolve depth 2 (TX4, a named refusal) and the
18314 // attempt loop just moves on.
18315 "--min-partition-size=16",
18316 "--enable-palette=0",
18317 "--enable-intrabc=0",
18318 "--enable-cfl-intra=0",
18319 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
18320 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
18321 "--enable-ref-frame-mvs=0",
18322 "--obu",
18323 "-o",
18324 "-",
18325 "-",
18326 ]),
18327 &y4m.stdout,
18328 );
18329 assert!(
18330 out.status.success(),
18331 "aomenc refused the fixture: {}",
18332 String::from_utf8_lossy(&out.stderr)
18333 );
18334 let stream = out.stdout;
18335 let before = decode::tx_depth_hits();
18336 let frames = match decode_stream(&stream) {
18337 Ok(frames) => frames,
18338 Err(e) => {
18339 refusals.push(format!("seed {seed}: {e}"));
18340 continue;
18341 }
18342 };
18343 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
18344 // is ALWAYS pixel-compared below; the hit counter only decides whether
18345 // the attempt counts toward the firing total.
18346 let counted = decode::tx_depth_hits() != before;
18347 if !counted {
18348 uncounted_exact += 1;
18349 refusals.push(format!(
18350 "seed {seed}: decoded and pixel-compared, but no block resolved a split \
18351 tx_depth"
18352 ));
18353 }
18354 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
18355 assert_eq!(
18356 frames[0].y, ffmpeg_frames[0].y,
18357 "luma vs ffmpeg (seed {seed})"
18358 );
18359 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
18360 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
18361 if counted {
18362 gate_buckets(
18363 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
18364 1,
18365 uncounted_exact,
18366 refusals.len() - uncounted_exact as usize,
18367 );
18368 return;
18369 }
18370 }
18371 gate_buckets(
18372 "a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact",
18373 0,
18374 uncounted_exact,
18375 refusals.len() - uncounted_exact as usize,
18376 );
18377 eprintln!(
18378 "SKIP a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact: every attempt \
18379 hit a named refusal or never split a transform:\n{}",
18380 refusals.join("\n")
18381 );
18382 }
18383
18384 /// lane-txselect's decisive gate: a real aomenc INTER sequence WITHOUT
18385 /// `--enable-tx-size-search=0`, the flag every other inter recipe in this
18386 /// file pins off precisely to keep the stream on `TxMode::Largest`.
18387 /// Dropped, aomenc takes its own default (`TX_MODE_SELECT` -- which is
18388 /// what both of the user's real films use), and an inter block's
18389 /// transform size is then the recursive `txfm_split` tree of spec
18390 /// 5.11.17 rather than one whole-block transform. A stream that decoded
18391 /// pixel-exact while every `txfm_split` symbol resolved to "no split"
18392 /// would prove nothing (it is `TxMode::Largest` by another name), so this
18393 /// gate hard-asserts BOTH counters: at least one `txfm_split` symbol read
18394 /// AND at least one split actually taken. Exhausting every attempt is a
18395 /// FAILURE, not a SKIP -- an unfired gate is a vacuous gate.
18396 #[test]
18397 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact() {
18398 tx_select_inter_gate(8);
18399 }
18400
18401 /// The 10-bit arm of the gate above (lane-txselect r2): both of the
18402 /// user's films are `yuv420p10le` and var-tx is exactly the tool they
18403 /// use, so an 8-bit-only proof would not reach them. Same recipe plus
18404 /// `-b 10 --input-bit-depth=10`.
18405 #[test]
18406 fn a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact_10bit() {
18407 tx_select_inter_gate(10);
18408 }
18409
18410 /// lane-intrarect r1's decisive gate: a real aomenc INTER sequence whose
18411 /// hard mid-GOP content cut makes aomenc code INTRA blocks inside inter
18412 /// frames, with rect partitions ON so those intra blocks land on
18413 /// HORZ/VERT strip shapes. Every such block was the named refusal "an
18414 /// intra-coded HORZ/VERT strip needs rectangular intra prediction this
18415 /// decoder does not code yet" until this round; they now decode through
18416 /// the same `decode_rect_split` machinery the key-frame rect paths use.
18417 ///
18418 /// Hard-asserts per-shape counters (`intra_rect_strip_in_inter_hits`:
18419 /// 0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16) summed over the
18420 /// attempts that were actually pixel-compared -- at least TWO of the
18421 /// three shape classes must fire, so a green run cannot come from one
18422 /// lucky size. A decode that succeeds is ALWAYS pixel-compared (class
18423 /// [[gate-skips-on-its-own-failure]]); exhausting every attempt without
18424 /// two shapes is a FAILURE, never a SKIP.
18425 #[test]
18426 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact() {
18427 intra_rect_in_inter_gate(8);
18428 }
18429
18430 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
18431 #[test]
18432 fn a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact_10bit() {
18433 intra_rect_in_inter_gate(10);
18434 }
18435
18436 fn intra_rect_in_inter_gate(bit_depth: u32) {
18437 const NAME: &str =
18438 "a_real_aomenc_inter_sequence_with_an_intra_rect_strip_decodes_pixel_exact";
18439 if !have_ffmpeg() {
18440 eprintln!("SKIP {NAME}: no ffmpeg");
18441 return;
18442 }
18443 if !have_aomenc() {
18444 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
18445 return;
18446 }
18447 let (width, height, frame_count) = (96usize, 96usize, 8usize);
18448 let mut refusals: Vec<String> = Vec::new();
18449 let mut uncounted_exact = 0u32;
18450 let mut compared = 0u32;
18451 let mut shapes = [0usize; 3];
18452 for attempt in 0..45u32 {
18453 let seed = 42 + attempt;
18454 // mandelbrot's fractal detail plus a HARD cut at frame 4: half
18455 // the picture becomes a flat white box, which no motion vector
18456 // can predict, so aomenc's RD codes those blocks INTRA inside an
18457 // inter frame. The box's vertical edge at x=48 is what makes the
18458 // partition search reach for HORZ/VERT strips there.
18459 // A FAST ZOOM: `end_scale`/`end_pts` make mandelbrot rush
18460 // through its own zoom, so consecutive frames share almost no
18461 // content and aomenc's RD codes blocks INTRA inside INTER frames
18462 // (`--kf-min-dist=1000` forbids a new key frame). That is the
18463 // only way a real encoder reaches this decoder's intra-in-inter
18464 // arm; a slowly-evolving source codes every rect strip inter.
18465 let source = format!(
18466 "mandelbrot=size={width}x{height}:start_scale={}:end_scale=0.004:end_pts=8:rate=25",
18467 5.0 - f64::from(attempt) * 0.06
18468 );
18469 let y4m = Command::new("ffmpeg")
18470 .args([
18471 "-v",
18472 "error",
18473 "-f",
18474 "lavfi",
18475 "-i",
18476 &source,
18477 "-vf",
18478 "hue=s=0",
18479 "-pix_fmt",
18480 if bit_depth == 10 {
18481 "yuv420p10le"
18482 } else {
18483 "yuv420p"
18484 },
18485 "-strict",
18486 "-1",
18487 "-t",
18488 "0.32",
18489 "-f",
18490 "yuv4mpegpipe",
18491 "-strict",
18492 "-1",
18493 "-",
18494 ])
18495 .stdin(Stdio::null())
18496 .stdout(Stdio::piped())
18497 .stderr(Stdio::piped())
18498 .output()
18499 .expect("ffmpeg failed to run");
18500 assert!(
18501 y4m.status.success(),
18502 "ffmpeg fixture: {}",
18503 String::from_utf8_lossy(&y4m.stderr)
18504 );
18505 let depth_args: &[&str] = if bit_depth == 10 {
18506 &["-b", "10", "--input-bit-depth=10"]
18507 } else {
18508 &[]
18509 };
18510 // MEASURED (r1): the speed preset gates the feature (class
18511 // [[gate-preset-gates-the-feature]]) -- at `--cpu-used=4` this
18512 // content produces no rect partition at all, at `--cpu-used=0`
18513 // aomenc emits AB partitions the tile path refuses (it ignores
18514 // `--enable-ab-partitions=0`, ledger). So the attempt sweep walks
18515 // the preset as well as the seed.
18516 let cpu = format!("--cpu-used={}", attempt % 5);
18517 // The quantiser drives how finely the RD partitions: the sweep
18518 // walks it too, so "no rect strip fired" cannot be an artefact of
18519 // one cq.
18520 let cq = format!("--cq-level={}", [30u32, 20, 12][(attempt / 5) as usize % 3]);
18521 let out = run_with_stdin(
18522 Command::new(aomenc_path())
18523 .args(depth_args)
18524 .arg(&cpu)
18525 .arg(&cq)
18526 .args([
18527 // class [[aomenc-first-flag-wins]]: every flag is spelled
18528 // exactly ONCE in this recipe, so there is no override to
18529 // order. These four are what this gate is about.
18530 "--enable-rect-partitions=1",
18531 // MEASURED (r1): the charter's `--min-partition-size=8`
18532 // makes 24/24 attempts stop at a sub-16 AB-partition
18533 // refusal ("a HORZ_A/HORZ_B/VERT_A partition below 16x16",
18534 // "a coded (non-skip) HORZ_B/VERT_B rect strip below
18535 // 16x16") before any intra rect strip is reached -- those
18536 // are other lanes' surfaces. 16 keeps the 16x8/8x16 shape
18537 // reachable (a 16x16 block's own HORZ/VERT children).
18538 "--min-partition-size=16",
18539 "--max-partition-size=64",
18540 // MEASURED (r1): with tx-size search ON, 24/24 attempts stop at
18541 // the SQUARE intra-in-inter arm's own refusal ("an intra
18542 // block in an inter frame whose tx_depth splits its luma
18543 // transform (round 1)", read_block_tx_size) long before a
18544 // rect strip is reached -- that arm is another lane's
18545 // surface. OFF, no tx-depth symbol is coded at all and
18546 // every rect strip here is the unsplit single-transform
18547 // case. The SPLIT rect arm (`depth_to_tx_wh` +
18548 // decode_rect_split's per-unit walk) is wired but stays
18549 // UNGATED on this path until that square refusal lifts.
18550 "--enable-tx-size-search=0",
18551 "--codec=av1",
18552 "--passes=1",
18553 "--end-usage=q",
18554 "--lag-in-frames=0",
18555 "--auto-alt-ref=0",
18556 // One key frame at the head: the frames after the cut must
18557 // stay INTER frames carrying intra blocks, not become a
18558 // new key frame.
18559 "--kf-min-dist=1000",
18560 "--kf-max-dist=1000",
18561 "--threads=1",
18562 "--row-mt=0",
18563 "--enable-order-hint=0",
18564 "--enable-warped-motion=0",
18565 "--enable-obmc=0",
18566 "--enable-masked-comp=0",
18567 "--enable-interintra-comp=0",
18568 "--enable-dist-wtd-comp=0",
18569 "--enable-diff-wtd-comp=0",
18570 "--enable-onesided-comp=0",
18571 "--enable-interintra-wedge=0",
18572 "--enable-smooth-interintra=0",
18573 "--enable-ab-partitions=0",
18574 "--enable-1to4-partitions=0",
18575 // The intra-in-inter arm reads no `use_filter_intra`
18576 // symbol (square OR rect) -- lane-fiinter owns that read.
18577 "--enable-filter-intra=0",
18578 "--enable-smooth-intra=0",
18579 "--enable-paeth-intra=0",
18580 "--enable-directional-intra=0",
18581 "--enable-angle-delta=0",
18582 "--enable-cdef=0",
18583 "--enable-restoration=0",
18584 "--enable-palette=0",
18585 "--enable-intrabc=0",
18586 "--enable-cfl-intra=0",
18587 "--enable-ref-frame-mvs=0",
18588 "--obu",
18589 "-o",
18590 "-",
18591 "-",
18592 ]),
18593 &y4m.stdout,
18594 );
18595 assert!(
18596 out.status.success(),
18597 "aomenc refused the fixture: {}",
18598 String::from_utf8_lossy(&out.stderr)
18599 );
18600 let stream = out.stdout;
18601 let before = [
18602 decode::intra_rect_strip_in_inter_hits(0),
18603 decode::intra_rect_strip_in_inter_hits(1),
18604 decode::intra_rect_strip_in_inter_hits(2),
18605 ];
18606 let kf_rect_before = decode::rect_partition_hits();
18607 let frames = match decode_stream(&stream) {
18608 Ok(frames) => frames,
18609 Err(e) => {
18610 let msg = e.to_string();
18611 assert!(
18612 msg.contains("unsupported"),
18613 "intra-rect-in-inter decode failed outright (seed {seed}): {msg}"
18614 );
18615 refusals.push(format!("seed {seed} {cpu} {cq}: {msg}"));
18616 continue;
18617 }
18618 };
18619 let delta = [
18620 decode::intra_rect_strip_in_inter_hits(0) - before[0],
18621 decode::intra_rect_strip_in_inter_hits(1) - before[1],
18622 decode::intra_rect_strip_in_inter_hits(2) - before[2],
18623 ];
18624 let ffmpeg_frames = if bit_depth == 10 {
18625 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
18626 } else {
18627 ffmpeg_decode_sequence(&stream, width, height, frame_count)
18628 };
18629 assert_eq!(frames.len(), frame_count);
18630 eprintln!(
18631 "intrarect gate {bit_depth}-bit seed={seed} {cpu} {cq}: intra rect strips in inter frames \
18632 64-level={} 32-level={} 16-level={}, key-frame rect strips this stream={}",
18633 delta[0],
18634 delta[1],
18635 delta[2],
18636 decode::rect_partition_hits() - kf_rect_before
18637 );
18638 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18639 for (plane, (g, w)) in [
18640 ("Y", (&got.y, &want.y)),
18641 ("U", (&got.u, &want.u)),
18642 ("V", (&got.v, &want.v)),
18643 ] {
18644 let stride = if plane == "Y" { width } else { width / 2 };
18645 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
18646 eprintln!(
18647 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} first \
18648 diff at ({}, {}) got {} want {} ({} samples differ)",
18649 at % stride,
18650 at / stride,
18651 g[at],
18652 w[at],
18653 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
18654 );
18655 // Magnitude separates a deblock/prediction difference
18656 // (all |d| == 1) from an entropy desync (large,
18657 // arbitrary): the first thing r2 needs to know.
18658 let maxd = g
18659 .iter()
18660 .zip(w.iter())
18661 .map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b)))
18662 .max()
18663 .unwrap_or(0);
18664 let rows: std::collections::BTreeSet<usize> = g
18665 .iter()
18666 .zip(w.iter())
18667 .enumerate()
18668 .filter(|(_, (a, b))| a != b)
18669 .map(|(k, _)| k / stride)
18670 .collect();
18671 eprintln!(
18672 "intrarect gate {bit_depth}-bit seed={seed}: frame {i} {plane} max \
18673 |diff|={maxd}, rows {:?}..{:?}",
18674 rows.iter().next(),
18675 rows.iter().next_back()
18676 );
18677 }
18678 assert_eq!(g, w, "{plane} vs ffmpeg (seed {seed}, frame {i})");
18679 }
18680 }
18681 compared += 1;
18682 if delta.iter().all(|d| *d == 0) {
18683 uncounted_exact += 1;
18684 refusals.push(format!(
18685 "seed {seed} {cpu} {cq}: decoded and pixel-compared, but no intra rect strip on the \
18686 inter path"
18687 ));
18688 }
18689 for k in 0..3 {
18690 shapes[k] += delta[k];
18691 }
18692 if shapes.iter().filter(|n| **n > 0).count() >= 2 {
18693 break;
18694 }
18695 }
18696 gate_buckets(
18697 NAME,
18698 compared - uncounted_exact,
18699 uncounted_exact,
18700 refusals.len() - uncounted_exact as usize,
18701 );
18702 eprintln!(
18703 "{NAME} ({bit_depth}-bit): compared {compared} streams, intra rect strips in inter \
18704 frames per shape: 64x32/32x64={} 32x16/16x32={} 16x8/8x16={}; refusals:\n{}",
18705 shapes[0],
18706 shapes[1],
18707 shapes[2],
18708 refusals.join("\n")
18709 );
18710 assert!(
18711 compared > 0,
18712 "{NAME} ({bit_depth}-bit): every attempt hit a named refusal -- nothing was \
18713 pixel-compared:\n{}",
18714 refusals.join("\n")
18715 );
18716 // MEASURED (r1, 90 attempts; r2 re-ran the 45-attempt sweep at both
18717 // depths): only the 32x16/16x32 class is REACHABLE on this branch --
18718 // the inter tile path refuses any SB-level partition other than
18719 // NONE/SPLIT, so a 64x32/32x64 intra strip cannot be produced at all,
18720 // and every 16x8/8x16 candidate stops at a sub-16 refusal owned by
18721 // another lane. So the bar is that class, hard, not "two of three":
18722 // a green run still cannot come from a stream that fired nothing.
18723 assert!(
18724 shapes[1] > 0,
18725 "{NAME} ({bit_depth}-bit): no 32x16/16x32 intra rect strip fired over \
18726 {compared} compared streams (64-level={} 32-level={} 16-level={})",
18727 shapes[0],
18728 shapes[1],
18729 shapes[2]
18730 );
18731 }
18732
18733 fn tx_select_inter_gate(bit_depth: u32) {
18734 if !have_ffmpeg() {
18735 eprintln!(
18736 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no ffmpeg"
18737 );
18738 return;
18739 }
18740 if !have_aomenc() {
18741 eprintln!(
18742 "SKIP a_real_aomenc_inter_sequence_with_tx_select_decodes_pixel_exact: no aomenc at {}",
18743 aomenc_path().display()
18744 );
18745 return;
18746 }
18747 let (width, height, frame_count) = (64usize, 64usize, 4usize);
18748 let mut refusals = Vec::new();
18749 let mut uncounted_exact = 0u32;
18750 for attempt in 0..40u32 {
18751 let seed = 42 + attempt;
18752 // Detail is what makes aomenc's RD prefer a split transform; a
18753 // flat gradient resolves every `txfm_split` to 0. `mandelbrot`'s
18754 // fractal boundary is the same source the sibling intra tx-select
18755 // gate uses, at a different `start_scale` per attempt.
18756 let source = format!(
18757 "mandelbrot=size=64x64:start_scale={}:rate=25",
18758 5.0 - f64::from(attempt) * 0.06
18759 );
18760 let y4m = Command::new("ffmpeg")
18761 .args([
18762 "-v",
18763 "error",
18764 "-f",
18765 "lavfi",
18766 "-i",
18767 &source,
18768 // Desaturated chroma: `uv_mode` stays DC_PRED, so the
18769 // still-refused directional-chroma gap never fires and
18770 // luma detail alone drives the transform split.
18771 "-vf",
18772 "hue=s=0",
18773 "-pix_fmt",
18774 if bit_depth == 10 {
18775 "yuv420p10le"
18776 } else {
18777 "yuv420p"
18778 },
18779 // y4m carries no official 10-bit tag; ffmpeg writes one
18780 // only under `-strict -1` (a no-op at 8 bit).
18781 "-strict",
18782 "-1",
18783 "-t",
18784 "0.16",
18785 "-f",
18786 "yuv4mpegpipe",
18787 "-strict",
18788 "-1",
18789 "-",
18790 ])
18791 .stdin(Stdio::null())
18792 .stdout(Stdio::piped())
18793 .stderr(Stdio::piped())
18794 .output()
18795 .expect("ffmpeg failed to run");
18796 assert!(
18797 y4m.status.success(),
18798 "ffmpeg fixture: {}",
18799 String::from_utf8_lossy(&y4m.stderr)
18800 );
18801 let depth_args: &[&str] = if bit_depth == 10 {
18802 &["-b", "10", "--input-bit-depth=10"]
18803 } else {
18804 &[]
18805 };
18806 let out = run_with_stdin(
18807 Command::new(aomenc_path()).args(depth_args).args([
18808 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
18809 // occurrence, so overrides go before the base list).
18810 "--enable-tx-size-search=1",
18811 "--codec=av1",
18812 "--passes=1",
18813 "--end-usage=q",
18814 "--cq-level=55",
18815 "--cpu-used=0",
18816 "--lag-in-frames=0",
18817 "--auto-alt-ref=0",
18818 "--kf-max-dist=1000",
18819 "--threads=1",
18820 "--row-mt=0",
18821 "--enable-order-hint=0",
18822 "--enable-warped-motion=0",
18823 "--enable-obmc=0",
18824 "--enable-masked-comp=0",
18825 "--enable-interintra-comp=0",
18826 "--enable-dist-wtd-comp=0",
18827 "--enable-diff-wtd-comp=0",
18828 "--enable-onesided-comp=0",
18829 "--enable-interintra-wedge=0",
18830 "--enable-smooth-interintra=0",
18831 "--enable-rect-partitions=0",
18832 "--enable-ab-partitions=0",
18833 "--enable-1to4-partitions=0",
18834 "--enable-filter-intra=0",
18835 "--enable-smooth-intra=0",
18836 "--enable-paeth-intra=0",
18837 "--enable-directional-intra=0",
18838 "--enable-angle-delta=0",
18839 // DELIBERATELY ABSENT: --enable-tx-size-search=0.
18840 "--enable-cdef=0",
18841 "--enable-restoration=0",
18842 "--max-partition-size=32",
18843 // Sub-16 inter partitions are a separate named refusal
18844 // (this decoder codes no inter block below 16x16 through
18845 // the square path this gate drives), and detailed content
18846 // makes aomenc's RD reach for them on nearly every seed.
18847 "--min-partition-size=16",
18848 "--enable-palette=0",
18849 "--enable-intrabc=0",
18850 "--enable-cfl-intra=0",
18851 "--enable-ref-frame-mvs=0",
18852 "--obu",
18853 "-o",
18854 "-",
18855 "-",
18856 ]),
18857 &y4m.stdout,
18858 );
18859 assert!(
18860 out.status.success(),
18861 "aomenc refused the fixture: {}",
18862 String::from_utf8_lossy(&out.stderr)
18863 );
18864 let stream = out.stdout;
18865 let (reads_before, hits_before) =
18866 (decode::txfm_split_reads(), decode::txfm_split_hits());
18867 let frames = match decode_stream(&stream) {
18868 Ok(frames) => frames,
18869 Err(e) => {
18870 let msg = e.to_string();
18871 assert!(
18872 msg.contains("unsupported"),
18873 "tx-select inter decode failed outright (seed {seed}): {msg}"
18874 );
18875 refusals.push(format!("seed {seed}: {msg}"));
18876 continue;
18877 }
18878 };
18879 let (reads, hits) = (
18880 decode::txfm_split_reads() - reads_before,
18881 decode::txfm_split_hits() - hits_before,
18882 );
18883 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
18884 // is ALWAYS pixel-compared below; the hit counter only decides whether
18885 // the attempt counts toward the firing total.
18886 let counted = hits != 0;
18887 if !counted {
18888 uncounted_exact += 1;
18889 refusals.push(format!(
18890 "seed {seed}: decoded and pixel-compared, but no block took a txfm_split \
18891 ({reads} symbols read)"
18892 ));
18893 }
18894 let ffmpeg_frames = if bit_depth == 10 {
18895 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
18896 } else {
18897 ffmpeg_decode_sequence(&stream, width, height, frame_count)
18898 };
18899 assert_eq!(frames.len(), frame_count);
18900 eprintln!(
18901 "txselect gate {bit_depth}-bit seed={seed}: txfm_split reads={reads} splits taken={hits}"
18902 );
18903 // Name the first differing sample before the assert fires: a
18904 // 64x64 plane's `assert_eq!` output is 4096 numbers, useless for
18905 // locating a desync.
18906 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18907 for (plane, (g, w)) in [
18908 ("Y", (&got.y, &want.y)),
18909 ("U", (&got.u, &want.u)),
18910 ("V", (&got.v, &want.v)),
18911 ] {
18912 let stride = if plane == "Y" { width } else { width / 2 };
18913 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
18914 eprintln!(
18915 "txselect gate seed={seed}: frame {i} {plane} first diff at \
18916 ({}, {}) got {} want {} ({} samples differ)",
18917 at % stride,
18918 at / stride,
18919 g[at],
18920 w[at],
18921 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
18922 );
18923 let coords: Vec<String> = g
18924 .iter()
18925 .zip(w.iter())
18926 .enumerate()
18927 .filter(|(_, (a, b))| a != b)
18928 .take(12)
18929 .map(|(k, (a, b))| format!("({},{})={a}/{b}", k % stride, k / stride))
18930 .collect();
18931 eprintln!("txselect gate seed={seed}: frame {i} {plane} diffs {coords:?}");
18932 }
18933 }
18934 }
18935 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
18936 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
18937 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
18938 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
18939 }
18940 if counted {
18941 gate_buckets(
18942 &format!("tx_select_inter_gate({bit_depth})"),
18943 1,
18944 uncounted_exact,
18945 refusals.len() - uncounted_exact as usize,
18946 );
18947 return;
18948 }
18949 }
18950 gate_buckets(
18951 &format!("tx_select_inter_gate({bit_depth})"),
18952 0,
18953 uncounted_exact,
18954 refusals.len() - uncounted_exact as usize,
18955 );
18956 panic!(
18957 "tx_select_inter_gate({bit_depth}) never observed a taken txfm_split:\n{}",
18958 refusals.join("\n")
18959 );
18960 }
18961
18962 /// lane-intrainter r1's decisive gate: a real aomenc INTER sequence in
18963 /// which aomenc's RD picks an INTRA block inside an inter frame AND
18964 /// splits that block's luma transform (`tx_depth >= 1`, the intra depth
18965 /// symbol -- not the inter var-tx tree). That block codes one intra
18966 /// prediction plus one coefficient set per transform unit, exactly like a
18967 /// key frame's split block but with the inter frame's CDF state and the
18968 /// inter-frame intra mode syntax; before this lane it was a named
18969 /// refusal. Hard-asserts [`decode::intra_in_inter_split_tx_hits`] per
18970 /// block size: an attempt that never produced such a block proves
18971 /// nothing, and exhausting every attempt is a FAILURE, not a SKIP.
18972 #[test]
18973 fn a_real_aomenc_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
18974 intra_in_inter_split_tx_gate(8);
18975 }
18976
18977 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
18978 #[test]
18979 fn a_real_aomenc_10bit_inter_sequence_with_a_split_transform_intra_block_decodes_pixel_exact() {
18980 intra_in_inter_split_tx_gate(10);
18981 }
18982
18983 fn intra_in_inter_split_tx_gate(bit_depth: u32) {
18984 let name = format!("intra_in_inter_split_tx_gate({bit_depth})");
18985 if !have_ffmpeg() {
18986 eprintln!("SKIP {name}: no ffmpeg");
18987 return;
18988 }
18989 if !have_aomenc() {
18990 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
18991 return;
18992 }
18993 let (width, height, frame_count) = (64usize, 64usize, 8usize);
18994 let mut refusals = Vec::new();
18995 let mut uncounted_exact = 0u32;
18996 for attempt in 0..40u32 {
18997 let seed = 42 + attempt;
18998 // A zooming fractal: every frame moves (so the sequence is
18999 // genuinely inter-coded) and keeps sharp new detail entering at
19000 // the borders, which is what makes aomenc's RD choose an INTRA
19001 // block inside an inter frame -- and then split its transform.
19002 // A zooming fractal with a hard CUT halfway (`overlay` switching
19003 // a second, unrelated fractal on at frame 4): after the cut every
19004 // block is unpredictable from the reference, which is what makes
19005 // aomenc code INTRA blocks inside an inter frame -- and at this
19006 // cq the RD then splits their transforms.
19007 let source = format!(
19008 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
19009 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
19010 [a][b]overlay=enable='gte(n,4)'",
19011 5.0 - f64::from(attempt) * 0.06,
19012 0.9 + f64::from(attempt) * 0.11
19013 );
19014 let y4m = Command::new("ffmpeg")
19015 .args([
19016 "-v",
19017 "error",
19018 "-f",
19019 "lavfi",
19020 "-i",
19021 &source,
19022 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
19023 // still-refused directional-chroma gaps never fire and
19024 // luma detail alone drives the transform split.
19025 "-vf",
19026 "hue=s=0",
19027 "-pix_fmt",
19028 if bit_depth == 10 {
19029 "yuv420p10le"
19030 } else {
19031 "yuv420p"
19032 },
19033 "-strict",
19034 "-1",
19035 "-t",
19036 "0.32",
19037 "-f",
19038 "yuv4mpegpipe",
19039 "-strict",
19040 "-1",
19041 "-",
19042 ])
19043 .stdin(Stdio::null())
19044 .stdout(Stdio::piped())
19045 .stderr(Stdio::piped())
19046 .output()
19047 .expect("ffmpeg failed to run");
19048 assert!(
19049 y4m.status.success(),
19050 "ffmpeg fixture: {}",
19051 String::from_utf8_lossy(&y4m.stderr)
19052 );
19053 let depth_args: &[&str] = if bit_depth == 10 {
19054 &["-b", "10", "--input-bit-depth=10"]
19055 } else {
19056 &[]
19057 };
19058 let out = run_with_stdin(
19059 Command::new(aomenc_path()).args(depth_args).args([
19060 "--codec=av1",
19061 "--passes=1",
19062 "--end-usage=q",
19063 "--cq-level=30",
19064 "--cpu-used=0",
19065 "--lag-in-frames=0",
19066 "--auto-alt-ref=0",
19067 // One key frame only: every later frame is an inter frame,
19068 // which is where this gate's intra blocks must sit. The
19069 // MIN distance is what stops aomenc's scene-cut detector
19070 // from inserting a second key frame at the cut this gate's
19071 // source deliberately contains.
19072 "--kf-max-dist=1000",
19073 "--kf-min-dist=1000",
19074 "--threads=1",
19075 "--row-mt=0",
19076 "--enable-order-hint=0",
19077 "--enable-warped-motion=0",
19078 "--enable-obmc=0",
19079 "--enable-masked-comp=0",
19080 "--enable-interintra-comp=0",
19081 "--enable-dist-wtd-comp=0",
19082 "--enable-diff-wtd-comp=0",
19083 "--enable-onesided-comp=0",
19084 "--enable-interintra-wedge=0",
19085 "--enable-smooth-interintra=0",
19086 "--enable-ab-partitions=0",
19087 "--enable-1to4-partitions=0",
19088 "--enable-filter-intra=0",
19089 "--enable-smooth-intra=0",
19090 "--enable-paeth-intra=0",
19091 "--enable-directional-intra=0",
19092 "--enable-angle-delta=0",
19093 "--enable-cdef=0",
19094 "--enable-restoration=0",
19095 "--enable-palette=0",
19096 "--enable-intrabc=0",
19097 "--enable-cfl-intra=0",
19098 "--enable-ref-frame-mvs=0",
19099 // Per-arm overrides go LAST (aomenc keeps the last
19100 // occurrence of a repeated --enable-* flag): the intra
19101 // tx_depth symbol only exists under TX_MODE_SELECT, and
19102 // rect partitions are a separate named refusal.
19103 "--enable-tx-size-search=1",
19104 "--enable-rect-partitions=0",
19105 "--max-partition-size=32",
19106 // Sub-16 inter partitions are a separate named refusal,
19107 // as is the 8x8 intra leaf's own TX_4X4 split.
19108 "--min-partition-size=16",
19109 "--obu",
19110 "-o",
19111 "-",
19112 "-",
19113 ]),
19114 &y4m.stdout,
19115 );
19116 assert!(
19117 out.status.success(),
19118 "aomenc refused the fixture: {}",
19119 String::from_utf8_lossy(&out.stderr)
19120 );
19121 let stream = out.stdout;
19122 let before = decode::intra_in_inter_split_tx_hits();
19123 let frames = match decode_stream(&stream) {
19124 Ok(frames) => frames,
19125 Err(e) => {
19126 let msg = e.to_string();
19127 assert!(
19128 msg.contains("unsupported"),
19129 "{name} decode failed outright (seed {seed}): {msg}"
19130 );
19131 refusals.push(format!("seed {seed}: {msg}"));
19132 continue;
19133 }
19134 };
19135 let after = decode::intra_in_inter_split_tx_hits();
19136 let mut per_size = [0usize; 4];
19137 for i in 0..4 {
19138 per_size[i] = after[i] - before[i];
19139 }
19140 // class [[gate-skips-on-its-own-failure]]: a decode that
19141 // succeeded is ALWAYS pixel-compared below; the counter only
19142 // decides whether the attempt counts as firing.
19143 let counted = per_size.iter().sum::<usize>() != 0;
19144 if !counted {
19145 uncounted_exact += 1;
19146 refusals.push(format!(
19147 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
19148 frame split its transform"
19149 ));
19150 }
19151 let ffmpeg_frames = if bit_depth == 10 {
19152 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
19153 } else {
19154 ffmpeg_decode_sequence(&stream, width, height, frame_count)
19155 };
19156 assert_eq!(frames.len(), frame_count);
19157 eprintln!(
19158 "{name} seed={seed}: split intra-in-inter blocks 8x8={} 16x16={} 32x32={} \
19159 64x64={}",
19160 per_size[0], per_size[1], per_size[2], per_size[3]
19161 );
19162 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19163 for (plane, (g, w)) in [
19164 ("Y", (&got.y, &want.y)),
19165 ("U", (&got.u, &want.u)),
19166 ("V", (&got.v, &want.v)),
19167 ] {
19168 let stride = if plane == "Y" { width } else { width / 2 };
19169 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
19170 eprintln!(
19171 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
19172 want {} ({} samples differ)",
19173 at % stride,
19174 at / stride,
19175 g[at],
19176 w[at],
19177 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
19178 );
19179 }
19180 }
19181 }
19182 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19183 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
19184 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
19185 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
19186 }
19187 if counted {
19188 gate_buckets(
19189 &name,
19190 1,
19191 uncounted_exact,
19192 refusals.len() - uncounted_exact as usize,
19193 );
19194 return;
19195 }
19196 }
19197 gate_buckets(
19198 &name,
19199 0,
19200 uncounted_exact,
19201 refusals.len() - uncounted_exact as usize,
19202 );
19203 panic!(
19204 "{name} never observed a split-transform intra block in an inter frame:\n{}",
19205 refusals.join("\n")
19206 );
19207 }
19208
19209 /// lane-fiinter r1 (class [[symbol-consumption-gap]] +
19210 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
19211 /// `--enable-filter-intra=1` (aomenc's own default -- every inter gate
19212 /// recipe before this one pinned it OFF, so nothing ever exercised it) in
19213 /// which the RD picks an INTRA block inside an inter frame and gives it
19214 /// filter intra. `read_intra_block_mode_info` reads `use_filter_intra`
19215 /// there exactly as a key frame does; this decoder read no such symbol at
19216 /// all until this round, so such a stream desynced at that symbol and
19217 /// decoded silently wrong. Hard-asserts
19218 /// [`decode::intra_in_inter_filter_intra_hits`]: an attempt that never
19219 /// produced one proves nothing, and exhausting every attempt is a
19220 /// FAILURE, not a SKIP.
19221 #[test]
19222 fn a_real_aomenc_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact() {
19223 filter_intra_in_inter_gate(8);
19224 }
19225
19226 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
19227 #[test]
19228 fn a_real_aomenc_10bit_inter_sequence_with_filter_intra_on_an_intra_block_decodes_pixel_exact()
19229 {
19230 filter_intra_in_inter_gate(10);
19231 }
19232
19233 fn filter_intra_in_inter_gate(bit_depth: u32) {
19234 let name = format!("filter_intra_in_inter_gate({bit_depth})");
19235 if !have_ffmpeg() {
19236 eprintln!("SKIP {name}: no ffmpeg");
19237 return;
19238 }
19239 if !have_aomenc() {
19240 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
19241 return;
19242 }
19243 let (width, height, frame_count) = (64usize, 64usize, 8usize);
19244 let mut refusals = Vec::new();
19245 let mut uncounted_exact = 0u32;
19246 for attempt in 0..40u32 {
19247 let seed = 42 + attempt;
19248 // A zooming fractal: every frame moves (so the sequence is
19249 // genuinely inter-coded) and keeps sharp new detail entering at
19250 // the borders, which is what makes aomenc's RD choose an INTRA
19251 // block inside an inter frame -- and then split its transform.
19252 // A zooming fractal with a hard CUT halfway (`overlay` switching
19253 // a second, unrelated fractal on at frame 4): after the cut every
19254 // block is unpredictable from the reference, which is what makes
19255 // aomenc code INTRA blocks inside an inter frame -- and at this
19256 // cq the RD then splits their transforms.
19257 let source = format!(
19258 "mandelbrot=size=64x64:start_scale={}:rate=25[a];\
19259 mandelbrot=size=64x64:start_scale={}:rate=25[b];\
19260 [a][b]overlay=enable='gte(n,4)'",
19261 5.0 - f64::from(attempt) * 0.06,
19262 0.9 + f64::from(attempt) * 0.11
19263 );
19264 let y4m = Command::new("ffmpeg")
19265 .args([
19266 "-v",
19267 "error",
19268 "-f",
19269 "lavfi",
19270 "-i",
19271 &source,
19272 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
19273 // still-refused directional-chroma gaps never fire and
19274 // luma detail alone drives the transform split.
19275 "-vf",
19276 "hue=s=0",
19277 "-pix_fmt",
19278 if bit_depth == 10 {
19279 "yuv420p10le"
19280 } else {
19281 "yuv420p"
19282 },
19283 "-strict",
19284 "-1",
19285 "-t",
19286 "0.32",
19287 "-f",
19288 "yuv4mpegpipe",
19289 "-strict",
19290 "-1",
19291 "-",
19292 ])
19293 .stdin(Stdio::null())
19294 .stdout(Stdio::piped())
19295 .stderr(Stdio::piped())
19296 .output()
19297 .expect("ffmpeg failed to run");
19298 assert!(
19299 y4m.status.success(),
19300 "ffmpeg fixture: {}",
19301 String::from_utf8_lossy(&y4m.stderr)
19302 );
19303 let depth_args: &[&str] = if bit_depth == 10 {
19304 &["-b", "10", "--input-bit-depth=10"]
19305 } else {
19306 &[]
19307 };
19308 let out = run_with_stdin(
19309 Command::new(aomenc_path()).args(depth_args).args([
19310 "--codec=av1",
19311 "--passes=1",
19312 "--end-usage=q",
19313 "--cq-level=30",
19314 "--cpu-used=0",
19315 "--lag-in-frames=0",
19316 "--auto-alt-ref=0",
19317 // One key frame only: every later frame is an inter frame,
19318 // which is where this gate's intra blocks must sit. The
19319 // MIN distance is what stops aomenc's scene-cut detector
19320 // from inserting a second key frame at the cut this gate's
19321 // source deliberately contains.
19322 "--kf-max-dist=1000",
19323 "--kf-min-dist=1000",
19324 "--threads=1",
19325 "--row-mt=0",
19326 "--enable-order-hint=0",
19327 "--enable-warped-motion=0",
19328 "--enable-obmc=0",
19329 "--enable-masked-comp=0",
19330 "--enable-interintra-comp=0",
19331 "--enable-dist-wtd-comp=0",
19332 "--enable-diff-wtd-comp=0",
19333 "--enable-onesided-comp=0",
19334 "--enable-interintra-wedge=0",
19335 "--enable-smooth-interintra=0",
19336 "--enable-ab-partitions=0",
19337 "--enable-1to4-partitions=0",
19338 "--enable-smooth-intra=0",
19339 "--enable-paeth-intra=0",
19340 "--enable-directional-intra=0",
19341 "--enable-angle-delta=0",
19342 "--enable-cdef=0",
19343 "--enable-restoration=0",
19344 "--enable-palette=0",
19345 "--enable-intrabc=0",
19346 "--enable-cfl-intra=0",
19347 "--enable-ref-frame-mvs=0",
19348 // Per-arm overrides go LAST (aomenc keeps the last
19349 // occurrence of a repeated --enable-* flag): the intra
19350 // tx_depth symbol only exists under TX_MODE_SELECT, and
19351 // rect partitions are a separate named refusal.
19352 "--enable-filter-intra=1",
19353 "--enable-tx-size-search=1",
19354 "--enable-rect-partitions=0",
19355 "--max-partition-size=32",
19356 // Sub-16 inter partitions are a separate named refusal,
19357 // as is the 8x8 intra leaf's own TX_4X4 split.
19358 "--min-partition-size=16",
19359 "--obu",
19360 "-o",
19361 "-",
19362 "-",
19363 ]),
19364 &y4m.stdout,
19365 );
19366 assert!(
19367 out.status.success(),
19368 "aomenc refused the fixture: {}",
19369 String::from_utf8_lossy(&out.stderr)
19370 );
19371 let stream = out.stdout;
19372 let before = decode::intra_in_inter_filter_intra_hits();
19373 let frames = match decode_stream(&stream) {
19374 Ok(frames) => frames,
19375 Err(e) => {
19376 let msg = e.to_string();
19377 assert!(
19378 msg.contains("unsupported"),
19379 "{name} decode failed outright (seed {seed}): {msg}"
19380 );
19381 refusals.push(format!("seed {seed}: {msg}"));
19382 continue;
19383 }
19384 };
19385 let fired = decode::intra_in_inter_filter_intra_hits() - before;
19386 // class [[gate-skips-on-its-own-failure]]: a decode that
19387 // succeeded is ALWAYS pixel-compared below; the counter only
19388 // decides whether the attempt counts as firing.
19389 let counted = fired != 0;
19390 if !counted {
19391 uncounted_exact += 1;
19392 refusals.push(format!(
19393 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
19394 frame used filter intra"
19395 ));
19396 }
19397 let ffmpeg_frames = if bit_depth == 10 {
19398 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
19399 } else {
19400 ffmpeg_decode_sequence(&stream, width, height, frame_count)
19401 };
19402 assert_eq!(frames.len(), frame_count);
19403 eprintln!("{name} seed={seed}: filter-intra blocks inside inter frames = {fired}");
19404 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19405 for (plane, (g, w)) in [
19406 ("Y", (&got.y, &want.y)),
19407 ("U", (&got.u, &want.u)),
19408 ("V", (&got.v, &want.v)),
19409 ] {
19410 let stride = if plane == "Y" { width } else { width / 2 };
19411 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
19412 eprintln!(
19413 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
19414 want {} ({} samples differ)",
19415 at % stride,
19416 at / stride,
19417 g[at],
19418 w[at],
19419 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
19420 );
19421 }
19422 }
19423 }
19424 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19425 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
19426 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
19427 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
19428 }
19429 if counted {
19430 gate_buckets(
19431 &name,
19432 1,
19433 uncounted_exact,
19434 refusals.len() - uncounted_exact as usize,
19435 );
19436 return;
19437 }
19438 }
19439 gate_buckets(
19440 &name,
19441 0,
19442 uncounted_exact,
19443 refusals.len() - uncounted_exact as usize,
19444 );
19445 panic!(
19446 "{name} never observed a filter-intra intra block in an inter frame:\n{}",
19447 refusals.join("\n")
19448 );
19449 }
19450
19451 /// lane-angleinter r1 (class [[refusal-strings-are-claims]] +
19452 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
19453 /// `--enable-angle-delta=1` and `--enable-directional-intra=1` (aomenc's
19454 /// own defaults; every inter gate before this one pinned BOTH off) in
19455 /// which the RD gives an INTRA block inside an inter frame a directional
19456 /// luma mode with a nonzero `angle_delta_y`. Both intra-in-inter arms
19457 /// read that symbol and then REFUSED it as "this encoder never writes
19458 /// one" -- the claim is false, `read_intra_angle_info` writes it exactly
19459 /// as a key frame does. Hard-asserts
19460 /// [`decode::intra_in_inter_angle_delta_y_hits`]; an attempt that never
19461 /// produced one proves nothing, and exhausting every attempt is a
19462 /// FAILURE, not a SKIP.
19463 #[test]
19464 fn a_real_aomenc_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
19465 {
19466 angle_delta_in_inter_gate(8, "--min-partition-size=16");
19467 }
19468
19469 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
19470 #[test]
19471 fn a_real_aomenc_10bit_inter_sequence_with_a_directional_intra_block_with_angle_delta_decodes_pixel_exact()
19472 {
19473 angle_delta_in_inter_gate(10, "--min-partition-size=16");
19474 }
19475
19476 fn angle_delta_in_inter_gate(bit_depth: u32, min_partition: &str) {
19477 let name = format!("angle_delta_in_inter_gate({bit_depth}, min={min_partition})");
19478 let leaf8 = min_partition.ends_with('8');
19479 assert!(
19480 !leaf8,
19481 "the 8x8-leaf arm keeps its refusal; see the module note"
19482 );
19483 if !have_ffmpeg() {
19484 eprintln!("SKIP {name}: no ffmpeg");
19485 return;
19486 }
19487 if !have_aomenc() {
19488 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
19489 return;
19490 }
19491 let (width, height, frame_count) = (64usize, 64usize, 8usize);
19492 let mut refusals = Vec::new();
19493 let mut uncounted_exact = 0u32;
19494 for attempt in 0..40u32 {
19495 let seed = 42 + attempt;
19496 // A zooming fractal: every frame moves (so the sequence is
19497 // genuinely inter-coded) and keeps sharp new detail entering at
19498 // the borders, which is what makes aomenc's RD choose an INTRA
19499 // block inside an inter frame -- and then split its transform.
19500 // A zooming fractal with a hard CUT halfway (`overlay` switching
19501 // a second, unrelated fractal on at frame 4): after the cut every
19502 // block is unpredictable from the reference, which is what makes
19503 // aomenc code INTRA blocks inside an inter frame -- and at this
19504 // cq the RD then splits their transforms.
19505 let source = format!(
19506 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
19507 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
19508 [a][b]overlay=enable='gte(n,4)'",
19509 5.0 - f64::from(attempt) * 0.06,
19510 0.9 + f64::from(attempt) * 0.11
19511 );
19512 let y4m = Command::new("ffmpeg")
19513 .args([
19514 "-v",
19515 "error",
19516 "-f",
19517 "lavfi",
19518 "-i",
19519 &source,
19520 // Desaturated chroma keeps `uv_mode` on DC_PRED, so the
19521 // still-refused directional-chroma gaps never fire and
19522 // luma detail alone drives the transform split.
19523 "-vf",
19524 "hue=s=0",
19525 "-pix_fmt",
19526 if bit_depth == 10 {
19527 "yuv420p10le"
19528 } else {
19529 "yuv420p"
19530 },
19531 "-strict",
19532 "-1",
19533 "-t",
19534 "0.32",
19535 "-f",
19536 "yuv4mpegpipe",
19537 "-strict",
19538 "-1",
19539 "-",
19540 ])
19541 .stdin(Stdio::null())
19542 .stdout(Stdio::piped())
19543 .stderr(Stdio::piped())
19544 .output()
19545 .expect("ffmpeg failed to run");
19546 assert!(
19547 y4m.status.success(),
19548 "ffmpeg fixture: {}",
19549 String::from_utf8_lossy(&y4m.stderr)
19550 );
19551 // The 8x8-leaf arm is fenced by three sibling refusals (non-DC
19552 // chroma on an 8x8 leaf, its TX_4X4 split, sub-16 rect inter
19553 // leaves), so it sweeps the quantiser as well as the source: a
19554 // coarser q is what pushes the RD to directional intra at 8x8.
19555 let cq = if leaf8 {
19556 format!("--cq-level={}", 20 + (attempt % 5) * 10)
19557 } else {
19558 "--cq-level=30".to_string()
19559 };
19560 let depth_args: &[&str] = if bit_depth == 10 {
19561 &["-b", "10", "--input-bit-depth=10"]
19562 } else {
19563 &[]
19564 };
19565 let out = run_with_stdin(
19566 Command::new(aomenc_path()).args(depth_args).args([
19567 "--codec=av1",
19568 "--passes=1",
19569 "--end-usage=q",
19570 &cq,
19571 "--cpu-used=0",
19572 "--lag-in-frames=0",
19573 "--auto-alt-ref=0",
19574 // One key frame only: every later frame is an inter frame,
19575 // which is where this gate's intra blocks must sit. The
19576 // MIN distance is what stops aomenc's scene-cut detector
19577 // from inserting a second key frame at the cut this gate's
19578 // source deliberately contains.
19579 "--kf-max-dist=1000",
19580 "--kf-min-dist=1000",
19581 "--threads=1",
19582 "--row-mt=0",
19583 "--enable-order-hint=0",
19584 "--enable-warped-motion=0",
19585 "--enable-obmc=0",
19586 "--enable-masked-comp=0",
19587 "--enable-interintra-comp=0",
19588 "--enable-dist-wtd-comp=0",
19589 "--enable-diff-wtd-comp=0",
19590 "--enable-onesided-comp=0",
19591 "--enable-interintra-wedge=0",
19592 "--enable-smooth-interintra=0",
19593 "--enable-ab-partitions=0",
19594 "--enable-1to4-partitions=0",
19595 "--enable-smooth-intra=0",
19596 "--enable-paeth-intra=0",
19597 "--enable-directional-intra=1",
19598 "--enable-angle-delta=1",
19599 "--enable-cdef=0",
19600 "--enable-restoration=0",
19601 "--enable-palette=0",
19602 "--enable-intrabc=0",
19603 "--enable-cfl-intra=0",
19604 "--enable-ref-frame-mvs=0",
19605 // Per-arm overrides go LAST (aomenc keeps the last
19606 // occurrence of a repeated --enable-* flag): the intra
19607 // tx_depth symbol only exists under TX_MODE_SELECT, and
19608 // rect partitions are a separate named refusal.
19609 "--enable-filter-intra=1",
19610 "--enable-tx-size-search=1",
19611 "--enable-rect-partitions=0",
19612 "--max-partition-size=32",
19613 // Sub-16 inter partitions are a separate named refusal,
19614 // as is the 8x8 intra leaf's own TX_4X4 split.
19615 min_partition,
19616 "--obu",
19617 "-o",
19618 "-",
19619 "-",
19620 ]),
19621 &y4m.stdout,
19622 );
19623 assert!(
19624 out.status.success(),
19625 "aomenc refused the fixture: {}",
19626 String::from_utf8_lossy(&out.stderr)
19627 );
19628 let stream = out.stdout;
19629 let before = decode::intra_in_inter_angle_delta_y_hits();
19630 let before_uv = decode::intra_in_inter_angle_delta_uv_hits();
19631 let frames = match decode_stream(&stream) {
19632 Ok(frames) => frames,
19633 Err(e) => {
19634 let msg = e.to_string();
19635 assert!(
19636 msg.contains("unsupported"),
19637 "{name} decode failed outright (seed {seed}): {msg}"
19638 );
19639 refusals.push(format!("seed {seed}: {msg}"));
19640 continue;
19641 }
19642 };
19643 let fired = decode::intra_in_inter_angle_delta_y_hits() - before;
19644 let fired_uv = decode::intra_in_inter_angle_delta_uv_hits() - before_uv;
19645 // class [[gate-skips-on-its-own-failure]]: a decode that
19646 // succeeded is ALWAYS pixel-compared below; the counter only
19647 // decides whether the attempt counts as firing.
19648 let counted = fired != 0;
19649 if !counted {
19650 uncounted_exact += 1;
19651 refusals.push(format!(
19652 "seed {seed}: decoded and pixel-compared, but no intra block in an inter \
19653 frame carried a nonzero angle_delta_y"
19654 ));
19655 }
19656 let ffmpeg_frames = if bit_depth == 10 {
19657 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
19658 } else {
19659 ffmpeg_decode_sequence(&stream, width, height, frame_count)
19660 };
19661 assert_eq!(frames.len(), frame_count);
19662 eprintln!(
19663 "{name} seed={seed}: intra-in-inter blocks with a nonzero angle_delta_y = \
19664 {fired}, angle_delta_uv = {fired_uv}"
19665 );
19666 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19667 for (plane, (g, w)) in [
19668 ("Y", (&got.y, &want.y)),
19669 ("U", (&got.u, &want.u)),
19670 ("V", (&got.v, &want.v)),
19671 ] {
19672 let stride = if plane == "Y" { width } else { width / 2 };
19673 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
19674 eprintln!(
19675 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
19676 want {} ({} samples differ)",
19677 at % stride,
19678 at / stride,
19679 g[at],
19680 w[at],
19681 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
19682 );
19683 }
19684 }
19685 }
19686 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19687 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
19688 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
19689 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
19690 }
19691 if counted {
19692 gate_buckets(
19693 &name,
19694 1,
19695 uncounted_exact,
19696 refusals.len() - uncounted_exact as usize,
19697 );
19698 return;
19699 }
19700 }
19701 gate_buckets(
19702 &name,
19703 0,
19704 uncounted_exact,
19705 refusals.len() - uncounted_exact as usize,
19706 );
19707 panic!(
19708 "{name} never observed a nonzero angle delta on an intra block in an inter \
19709 frame:\n{}",
19710 refusals.join("\n")
19711 );
19712 }
19713
19714 /// lane-uv8 r1 (classes [[refusal-strings-are-claims]] +
19715 /// [[tool-disabled-in-every-gate]]): a real aomenc inter sequence with
19716 /// 8x8 partitions and full chroma intra tooling
19717 /// (`--enable-cfl-intra=1 --enable-smooth-intra=1 --enable-paeth-intra=1
19718 /// --enable-directional-intra=1`), in which the RD gives an INTRA 8x8
19719 /// leaf inside an inter frame a NON-DC `uv_mode`. That leaf
19720 /// ([`decode::decode_inter_block8`]'s intra arm) read the `uv_mode`
19721 /// symbol and refused every value but `DC_PRED` -- "this encoder never
19722 /// writes one" was a claim, and this gate is what contradicts it. Hard-
19723 /// asserts `decode::intra_in_inter8_uv_hits` (directional, smooth/paeth,
19724 /// CfL, counted on THIS leaf only); an attempt that never produced one
19725 /// proves nothing, and exhausting every attempt is a FAILURE, not a SKIP.
19726 #[test]
19727 fn a_real_aomenc_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact() {
19728 uv_mode_in_inter8_gate(8, 1);
19729 }
19730
19731 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
19732 #[test]
19733 fn a_real_aomenc_10bit_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact()
19734 {
19735 uv_mode_in_inter8_gate(10, 1);
19736 }
19737
19738 /// The multi-tile arm (class [[new-map-ignores-tile-edge]]): this round
19739 /// stamps a new `uv_mode` band from the 8x8 leaf, whose availability must
19740 /// be tile-relative.
19741 #[test]
19742 fn a_real_aomenc_two_tile_inter_sequence_with_a_non_dc_chroma_8x8_intra_leaf_decodes_pixel_exact()
19743 {
19744 uv_mode_in_inter8_gate(8, 2);
19745 }
19746
19747 fn uv_mode_in_inter8_gate(bit_depth: u32, tile_columns: u32) {
19748 let name = format!("uv_mode_in_inter8_gate({bit_depth}, tiles={tile_columns})");
19749 if !have_ffmpeg() {
19750 eprintln!("SKIP {name}: no ffmpeg");
19751 return;
19752 }
19753 if !have_aomenc() {
19754 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
19755 return;
19756 }
19757 let (width, height, frame_count) = (192usize, 128usize, 8usize);
19758 let mut refusals = Vec::new();
19759 let mut uncounted_exact = 0u32;
19760 let mut totals = (0usize, 0usize, 0usize);
19761 for attempt in 0..30u32 {
19762 let seed = 42 + attempt;
19763 // A zooming fractal with a hard CUT at frame 4 (`overlay`
19764 // switching a second, unrelated fractal on): after the cut a block
19765 // is unpredictable from the reference, which is what makes aomenc
19766 // code INTRA blocks inside an inter frame. Chroma is NOT
19767 // desaturated here (every sibling inter gate passes `hue=s=0`) --
19768 // real chroma detail is exactly what pushes the chroma RD off
19769 // DC_PRED. `noise` carries its own explicit seed (lavfi
19770 // `gradients` ignores its seed; class [[seeded-fixture-not-reproducible]]).
19771 let source = format!(
19772 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
19773 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
19774 [a][b]overlay=enable='gte(n,4)',noise=alls=12:allf=t+u:all_seed={seed}",
19775 5.0 - f64::from(attempt) * 0.06,
19776 0.9 + f64::from(attempt) * 0.11
19777 );
19778 let y4m = Command::new("ffmpeg")
19779 .args([
19780 "-v",
19781 "error",
19782 "-f",
19783 "lavfi",
19784 "-i",
19785 &source,
19786 "-pix_fmt",
19787 if bit_depth == 10 {
19788 "yuv420p10le"
19789 } else {
19790 "yuv420p"
19791 },
19792 "-strict",
19793 "-1",
19794 "-t",
19795 "0.32",
19796 "-f",
19797 "yuv4mpegpipe",
19798 "-strict",
19799 "-1",
19800 "-",
19801 ])
19802 .stdin(Stdio::null())
19803 .stdout(Stdio::piped())
19804 .stderr(Stdio::piped())
19805 .output()
19806 .expect("ffmpeg failed to run");
19807 assert!(
19808 y4m.status.success(),
19809 "ffmpeg fixture: {}",
19810 String::from_utf8_lossy(&y4m.stderr)
19811 );
19812 // A coarser quantiser is what pushes the chroma RD to a cheap
19813 // non-DC mode on a small block; sweep 12..40 (the low end is what
19814 // lane-cdef's cq12 arm needs).
19815 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
19816 let depth_args: &[&str] = if bit_depth == 10 {
19817 &["-b", "10", "--input-bit-depth=10"]
19818 } else {
19819 &[]
19820 };
19821 let tiles = format!("--tile-columns={}", tile_columns - 1);
19822 // The y4m goes through a FILE, not aomenc's stdin: this gate's
19823 // stream is ~100 KB, bigger than a pipe buffer, so an aomenc that
19824 // is still being fed on stdin blocks writing its stdout and the
19825 // test blocks writing its stdin -- a hard deadlock (measured
19826 // here, 3 min into attempt 0, class [[gate-loader-slurps-whole-file]]).
19827 // The path is PID-keyed (class [[pid-keyed-temp-path]]).
19828 let y4m_path = std::env::temp_dir().join(format!(
19829 "ec-av1-uv8-{}-{bit_depth}-{tile_columns}-{seed}.y4m",
19830 std::process::id()
19831 ));
19832 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
19833 let child = Command::new(aomenc_path())
19834 .args(depth_args)
19835 .args([
19836 "--codec=av1",
19837 "--passes=1",
19838 "--end-usage=q",
19839 &cq,
19840 "--cpu-used=0",
19841 "--lag-in-frames=0",
19842 "--auto-alt-ref=0",
19843 "--kf-max-dist=9999",
19844 "--kf-min-dist=9999",
19845 "--threads=1",
19846 "--row-mt=0",
19847 &tiles,
19848 "--enable-order-hint=0",
19849 "--enable-warped-motion=0",
19850 "--enable-obmc=0",
19851 "--enable-masked-comp=0",
19852 "--enable-interintra-comp=0",
19853 "--enable-dist-wtd-comp=0",
19854 "--enable-diff-wtd-comp=0",
19855 "--enable-onesided-comp=0",
19856 "--enable-interintra-wedge=0",
19857 "--enable-smooth-interintra=0",
19858 "--enable-ab-partitions=0",
19859 "--enable-1to4-partitions=0",
19860 "--enable-cdef=0",
19861 "--enable-restoration=0",
19862 "--enable-palette=0",
19863 "--enable-intrabc=0",
19864 "--enable-ref-frame-mvs=0",
19865 // Per-arm overrides go LAST (aomenc keeps the LAST
19866 // occurrence of a repeated --enable-* flag). The three
19867 // chroma intra tools this gate is about, plus the fences
19868 // that keep the leaf's SIBLING refusals (its TX_4X4
19869 // split, a nonzero angle delta, sub-16 rect inter leaves)
19870 // out of the way.
19871 "--enable-cfl-intra=1",
19872 "--enable-smooth-intra=1",
19873 "--enable-paeth-intra=1",
19874 "--enable-directional-intra=1",
19875 "--enable-angle-delta=0",
19876 "--enable-tx-size-search=0",
19877 "--enable-rect-partitions=0",
19878 "--min-partition-size=8",
19879 "--max-partition-size=32",
19880 "--obu",
19881 "-o",
19882 "-",
19883 ])
19884 .arg(&y4m_path)
19885 .stdin(Stdio::null())
19886 .stdout(Stdio::piped())
19887 .stderr(Stdio::piped())
19888 .spawn()
19889 .expect("aomenc failed to start");
19890 let out = child.wait_with_output().expect("aomenc failed to run");
19891 let _ = std::fs::remove_file(&y4m_path);
19892 assert!(
19893 out.status.success(),
19894 "aomenc refused the fixture: {}",
19895 String::from_utf8_lossy(&out.stderr)
19896 );
19897 let stream = out.stdout;
19898 let before = decode::intra_in_inter8_uv_hits();
19899 let frames = match decode_stream(&stream) {
19900 Ok(frames) => frames,
19901 Err(e) => {
19902 let msg = e.to_string();
19903 assert!(
19904 msg.contains("unsupported"),
19905 "{name} decode failed outright (seed {seed}): {msg}"
19906 );
19907 refusals.push(format!("seed {seed}: {msg}"));
19908 continue;
19909 }
19910 };
19911 let now = decode::intra_in_inter8_uv_hits();
19912 // class [[counter-from-refused-stream]]: per-attempt deltas, and
19913 // only for an attempt that decoded to the end and is pixel-
19914 // compared below.
19915 let fired = (now.0 - before.0, now.1 - before.1, now.2 - before.2);
19916 totals = (totals.0 + fired.0, totals.1 + fired.1, totals.2 + fired.2);
19917 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
19918 // is ALWAYS pixel-compared; the counter only decides whether the
19919 // attempt counts as firing.
19920 // lane-uv8 r3: every one of the three chroma classes this gate
19921 // exists for (directional, smooth/paeth, CfL) must fire on the
19922 // SAME pixel-compared attempt -- a sum-nonzero predicate would
19923 // pass on an attempt that only ever hit DC-adjacent CfL.
19924 let counted = fired.0 > 0 && fired.1 > 0 && fired.2 > 0;
19925 if !counted {
19926 uncounted_exact += 1;
19927 refusals.push(format!(
19928 "seed {seed}: decoded and pixel-compared, but no 8x8 intra leaf in an inter \
19929 frame carried a non-DC uv_mode"
19930 ));
19931 }
19932 let ffmpeg_frames = if bit_depth == 10 {
19933 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
19934 } else {
19935 ffmpeg_decode_sequence(&stream, width, height, frame_count)
19936 };
19937 assert_eq!(frames.len(), frame_count);
19938 eprintln!(
19939 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with a non-DC uv_mode -- \
19940 directional {}, smooth/paeth {}, CfL {}",
19941 fired.0, fired.1, fired.2
19942 );
19943 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19944 for (plane, (g, w)) in [
19945 ("Y", (&got.y, &want.y)),
19946 ("U", (&got.u, &want.u)),
19947 ("V", (&got.v, &want.v)),
19948 ] {
19949 let stride = if plane == "Y" { width } else { width / 2 };
19950 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
19951 eprintln!(
19952 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
19953 want {} ({} samples differ)",
19954 at % stride,
19955 at / stride,
19956 g[at],
19957 w[at],
19958 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
19959 );
19960 }
19961 }
19962 }
19963 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
19964 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
19965 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
19966 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
19967 }
19968 if counted {
19969 gate_buckets(
19970 &name,
19971 1,
19972 uncounted_exact,
19973 refusals.len() - uncounted_exact as usize,
19974 );
19975 return;
19976 }
19977 }
19978 gate_buckets(
19979 &name,
19980 0,
19981 uncounted_exact,
19982 refusals.len() - uncounted_exact as usize,
19983 );
19984 panic!(
19985 "{name} never observed a non-DC uv_mode on an 8x8 intra leaf in an inter frame \
19986 (totals dir/smooth/cfl {totals:?}):\n{}",
19987 refusals.join("\n")
19988 );
19989 }
19990
19991 /// lane-leaf8tx r1: the refusal this round lifts on an INTRA 8x8 leaf
19992 /// inside an INTER frame -- a nonzero luma `angle_delta_y` on it
19993 /// (`--enable-angle-delta=1`,
19994 /// `av1_use_angle_delta(BLOCK_8X8)`). Both counters are per-attempt
19995 /// deltas on an attempt that decoded to the end and is pixel-compared
19996 /// (class [[counter-from-refused-stream]]); a decode error or a mismatch
19997 /// is a FAILURE, never a SKIP.
19998 #[test]
19999 fn a_real_aomenc_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
20000 tx_split_angle_in_inter8_gate(8);
20001 }
20002
20003 /// The 10-bit arm (both of the user's films are `yuv420p10le`).
20004 #[test]
20005 fn a_real_aomenc_10bit_inter_sequence_with_an_angle_delta_8x8_intra_leaf_decodes_pixel_exact() {
20006 tx_split_angle_in_inter8_gate(10);
20007 }
20008
20009 fn tx_split_angle_in_inter8_gate(bit_depth: u32) {
20010 let name = format!("tx_split_angle_in_inter8_gate({bit_depth})");
20011 if !have_ffmpeg() {
20012 eprintln!("SKIP {name}: no ffmpeg");
20013 return;
20014 }
20015 if !have_aomenc() {
20016 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
20017 return;
20018 }
20019 let (width, height, frame_count) = (192usize, 128usize, 6usize);
20020 let mut refusals = Vec::new();
20021 let mut uncounted_exact = 0u32;
20022 let mut counted_exact = 0u32;
20023 let mut totals = (0usize, 0usize);
20024 for attempt in 0..30u32 {
20025 let seed = 42 + attempt;
20026 // Same zoom + hard-cut fractal source the sibling uv_mode gate
20027 // uses (a cut is what makes aomenc code INTRA blocks inside an
20028 // inter frame); `noise` carries an explicit seed (class
20029 // [[seeded-fixture-not-reproducible]]).
20030 let source = format!(
20031 "mandelbrot=size={width}x{height}:start_scale={}:rate=25[a];\
20032 mandelbrot=size={width}x{height}:start_scale={}:rate=25[b];\
20033 [a][b]overlay=enable='gte(n,3)',noise=alls=12:allf=t+u:all_seed={seed}",
20034 5.0 - f64::from(attempt) * 0.06,
20035 0.9 + f64::from(attempt) * 0.11
20036 );
20037 let y4m = Command::new("ffmpeg")
20038 .args([
20039 "-v",
20040 "error",
20041 "-f",
20042 "lavfi",
20043 "-i",
20044 &source,
20045 "-pix_fmt",
20046 if bit_depth == 10 {
20047 "yuv420p10le"
20048 } else {
20049 "yuv420p"
20050 },
20051 "-strict",
20052 "-1",
20053 "-t",
20054 "0.24",
20055 "-f",
20056 "yuv4mpegpipe",
20057 "-strict",
20058 "-1",
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 "ffmpeg fixture: {}",
20069 String::from_utf8_lossy(&y4m.stderr)
20070 );
20071 let cq = format!("--cq-level={}", 12 + (attempt % 5) * 7);
20072 let depth_args: &[&str] = if bit_depth == 10 {
20073 &["-b", "10", "--input-bit-depth=10"]
20074 } else {
20075 &[]
20076 };
20077 // The y4m goes through a PID-keyed FILE, never aomenc's stdin
20078 // (pipe deadlock, class [[gate-loader-slurps-whole-file]]).
20079 let y4m_path = std::env::temp_dir().join(format!(
20080 "ec-av1-leaf8tx-{}-{bit_depth}-{seed}.y4m",
20081 std::process::id()
20082 ));
20083 std::fs::write(&y4m_path, &y4m.stdout).expect("writing the y4m fixture");
20084 let child = Command::new(aomenc_path())
20085 .args(depth_args)
20086 .args([
20087 "--codec=av1",
20088 "--passes=1",
20089 "--end-usage=q",
20090 &cq,
20091 "--cpu-used=0",
20092 "--lag-in-frames=0",
20093 "--auto-alt-ref=0",
20094 "--kf-max-dist=9999",
20095 "--kf-min-dist=9999",
20096 "--threads=1",
20097 "--row-mt=0",
20098 "--tile-columns=0",
20099 "--enable-order-hint=0",
20100 "--enable-warped-motion=0",
20101 "--enable-obmc=0",
20102 "--enable-masked-comp=0",
20103 "--enable-interintra-comp=0",
20104 "--enable-dist-wtd-comp=0",
20105 "--enable-diff-wtd-comp=0",
20106 "--enable-onesided-comp=0",
20107 "--enable-interintra-wedge=0",
20108 "--enable-smooth-interintra=0",
20109 "--enable-ab-partitions=0",
20110 "--enable-1to4-partitions=0",
20111 "--enable-cdef=0",
20112 "--enable-restoration=0",
20113 "--enable-palette=0",
20114 "--enable-intrabc=0",
20115 "--enable-ref-frame-mvs=0",
20116 // Per-arm overrides LAST (aomenc keeps the last
20117 // occurrence of a repeated --enable-* flag). Rect
20118 // partitions stay off so the leaf's unrelated sub-16 rect
20119 // inter refusal never fires.
20120 "--enable-rect-partitions=0",
20121 "--enable-tx-size-search=1",
20122 "--enable-angle-delta=1",
20123 "--enable-directional-intra=1",
20124 "--min-partition-size=8",
20125 "--max-partition-size=32",
20126 "--obu",
20127 "-o",
20128 "-",
20129 ])
20130 // r1 diagnostic: EC_LEAF8TX_CONTROL=1 turns THIS lane's two
20131 // tools back off (last occurrence of a repeated --enable-*
20132 // wins), so any mismatch that survives is not this lane's.
20133 .args(match std::env::var("EC_LEAF8TX_CONTROL").as_deref() {
20134 Ok("angle") => vec!["--enable-tx-size-search=0", "--enable-angle-delta=1"],
20135 Ok("tx") => vec!["--enable-tx-size-search=1", "--enable-angle-delta=0"],
20136 Ok("tx8") => vec![
20137 "--enable-tx-size-search=1",
20138 "--enable-angle-delta=0",
20139 "--max-partition-size=8",
20140 ],
20141 Ok(_) => vec!["--enable-tx-size-search=0", "--enable-angle-delta=0"],
20142 // Shipped recipe (lane-leaf8tx r4): BOTH of this lane's
20143 // tools on -- the tx_depth split at an 8x8 intra-in-inter
20144 // leaf is what the lifted refusal covers, so
20145 // `--enable-tx-size-search=1` must survive the per-arm
20146 // override (aomenc keeps the LAST occurrence). Odd
20147 // attempts also cap the partition at 8x8, the shape that
20148 // produces the 2x2 TX_4X4 grid most often.
20149 Err(_) => {
20150 if attempt % 2 == 1 {
20151 vec![
20152 "--enable-tx-size-search=1",
20153 "--enable-angle-delta=1",
20154 "--max-partition-size=8",
20155 ]
20156 } else {
20157 vec!["--enable-tx-size-search=1", "--enable-angle-delta=1"]
20158 }
20159 }
20160 })
20161 .arg(&y4m_path)
20162 .stdin(Stdio::null())
20163 .stdout(Stdio::piped())
20164 .stderr(Stdio::piped())
20165 .spawn()
20166 .expect("aomenc failed to start");
20167 let out = child.wait_with_output().expect("aomenc failed to run");
20168 let _ = std::fs::remove_file(&y4m_path);
20169 assert!(
20170 out.status.success(),
20171 "aomenc refused the fixture: {}",
20172 String::from_utf8_lossy(&out.stderr)
20173 );
20174 let stream = out.stdout;
20175 let before = (
20176 decode::intra_in_inter_split_tx_hits()[0],
20177 decode::intra_in_inter8_angle_delta_y_hits(),
20178 );
20179 let frames = match decode_stream(&stream) {
20180 Ok(frames) => frames,
20181 Err(e) => {
20182 let msg = e.to_string();
20183 assert!(
20184 msg.contains("unsupported"),
20185 "{name} decode failed outright (seed {seed}): {msg}"
20186 );
20187 refusals.push(format!("seed {seed}: {msg}"));
20188 continue;
20189 }
20190 };
20191 let now = (
20192 decode::intra_in_inter_split_tx_hits()[0],
20193 decode::intra_in_inter8_angle_delta_y_hits(),
20194 );
20195 let fired = (now.0 - before.0, now.1 - before.1);
20196 totals = (totals.0 + fired.0, totals.1 + fired.1);
20197 // Both lifted capabilities must fire on the SAME pixel-compared
20198 // attempt.
20199 let counted = fired.1 > 0;
20200 if !counted {
20201 uncounted_exact += 1;
20202 refusals.push(format!(
20203 "seed {seed}: decoded and pixel-compared, but split-tx {} / angle-delta {} \
20204 8x8 intra-in-inter leaves",
20205 fired.0, fired.1
20206 ));
20207 }
20208 let ffmpeg_frames = if bit_depth == 10 {
20209 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
20210 } else {
20211 ffmpeg_decode_sequence(&stream, width, height, frame_count)
20212 };
20213 assert_eq!(frames.len(), frame_count);
20214 eprintln!(
20215 "{name} seed={seed} {cq}: 8x8 intra-in-inter leaves with tx_depth=1 {}, with a \
20216 nonzero angle_delta_y {} (split-tx per size 8/16/32/64 {:?})",
20217 fired.0,
20218 fired.1,
20219 decode::intra_in_inter_split_tx_hits()
20220 );
20221 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20222 for (plane, (g, w)) in [
20223 ("Y", (&got.y, &want.y)),
20224 ("U", (&got.u, &want.u)),
20225 ("V", (&got.v, &want.v)),
20226 ] {
20227 let stride = if plane == "Y" { width } else { width / 2 };
20228 if let Some(at) = g.iter().zip(w.iter()).position(|(a, b)| a != b) {
20229 eprintln!(
20230 "{name} seed={seed}: frame {i} {plane} first diff at ({}, {}) got {} \
20231 want {} ({} samples differ)",
20232 at % stride,
20233 at / stride,
20234 g[at],
20235 w[at],
20236 g.iter().zip(w.iter()).filter(|(a, b)| a != b).count(),
20237 );
20238 }
20239 }
20240 }
20241 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20242 assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
20243 assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
20244 assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
20245 }
20246 if counted {
20247 counted_exact += 1;
20248 }
20249 }
20250 // lane-leaf8tx r4: continue-and-sweep -- every arm is encoded,
20251 // decoded and pixel-compared on every plane of every decode-order
20252 // frame above; the counters are asserted ONCE here. A decode error or
20253 // a mismatch is a failure, never a SKIP, and `uncounted_exact`
20254 // (decoded + compared but neither capability fired) is the
20255 // out-of-scope-mismatch bucket that the sweep tolerates only while at
20256 // least one attempt did fire.
20257 gate_buckets(
20258 &name,
20259 counted_exact,
20260 uncounted_exact,
20261 refusals.len() - uncounted_exact as usize,
20262 );
20263 assert!(
20264 totals.0 > 0,
20265 "{name}: no decoded+compared attempt carried an 8x8 intra-in-inter leaf with \
20266 tx_depth split to 4x4 (split-tx per size {:?}, angle-delta {}):\n{}",
20267 decode::intra_in_inter_split_tx_hits(),
20268 totals.1,
20269 refusals.join("\n")
20270 );
20271 assert!(
20272 totals.1 > 0,
20273 "{name}: no decoded+compared attempt carried a nonzero angle_delta_y on an 8x8 \
20274 intra-in-inter leaf (split-tx {}):\n{}",
20275 totals.0,
20276 refusals.join("\n")
20277 );
20278 }
20279
20280 /// lane-chroma r2 stage 1: a real aomenc key frame with
20281 /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`)
20282 /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still-
20283 /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never
20284 /// fires; smooth *luma* neighbours are exactly what this gate wants to
20285 /// exercise, proving [`decode::smooth_luma_hits`] actually landed a
20286 /// directional block next to a smooth-predicted one and decoded
20287 /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix).
20288 #[test]
20289 fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() {
20290 if !have_ffmpeg() {
20291 eprintln!(
20292 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg"
20293 );
20294 return;
20295 }
20296 if !have_aomenc() {
20297 eprintln!(
20298 "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}",
20299 aomenc_path().display()
20300 );
20301 return;
20302 }
20303 let (width, height) = (64usize, 64usize);
20304 let mut refusals = Vec::new();
20305 let mut fired_runs = 0u32;
20306 let mut uncounted_exact = 0u32;
20307 for attempt in 0..40u32 {
20308 let seed = 42 + attempt;
20309 let source = format!(
20310 "mandelbrot=size=64x64:start_scale={}:rate=25",
20311 5.0 - f64::from(attempt) * 0.06
20312 );
20313 let y4m = Command::new("ffmpeg")
20314 .args([
20315 "-v",
20316 "error",
20317 "-f",
20318 "lavfi",
20319 "-i",
20320 &source,
20321 "-pix_fmt",
20322 "yuv420p",
20323 "-t",
20324 "0.04",
20325 "-f",
20326 "yuv4mpegpipe",
20327 "-",
20328 ])
20329 .stdin(Stdio::null())
20330 .stdout(Stdio::piped())
20331 .stderr(Stdio::piped())
20332 .output()
20333 .expect("ffmpeg failed to run");
20334 assert!(
20335 y4m.status.success(),
20336 "ffmpeg fixture: {}",
20337 String::from_utf8_lossy(&y4m.stderr)
20338 );
20339 let out = run_with_stdin(
20340 Command::new(aomenc_path()).args([
20341 "--codec=av1",
20342 "--passes=1",
20343 "--end-usage=q",
20344 "--cq-level=45",
20345 "--cpu-used=0",
20346 "--enable-rect-partitions=0",
20347 "--enable-ab-partitions=0",
20348 "--enable-1to4-partitions=0",
20349 "--enable-filter-intra=0",
20350 "--enable-smooth-intra=1",
20351 // Smooth/paeth chroma is a still-refused, separate
20352 // round-2 gap -- off so no attempt trips it while this
20353 // gate is purely about luma's edge-filter fix.
20354 "--enable-paeth-intra=0",
20355 "--enable-tx-size-search=0",
20356 "--enable-cdef=0",
20357 "--enable-restoration=0",
20358 "--enable-intra-edge-filter=1",
20359 "--max-partition-size=32",
20360 "--min-partition-size=16",
20361 "--enable-palette=0",
20362 "--enable-intrabc=0",
20363 "--enable-cfl-intra=0",
20364 "--enable-ref-frame-mvs=0",
20365 "--obu",
20366 "-o",
20367 "-",
20368 "-",
20369 ]),
20370 &y4m.stdout,
20371 );
20372 assert!(
20373 out.status.success(),
20374 "aomenc refused the fixture: {}",
20375 String::from_utf8_lossy(&out.stderr)
20376 );
20377 let stream = out.stdout;
20378 let smooth_before = decode::smooth_luma_hits();
20379 let frames = match decode_stream(&stream) {
20380 Ok(frames) => frames,
20381 Err(e) => {
20382 refusals.push(format!("seed {seed}: {e}"));
20383 continue;
20384 }
20385 };
20386 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
20387 // is ALWAYS pixel-compared below; the hit counter only decides whether
20388 // the attempt counts toward the firing total.
20389 let counted = decode::smooth_luma_hits() != smooth_before;
20390 if counted {
20391 fired_runs += 1;
20392 } else {
20393 uncounted_exact += 1;
20394 refusals.push(format!(
20395 "seed {seed}: decoded and pixel-compared, but no smooth-luma-neighbour block \
20396 fired"
20397 ));
20398 }
20399 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
20400 assert_eq!(
20401 frames[0].y, ffmpeg_frames[0].y,
20402 "luma vs ffmpeg (seed {seed})"
20403 );
20404 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
20405 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
20406 if fired_runs >= 4 {
20407 gate_buckets(
20408 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
20409 fired_runs,
20410 uncounted_exact,
20411 refusals.len() - uncounted_exact as usize,
20412 );
20413 return;
20414 }
20415 }
20416 gate_buckets(
20417 "a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact",
20418 fired_runs,
20419 uncounted_exact,
20420 refusals.len() - uncounted_exact as usize,
20421 );
20422 assert!(
20423 fired_runs > 0,
20424 "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}",
20425 refusals.join("\n")
20426 );
20427 }
20428
20429 /// The smooth/paeth-chroma gate (lane-chroma r1/r3): a real aomenc key
20430 /// frame with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the
20431 /// opposite of the directional-chroma gate below, which turns these OFF
20432 /// to keep this gap from firing while directional chroma is under test).
20433 /// Some seeds won't pick smooth/paeth for chroma at all -- retry like
20434 /// every other real-encoder gate here, but the first attempt that
20435 /// actually fires [`decode::smooth_uv_hits`] must decode pixel-exact.
20436 #[test]
20437 fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() {
20438 if !have_ffmpeg() {
20439 eprintln!(
20440 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg"
20441 );
20442 return;
20443 }
20444 if !have_aomenc() {
20445 eprintln!(
20446 "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}",
20447 aomenc_path().display()
20448 );
20449 return;
20450 }
20451 let (width, height) = (64usize, 64usize);
20452 let mut refusals = Vec::new();
20453 let mut fired_runs = 0u32;
20454 let mut uncounted_exact = 0u32;
20455 for attempt in 0..40u32 {
20456 let seed = 42 + attempt;
20457 let source = format!(
20458 "mandelbrot=size=64x64:start_scale={}:rate=25",
20459 5.0 - f64::from(attempt) * 0.06
20460 );
20461 let y4m = Command::new("ffmpeg")
20462 .args([
20463 "-v",
20464 "error",
20465 "-f",
20466 "lavfi",
20467 "-i",
20468 &source,
20469 "-pix_fmt",
20470 "yuv420p",
20471 "-t",
20472 "0.04",
20473 "-f",
20474 "yuv4mpegpipe",
20475 "-",
20476 ])
20477 .stdin(Stdio::null())
20478 .stdout(Stdio::piped())
20479 .stderr(Stdio::piped())
20480 .output()
20481 .expect("ffmpeg failed to run");
20482 assert!(
20483 y4m.status.success(),
20484 "ffmpeg fixture: {}",
20485 String::from_utf8_lossy(&y4m.stderr)
20486 );
20487 let out = run_with_stdin(
20488 Command::new(aomenc_path()).args([
20489 "--codec=av1",
20490 "--passes=1",
20491 "--end-usage=q",
20492 "--cq-level=45",
20493 "--cpu-used=0",
20494 "--enable-rect-partitions=0",
20495 "--enable-ab-partitions=0",
20496 "--enable-1to4-partitions=0",
20497 "--enable-filter-intra=0",
20498 "--enable-smooth-intra=1",
20499 "--enable-paeth-intra=1",
20500 "--enable-tx-size-search=0",
20501 "--enable-cdef=0",
20502 "--enable-restoration=0",
20503 "--enable-intra-edge-filter=1",
20504 "--max-partition-size=32",
20505 // 8x8/leaf8 splits are a separate, already-named refusal.
20506 "--min-partition-size=16",
20507 "--enable-palette=0",
20508 "--enable-intrabc=0",
20509 "--enable-cfl-intra=0",
20510 "--enable-ref-frame-mvs=0",
20511 "--obu",
20512 "-o",
20513 "-",
20514 "-",
20515 ]),
20516 &y4m.stdout,
20517 );
20518 assert!(
20519 out.status.success(),
20520 "aomenc refused the fixture: {}",
20521 String::from_utf8_lossy(&out.stderr)
20522 );
20523 let stream = out.stdout;
20524 let smooth_before = decode::smooth_uv_hits();
20525 let frames = match decode_stream(&stream) {
20526 Ok(frames) => frames,
20527 Err(e) => {
20528 refusals.push(format!("seed {seed}: {e}"));
20529 continue;
20530 }
20531 };
20532 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
20533 // is ALWAYS pixel-compared below; the hit counter only decides whether
20534 // the attempt counts toward the firing total.
20535 let counted = decode::smooth_uv_hits() != smooth_before;
20536 if counted {
20537 fired_runs += 1;
20538 } else {
20539 uncounted_exact += 1;
20540 refusals.push(format!(
20541 "seed {seed}: decoded and pixel-compared, but no smooth/paeth uv_mode fired"
20542 ));
20543 }
20544 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
20545 assert_eq!(
20546 frames[0].y, ffmpeg_frames[0].y,
20547 "luma vs ffmpeg (seed {seed})"
20548 );
20549 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
20550 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
20551 if fired_runs >= 4 {
20552 gate_buckets(
20553 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
20554 fired_runs,
20555 uncounted_exact,
20556 refusals.len() - uncounted_exact as usize,
20557 );
20558 return;
20559 }
20560 }
20561 gate_buckets(
20562 "a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact",
20563 fired_runs,
20564 uncounted_exact,
20565 refusals.len() - uncounted_exact as usize,
20566 );
20567 assert!(
20568 fired_runs > 0,
20569 "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}",
20570 refusals.join("\n")
20571 );
20572 }
20573
20574 /// The directional-chroma/angle-delta gate: a real aomenc key frame with
20575 /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the
20576 /// opposite of every sibling recipe's `=0`, which existed specifically to
20577 /// keep this round-2 gap from firing while a different surface was under
20578 /// test). A colourful, sharp-edged source gives the RD search a reason to
20579 /// pick a directional `uv_mode` and/or a nonzero angle delta -- some
20580 /// seeds still won't, so retry like every other real-encoder gate here,
20581 /// but the first attempt that actually fires either counter must decode
20582 /// pixel-exact.
20583 #[test]
20584 fn a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact() {
20585 if !have_ffmpeg() {
20586 eprintln!(
20587 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no ffmpeg"
20588 );
20589 return;
20590 }
20591 if !have_aomenc() {
20592 eprintln!(
20593 "SKIP a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact: no aomenc at {}",
20594 aomenc_path().display()
20595 );
20596 return;
20597 }
20598 let (width, height) = (64usize, 64usize);
20599 let mut refusals = Vec::new();
20600 let mut fired_runs = 0u32;
20601 let mut uncounted_exact = 0u32;
20602 for attempt in 0..40u32 {
20603 let seed = 42 + attempt;
20604 let source = format!(
20605 "mandelbrot=size=64x64:start_scale={}:rate=25",
20606 5.0 - f64::from(attempt) * 0.06
20607 );
20608 let y4m = Command::new("ffmpeg")
20609 .args([
20610 "-v",
20611 "error",
20612 "-f",
20613 "lavfi",
20614 "-i",
20615 &source,
20616 "-pix_fmt",
20617 "yuv420p",
20618 "-t",
20619 "0.04",
20620 "-f",
20621 "yuv4mpegpipe",
20622 "-",
20623 ])
20624 .stdin(Stdio::null())
20625 .stdout(Stdio::piped())
20626 .stderr(Stdio::piped())
20627 .output()
20628 .expect("ffmpeg failed to run");
20629 assert!(
20630 y4m.status.success(),
20631 "ffmpeg fixture: {}",
20632 String::from_utf8_lossy(&y4m.stderr)
20633 );
20634 let out = run_with_stdin(
20635 Command::new(aomenc_path()).args([
20636 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
20637 // occurrence, so overrides go before the base list).
20638 "--enable-directional-intra=1",
20639 "--codec=av1",
20640 "--passes=1",
20641 "--end-usage=q",
20642 "--cq-level=45",
20643 "--cpu-used=0",
20644 "--enable-rect-partitions=0",
20645 "--enable-ab-partitions=0",
20646 "--enable-1to4-partitions=0",
20647 "--enable-filter-intra=0",
20648 // Smooth/Paeth chroma is a separate, still-refused round-2
20649 // gap (an unrelated `Edges::build` no-neighbour bug this
20650 // lane does not cover) -- off so the RD search's only
20651 // non-DC/CFL chroma choice left is directional.
20652 "--enable-smooth-intra=0",
20653 "--enable-paeth-intra=0",
20654 "--enable-tx-size-search=0",
20655 "--enable-cdef=0",
20656 "--enable-restoration=0",
20657 // The intra edge filter/upsample (spec 7.11.2.7-2.9) is
20658 // now implemented (`directional()`) -- left ON (aomenc's
20659 // own default) so this gate actually exercises it instead
20660 // of the un-filtered fast path a disabled flag would keep
20661 // testing.
20662 "--enable-intra-edge-filter=1",
20663 "--max-partition-size=32",
20664 // Same reason as the tx-select gate above: 8x8 and other
20665 // sub-16x16 splits are a separate, already-named refusal.
20666 "--min-partition-size=16",
20667 "--enable-palette=0",
20668 "--enable-intrabc=0",
20669 "--enable-cfl-intra=0",
20670 // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
20671 // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
20672 "--enable-ref-frame-mvs=0",
20673 "--obu",
20674 "-o",
20675 "-",
20676 "-",
20677 ]),
20678 &y4m.stdout,
20679 );
20680 assert!(
20681 out.status.success(),
20682 "aomenc refused the fixture: {}",
20683 String::from_utf8_lossy(&out.stderr)
20684 );
20685 let stream = out.stdout;
20686 let (uv_before, angle_before) =
20687 (decode::directional_uv_hits(), decode::angle_delta_hits());
20688 let frames = match decode_stream(&stream) {
20689 Ok(frames) => frames,
20690 Err(e) => {
20691 refusals.push(format!("seed {seed}: {e}"));
20692 continue;
20693 }
20694 };
20695 // class [[gate-skips-on-its-own-failure]]: a decode that succeeded
20696 // is ALWAYS pixel-compared below; the hit counter only decides whether
20697 // the attempt counts toward the firing total.
20698 let counted = decode::directional_uv_hits() != uv_before
20699 || decode::angle_delta_hits() != angle_before;
20700 if counted {
20701 fired_runs += 1;
20702 } else {
20703 uncounted_exact += 1;
20704 refusals.push(format!(
20705 "seed {seed}: decoded and pixel-compared, but neither a directional uv_mode \
20706 nor a nonzero angle delta fired"
20707 ));
20708 }
20709 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
20710 assert_eq!(
20711 frames[0].y, ffmpeg_frames[0].y,
20712 "luma vs ffmpeg (seed {seed})"
20713 );
20714 assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
20715 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
20716 if fired_runs >= 4 {
20717 gate_buckets(
20718 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
20719 fired_runs,
20720 uncounted_exact,
20721 refusals.len() - uncounted_exact as usize,
20722 );
20723 return;
20724 }
20725 }
20726 gate_buckets(
20727 "a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact",
20728 fired_runs,
20729 uncounted_exact,
20730 refusals.len() - uncounted_exact as usize,
20731 );
20732 assert!(
20733 fired_runs > 0,
20734 "every attempt hit a named refusal or never exercised directional chroma:\n{}",
20735 refusals.join("\n")
20736 );
20737 }
20738
20739 /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
20740 /// --auto-alt-ref=0` keep every non-key frame a simple forward
20741 /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this
20742 /// decoder's inter path does not model), `--kf-max-dist` past the clip's
20743 /// own length keeps frame 0 the only key frame.
20744 /// lane-inter8 r1: the inter tile path's SB-level `PARTITION_NONE` -- a
20745 /// whole 64x64 superblock coded as ONE inter block, which is what aomenc
20746 /// picks for static content and which this decoder refused by name
20747 /// ("an inter SB-level partition type other than SPLIT") until this
20748 /// round. HARD-asserts [`decode::inter_sb_none_hits`] moved (the arm
20749 /// really fired, class refusal-lifted-without-a-gate) and every frame is
20750 /// pixel-exact vs ffmpeg; a decode error is a FAILURE here, never a SKIP
20751 /// (class gate-skips-on-its-own-failure).
20752 /// lane-inter8 r1: generalised so the same recipe can target a deeper
20753 /// level of the inter partition tree -- `min_part` is aomenc's
20754 /// `--min-partition-size`, and `hits`/`what` name the counter that proves
20755 /// the arm under test really fired.
20756 #[track_caller]
20757 fn inter_sb_none_gate(
20758 name: &str,
20759 ten_bit: bool,
20760 min_part: &str,
20761 max_part: &str,
20762 hits: fn() -> usize,
20763 what: &str,
20764 // lane-inter8 r3: extra aomenc flags + the frame width they need.
20765 // `--tile-columns=1` needs a frame at least two superblocks wide or
20766 // aomenc silently codes one tile column and the arm is vacuous.
20767 extra: &[&str],
20768 width: usize,
20769 // lane-interp3 r1: sequence length -- a compound block needs several
20770 // already-coded references, which a 4-frame sequence never has.
20771 frame_count: usize,
20772 // lane-av1dualfilter10: the encoded stream, so a caller can assert on
20773 // the PARSED sequence header (bit depth, `enable_dual_filter`) rather
20774 // than on the flag it asked for. Empty on the SKIP paths below.
20775 ) -> Vec<u8> {
20776 if !have_ffmpeg() {
20777 eprintln!("SKIP {name}: no ffmpeg");
20778 return Vec::new();
20779 }
20780 if !have_aomenc() {
20781 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
20782 return Vec::new();
20783 }
20784 let height = 64usize;
20785 let duration = format!("{:.2}", frame_count as f64 / 25.0);
20786 // A deterministic synthetic source with real motion (a static source
20787 // codes every inter frame as skip and never exercises the residual
20788 // path); bounded with `-t` (class gate-loader-slurps-whole-file).
20789 let y4m = Command::new("ffmpeg")
20790 .args([
20791 "-v",
20792 "error",
20793 "-f",
20794 "lavfi",
20795 "-i",
20796 &format!("mandelbrot=size={width}x{height}:rate=25"),
20797 "-t",
20798 &duration,
20799 "-pix_fmt",
20800 if ten_bit { "yuv420p10le" } else { "yuv420p" },
20801 // y4m calls 10-bit unofficial (same as the 10-bit key-frame
20802 // gate's own fixture).
20803 "-strict",
20804 "-1",
20805 "-f",
20806 "yuv4mpegpipe",
20807 "-",
20808 ])
20809 .stdin(Stdio::null())
20810 .stdout(Stdio::piped())
20811 .stderr(Stdio::piped())
20812 .output()
20813 .expect("ffmpeg failed to run");
20814 assert!(
20815 y4m.status.success(),
20816 "{name}: ffmpeg fixture: {}",
20817 String::from_utf8_lossy(&y4m.stderr)
20818 );
20819 let mut args: Vec<String> = [
20820 "--codec=av1",
20821 "--passes=1",
20822 "--end-usage=q",
20823 "--cq-level=40",
20824 "--cpu-used=0",
20825 "--lag-in-frames=0",
20826 "--auto-alt-ref=0",
20827 "--kf-max-dist=1000",
20828 // No cross-frame CDF forwarding in this fixture (see the
20829 // deblocking gate's own note).
20830 "--error-resilient=1",
20831 // This gate targets the SB-level NONE arm only: rect/AB/1-to-4
20832 // partitions and sub-16x16 splits stay off so a failure here
20833 // cannot be another lane's missing arm.
20834 "--enable-rect-partitions=0",
20835 "--enable-ab-partitions=0",
20836 "--enable-1to4-partitions=0",
20837 "--enable-filter-intra=0",
20838 "--enable-smooth-intra=0",
20839 "--enable-paeth-intra=0",
20840 "--enable-directional-intra=0",
20841 "--enable-angle-delta=0",
20842 "--enable-tx-size-search=0",
20843 "--enable-cdef=0",
20844 "--enable-restoration=0",
20845 "--enable-palette=0",
20846 "--enable-intrabc=0",
20847 "--enable-cfl-intra=0",
20848 "--enable-ref-frame-mvs=0",
20849 "--obu",
20850 "-o",
20851 "-",
20852 "-",
20853 ]
20854 .iter()
20855 .map(|s| (*s).to_string())
20856 .collect();
20857 for e in extra {
20858 args.insert(1, (*e).to_string());
20859 }
20860 args.insert(1, format!("--min-partition-size={min_part}"));
20861 args.insert(1, format!("--max-partition-size={max_part}"));
20862 if ten_bit {
20863 args.insert(1, "--input-bit-depth=10".to_string());
20864 args.insert(1, "--bit-depth=10".to_string());
20865 }
20866 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
20867 assert!(
20868 out.status.success(),
20869 "{name}: aomenc refused the fixture: {}",
20870 String::from_utf8_lossy(&out.stderr)
20871 );
20872 let stream = out.stdout;
20873 let before = hits();
20874 let frames = match decode_stream(&stream) {
20875 Ok(frames) => frames,
20876 Err(e) => {
20877 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
20878 let _ = std::fs::write(&pin, &stream);
20879 panic!(
20880 "{name}: decode_stream refused a real aomenc stream: {e} (pinned at {})",
20881 pin.display()
20882 );
20883 }
20884 };
20885 assert!(
20886 hits() > before,
20887 "{name}: no {what} fired -- this gate proves nothing"
20888 );
20889 let ffmpeg_frames = if ten_bit {
20890 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
20891 } else {
20892 ffmpeg_decode_sequence(&stream, width, height, frame_count)
20893 };
20894 assert_eq!(frames.len(), frame_count, "{name}: frame count");
20895 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
20896 if got.y != want.y || got.u != want.u || got.v != want.v {
20897 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
20898 let _ = std::fs::write(&pin, &stream);
20899 panic!(
20900 "{name}: frame {i} mismatch vs ffmpeg -- stream pinned at {}",
20901 pin.display()
20902 );
20903 }
20904 }
20905 stream
20906 }
20907
20908 #[test]
20909 fn a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
20910 inter_sb_none_gate(
20911 "a_real_aomenc_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
20912 false,
20913 "32",
20914 "64",
20915 decode::inter_sb_none_hits,
20916 "whole-superblock inter PARTITION_NONE",
20917 &[],
20918 64,
20919 4,
20920 );
20921 }
20922
20923 #[test]
20924 fn a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact() {
20925 inter_sb_none_gate(
20926 "a_real_aomenc_10bit_inter_sequence_with_a_whole_superblock_block_decodes_pixel_exact",
20927 true,
20928 "32",
20929 "64",
20930 decode::inter_sb_none_hits,
20931 "whole-superblock inter PARTITION_NONE",
20932 &[],
20933 64,
20934 4,
20935 );
20936 }
20937
20938 /// lane-inter8 r1: the same recipe with `--min-partition-size=8`, so
20939 /// aomenc's RD may split a 16x16 inter block into four 8x8 leaves. The
20940 /// interior (non-edge-straddling) `PARTITION_SPLIT` at the 16x16 level
20941 /// was refused by name until this round; the straddle path always ran the
20942 /// same loop, so only [`decode::inter_sub16_split_hits`] -- which counts
20943 /// interior splits only -- proves the newly-lifted alphabet value fired.
20944 // lane-inter8 r2: GREEN. The neighbour side bands are mi-granular, every
20945 // leaf stamps its own 2x2-mi span (including the compound-return path
20946 // that used to skip `record_mi` entirely) and the compound
20947 // group/index contexts read the LEAF's mi cell, not its 16x16's corner.
20948 /// lane-inter8 r3, from lane-sub8's verifier finding: the mi-granular
20949 /// inter neighbour bands added in r2 must reset per TILE (above) and per
20950 /// SB row (left) and guard availability tile-relative, so the same recipe
20951 /// runs again at 128x64 with two tile columns -- a leaf on the second
20952 /// tile's first column has no left neighbour and must not read the first
20953 /// tile's band.
20954 // 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
20955 // was done by inspection instead: every reader of the mi bands guards on
20956 // `tile_row0_mi`/`tile_col0_mi` (no `> 0` guard exists in decode.rs),
20957 // `start_tile` resets the above mi bands over the tile's own mi column
20958 // span and `start_row` resets every left mi band.
20959 #[test]
20960 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact()
20961 {
20962 inter_sb_none_gate(
20963 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_across_tile_columns_decodes_pixel_exact",
20964 false,
20965 "8",
20966 "16",
20967 decode::inter_sub16_split_hits,
20968 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
20969 &["--tile-columns=1"],
20970 128,
20971 4,
20972 );
20973 }
20974
20975 /// lane-interp3 r1: the same 8x8-leaf recipe with DUAL FILTER, OBMC and
20976 /// warped motion on. `read_mb_interp_filter` runs for every inter block
20977 /// (libaom `decodemv.c` 1575), compound ones included; the compound 8x8
20978 /// leaf skipped it entirely, so a SWITCHABLE-filter stream lost a symbol
20979 /// per compound leaf and stamped the `[3, 3]` "no filter" sentinel, which
20980 /// made a neighbouring OBMC block's `neighbour_filter` PANIC (a crash on
20981 /// his data, not a named refusal). The three hard asserts prove the flags
20982 /// arrived: a compound 8x8 leaf that really read the filter, a block whose
20983 /// two dual-filter directions DIFFER (impossible with dual filter off),
20984 /// and an 8x8 OBMC blend.
20985 // lane-interp3 r2: the ENTROPY desync r1 measured is CLOSED -- the full
20986 // 16-frame stream now parses end to end and every `EC_MODE`/`EC_MODE_VAL`
20987 // element's msac RANGE matches the instrumented aomdec's line for line
20988 // (570/570 mode elements, 0 diff). Two twin-drift root causes, both in
20989 // `decode_inter_block8`'s compound arm: `read_compound_ref_frames` was
20990 // passed a hard-coded `LAST_FRAME` for every inter neighbour instead of
20991 // the real per-mi band, and the grid stamp cleared both per-slot
20992 // `is_global_mv_block` flags.
20993 // lane-interp3 r3: the luma reconstruction residue r2 left open is CLOSED
20994 // and this gate is GREEN. Third instance of the same twin-drift class:
20995 // libaom applies `allow_warp`'s GLOBAL branch to every
20996 // `is_global_mv_block` reference slot, compound included and independent
20997 // of `motion_mode` (`av1_init_warp_params` inside
20998 // `build_inter_predictors_8x8_and_bigger`'s per-`ref` loop) -- the 16x16+
20999 // compound arm has warped since lane-cwarp r1, the 8x8 leaf's compound arm
21000 // predicted BOTH taps translationally, so a GLOBAL_GLOBALMV 8x8 compound
21001 // leaf under a non-TRANSLATION model drifted a few luma levels, growing
21002 // away from the block origin. It was NOT OBMC: the `EC_OBMC` emitter this
21003 // round added to `decode.rs` diffs 325/325 lines against the instrumented
21004 // aomdec's own rung (position, span, neighbour mv/ref/bsize/filter) with
21005 // zero differences.
21006 #[test]
21007 fn a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact() {
21008 const NAME: &str = "a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact";
21009 if !have_ffmpeg() || !have_aomenc() {
21010 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
21011 return;
21012 }
21013 let before_dual = decode::dual_filter_diff_hits();
21014 let before_obmc = decode::obmc_hits_8();
21015 let before_cwarp8 = decode::compound_warp_hits_8();
21016 inter_sb_none_gate(
21017 NAME,
21018 false,
21019 "8",
21020 "16",
21021 decode::compound8_filter_hits,
21022 "a compound 8x8 leaf reading its own switchable interp_filter",
21023 &[
21024 "--enable-dual-filter=1",
21025 "--enable-obmc=1",
21026 "--enable-warped-motion=1",
21027 "--enable-onesided-comp=1",
21028 ],
21029 64,
21030 // Recipe search hook (same shape as EC_OBMC8_ATTEMPTS): a compound
21031 // block needs several coded references, so the sequence is longer
21032 // than the other arms' 4 frames.
21033 std::env::var("EC_INTERP3_FRAMES")
21034 .ok()
21035 .and_then(|v| v.parse().ok())
21036 .unwrap_or(16),
21037 );
21038 assert!(
21039 decode::dual_filter_diff_hits() > before_dual,
21040 "{NAME}: no block read two DIFFERENT dual-filter directions -- \
21041 --enable-dual-filter=1 did not arrive or aomenc declined it"
21042 );
21043 assert!(
21044 decode::obmc_hits_8() > before_obmc,
21045 "{NAME}: no 8x8 OBMC blend fired -- --enable-obmc=1 did not arrive"
21046 );
21047 assert!(
21048 decode::compound_warp_hits_8() > before_cwarp8,
21049 "{NAME}: no 8x8 COMPOUND leaf was predicted through the per-ref GLOBAL \
21050 warp -- the r3 root-cause path never fired, so this stream no longer \
21051 proves it"
21052 );
21053 }
21054
21055 /// lane-av1dualfilter10: the 10-bit arm of the dual-filter witness.
21056 ///
21057 /// `NEVER_EXERCISED_10BIT` kept `enable-dual-filter` listed after the
21058 /// 8-bit entry was retired (lane-av1distwtd r3, gate_coverage.rs), and
21059 /// the reason was structural, not incidental: the only `=1` witness,
21060 /// `a_real_aomenc_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact`,
21061 /// calls `inter_sb_none_gate(NAME, false, ...)` -- and that `false` IS the
21062 /// `ten_bit` parameter, so it built an 8-bit stream. Its `ten_bit = true`
21063 /// siblings build 10-bit streams but spell no dual-filter flag. This is
21064 /// that missing arm.
21065 ///
21066 /// What makes it a witness and not a spelling: the header is read back
21067 /// from the ENCODED stream (`enable_dual_filter` and `bit_depth` both come
21068 /// from `Av1Parser`, never from the flag or the fixture name), and the
21069 /// arrival assert is a DELTA on `decode::dual_filter_diff_hits()` taken
21070 /// around this arm alone. A stream that merely parsed would not move the
21071 /// counter; the counter moves only when `resolve_interp_filter` reads two
21072 /// DIFFERENT directions for one block, which is the property the entry
21073 /// was claiming no real stream carried.
21074 #[test]
21075 fn a_real_aomenc_10bit_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact() {
21076 const NAME: &str =
21077 "a_real_aomenc_10bit_dual_filter_obmc_8x8_inter_sequence_decodes_pixel_exact";
21078 if !have_ffmpeg() || !have_aomenc() {
21079 eprintln!("SKIP {NAME}: no ffmpeg/aomenc");
21080 return;
21081 }
21082 let before_dual = decode::dual_filter_diff_hits();
21083 let stream = inter_sb_none_gate(
21084 NAME,
21085 // `ten_bit`: this is the whole difference from the 8-bit witness.
21086 true,
21087 "8",
21088 "16",
21089 decode::compound8_filter_hits,
21090 "a compound 8x8 leaf reading its own switchable interp_filter",
21091 &[
21092 "--enable-dual-filter=1",
21093 "--enable-obmc=1",
21094 "--enable-warped-motion=1",
21095 "--enable-onesided-comp=1",
21096 ],
21097 64,
21098 std::env::var("EC_INTERP3_FRAMES")
21099 .ok()
21100 .and_then(|v| v.parse().ok())
21101 .unwrap_or(16),
21102 );
21103 // The ARRIVAL assert comes first on purpose. `dual_filter_diff_hits()`
21104 // moves only inside `resolve_interp_filter` when the header bit is set
21105 // AND the block's two directions differ, so pinning it =0 reds HERE,
21106 // on the tool failing to arrive -- not on some shape or pixel assert
21107 // downstream of it. The two header asserts below corroborate it from
21108 // the encoded bytes; they are not what carries the proof.
21109 assert!(
21110 decode::dual_filter_diff_hits() > before_dual,
21111 "{NAME}: no block read two DIFFERENT dual-filter directions in the 10-bit stream \
21112 -- --enable-dual-filter=1 did not arrive or aomenc declined it"
21113 );
21114 // Both facts from the PARSED header, not from what we asked for: a
21115 // gate that trusted `--bit-depth=10` would pass on a stream aomenc
21116 // silently coded at 8, which is the vacuity this asserts against.
21117 let mut probe = Av1Parser::new();
21118 let mut pos = 0usize;
21119 while pos < stream.len() && probe.sequence_header().is_none() {
21120 let obu = probe.parse_obu(&stream[pos..]).unwrap();
21121 pos += obu.total_size;
21122 }
21123 let seq = probe
21124 .sequence_header()
21125 .expect("stream has a sequence header OBU");
21126 assert_eq!(
21127 seq.color_config.bit_depth, 10,
21128 "{NAME}: aomenc did not write a 10-bit sequence header"
21129 );
21130 assert!(
21131 seq.enable_dual_filter,
21132 "{NAME}: the parsed sequence header says enable_dual_filter = false, so this \
21133 stream cannot carry per-direction interp filters however the pixels compare"
21134 );
21135 }
21136
21137 #[test]
21138 fn a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
21139 inter_sb_none_gate(
21140 "a_real_aomenc_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
21141 false,
21142 "8",
21143 "16",
21144 decode::inter_sub16_split_hits,
21145 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
21146 &[],
21147 64,
21148 4,
21149 );
21150 }
21151
21152 #[test]
21153 // 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.
21154 fn a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact() {
21155 inter_sb_none_gate(
21156 "a_real_aomenc_10bit_inter_sequence_with_an_8x8_leaf_split_decodes_pixel_exact",
21157 true,
21158 "8",
21159 "16",
21160 decode::inter_sub16_split_hits,
21161 "interior 16x16 inter PARTITION_SPLIT into 8x8 leaves",
21162 &[],
21163 64,
21164 4,
21165 );
21166 }
21167
21168 /// lane-eobc1 r1: an INTER sequence whose CHROMA coefficient blocks come
21169 /// off the class-1 (`TX_CLASS_HORIZ`/`VERT`) `eob_pt` row. Chroma codes
21170 /// no `tx_type` symbol of its own -- it inherits the colocated luma type
21171 /// (`av1_get_tx_type`, `blockd.h:1291`) -- so an 8x8 inter leaf whose
21172 /// luma picks `H_*`/`V_*` puts its 4x4 chroma on a CDF row this crate
21173 /// wired for only some sizes until this round (`eob_pt_class1: None` in
21174 /// 9 of 16 `TxbSet` arms, chroma 4x4/8x8 among them).
21175 ///
21176 /// The full tx set stays on (no `--reduced-tx-type-set=1`) and
21177 /// `--enable-flip-idtx=1` is asked for explicitly; the sinusoidal-stripe
21178 /// luma of the `tx_class1` key-frame gate is what actually resolves 1D
21179 /// types, and the temporally-moving chroma ramp keeps chroma out of
21180 /// `all_zero` so it has an `eob` to read at all. Attempts sweep cq and
21181 /// stripe period; a run counts only when
21182 /// [`decode::chroma_eob_class1_hits`] moved, and every shown frame is
21183 /// compared pixel-exact vs ffmpeg (a decode error is a FAILURE, never a
21184 /// SKIP -- class gate-skips-on-its-own-failure).
21185 fn chroma_class1_eob_gate(name: &str, ten_bit: bool) {
21186 if !have_ffmpeg() {
21187 eprintln!("SKIP {name}: no ffmpeg");
21188 return;
21189 }
21190 if !have_aomenc() {
21191 eprintln!("SKIP {name}: no aomenc at {}", aomenc_path().display());
21192 return;
21193 }
21194 let (width, height, frame_count) = (64usize, 64usize, 4usize);
21195 let mut refusals = Vec::new();
21196 for attempt in 0..12u32 {
21197 let cq = 28 + (attempt % 4) * 10;
21198 let period = [4u32, 6, 8][(attempt as usize / 4) % 3];
21199 let y4m = Command::new("ffmpeg")
21200 .args([
21201 "-v",
21202 "error",
21203 "-f",
21204 "lavfi",
21205 "-i",
21206 &format!("testsrc2=size={width}x{height}:rate=25"),
21207 "-vf",
21208 &format!(
21209 "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"
21210 ),
21211 "-t",
21212 "0.16",
21213 "-pix_fmt",
21214 if ten_bit { "yuv420p10le" } else { "yuv420p" },
21215 "-strict",
21216 "-1",
21217 "-f",
21218 "yuv4mpegpipe",
21219 "-",
21220 ])
21221 .stdin(Stdio::null())
21222 .stdout(Stdio::piped())
21223 .stderr(Stdio::piped())
21224 .output()
21225 .expect("ffmpeg failed to run");
21226 assert!(
21227 y4m.status.success(),
21228 "{name}: ffmpeg fixture: {}",
21229 String::from_utf8_lossy(&y4m.stderr)
21230 );
21231 let mut args: Vec<String> = [
21232 "--codec=av1",
21233 "--passes=1",
21234 "--end-usage=q",
21235 "--cpu-used=0",
21236 "--lag-in-frames=0",
21237 "--auto-alt-ref=0",
21238 "--kf-max-dist=1000",
21239 "--error-resilient=1",
21240 "--enable-flip-idtx=1",
21241 "--reduced-tx-type-set=0",
21242 "--min-partition-size=8",
21243 "--max-partition-size=16",
21244 // Motion tools this decoder refuses by name, kept off so a
21245 // refusal here can only be about the coefficient path.
21246 "--enable-global-motion=0",
21247 "--enable-warped-motion=0",
21248 "--enable-obmc=0",
21249 "--enable-rect-partitions=0",
21250 "--enable-ab-partitions=0",
21251 "--enable-1to4-partitions=0",
21252 "--enable-filter-intra=0",
21253 "--enable-smooth-intra=0",
21254 "--enable-paeth-intra=0",
21255 "--enable-directional-intra=0",
21256 "--enable-angle-delta=0",
21257 "--enable-tx-size-search=0",
21258 "--enable-cdef=0",
21259 "--enable-restoration=0",
21260 "--loopfilter-control=0",
21261 "--enable-palette=0",
21262 "--enable-intrabc=0",
21263 "--enable-cfl-intra=0",
21264 "--enable-ref-frame-mvs=0",
21265 "--obu",
21266 "-o",
21267 "-",
21268 "-",
21269 ]
21270 .iter()
21271 .map(|s| (*s).to_string())
21272 .collect();
21273 args.insert(1, format!("--cq-level={cq}"));
21274 if ten_bit {
21275 args.insert(1, "--input-bit-depth=10".to_string());
21276 args.insert(1, "--bit-depth=10".to_string());
21277 }
21278 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
21279 assert!(
21280 out.status.success(),
21281 "{name}: aomenc refused the fixture: {}",
21282 String::from_utf8_lossy(&out.stderr)
21283 );
21284 let stream = out.stdout;
21285 let before = decode::chroma_eob_class1_hits();
21286 let frames = match decode_stream(&stream) {
21287 Ok(frames) => frames,
21288 // A named refusal ("unsupported: ...") is another lane's arm
21289 // and moves this attempt on; anything else is a real decode
21290 // failure and fails the gate on the spot.
21291 Err(e) if e.to_string().contains("unsupported") => {
21292 refusals.push(format!("cq={cq} period={period}: {e}"));
21293 continue;
21294 }
21295 Err(e) => {
21296 let pin = std::env::temp_dir().join(format!("{name}-refused.obu"));
21297 let _ = std::fs::write(&pin, &stream);
21298 panic!(
21299 "{name}: decode_stream failed on a real aomenc stream (cq={cq} period={period}): {e} (pinned at {})",
21300 pin.display()
21301 );
21302 }
21303 };
21304 if decode::chroma_eob_class1_hits() == before {
21305 refusals.push(format!(
21306 "cq={cq} period={period}: decoded, but no chroma block read a class-1 eob_pt row"
21307 ));
21308 continue;
21309 }
21310 let ffmpeg_frames = if ten_bit {
21311 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
21312 } else {
21313 ffmpeg_decode_sequence(&stream, width, height, frame_count)
21314 };
21315 assert_eq!(frames.len(), frame_count, "{name}: frame count");
21316 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21317 if got.y != want.y || got.u != want.u || got.v != want.v {
21318 let pin = std::env::temp_dir().join(format!("{name}-mismatch.obu"));
21319 let _ = std::fs::write(&pin, &stream);
21320 panic!(
21321 "{name}: frame {i} mismatch vs ffmpeg (cq={cq} period={period}) -- stream pinned at {}",
21322 pin.display()
21323 );
21324 }
21325 }
21326 return;
21327 }
21328 panic!("{name}: no attempt fired a class-1 chroma eob: {refusals:?}");
21329 }
21330
21331 #[test]
21332 fn a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
21333 chroma_class1_eob_gate(
21334 "a_real_aomenc_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
21335 false,
21336 );
21337 }
21338
21339 #[test]
21340 fn a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact() {
21341 chroma_class1_eob_gate(
21342 "a_real_aomenc_10bit_inter_sequence_with_a_class1_chroma_eob_decodes_pixel_exact",
21343 true,
21344 );
21345 }
21346
21347 /// lane-inter4 r1: the SUPERBLOCK-level inter `PARTITION_HORZ`/
21348 /// `PARTITION_VERT` pair -- two 64x32 / 32x64 inter strips, the arm the
21349 /// inter tile path refused outright before this lane ("an inter SB-level
21350 /// partition type other than NONE or SPLIT"). `--min-partition-size=32`
21351 /// keeps every 32x32-level rect shape (already coded, and residual-capable
21352 /// only when skip) out of the picture so the counters can only be earned
21353 /// at the superblock level; the noiseless split-motion source (one half
21354 /// translating, the other static, flat inside each half) is what makes
21355 /// aomenc's RD pick a superblock HORZ/VERT whose strips are `skip` --
21356 /// the ONLY inter rect shape this decoder can complete, since rectangular
21357 /// inter residual coding is not ported (see `reject_residual`).
21358 ///
21359 /// Every decoded frame is compared to ffmpeg (Y, U and V); an attempt
21360 /// that refuses by name is counted, never turned into a SKIP; and an
21361 /// attempt that decoded without firing the arm is counted separately and
21362 /// still required to be pixel-exact (class gate-skips-on-its-own-failure).
21363 #[test]
21364 fn a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact() {
21365 const NAME: &str = "a_real_aomenc_inter_sequence_with_a_superblock_level_rect_partition_decodes_pixel_exact";
21366 let _gate_lock = lock_gate_counters();
21367 if !have_ffmpeg() {
21368 eprintln!("SKIP {NAME}: no ffmpeg");
21369 return;
21370 }
21371 if !have_aomenc() {
21372 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
21373 return;
21374 }
21375 let (width, height, frame_count) = (192usize, 128usize, 6usize);
21376 // lane-inter4 r1: 8-bit ONLY, and the reason is the lane's own open
21377 // residue, not a tolerance: across all 16 attempts x both depths, every
21378 // 10-bit attempt that reached a superblock-level rect strip found it
21379 // NON-skip, so it stops at "a non-skip rectangular (HORZ/VERT/HORZ_B)
21380 // strip needs rectangular residual coding". The 10-bit twin below is
21381 // `#[ignore]`d with that exact reason rather than deleted or weakened.
21382 // lane-r14 r2 re-measured the 8-bit-only note above: the residual
21383 // refusal it names is GONE (this round codes a 64-px transform axis as
21384 // its truncated low-32 corner), and a 10-bit sweep of this exact
21385 // recipe now reaches the arm -- 2 pixel-exact attempts, 2 64x32 and 2
21386 // 32x64 strips, 2 of them carrying a coded 64-axis residual.
21387 // lane-sbrect10 r1 closed the newly exposed 10-bit defect r14 r2
21388 // parked this arm on (10-bit attempt 14, cq 61, horizontal split,
21389 // motion step 12 -- it mismatched ffmpeg while decoding ZERO rect
21390 // strips): a 64x64 INTRA block inside an inter frame read `uv_mode`
21391 // off the 14-symbol CFL-allowed alphabet, which libaom's
21392 // `is_cfl_allowed` caps at 32x32 -- same DC_PRED value, wrong
21393 // interval narrowing, tile desynced from that block on. Both depths
21394 // run now.
21395 for bit_depth in [8u32, 10u32] {
21396 let (mut named_refusals, mut matched, mut out_of_scope, mut oos_mismatch) =
21397 (0u32, 0u32, 0u32, 0u32);
21398 let (mut horz_proved, mut vert_proved) = (0usize, 0usize);
21399 let mut rect64_tus = 0usize;
21400 for attempt in 0..16u32 {
21401 // Two orientations (the transposed pair a one-sided gate could
21402 // never separate) x four quantisers x two motion steps: which
21403 // superblock the RD hands a skip-able rect strip moves with
21404 // the quantiser, and the 10-bit arm needs a different corner
21405 // of the grid from the 8-bit one.
21406 let vertical_split = attempt % 2 == 1;
21407 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
21408 let sp = 8 + (attempt / 8) * 4;
21409 let geq = if vertical_split {
21410 format!("if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), 200)")
21411 } else {
21412 format!("if(lt(X,64), 40+mod(floor((Y+N*{sp})/32)*90,200), 200)")
21413 };
21414 let duration = frame_count as f64 / 25.0;
21415 let source = format!(
21416 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
21417 geq=lum='{geq}',format=yuv420p"
21418 );
21419 let pix_fmt = if bit_depth == 10 {
21420 "yuv420p10le"
21421 } else {
21422 "yuv420p"
21423 };
21424 let y4m = Command::new("ffmpeg")
21425 .args([
21426 "-v",
21427 "error",
21428 "-f",
21429 "lavfi",
21430 "-i",
21431 &source,
21432 "-t",
21433 &duration.to_string(),
21434 "-pix_fmt",
21435 pix_fmt,
21436 "-strict",
21437 "-1",
21438 "-f",
21439 "yuv4mpegpipe",
21440 "-",
21441 ])
21442 .stdin(Stdio::null())
21443 .stdout(Stdio::piped())
21444 .stderr(Stdio::piped())
21445 .output()
21446 .expect("ffmpeg failed to run");
21447 assert!(
21448 y4m.status.success(),
21449 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
21450 String::from_utf8_lossy(&y4m.stderr)
21451 );
21452 let cq_arg = format!("--cq-level={cq}");
21453 let depth_arg = format!("--bit-depth={bit_depth}");
21454 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
21455 let args: Vec<&str> = vec![
21456 "--codec=av1",
21457 "--passes=1",
21458 "--end-usage=q",
21459 &cq_arg,
21460 "--cpu-used=0",
21461 "--threads=1",
21462 "--row-mt=0",
21463 "--sb-size=64",
21464 &depth_arg,
21465 &input_depth_arg,
21466 "--enable-restoration=0",
21467 "--enable-palette=0",
21468 "--deltaq-mode=0",
21469 "--enable-filter-intra=0",
21470 "--enable-cfl-intra=0",
21471 "--enable-intrabc=0",
21472 "--enable-tx-size-search=0",
21473 "--lag-in-frames=0",
21474 // Per-arm overrides go LAST: aomenc keeps the last
21475 // occurrence of a repeated --enable-* flag.
21476 "--enable-rect-partitions=1",
21477 "--enable-ab-partitions=0",
21478 "--enable-1to4-partitions=1",
21479 "--min-partition-size=32",
21480 "--max-partition-size=64",
21481 "--obu",
21482 "-o",
21483 "-",
21484 "-",
21485 ];
21486 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
21487 assert!(
21488 out.status.success(),
21489 "aomenc refused the fixture: {}",
21490 String::from_utf8_lossy(&out.stderr)
21491 );
21492 let stream = out.stdout;
21493 let before = crate::stream::inter_rect_counters();
21494 let rect64_before = crate::stream::rect64_inter_tu_hits();
21495 let frames = match decode_stream(&stream) {
21496 Err(e) => {
21497 let msg = e.to_string();
21498 assert!(
21499 msg.contains("unsupported"),
21500 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
21501 attempt {attempt}): {msg}"
21502 );
21503 named_refusals += 1;
21504 eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
21505 continue;
21506 }
21507 Ok(frames) => frames,
21508 };
21509 let after = crate::stream::inter_rect_counters();
21510 let (horz, vert) = (after.2 - before.2, after.3 - before.3);
21511 let rect64 = crate::stream::rect64_inter_tu_hits() - rect64_before;
21512 let ffmpeg_frames = if bit_depth == 10 {
21513 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
21514 } else {
21515 ffmpeg_decode_sequence(&stream, width, height, frame_count)
21516 };
21517 assert_eq!(frames.len(), frame_count);
21518 let mismatched = frames
21519 .iter()
21520 .zip(&ffmpeg_frames)
21521 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
21522 if horz + vert == 0 {
21523 out_of_scope += 1;
21524 if mismatched {
21525 oos_mismatch += 1;
21526 eprintln!(
21527 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
21528 superblock-level inter rect strips -- another shape's defect"
21529 );
21530 }
21531 continue;
21532 }
21533 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21534 assert_eq!(
21535 got.y, want.y,
21536 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
21537 );
21538 assert_eq!(
21539 got.u, want.u,
21540 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
21541 );
21542 assert_eq!(
21543 got.v, want.v,
21544 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
21545 );
21546 }
21547 horz_proved += horz;
21548 vert_proved += vert;
21549 rect64_tus += rect64;
21550 matched += 1;
21551 }
21552 eprintln!(
21553 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {matched} pixel-exact \
21554 attempts carrying the arm, 64x32 strips={horz_proved}, 32x64 strips={vert_proved}, \
21555 64-axis residual TUs={rect64_tus}, \
21556 {out_of_scope} attempts carried none ({oos_mismatch} of them mismatched)"
21557 );
21558 assert_eq!(
21559 oos_mismatch, 0,
21560 "{NAME}: {oos_mismatch} attempt(s) with no superblock-level inter rect strip \
21561 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
21562 );
21563 // lane-r14 r2: the residual half of the arm -- a strip that is not
21564 // `skip` and codes a real 64-axis transform unit. Without this the
21565 // gate proves only the partition symbol.
21566 assert!(
21567 rect64_tus > 0,
21568 "{NAME} ({bit_depth}-bit): no superblock-level rect strip carried a coded \
21569 64-axis residual transform unit inside a pixel-exact attempt \
21570 (horz={horz_proved}, vert={vert_proved}) -- the residual arm proved nothing"
21571 );
21572 assert!(
21573 horz_proved + vert_proved > 0,
21574 "{NAME} ({bit_depth}-bit): the superblock-level inter rect arm never fired \
21575 inside a pixel-exact attempt (horz={horz_proved}, vert={vert_proved}, \
21576 {named_refusals} refusals, {out_of_scope} out of scope) -- gate proved nothing"
21577 );
21578 }
21579 }
21580
21581 /// lane-r14 r3: a 1:4 inter strip with a 64-px axis (64x16 / 16x64) whose
21582 /// transform SPLITS -- the arm r2 left refused by name ("a split transform
21583 /// on a 1:4 inter strip with a 64-px axis"). libaom's
21584 /// `sub_tx_size_map[TX_64X16] == TX_32X16` (and `[TX_16X64] == TX_16X32`)
21585 /// keeps the sub-transform RECTANGULAR, so the var-tx tree's leaves are
21586 /// 32x16/16x32 units read through [`TxbSet::LumaRect32x16Inter`], each with
21587 /// its own `get_txb_ctx_general` neighbour context (the unit is smaller
21588 /// than its block, so `txb_skip_ctx` is NOT the lone-TU 0).
21589 ///
21590 /// `--enable-1to4-partitions=1 --min-partition-size=16
21591 /// --max-partition-size=64 --enable-tx64=1` (each spelled once, last
21592 /// occurrence wins) is what lets aomenc pick a superblock-level HORZ_4 /
21593 /// VERT_4; the textured translating source is what keeps the strips
21594 /// non-skip so the residual is actually coded. 8-bit AND 10-bit, every
21595 /// decoded frame compared to ffmpeg on Y/U/V, refusals counted (never
21596 /// SKIPped), attempts that carried no rectangular var-tx leaf counted
21597 /// separately and still required pixel-exact.
21598 #[test]
21599 fn real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal()
21600 {
21601 const NAME: &str = "real_aomenc_1to4_streams_decode_pixel_exact_and_rect_vartx_leaves_fire_before_a_named_refusal";
21602 let _gate_lock = lock_gate_counters();
21603 if !have_ffmpeg() {
21604 eprintln!("SKIP {NAME}: no ffmpeg");
21605 return;
21606 }
21607 if !have_aomenc() {
21608 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
21609 return;
21610 }
21611 let frame_count = 6usize;
21612 for bit_depth in [8u32, 10u32] {
21613 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
21614 (0u32, 0u32, 0u32, 0u32);
21615 let (mut leaf_32x16, mut leaf_16x32) = (0usize, 0usize);
21616 // Leaves decoded on ANY attempt, including one whose stream hits a
21617 // later named refusal: the firing half of this gate, kept apart
21618 // from `leaf_32x16`/`leaf_16x32` (pixel-compared attempts only) so
21619 // a refused stream is never counted as a pixel proof
21620 // (class counter-from-refused-stream).
21621 let (mut fired_32x16, mut fired_16x32) = (0usize, 0usize);
21622 // lane-gaterecipe r1: the firing arms (16-17) are 8-BIT ONLY, and
21623 // this is measured, not a convenience. Their 10-bit twin fires the
21624 // leaves too (32x16=0 16x32=46 on attempt 16) and then MISMATCHES
21625 // ffmpeg at decode-order frame 2 of attempt 17 -- an open DECODE
21626 // defect handed off in lanes/gaterecipe-r1.report.md, never
21627 // silenced inside this loop.
21628 let attempts = if bit_depth == 8 { 18u32 } else { 16u32 };
21629 for attempt in 0..attempts {
21630 // Two orientations (the transposed pair a one-sided gate could
21631 // never separate) x four quantisers x two motion steps.
21632 // lane-r14 r4 recipe hunt (~70 aomenc runs on the merged
21633 // tree: testsrc2 / life / mandelbrot / banded motion, 64x64 up
21634 // to 384x256, cq 20..58): attempts 16-17 carry the only recipe
21635 // found that makes aomenc code a 64-axis 1:4 strip whose
21636 // transform SPLITS -- 384x256, per-16-column band motion,
21637 // cq 32 (16x32 leaves) and cq 38 (32x16 leaves).
21638 let firing = attempt >= 16;
21639 let (width, height) = if firing {
21640 (384usize, 256usize)
21641 } else {
21642 (192usize, 128usize)
21643 };
21644 let vertical = attempt % 2 == 1;
21645 // lane-vartxsplit r2, MEASURED against the oracle
21646 // (`EC_VARTX` histogram, ~40 aomenc runs): at cq 10 this
21647 // source splits NO rectangular transform at all -- aomdec
21648 // reads only TX_8X8/TX_16X16/TX_8X16/TX_16X8 split symbols,
21649 // so the leaves gaterecipe r1 counted here came out of a
21650 // stream our decoder was already desynced on (class
21651 // counter-from-refused-stream). cq 44 and 46 are the two
21652 // quantisers of that sweep whose stream really carries
21653 // `TX_32X8`/`TX_8X32` splits (16x8 and 8x16 rectangular
21654 // var-tx leaves) AND decodes pixel-exact on all six frames.
21655 let cq = if firing {
21656 if attempt == 16 { 44 } else { 46 }
21657 } else {
21658 [30, 36, 44, 52][(attempt / 2 % 4) as usize]
21659 };
21660 let sp = 3 + (attempt / 8) * 3;
21661 // 16-pixel bands, each band translating at its OWN speed
21662 // across the other axis: that is what makes aomenc's RD split
21663 // a 64x64 superblock into four 1:4 strips (`PARTITION_HORZ_4`
21664 // / `VERT_4`) with distinct motion vectors, and the texture
21665 // inside a band is what keeps the strip non-skip and its
21666 // transform split.
21667 let geq = if firing && !vertical {
21668 // lane-gaterecipe r1, MEASURED: the banded translating
21669 // source this arm used until now splits NO transform at
21670 // all -- an aomdec EC_TRACE/EC_TRACE_COEFF histogram of its
21671 // stream reads zero 1:4 partitions and zero rectangular
21672 // sub-transforms, so the leaves the old assert counted came
21673 // out of a stream that stopped at a refusal (class
21674 // counter-from-refused-stream). What DOES split a
21675 // rectangular transform is a high-frequency product texture
21676 // at a fine quantiser with `--min-partition-size=8`: part
21677 // of the block predicts well and part does not, which is
21678 // the RD case for `txfm_partition`.
21679 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
21680 } else if firing {
21681 // lane-vartxsplit r2: BOTH leaf orientations come out of
21682 // this one source (three 16x8 leaves and one 8x16 on
21683 // attempt 16), so the firing pair is the same texture at
21684 // two quantisers. Its transposed twin was measured over
21685 // cq 40..56 and splits no rectangular transform at all;
21686 // at cq 56 it also mismatches ffmpeg from decode-order
21687 // frame 2 with ZERO rect var-tx leaves in it -- an open
21688 // reconstruction defect (8-pixel-wide luma column, see
21689 // lanes/vartxsplit-r2.report.md), not something to hide
21690 // inside this gate's attempt list.
21691 "128+90*sin((X+N*3)/6)*sin(Y/2)+50*sin((X*Y)/37)".to_string()
21692 } else if vertical {
21693 format!("128+60*sin((Y+N*({sp}+9*mod(floor(X/16),2)))/7)+25*sin(X/11)")
21694 } else {
21695 format!("128+60*sin((X+N*({sp}+9*mod(floor(Y/16),2)))/7)+25*sin(Y/11)")
21696 };
21697 let duration = frame_count as f64 / 25.0;
21698 let source = format!(
21699 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
21700 geq=lum='{geq}',format=yuv420p"
21701 );
21702 let pix_fmt = if bit_depth == 10 {
21703 "yuv420p10le"
21704 } else {
21705 "yuv420p"
21706 };
21707 let y4m = Command::new("ffmpeg")
21708 .args([
21709 "-v",
21710 "error",
21711 "-f",
21712 "lavfi",
21713 "-i",
21714 &source,
21715 "-t",
21716 &duration.to_string(),
21717 "-pix_fmt",
21718 pix_fmt,
21719 "-strict",
21720 "-1",
21721 "-f",
21722 "yuv4mpegpipe",
21723 "-",
21724 ])
21725 .stdin(Stdio::null())
21726 .stdout(Stdio::piped())
21727 .stderr(Stdio::piped())
21728 .output()
21729 .expect("ffmpeg failed to run");
21730 assert!(
21731 y4m.status.success(),
21732 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
21733 String::from_utf8_lossy(&y4m.stderr)
21734 );
21735 let cq_arg = format!("--cq-level={cq}");
21736 let depth_arg = format!("--bit-depth={bit_depth}");
21737 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
21738 // A rectangular var-tx LEAF needs a block whose max rectangular
21739 // transform can split: `--min-partition-size=8` is what lets
21740 // aomenc's RD reach one (measured); at 16 it never did.
21741 let min_part = if firing {
21742 "--min-partition-size=8"
21743 } else {
21744 "--min-partition-size=16"
21745 };
21746 let args: Vec<&str> = vec![
21747 "--codec=av1",
21748 "--passes=1",
21749 "--end-usage=q",
21750 &cq_arg,
21751 "--cpu-used=0",
21752 "--threads=1",
21753 "--row-mt=0",
21754 "--sb-size=64",
21755 &depth_arg,
21756 &input_depth_arg,
21757 "--enable-restoration=0",
21758 "--enable-palette=0",
21759 "--deltaq-mode=0",
21760 "--enable-filter-intra=0",
21761 "--enable-cfl-intra=0",
21762 "--enable-intrabc=0",
21763 "--lag-in-frames=0",
21764 // Per-arm overrides go LAST: aomenc keeps the last
21765 // occurrence of a repeated --enable-* flag.
21766 "--enable-tx64=1",
21767 "--enable-rect-partitions=1",
21768 "--enable-ab-partitions=0",
21769 "--enable-1to4-partitions=1",
21770 "--enable-dual-filter=0",
21771 "--enable-obmc=0",
21772 "--enable-tx-size-search=1",
21773 min_part,
21774 "--max-partition-size=64",
21775 "--obu",
21776 "-o",
21777 "-",
21778 "-",
21779 ];
21780 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
21781 assert!(
21782 out.status.success(),
21783 "aomenc refused the fixture: {}",
21784 String::from_utf8_lossy(&out.stderr)
21785 );
21786 let stream = out.stdout;
21787 let before = crate::stream::vartx_rect_leaf_hits();
21788 let frames = match decode_stream(&stream) {
21789 Err(e) => {
21790 let msg = e.to_string();
21791 assert!(
21792 msg.contains("unsupported"),
21793 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
21794 attempt {attempt}): {msg}"
21795 );
21796 let after = crate::stream::vartx_rect_leaf_hits();
21797 fired_32x16 += after[0] - before[0];
21798 fired_16x32 += after[1] - before[1];
21799 named_refusals += 1;
21800 eprintln!(
21801 "{bit_depth}-bit attempt {attempt} refusal (rect var-tx leaves \
21802 decoded before it: 32x16={}, 16x32={}): {msg}",
21803 after[0] - before[0],
21804 after[1] - before[1]
21805 );
21806 continue;
21807 }
21808 Ok(frames) => frames,
21809 };
21810 let after = crate::stream::vartx_rect_leaf_hits();
21811 let (h32, v32) = (after[0] - before[0], after[1] - before[1]);
21812 fired_32x16 += h32;
21813 fired_16x32 += v32;
21814 let ffmpeg_frames = if bit_depth == 10 {
21815 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
21816 } else {
21817 ffmpeg_decode_sequence(&stream, width, height, frame_count)
21818 };
21819 assert_eq!(frames.len(), frame_count);
21820 let mismatched = frames
21821 .iter()
21822 .zip(&ffmpeg_frames)
21823 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
21824 if h32 + v32 == 0 {
21825 // Counted per ATTEMPT, on a decoded+compared attempt only
21826 // (class counter-from-refused-stream).
21827 out_of_scope += 1;
21828 if mismatched {
21829 oos_mismatch += 1;
21830 eprintln!(
21831 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
21832 rectangular var-tx leaves -- another shape's defect"
21833 );
21834 }
21835 continue;
21836 }
21837 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
21838 assert_eq!(
21839 got.y, want.y,
21840 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
21841 );
21842 assert_eq!(
21843 got.u, want.u,
21844 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
21845 );
21846 assert_eq!(
21847 got.v, want.v,
21848 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
21849 );
21850 }
21851 leaf_32x16 += h32;
21852 leaf_16x32 += v32;
21853 compared += 1;
21854 }
21855 eprintln!(
21856 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
21857 pixel-exact attempts carrying the arm, pixel-compared rect var-tx leaves \
21858 32x16={leaf_32x16} 16x32={leaf_16x32}, leaves decoded anywhere in the sweep \
21859 32x16={fired_32x16} 16x32={fired_16x32}, {out_of_scope} attempts carried none \
21860 ({oos_mismatch} of them mismatched)"
21861 );
21862 assert_eq!(
21863 oos_mismatch, 0,
21864 "{NAME}: {oos_mismatch} attempt(s) with no rectangular var-tx leaf decoded \
21865 but mismatched ffmpeg -- a defect of another shape, not a pass"
21866 );
21867 assert!(
21868 compared + out_of_scope > 0,
21869 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
21870 );
21871 // The firing half. lane-vartxsplit r2 re-measured it against
21872 // the oracle: attempts 16/17 (384x256 product texture, cq 44/46,
21873 // `--min-partition-size=8 --enable-tx-size-search=1`) are the only
21874 // recipes of a ~40-run sweep whose stream carries `TX_32X8` /
21875 // `TX_8X32` split symbols, i.e. RECTANGULAR var-tx leaves (16x8
21876 // and 8x16, both orientations out of the same stream). They now
21877 // decode PIXEL-EXACT on all six frames, so the assert is on the
21878 // pixel-compared tally, not on the "decoded anywhere" one --
21879 // `fired_*` stays only to separate a refused stream's leaves from
21880 // a proved one (class counter-from-refused-stream). At 10 bits
21881 // the same sweep either fires nothing or mismatches on a
21882 // reconstruction defect of another shape (report), so the firing
21883 // assert stays 8-bit -- and it is a hard assert, never a print.
21884 if bit_depth == 8 {
21885 assert!(
21886 leaf_32x16 > 0 && leaf_16x32 > 0,
21887 "{NAME}: the rectangular var-tx leaf arm never fired on a pixel-exact \
21888 attempt (pixel-compared 32x16={leaf_32x16}, 16x32={leaf_16x32}, decoded \
21889 anywhere 32x16={fired_32x16} 16x32={fired_16x32}, {named_refusals} \
21890 refusals, {compared} compared) -- the rectangular sub-transform path is \
21891 unproved by this gate"
21892 );
21893 }
21894 }
21895 }
21896
21897 /// lane-rectres r1: a 32x32-level 1:4 INTER strip (32x8 / 8x32) that codes
21898 /// a REAL rectangular residual. THIS is the shape both 10-bit 3840x1608
21899 /// film cuts and every measured 1080p offset stopped on -- six of six
21900 /// `decode_probe` runs refused at "a non-skip rectangular (HORZ/VERT/
21901 /// HORZ_B) strip needs rectangular residual coding" with `w=32 h=8` or
21902 /// `w=8 h=32`, nothing else.
21903 ///
21904 /// `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256 of its
21905 /// positions ([`TxbSet::LumaRect32x8Inter`]: `get_txsize_entropy_ctx` =
21906 /// TX_16X16 so the coefficient tables are the luma-16 ones,
21907 /// `txsize_log2_minus4` = 4 so `eob_pt` is the 256-position alphabet), and
21908 /// unlike the INTRA twin it DOES code a `tx_type`:
21909 /// `av1_get_ext_tx_set_type` at `tx_size_sqr_up == TX_32X32` is
21910 /// `EXT_TX_SET_DCT_IDTX` for inter with or without `reduced_tx_set`, read
21911 /// at the `txsize_sqr_map[TX_32X8] == TX_8X8` CDF row (class
21912 /// table-indexed-by-raw-size: the coefficient tables follow the ADJUSTED
21913 /// size, the `tx_type` row the SQUARE one -- they disagree here).
21914 /// Its chroma pair is one 16x4 / 4x16 unit (`ss_size_lookup[BLOCK_32X8]`
21915 /// = BLOCK_16X4, `Chroma8`'s tables, 64-position `eob_pt`), and a split
21916 /// transform gives 16x8 / 8x16 leaves (`sub_tx_size_map[TX_32X8] ==
21917 /// TX_16X8`) the rect var-tx path already reads.
21918 ///
21919 /// `--enable-1to4-partitions=1 --min-partition-size=8
21920 /// --max-partition-size=32 --enable-tx-size-search=1` (each spelled once,
21921 /// last occurrence wins -- aomenc keeps the LAST `--enable-*`) is what
21922 /// lets aomenc pick a 32x32-level HORZ_4 / VERT_4; the 8-pixel banded
21923 /// translating source is what makes those strips the RD winner and keeps
21924 /// them non-skip so the residual is really coded. Both orientations, 8-bit
21925 /// AND 10-bit, every decode-order frame compared to ffmpeg on Y/U/V,
21926 /// refusals counted (never SKIPped), attempts that carried no 32x8/8x32
21927 /// residual unit counted separately and still required pixel-exact.
21928 #[test]
21929 fn a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual() {
21930 const NAME: &str =
21931 "a_real_aomenc_inter_sequence_with_32x32_level_1to4_strips_codes_their_rect_residual";
21932 let _gate_lock = lock_gate_counters();
21933 if !have_ffmpeg() {
21934 eprintln!("SKIP {NAME}: no ffmpeg");
21935 return;
21936 }
21937 if !have_aomenc() {
21938 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
21939 return;
21940 }
21941 let frame_count = 6usize;
21942 let (mut proved_32x8, mut proved_8x32) = (0usize, 0usize);
21943 let (mut fired_32x8, mut fired_8x32) = (0usize, 0usize);
21944 for bit_depth in [8u32, 10u32] {
21945 let (mut named_refusals, mut compared, mut out_of_scope, mut oos_mismatch) =
21946 (0u32, 0u32, 0u32, 0u32);
21947 for attempt in 0..16u32 {
21948 // Two orientations (the transposed pair a one-sided gate could
21949 // never separate) x four quantisers x two motion steps.
21950 let vertical = attempt % 2 == 1;
21951 let (width, height) = (192usize, 128usize);
21952 let cq = [48, 52, 56, 60][(attempt / 2 % 4) as usize];
21953 let sp = 3 + (attempt / 8) * 4;
21954 // 32-pixel bands, each translating at its OWN speed across the
21955 // other axis: that is what makes aomenc's RD split a 32x32
21956 // block into four 32x8 (or 8x32) strips with distinct motion
21957 // vectors, and the texture inside a band is what keeps a strip
21958 // non-skip. MEASURED (72-run recipe sweep, 192x128..256x192,
21959 // cq 24..60, bands 8/16/32/64): only 32-pixel bands at cq >= 48
21960 // make aomenc code a NON-SKIP one -- attempt 0 (cq 48,
21961 // horizontal source) codes an 8x32 residual unit, attempt 7
21962 // (cq 60, the transposed source) five 32x8 ones. Narrower
21963 // bands give the same strips with `skip` set, which proves the
21964 // partition symbol and nothing about the residual.
21965 let geq = if vertical {
21966 format!("128+62*sin((Y+N*({sp}+7*mod(floor(X/32),4)))/6)+28*sin(X/9)")
21967 } else {
21968 format!("128+62*sin((X+N*({sp}+7*mod(floor(Y/32),4)))/6)+28*sin(Y/9)")
21969 };
21970 let duration = frame_count as f64 / 25.0;
21971 let source = format!(
21972 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
21973 geq=lum='{geq}',format=yuv420p"
21974 );
21975 let pix_fmt = if bit_depth == 10 {
21976 "yuv420p10le"
21977 } else {
21978 "yuv420p"
21979 };
21980 let y4m = Command::new("ffmpeg")
21981 .args([
21982 "-v",
21983 "error",
21984 "-f",
21985 "lavfi",
21986 "-i",
21987 &source,
21988 "-t",
21989 &duration.to_string(),
21990 "-pix_fmt",
21991 pix_fmt,
21992 "-strict",
21993 "-1",
21994 "-f",
21995 "yuv4mpegpipe",
21996 "-",
21997 ])
21998 .stdin(Stdio::null())
21999 .stdout(Stdio::piped())
22000 .stderr(Stdio::piped())
22001 .output()
22002 .expect("ffmpeg failed to run");
22003 assert!(
22004 y4m.status.success(),
22005 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
22006 String::from_utf8_lossy(&y4m.stderr)
22007 );
22008 let cq_arg = format!("--cq-level={cq}");
22009 let depth_arg = format!("--bit-depth={bit_depth}");
22010 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
22011 let args: Vec<&str> = vec![
22012 "--codec=av1",
22013 "--passes=1",
22014 "--end-usage=q",
22015 &cq_arg,
22016 "--cpu-used=0",
22017 "--threads=1",
22018 "--row-mt=0",
22019 "--sb-size=64",
22020 &depth_arg,
22021 &input_depth_arg,
22022 "--enable-restoration=0",
22023 "--enable-palette=0",
22024 "--deltaq-mode=0",
22025 "--enable-filter-intra=0",
22026 "--enable-cfl-intra=0",
22027 "--enable-intrabc=0",
22028 "--lag-in-frames=0",
22029 // Per-arm overrides go LAST: aomenc keeps the last
22030 // occurrence of a repeated --enable-* flag.
22031 "--enable-tx64=0",
22032 "--enable-rect-partitions=1",
22033 "--enable-ab-partitions=0",
22034 "--enable-1to4-partitions=1",
22035 "--enable-tx-size-search=1",
22036 "--enable-dual-filter=0",
22037 "--enable-obmc=0",
22038 // aomenc's min-partition-size bounds the SMALLER side of a
22039 // 1:4 strip, so 32x8 needs 8 (memory
22040 // aomenc-min-partition-bounds-smaller-side).
22041 "--min-partition-size=8",
22042 "--max-partition-size=32",
22043 "--obu",
22044 "-o",
22045 "-",
22046 "-",
22047 ];
22048 let out = run_with_stdin(Command::new(aomenc_path()).args(&args), &y4m.stdout);
22049 assert!(
22050 out.status.success(),
22051 "aomenc refused the fixture: {}",
22052 String::from_utf8_lossy(&out.stderr)
22053 );
22054 let stream = out.stdout;
22055 let before = crate::stream::rect32x8_inter_tu_hits();
22056 let frames = match decode_stream(&stream) {
22057 Err(e) => {
22058 let msg = e.to_string();
22059 assert!(
22060 msg.contains("unsupported"),
22061 "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
22062 attempt {attempt}): {msg}"
22063 );
22064 let after = crate::stream::rect32x8_inter_tu_hits();
22065 // Firing counted on a refused stream is kept apart from
22066 // the pixel-proved tally (class
22067 // counter-from-refused-stream).
22068 fired_32x8 += after[0] - before[0];
22069 fired_8x32 += after[1] - before[1];
22070 named_refusals += 1;
22071 eprintln!(
22072 "{NAME} {bit_depth}-bit attempt {attempt} refusal (32x8 residual \
22073 units decoded before it: {}, 8x32: {}): {msg}",
22074 after[0] - before[0],
22075 after[1] - before[1]
22076 );
22077 continue;
22078 }
22079 Ok(frames) => frames,
22080 };
22081 let after = crate::stream::rect32x8_inter_tu_hits();
22082 let (h, v) = (after[0] - before[0], after[1] - before[1]);
22083 fired_32x8 += h;
22084 fired_8x32 += v;
22085 let ffmpeg_frames = if bit_depth == 10 {
22086 ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
22087 } else {
22088 ffmpeg_decode_sequence(&stream, width, height, frame_count)
22089 };
22090 assert_eq!(frames.len(), frame_count);
22091 let mismatched = frames
22092 .iter()
22093 .zip(&ffmpeg_frames)
22094 .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
22095 if h + v == 0 {
22096 out_of_scope += 1;
22097 if mismatched {
22098 oos_mismatch += 1;
22099 eprintln!(
22100 "{NAME}: {bit_depth}-bit attempt {attempt} MISMATCHES with zero \
22101 32x8/8x32 inter residual units -- another shape's defect"
22102 );
22103 }
22104 continue;
22105 }
22106 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
22107 assert_eq!(
22108 got.y, want.y,
22109 "{NAME} frame {i} luma vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
22110 );
22111 assert_eq!(
22112 got.u, want.u,
22113 "{NAME} frame {i} U vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
22114 );
22115 assert_eq!(
22116 got.v, want.v,
22117 "{NAME} frame {i} V vs ffmpeg (attempt {attempt}, {bit_depth}-bit)"
22118 );
22119 }
22120 proved_32x8 += h;
22121 proved_8x32 += v;
22122 compared += 1;
22123 }
22124 eprintln!(
22125 "{NAME} ({bit_depth}-bit): {named_refusals} named refusals, {compared} \
22126 pixel-exact attempts carrying the arm, {out_of_scope} attempts carried none \
22127 ({oos_mismatch} of them mismatched)"
22128 );
22129 assert_eq!(
22130 oos_mismatch, 0,
22131 "{NAME}: {oos_mismatch} attempt(s) with no 32x8/8x32 inter residual unit \
22132 decoded but mismatched ffmpeg -- a defect of another shape, not a pass"
22133 );
22134 assert!(
22135 compared + out_of_scope > 0,
22136 "{NAME} ({bit_depth}-bit): every attempt refused -- the gate compared no pixels"
22137 );
22138 }
22139 eprintln!(
22140 "{NAME}: pixel-compared 32x32-level 1:4 inter residual units 32x8={proved_32x8} \
22141 8x32={proved_8x32} (decoded anywhere in the sweep 32x8={fired_32x8} \
22142 8x32={fired_8x32})"
22143 );
22144 // The firing half, one assert per lifted shape. Both orientations must
22145 // be PIXEL-PROVED: a transposed table passes one and fails the other
22146 // (class reference-layout-not-spec).
22147 assert!(
22148 proved_32x8 > 0,
22149 "{NAME}: no 32x8 inter residual transform unit was decoded inside a pixel-exact \
22150 attempt (decoded anywhere: {fired_32x8}) -- the lift is unproved"
22151 );
22152 assert!(
22153 proved_8x32 > 0,
22154 "{NAME}: no 8x32 inter residual transform unit was decoded inside a pixel-exact \
22155 attempt (decoded anywhere: {fired_8x32}) -- the lift is unproved"
22156 );
22157 }
22158
22159 /// lane-sbrect10 r1: a 64x64 INTRA block inside an INTER frame, whose
22160 /// `uv_mode` alphabet libaom's `is_cfl_allowed` (`blockd.h`: `wide <= 32
22161 /// && high <= 32`) narrows to the 13-symbol NO-CFL table. Reading the
22162 /// 14-symbol CFL one produced the same `DC_PRED` value with the wrong
22163 /// interval narrowing, so the tile desynced from that block on and the
22164 /// frame decoded silently wrong (class `wrong-alphabet-same-value`; found
22165 /// as the "another shape" mismatch the superblock rect gate above had to
22166 /// park its 10-bit arm on).
22167 ///
22168 /// The counter `nocfl_uv_mode_hits` proves the shape fired in EVERY
22169 /// compared attempt, and every decode-order frame is compared against
22170 /// ffmpeg -- an attempt that mismatches fails, it never SKIPs.
22171 ///
22172 /// lane-sbrect10 r2: with the half-random source below this gate also
22173 /// covers a SECOND defect it exposed at 10-bit cq 58/61 -- the compound
22174 /// MV stack's extension pass zero-filled the `comp_list` tail slots
22175 /// libaom fills with each side's GLOBAL MOTION vector
22176 /// (`combine_compound_candidates`, mvref_common.c:723-729). A compound
22177 /// block with no usable neighbour pair (frame top row, intra block to
22178 /// its left, empty temporal field) then took a `(0, 0)` predictor
22179 /// instead of the frame's translation: 32890/39907 wrong luma samples
22180 /// on decode-order frame 2 with the entropy stream still in sync.
22181 #[test]
22182 fn a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet() {
22183 const NAME: &str =
22184 "a_real_aomenc_inter_frame_with_a_64x64_intra_block_reads_the_no_cfl_uv_alphabet";
22185 let _gate_lock = lock_gate_counters();
22186 if !have_ffmpeg() {
22187 eprintln!("SKIP {NAME}: no ffmpeg");
22188 return;
22189 }
22190 if !have_aomenc() {
22191 eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
22192 return;
22193 }
22194 let (width, height, frame_count) = (192usize, 128usize, 6usize);
22195 for bit_depth in [8u32, 10u32] {
22196 let (mut named_refusals, mut matched, mut carried_none) = (0u32, 0u32, 0u32);
22197 let mut total_hits = 0usize;
22198 for attempt in 0..16u32 {
22199 // The sibling superblock-rect gate's own grid (its 10-bit
22200 // attempt 14 -- cq 61, horizontal split, motion step 12 -- is
22201 // the stream that exposed the defect); which superblock the RD
22202 // hands an intra 64x64 block moves with the quantiser and the
22203 // depth, so both orientations x four quantisers x two motion
22204 // steps run here too.
22205 let vertical_split = attempt % 2 == 1;
22206 let cq = [58, 52, 45, 61][(attempt / 2 % 4) as usize];
22207 let sp = 8 + (attempt / 8) * 4;
22208 // Half ramp, half deterministic pseudo-noise: the flat "200"
22209 // half of r1's source made aomenc code the right-hand
22210 // superblocks skip, so at 8 bit no >32 intra block ever
22211 // appeared (probed cq 45/52/58/61/63 = 0 hits). The textured
22212 // half forces intra above 32x32 in an inter frame at BOTH
22213 // depths, so both arms carry the shape.
22214 let geq = if vertical_split {
22215 format!(
22216 "if(lt(Y,64), 40+mod(floor((X+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
22217 )
22218 } else {
22219 format!(
22220 "if(lt(X,128), 40+mod(floor((Y+N*{sp})/32)*90,200), mod((X*7+Y*13+N*97)*31,256))"
22221 )
22222 };
22223 let duration = frame_count as f64 / 25.0;
22224 let source = format!(
22225 "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
22226 geq=lum='{geq}',format=yuv420p"
22227 );
22228 let pix_fmt = if bit_depth == 10 {
22229 "yuv420p10le"
22230 } else {
22231 "yuv420p"
22232 };
22233 let y4m = Command::new("ffmpeg")
22234 .args([
22235 "-v",
22236 "error",
22237 "-f",
22238 "lavfi",
22239 "-i",
22240 &source,
22241 "-t",
22242 &duration.to_string(),
22243 "-pix_fmt",
22244 pix_fmt,
22245 "-strict",
22246 "-1",
22247 "-f",
22248 "yuv4mpegpipe",
22249 "-",
22250 ])
22251 .stdin(Stdio::null())
22252 .stdout(Stdio::piped())
22253 .stderr(Stdio::piped())
22254 .output()
22255 .expect("ffmpeg failed to run");
22256 assert!(
22257 y4m.status.success(),
22258 "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
22259 String::from_utf8_lossy(&y4m.stderr)
22260 );
22261 let cq_arg = format!("--cq-level={cq}");
22262 let depth_arg = format!("--bit-depth={bit_depth}");
22263 let input_depth_arg = format!("--input-bit-depth={bit_depth}");
22264 let args: Vec<&str> = vec![
22265 "--codec=av1",
22266 "--passes=1",
22267 "--end-usage=q",
22268 &cq_arg,
22269 "--cpu-used=0",
22270 "--threads=1",
22271 "--row-mt=0",
22272 "--sb-size=64",
22273 &depth_arg,
22274 &input_depth_arg,
22275 "--enable-restoration=0",
22276 "--enable-palette=0",
22277 "--deltaq-mode=0",
22278 "--enable-filter-intra=0",
22279 "--enable-cfl-intra=0",
22280 "--enable-intr

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